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.

277657 lines
7.4MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER >= 1400
  132. #define JUCE_USE_INTRINSICS 1
  133. #endif
  134. #else
  135. #error unknown compiler
  136. #endif
  137. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  138. /*** End of inlined file: juce_TargetPlatform.h ***/
  139. // FORCE_AMALGAMATOR_INCLUDE
  140. /*** Start of inlined file: juce_Config.h ***/
  141. #ifndef __JUCE_CONFIG_JUCEHEADER__
  142. #define __JUCE_CONFIG_JUCEHEADER__
  143. /*
  144. This file contains macros that enable/disable various JUCE features.
  145. */
  146. /** The name of the namespace that all Juce classes and functions will be
  147. put inside. If this is not defined, no namespace will be used.
  148. */
  149. #ifndef JUCE_NAMESPACE
  150. #define JUCE_NAMESPACE juce
  151. #endif
  152. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  153. project settings, but if you define this value, you can override this to force
  154. it to be true or false.
  155. */
  156. #ifndef JUCE_FORCE_DEBUG
  157. //#define JUCE_FORCE_DEBUG 0
  158. #endif
  159. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  160. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  161. Enabling it will also leave this turned on in release builds. When it's disabled,
  162. however, the jassert and jassertfalse macros will not be compiled in a
  163. release build.
  164. @see jassert, jassertfalse, Logger
  165. */
  166. #ifndef JUCE_LOG_ASSERTIONS
  167. #define JUCE_LOG_ASSERTIONS 0
  168. #endif
  169. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  170. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  171. on your Windows build machine.
  172. See the comments in the ASIOAudioIODevice class's header file for more
  173. info about this.
  174. */
  175. #ifndef JUCE_ASIO
  176. #define JUCE_ASIO 0
  177. #endif
  178. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  179. */
  180. #ifndef JUCE_WASAPI
  181. #define JUCE_WASAPI 0
  182. #endif
  183. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  184. */
  185. #ifndef JUCE_DIRECTSOUND
  186. #define JUCE_DIRECTSOUND 1
  187. #endif
  188. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  189. #ifndef JUCE_ALSA
  190. #define JUCE_ALSA 1
  191. #endif
  192. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  193. #ifndef JUCE_JACK
  194. #define JUCE_JACK 0
  195. #endif
  196. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  197. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  198. installed, and its header files will need to be on your include path.
  199. */
  200. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  201. #define JUCE_QUICKTIME 0
  202. #endif
  203. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  204. #undef JUCE_QUICKTIME
  205. #endif
  206. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  207. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  208. */
  209. #ifndef JUCE_OPENGL
  210. #define JUCE_OPENGL 1
  211. #endif
  212. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  213. If your app doesn't need to read FLAC files, you might want to disable this to
  214. reduce the size of your codebase and build time.
  215. */
  216. #ifndef JUCE_USE_FLAC
  217. #define JUCE_USE_FLAC 1
  218. #endif
  219. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  220. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  221. reduce the size of your codebase and build time.
  222. */
  223. #ifndef JUCE_USE_OGGVORBIS
  224. #define JUCE_USE_OGGVORBIS 1
  225. #endif
  226. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  227. Unless you're using CD-burning, you should probably turn this flag off to
  228. reduce code size.
  229. */
  230. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  231. #define JUCE_USE_CDBURNER 0
  232. #endif
  233. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  234. Unless you're using CD-reading, you should probably turn this flag off to
  235. reduce code size.
  236. */
  237. #ifndef JUCE_USE_CDREADER
  238. #define JUCE_USE_CDREADER 0
  239. #endif
  240. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  241. */
  242. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  243. #define JUCE_USE_CAMERA 0
  244. #endif
  245. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  246. gets repainted will flash in a random colour, so that you can check exactly how much and how
  247. often your components are being drawn.
  248. */
  249. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  250. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  251. #endif
  252. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  253. Unless you specifically want to disable this, it's best to leave this option turned on.
  254. */
  255. #ifndef JUCE_USE_XINERAMA
  256. #define JUCE_USE_XINERAMA 1
  257. #endif
  258. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  259. turned on unless you have a good reason to disable it.
  260. */
  261. #ifndef JUCE_USE_XSHM
  262. #define JUCE_USE_XSHM 1
  263. #endif
  264. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  265. */
  266. #ifndef JUCE_USE_XRENDER
  267. #define JUCE_USE_XRENDER 0
  268. #endif
  269. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  270. unless you have a good reason to disable it.
  271. */
  272. #ifndef JUCE_USE_XCURSOR
  273. #define JUCE_USE_XCURSOR 1
  274. #endif
  275. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  276. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  277. you're building a plugin hosting app.
  278. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  279. */
  280. #ifndef JUCE_PLUGINHOST_VST
  281. #define JUCE_PLUGINHOST_VST 0
  282. #endif
  283. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  284. of course, and should only be enabled if you're building a plugin hosting app.
  285. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  286. */
  287. #ifndef JUCE_PLUGINHOST_AU
  288. #define JUCE_PLUGINHOST_AU 0
  289. #endif
  290. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  291. This should be enabled if you're writing a console application.
  292. */
  293. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  294. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  295. #endif
  296. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  297. If you're not using any embedded web-pages, turning this off may reduce your code size.
  298. */
  299. #ifndef JUCE_WEB_BROWSER
  300. #define JUCE_WEB_BROWSER 1
  301. #endif
  302. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  303. Carbon isn't required for a normal app, but may be needed by specialised classes like
  304. plugin-hosts, which support older APIs.
  305. */
  306. #ifndef JUCE_SUPPORT_CARBON
  307. #define JUCE_SUPPORT_CARBON 1
  308. #endif
  309. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  310. You might need to tweak this if you're linking to an external zlib library in your app,
  311. but for normal apps, this option should be left alone.
  312. */
  313. #ifndef JUCE_INCLUDE_ZLIB_CODE
  314. #define JUCE_INCLUDE_ZLIB_CODE 1
  315. #endif
  316. #ifndef JUCE_INCLUDE_FLAC_CODE
  317. #define JUCE_INCLUDE_FLAC_CODE 1
  318. #endif
  319. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  320. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  321. #endif
  322. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  323. #define JUCE_INCLUDE_PNGLIB_CODE 1
  324. #endif
  325. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  326. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  327. #endif
  328. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  329. (Currently, this only affects Windows builds in debug mode).
  330. */
  331. #ifndef JUCE_CHECK_MEMORY_LEAKS
  332. #define JUCE_CHECK_MEMORY_LEAKS 1
  333. #endif
  334. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  335. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  336. are passed to the JUCEApplication::unhandledException() callback for logging.
  337. */
  338. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  339. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  340. #endif
  341. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  342. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  343. #undef JUCE_QUICKTIME
  344. #define JUCE_QUICKTIME 0
  345. #undef JUCE_OPENGL
  346. #define JUCE_OPENGL 0
  347. #undef JUCE_USE_CDBURNER
  348. #define JUCE_USE_CDBURNER 0
  349. #undef JUCE_USE_CDREADER
  350. #define JUCE_USE_CDREADER 0
  351. #undef JUCE_WEB_BROWSER
  352. #define JUCE_WEB_BROWSER 0
  353. #undef JUCE_PLUGINHOST_AU
  354. #define JUCE_PLUGINHOST_AU 0
  355. #undef JUCE_PLUGINHOST_VST
  356. #define JUCE_PLUGINHOST_VST 0
  357. #endif
  358. #endif
  359. /*** End of inlined file: juce_Config.h ***/
  360. // FORCE_AMALGAMATOR_INCLUDE
  361. #ifndef JUCE_BUILD_CORE
  362. #define JUCE_BUILD_CORE 1
  363. #endif
  364. #ifndef JUCE_BUILD_MISC
  365. #define JUCE_BUILD_MISC 1
  366. #endif
  367. #ifndef JUCE_BUILD_GUI
  368. #define JUCE_BUILD_GUI 1
  369. #endif
  370. #ifndef JUCE_BUILD_NATIVE
  371. #define JUCE_BUILD_NATIVE 1
  372. #endif
  373. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  374. #undef JUCE_BUILD_MISC
  375. #undef JUCE_BUILD_GUI
  376. #endif
  377. //==============================================================================
  378. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  379. #if JUCE_WINDOWS
  380. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  381. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  383. #ifndef STRICT
  384. #define STRICT 1
  385. #endif
  386. #undef WIN32_LEAN_AND_MEAN
  387. #define WIN32_LEAN_AND_MEAN 1
  388. #if JUCE_MSVC
  389. #pragma warning (push)
  390. #pragma warning (disable : 4100 4201 4514 4312 4995)
  391. #endif
  392. #define _WIN32_WINNT 0x0500
  393. #define _UNICODE 1
  394. #define UNICODE 1
  395. #ifndef _WIN32_IE
  396. #define _WIN32_IE 0x0400
  397. #endif
  398. #include <windows.h>
  399. #include <windowsx.h>
  400. #include <commdlg.h>
  401. #include <shellapi.h>
  402. #include <mmsystem.h>
  403. #include <vfw.h>
  404. #include <tchar.h>
  405. #include <stddef.h>
  406. #include <ctime>
  407. #include <wininet.h>
  408. #include <nb30.h>
  409. #include <iphlpapi.h>
  410. #include <mapi.h>
  411. #include <float.h>
  412. #include <process.h>
  413. #include <Exdisp.h>
  414. #include <exdispid.h>
  415. #include <shlobj.h>
  416. #if ! JUCE_MINGW
  417. #include <crtdbg.h>
  418. #include <comutil.h>
  419. #endif
  420. #if JUCE_OPENGL
  421. #include <gl/gl.h>
  422. #endif
  423. #undef PACKED
  424. #if JUCE_ASIO
  425. /*
  426. This is very frustrating - we only need to use a handful of definitions from
  427. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  428. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  429. implementation...
  430. ..unfortunately that would break Steinberg's license agreement for use of
  431. their SDK, so I'm not allowed to do this.
  432. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  433. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  434. (see www.steinberg.net/Steinberg/Developers.asp).
  435. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  436. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  437. if you prefer). Make sure that your header search path will find the
  438. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  439. files are actually needed - so to simplify things, you could just copy
  440. these into your JUCE directory).
  441. If you're compiling and you get an error here because you don't have the
  442. ASIO SDK installed, you can disable ASIO support by commenting-out the
  443. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  444. */
  445. #include "iasiodrv.h"
  446. #endif
  447. #if JUCE_USE_CDBURNER
  448. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  449. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  450. flag in juce_Config.h to avoid these includes.
  451. */
  452. #include <imapi.h>
  453. #include <imapierror.h>
  454. #endif
  455. #if JUCE_USE_CAMERA
  456. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  457. These files are provided in the normal Windows SDK, but some Microsoft plonker
  458. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  459. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  460. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  461. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  462. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  463. The dummy file just needs to contain the following content:
  464. #define __IDxtCompositor_INTERFACE_DEFINED__
  465. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  466. #define __IDxtJpeg_INTERFACE_DEFINED__
  467. #define __IDxtKey_INTERFACE_DEFINED__
  468. ..and that should be enough to convince qedit.h that you have the SDK!
  469. */
  470. #include <dshow.h>
  471. #include <qedit.h>
  472. #include <dshowasf.h>
  473. #endif
  474. #if JUCE_WASAPI
  475. #include <MMReg.h>
  476. #include <mmdeviceapi.h>
  477. #include <Audioclient.h>
  478. #include <Avrt.h>
  479. #include <functiondiscoverykeys.h>
  480. #endif
  481. #if JUCE_QUICKTIME
  482. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  483. add its header directory to your include path.
  484. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  485. flag in juce_Config.h
  486. */
  487. #include <Movies.h>
  488. #include <QTML.h>
  489. #include <QuickTimeComponents.h>
  490. #include <MediaHandlers.h>
  491. #include <ImageCodec.h>
  492. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  493. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  494. your include search path to make these import statements work.
  495. */
  496. #import <QTOLibrary.dll>
  497. #import <QTOControl.dll>
  498. #endif
  499. #if JUCE_MSVC
  500. #pragma warning (pop)
  501. #endif
  502. /** A simple COM smart pointer.
  503. Avoids having to include ATL just to get one of these.
  504. */
  505. template <class ComClass>
  506. class ComSmartPtr
  507. {
  508. public:
  509. ComSmartPtr() throw() : p (0) {}
  510. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  511. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  512. ~ComSmartPtr() { if (p != 0) p->Release(); }
  513. operator ComClass*() const throw() { return p; }
  514. ComClass& operator*() const throw() { return *p; }
  515. ComClass** operator&() throw() { return &p; }
  516. ComClass* operator->() const throw() { return p; }
  517. ComClass* operator= (ComClass* const newP)
  518. {
  519. if (newP != 0) newP->AddRef();
  520. if (p != 0) p->Release();
  521. p = newP;
  522. return newP;
  523. }
  524. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  525. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  526. {
  527. #ifndef __MINGW32__
  528. operator= (0);
  529. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  530. #else
  531. return S_FALSE;
  532. #endif
  533. }
  534. private:
  535. ComClass* p;
  536. };
  537. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  538. */
  539. template <class ComClass>
  540. class ComBaseClassHelper : public ComClass
  541. {
  542. public:
  543. ComBaseClassHelper() : refCount (1) {}
  544. virtual ~ComBaseClassHelper() {}
  545. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  546. {
  547. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  548. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  549. *result = 0;
  550. return E_NOINTERFACE;
  551. }
  552. ULONG __stdcall AddRef() { return ++refCount; }
  553. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  554. protected:
  555. int refCount;
  556. };
  557. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  558. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  559. #elif JUCE_LINUX
  560. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  561. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  563. /*
  564. This file wraps together all the linux-specific headers, so
  565. that we can include them all just once, and compile all our
  566. platform-specific stuff in one big lump, keeping it out of the
  567. way of the rest of the codebase.
  568. */
  569. #include <sched.h>
  570. #include <pthread.h>
  571. #include <sys/time.h>
  572. #include <errno.h>
  573. #include <sys/stat.h>
  574. #include <sys/dir.h>
  575. #include <sys/ptrace.h>
  576. #include <sys/vfs.h>
  577. #include <sys/wait.h>
  578. #include <fnmatch.h>
  579. #include <utime.h>
  580. #include <pwd.h>
  581. #include <fcntl.h>
  582. #include <dlfcn.h>
  583. #include <netdb.h>
  584. #include <arpa/inet.h>
  585. #include <netinet/in.h>
  586. #include <sys/types.h>
  587. #include <sys/ioctl.h>
  588. #include <sys/socket.h>
  589. #include <net/if.h>
  590. #include <sys/sysinfo.h>
  591. #include <sys/file.h>
  592. #include <signal.h>
  593. /* Got a build error here? You'll need to install the freetype library...
  594. The name of the package to install is "libfreetype6-dev".
  595. */
  596. #include <ft2build.h>
  597. #include FT_FREETYPE_H
  598. #include <X11/Xlib.h>
  599. #include <X11/Xatom.h>
  600. #include <X11/Xresource.h>
  601. #include <X11/Xutil.h>
  602. #include <X11/Xmd.h>
  603. #include <X11/keysym.h>
  604. #include <X11/cursorfont.h>
  605. #if JUCE_USE_XINERAMA
  606. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  607. #include <X11/extensions/Xinerama.h>
  608. #endif
  609. #if JUCE_USE_XSHM
  610. #include <X11/extensions/XShm.h>
  611. #include <sys/shm.h>
  612. #include <sys/ipc.h>
  613. #endif
  614. #if JUCE_USE_XRENDER
  615. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  616. #include <X11/extensions/Xrender.h>
  617. #include <X11/extensions/Xcomposite.h>
  618. #endif
  619. #if JUCE_USE_XCURSOR
  620. // If you're missing this header, try installing the libxcursor-dev package
  621. #include <X11/Xcursor/Xcursor.h>
  622. #endif
  623. #if JUCE_OPENGL
  624. /* Got an include error here?
  625. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  626. and "freeglut3-dev".
  627. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  628. want to disable it.
  629. */
  630. #include <GL/glx.h>
  631. #endif
  632. #undef KeyPress
  633. #if JUCE_ALSA
  634. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  635. not got your paths set up correctly to find its header files.
  636. The package you need to install to get ASLA support is "libasound2-dev".
  637. If you don't have the ALSA library and don't want to build Juce with audio support,
  638. just disable the JUCE_ALSA flag in juce_Config.h
  639. */
  640. #include <alsa/asoundlib.h>
  641. #endif
  642. #if JUCE_JACK
  643. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  644. installed, or you've not got your paths set up correctly to find its header files.
  645. The package you need to install to get JACK support is "libjack-dev".
  646. If you don't have the jack-audio-connection-kit library and don't want to build
  647. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  648. */
  649. #include <jack/jack.h>
  650. //#include <jack/transport.h>
  651. #endif
  652. #undef SIZEOF
  653. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  654. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  655. #elif JUCE_MAC || JUCE_IPHONE
  656. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  657. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  659. /*
  660. This file wraps together all the mac-specific code, so that
  661. we can include all the native headers just once, and compile all our
  662. platform-specific stuff in one big lump, keeping it out of the way of
  663. the rest of the codebase.
  664. */
  665. #define USE_COREGRAPHICS_RENDERING 1
  666. #if JUCE_IOS
  667. #import <Foundation/Foundation.h>
  668. #import <UIKit/UIKit.h>
  669. #import <AudioToolbox/AudioToolbox.h>
  670. #import <AVFoundation/AVFoundation.h>
  671. #import <CoreData/CoreData.h>
  672. #import <MobileCoreServices/MobileCoreServices.h>
  673. #import <QuartzCore/QuartzCore.h>
  674. #include <sys/fcntl.h>
  675. #if JUCE_OPENGL
  676. #include <OpenGLES/ES1/gl.h>
  677. #include <OpenGLES/ES1/glext.h>
  678. #endif
  679. #else
  680. #import <Cocoa/Cocoa.h>
  681. #import <CoreAudio/HostTime.h>
  682. #import <CoreAudio/AudioHardware.h>
  683. #import <CoreMIDI/MIDIServices.h>
  684. #import <QTKit/QTKit.h>
  685. #import <WebKit/WebKit.h>
  686. #import <DiscRecording/DiscRecording.h>
  687. #import <IOKit/IOKitLib.h>
  688. #import <IOKit/IOCFPlugIn.h>
  689. #import <IOKit/hid/IOHIDLib.h>
  690. #import <IOKit/hid/IOHIDKeys.h>
  691. #import <IOKit/pwr_mgt/IOPMLib.h>
  692. #include <Carbon/Carbon.h>
  693. #include <sys/dir.h>
  694. #endif
  695. #include <sys/socket.h>
  696. #include <sys/sysctl.h>
  697. #include <sys/stat.h>
  698. #include <sys/param.h>
  699. #include <sys/mount.h>
  700. #include <fnmatch.h>
  701. #include <utime.h>
  702. #include <dlfcn.h>
  703. #include <ifaddrs.h>
  704. #include <net/if_dl.h>
  705. #include <mach/mach_time.h>
  706. #if MACOS_10_4_OR_EARLIER
  707. #include <GLUT/glut.h>
  708. #endif
  709. #if ! CGFLOAT_DEFINED
  710. #define CGFloat float
  711. #endif
  712. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  713. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  714. #else
  715. #error "Unknown platform!"
  716. #endif
  717. #endif
  718. //==============================================================================
  719. #define DONT_SET_USING_JUCE_NAMESPACE 1
  720. #undef max
  721. #undef min
  722. #define NO_DUMMY_DECL
  723. #if JUCE_BUILD_NATIVE
  724. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  725. #endif
  726. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  727. #pragma warning (disable: 4309 4305)
  728. #endif
  729. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  730. BEGIN_JUCE_NAMESPACE
  731. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  732. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  733. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  734. /**
  735. Creates a floating carbon window that can be used to hold a carbon UI.
  736. This is a handy class that's designed to be inlined where needed, e.g.
  737. in the audio plugin hosting code.
  738. */
  739. class CarbonViewWrapperComponent : public Component,
  740. public ComponentMovementWatcher,
  741. public Timer
  742. {
  743. public:
  744. CarbonViewWrapperComponent()
  745. : ComponentMovementWatcher (this),
  746. wrapperWindow (0),
  747. embeddedView (0),
  748. recursiveResize (false)
  749. {
  750. }
  751. virtual ~CarbonViewWrapperComponent()
  752. {
  753. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  754. }
  755. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  756. virtual void removeView (HIViewRef embeddedView) = 0;
  757. virtual void mouseDown (int, int) {}
  758. virtual void paint() {}
  759. virtual bool getEmbeddedViewSize (int& w, int& h)
  760. {
  761. if (embeddedView == 0)
  762. return false;
  763. HIRect bounds;
  764. HIViewGetBounds (embeddedView, &bounds);
  765. w = jmax (1, roundToInt (bounds.size.width));
  766. h = jmax (1, roundToInt (bounds.size.height));
  767. return true;
  768. }
  769. void createWindow()
  770. {
  771. if (wrapperWindow == 0)
  772. {
  773. Rect r;
  774. r.left = getScreenX();
  775. r.top = getScreenY();
  776. r.right = r.left + getWidth();
  777. r.bottom = r.top + getHeight();
  778. CreateNewWindow (kDocumentWindowClass,
  779. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  780. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  781. &r, &wrapperWindow);
  782. jassert (wrapperWindow != 0);
  783. if (wrapperWindow == 0)
  784. return;
  785. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  786. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  787. [ownerWindow addChildWindow: carbonWindow
  788. ordered: NSWindowAbove];
  789. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  790. EventTypeSpec windowEventTypes[] =
  791. {
  792. { kEventClassWindow, kEventWindowGetClickActivation },
  793. { kEventClassWindow, kEventWindowHandleDeactivate },
  794. { kEventClassWindow, kEventWindowBoundsChanging },
  795. { kEventClassMouse, kEventMouseDown },
  796. { kEventClassMouse, kEventMouseMoved },
  797. { kEventClassMouse, kEventMouseDragged },
  798. { kEventClassMouse, kEventMouseUp},
  799. { kEventClassWindow, kEventWindowDrawContent },
  800. { kEventClassWindow, kEventWindowShown },
  801. { kEventClassWindow, kEventWindowHidden }
  802. };
  803. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  804. InstallWindowEventHandler (wrapperWindow, upp,
  805. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  806. windowEventTypes, this, &eventHandlerRef);
  807. setOurSizeToEmbeddedViewSize();
  808. setEmbeddedWindowToOurSize();
  809. creationTime = Time::getCurrentTime();
  810. }
  811. }
  812. void deleteWindow()
  813. {
  814. removeView (embeddedView);
  815. embeddedView = 0;
  816. if (wrapperWindow != 0)
  817. {
  818. RemoveEventHandler (eventHandlerRef);
  819. DisposeWindow (wrapperWindow);
  820. wrapperWindow = 0;
  821. }
  822. }
  823. void setOurSizeToEmbeddedViewSize()
  824. {
  825. int w, h;
  826. if (getEmbeddedViewSize (w, h))
  827. {
  828. if (w != getWidth() || h != getHeight())
  829. {
  830. startTimer (50);
  831. setSize (w, h);
  832. if (getParentComponent() != 0)
  833. getParentComponent()->setSize (w, h);
  834. }
  835. else
  836. {
  837. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  838. }
  839. }
  840. else
  841. {
  842. stopTimer();
  843. }
  844. }
  845. void setEmbeddedWindowToOurSize()
  846. {
  847. if (! recursiveResize)
  848. {
  849. recursiveResize = true;
  850. if (embeddedView != 0)
  851. {
  852. HIRect r;
  853. r.origin.x = 0;
  854. r.origin.y = 0;
  855. r.size.width = (float) getWidth();
  856. r.size.height = (float) getHeight();
  857. HIViewSetFrame (embeddedView, &r);
  858. }
  859. if (wrapperWindow != 0)
  860. {
  861. Rect wr;
  862. wr.left = getScreenX();
  863. wr.top = getScreenY();
  864. wr.right = wr.left + getWidth();
  865. wr.bottom = wr.top + getHeight();
  866. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  867. ShowWindow (wrapperWindow);
  868. }
  869. recursiveResize = false;
  870. }
  871. }
  872. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  873. {
  874. setEmbeddedWindowToOurSize();
  875. }
  876. void componentPeerChanged()
  877. {
  878. deleteWindow();
  879. createWindow();
  880. }
  881. void componentVisibilityChanged (Component&)
  882. {
  883. if (isShowing())
  884. createWindow();
  885. else
  886. deleteWindow();
  887. setEmbeddedWindowToOurSize();
  888. }
  889. static void recursiveHIViewRepaint (HIViewRef view)
  890. {
  891. HIViewSetNeedsDisplay (view, true);
  892. HIViewRef child = HIViewGetFirstSubview (view);
  893. while (child != 0)
  894. {
  895. recursiveHIViewRepaint (child);
  896. child = HIViewGetNextView (child);
  897. }
  898. }
  899. void timerCallback()
  900. {
  901. setOurSizeToEmbeddedViewSize();
  902. // To avoid strange overpainting problems when the UI is first opened, we'll
  903. // repaint it a few times during the first second that it's on-screen..
  904. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  905. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  906. }
  907. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  908. EventRef event)
  909. {
  910. switch (GetEventKind (event))
  911. {
  912. case kEventWindowHandleDeactivate:
  913. ActivateWindow (wrapperWindow, TRUE);
  914. break;
  915. case kEventWindowGetClickActivation:
  916. {
  917. getTopLevelComponent()->toFront (false);
  918. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  919. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  920. sizeof (ClickActivationResult), &howToHandleClick);
  921. HIViewSetNeedsDisplay (embeddedView, true);
  922. }
  923. break;
  924. }
  925. return noErr;
  926. }
  927. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  928. EventRef event, void* userData)
  929. {
  930. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  931. }
  932. protected:
  933. WindowRef wrapperWindow;
  934. HIViewRef embeddedView;
  935. bool recursiveResize;
  936. Time creationTime;
  937. EventHandlerRef eventHandlerRef;
  938. };
  939. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  940. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  941. END_JUCE_NAMESPACE
  942. #endif
  943. #define JUCE_AMALGAMATED_TEMPLATE 1
  944. //==============================================================================
  945. #if JUCE_BUILD_CORE
  946. /*** Start of inlined file: juce_FileLogger.cpp ***/
  947. BEGIN_JUCE_NAMESPACE
  948. FileLogger::FileLogger (const File& logFile_,
  949. const String& welcomeMessage,
  950. const int maxInitialFileSizeBytes)
  951. : logFile (logFile_)
  952. {
  953. if (maxInitialFileSizeBytes >= 0)
  954. trimFileSize (maxInitialFileSizeBytes);
  955. if (! logFile_.exists())
  956. {
  957. // do this so that the parent directories get created..
  958. logFile_.create();
  959. }
  960. logStream = logFile_.createOutputStream (256);
  961. jassert (logStream != 0);
  962. String welcome;
  963. welcome << "\r\n**********************************************************\r\n"
  964. << welcomeMessage
  965. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  966. << "\r\n";
  967. logMessage (welcome);
  968. }
  969. FileLogger::~FileLogger()
  970. {
  971. }
  972. void FileLogger::logMessage (const String& message)
  973. {
  974. if (logStream != 0)
  975. {
  976. DBG (message);
  977. const ScopedLock sl (logLock);
  978. (*logStream) << message << "\r\n";
  979. logStream->flush();
  980. }
  981. }
  982. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  983. {
  984. if (maxFileSizeBytes <= 0)
  985. {
  986. logFile.deleteFile();
  987. }
  988. else
  989. {
  990. const int64 fileSize = logFile.getSize();
  991. if (fileSize > maxFileSizeBytes)
  992. {
  993. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  994. jassert (in != 0);
  995. if (in != 0)
  996. {
  997. in->setPosition (fileSize - maxFileSizeBytes);
  998. String content;
  999. {
  1000. MemoryBlock contentToSave;
  1001. contentToSave.setSize (maxFileSizeBytes + 4);
  1002. contentToSave.fillWith (0);
  1003. in->read (contentToSave.getData(), maxFileSizeBytes);
  1004. in = 0;
  1005. content = contentToSave.toString();
  1006. }
  1007. int newStart = 0;
  1008. while (newStart < fileSize
  1009. && content[newStart] != '\n'
  1010. && content[newStart] != '\r')
  1011. ++newStart;
  1012. logFile.deleteFile();
  1013. logFile.appendText (content.substring (newStart), false, false);
  1014. }
  1015. }
  1016. }
  1017. }
  1018. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1019. const String& logFileName,
  1020. const String& welcomeMessage,
  1021. const int maxInitialFileSizeBytes)
  1022. {
  1023. #if JUCE_MAC
  1024. File logFile ("~/Library/Logs");
  1025. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1026. .getChildFile (logFileName);
  1027. #else
  1028. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1029. if (logFile.isDirectory())
  1030. {
  1031. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1032. .getChildFile (logFileName);
  1033. }
  1034. #endif
  1035. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1036. }
  1037. END_JUCE_NAMESPACE
  1038. /*** End of inlined file: juce_FileLogger.cpp ***/
  1039. /*** Start of inlined file: juce_Logger.cpp ***/
  1040. BEGIN_JUCE_NAMESPACE
  1041. Logger::Logger()
  1042. {
  1043. }
  1044. Logger::~Logger()
  1045. {
  1046. }
  1047. Logger* Logger::currentLogger = 0;
  1048. void Logger::setCurrentLogger (Logger* const newLogger,
  1049. const bool deleteOldLogger)
  1050. {
  1051. Logger* const oldLogger = currentLogger;
  1052. currentLogger = newLogger;
  1053. if (deleteOldLogger)
  1054. delete oldLogger;
  1055. }
  1056. void Logger::writeToLog (const String& message)
  1057. {
  1058. if (currentLogger != 0)
  1059. currentLogger->logMessage (message);
  1060. else
  1061. outputDebugString (message);
  1062. }
  1063. #if JUCE_LOG_ASSERTIONS
  1064. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1065. {
  1066. String m ("JUCE Assertion failure in ");
  1067. m << filename << ", line " << lineNum;
  1068. Logger::writeToLog (m);
  1069. }
  1070. #endif
  1071. END_JUCE_NAMESPACE
  1072. /*** End of inlined file: juce_Logger.cpp ***/
  1073. /*** Start of inlined file: juce_Random.cpp ***/
  1074. BEGIN_JUCE_NAMESPACE
  1075. Random::Random (const int64 seedValue) throw()
  1076. : seed (seedValue)
  1077. {
  1078. }
  1079. Random::~Random() throw()
  1080. {
  1081. }
  1082. void Random::setSeed (const int64 newSeed) throw()
  1083. {
  1084. seed = newSeed;
  1085. }
  1086. void Random::combineSeed (const int64 seedValue) throw()
  1087. {
  1088. seed ^= nextInt64() ^ seedValue;
  1089. }
  1090. void Random::setSeedRandomly()
  1091. {
  1092. combineSeed ((int64) (pointer_sized_int) this);
  1093. combineSeed (Time::getMillisecondCounter());
  1094. combineSeed (Time::getHighResolutionTicks());
  1095. combineSeed (Time::getHighResolutionTicksPerSecond());
  1096. combineSeed (Time::currentTimeMillis());
  1097. }
  1098. int Random::nextInt() throw()
  1099. {
  1100. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1101. return (int) (seed >> 16);
  1102. }
  1103. int Random::nextInt (const int maxValue) throw()
  1104. {
  1105. jassert (maxValue > 0);
  1106. return (nextInt() & 0x7fffffff) % maxValue;
  1107. }
  1108. int64 Random::nextInt64() throw()
  1109. {
  1110. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1111. }
  1112. bool Random::nextBool() throw()
  1113. {
  1114. return (nextInt() & 0x80000000) != 0;
  1115. }
  1116. float Random::nextFloat() throw()
  1117. {
  1118. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1119. }
  1120. double Random::nextDouble() throw()
  1121. {
  1122. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1123. }
  1124. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1125. {
  1126. BigInteger n;
  1127. do
  1128. {
  1129. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1130. }
  1131. while (n >= maximumValue);
  1132. return n;
  1133. }
  1134. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1135. {
  1136. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1137. while ((startBit & 31) != 0 && numBits > 0)
  1138. {
  1139. arrayToChange.setBit (startBit++, nextBool());
  1140. --numBits;
  1141. }
  1142. while (numBits >= 32)
  1143. {
  1144. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1145. startBit += 32;
  1146. numBits -= 32;
  1147. }
  1148. while (--numBits >= 0)
  1149. arrayToChange.setBit (startBit + numBits, nextBool());
  1150. }
  1151. Random& Random::getSystemRandom() throw()
  1152. {
  1153. static Random sysRand (1);
  1154. return sysRand;
  1155. }
  1156. END_JUCE_NAMESPACE
  1157. /*** End of inlined file: juce_Random.cpp ***/
  1158. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1159. BEGIN_JUCE_NAMESPACE
  1160. RelativeTime::RelativeTime (const double seconds_) throw()
  1161. : seconds (seconds_)
  1162. {
  1163. }
  1164. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1165. : seconds (other.seconds)
  1166. {
  1167. }
  1168. RelativeTime::~RelativeTime() throw()
  1169. {
  1170. }
  1171. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1172. {
  1173. return RelativeTime (milliseconds * 0.001);
  1174. }
  1175. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1176. {
  1177. return RelativeTime (milliseconds * 0.001);
  1178. }
  1179. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1180. {
  1181. return RelativeTime (numberOfMinutes * 60.0);
  1182. }
  1183. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1184. {
  1185. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1186. }
  1187. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1188. {
  1189. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1190. }
  1191. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1192. {
  1193. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1194. }
  1195. int64 RelativeTime::inMilliseconds() const throw()
  1196. {
  1197. return (int64)(seconds * 1000.0);
  1198. }
  1199. double RelativeTime::inMinutes() const throw()
  1200. {
  1201. return seconds / 60.0;
  1202. }
  1203. double RelativeTime::inHours() const throw()
  1204. {
  1205. return seconds / (60.0 * 60.0);
  1206. }
  1207. double RelativeTime::inDays() const throw()
  1208. {
  1209. return seconds / (60.0 * 60.0 * 24.0);
  1210. }
  1211. double RelativeTime::inWeeks() const throw()
  1212. {
  1213. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1214. }
  1215. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1216. {
  1217. if (seconds < 0.001 && seconds > -0.001)
  1218. return returnValueForZeroTime;
  1219. String result;
  1220. if (seconds < 0)
  1221. result = "-";
  1222. int fieldsShown = 0;
  1223. int n = abs ((int) inWeeks());
  1224. if (n > 0)
  1225. {
  1226. result << n << ((n == 1) ? TRANS(" week ")
  1227. : TRANS(" weeks "));
  1228. ++fieldsShown;
  1229. }
  1230. n = abs ((int) inDays()) % 7;
  1231. if (n > 0)
  1232. {
  1233. result << n << ((n == 1) ? TRANS(" day ")
  1234. : TRANS(" days "));
  1235. ++fieldsShown;
  1236. }
  1237. if (fieldsShown < 2)
  1238. {
  1239. n = abs ((int) inHours()) % 24;
  1240. if (n > 0)
  1241. {
  1242. result << n << ((n == 1) ? TRANS(" hr ")
  1243. : TRANS(" hrs "));
  1244. ++fieldsShown;
  1245. }
  1246. if (fieldsShown < 2)
  1247. {
  1248. n = abs ((int) inMinutes()) % 60;
  1249. if (n > 0)
  1250. {
  1251. result << n << ((n == 1) ? TRANS(" min ")
  1252. : TRANS(" mins "));
  1253. ++fieldsShown;
  1254. }
  1255. if (fieldsShown < 2)
  1256. {
  1257. n = abs ((int) inSeconds()) % 60;
  1258. if (n > 0)
  1259. {
  1260. result << n << ((n == 1) ? TRANS(" sec ")
  1261. : TRANS(" secs "));
  1262. ++fieldsShown;
  1263. }
  1264. if (fieldsShown < 1)
  1265. {
  1266. n = abs ((int) inMilliseconds()) % 1000;
  1267. if (n > 0)
  1268. {
  1269. result << n << TRANS(" ms");
  1270. ++fieldsShown;
  1271. }
  1272. }
  1273. }
  1274. }
  1275. }
  1276. return result.trimEnd();
  1277. }
  1278. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1279. {
  1280. seconds = other.seconds;
  1281. return *this;
  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. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1296. {
  1297. return seconds < other.seconds;
  1298. }
  1299. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1300. {
  1301. return seconds >= other.seconds;
  1302. }
  1303. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1304. {
  1305. return seconds <= other.seconds;
  1306. }
  1307. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1308. {
  1309. return RelativeTime (seconds + timeToAdd.seconds);
  1310. }
  1311. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1312. {
  1313. return RelativeTime (seconds - timeToSubtract.seconds);
  1314. }
  1315. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1316. {
  1317. return RelativeTime (seconds + secondsToAdd);
  1318. }
  1319. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1320. {
  1321. return RelativeTime (seconds - secondsToSubtract);
  1322. }
  1323. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1324. {
  1325. seconds += timeToAdd.seconds;
  1326. return *this;
  1327. }
  1328. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1329. {
  1330. seconds -= timeToSubtract.seconds;
  1331. return *this;
  1332. }
  1333. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1334. {
  1335. seconds += secondsToAdd;
  1336. return *this;
  1337. }
  1338. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1339. {
  1340. seconds -= secondsToSubtract;
  1341. return *this;
  1342. }
  1343. END_JUCE_NAMESPACE
  1344. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1345. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1346. BEGIN_JUCE_NAMESPACE
  1347. SystemStats::CPUFlags SystemStats::cpuFlags;
  1348. const String SystemStats::getJUCEVersion()
  1349. {
  1350. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1351. + "." + String (JUCE_MINOR_VERSION)
  1352. + "." + String (JUCE_BUILDNUMBER);
  1353. }
  1354. const StringArray SystemStats::getMACAddressStrings()
  1355. {
  1356. int64 macAddresses [16];
  1357. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1358. StringArray s;
  1359. for (int i = 0; i < numAddresses; ++i)
  1360. {
  1361. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1362. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1363. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1364. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1365. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1366. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1367. }
  1368. return s;
  1369. }
  1370. #ifdef JUCE_DLL
  1371. void* juce_Malloc (const int size)
  1372. {
  1373. return malloc (size);
  1374. }
  1375. void* juce_Calloc (const int size)
  1376. {
  1377. return calloc (1, size);
  1378. }
  1379. void* juce_Realloc (void* const block, const int size)
  1380. {
  1381. return realloc (block, size);
  1382. }
  1383. void juce_Free (void* const block)
  1384. {
  1385. free (block);
  1386. }
  1387. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1388. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1389. {
  1390. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1391. }
  1392. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1393. {
  1394. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1395. }
  1396. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1397. {
  1398. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1399. }
  1400. void juce_DebugFree (void* const block)
  1401. {
  1402. _free_dbg (block, _NORMAL_BLOCK);
  1403. }
  1404. #endif
  1405. #endif
  1406. END_JUCE_NAMESPACE
  1407. /*** End of inlined file: juce_SystemStats.cpp ***/
  1408. /*** Start of inlined file: juce_Time.cpp ***/
  1409. #if JUCE_MSVC
  1410. #pragma warning (push)
  1411. #pragma warning (disable: 4514)
  1412. #endif
  1413. #ifndef JUCE_WINDOWS
  1414. #include <sys/time.h>
  1415. #else
  1416. #include <ctime>
  1417. #endif
  1418. #include <sys/timeb.h>
  1419. #if JUCE_MSVC
  1420. #pragma warning (pop)
  1421. #ifdef _INC_TIME_INL
  1422. #define USE_NEW_SECURE_TIME_FNS
  1423. #endif
  1424. #endif
  1425. BEGIN_JUCE_NAMESPACE
  1426. namespace TimeHelpers
  1427. {
  1428. static struct tm millisToLocal (const int64 millis) throw()
  1429. {
  1430. struct tm result;
  1431. const int64 seconds = millis / 1000;
  1432. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1433. {
  1434. // use extended maths for dates beyond 1970 to 2037..
  1435. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1436. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1437. const int days = (int) (jdm / literal64bit (86400));
  1438. const int a = 32044 + days;
  1439. const int b = (4 * a + 3) / 146097;
  1440. const int c = a - (b * 146097) / 4;
  1441. const int d = (4 * c + 3) / 1461;
  1442. const int e = c - (d * 1461) / 4;
  1443. const int m = (5 * e + 2) / 153;
  1444. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1445. result.tm_mon = m + 2 - 12 * (m / 10);
  1446. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1447. result.tm_wday = (days + 1) % 7;
  1448. result.tm_yday = -1;
  1449. int t = (int) (jdm % literal64bit (86400));
  1450. result.tm_hour = t / 3600;
  1451. t %= 3600;
  1452. result.tm_min = t / 60;
  1453. result.tm_sec = t % 60;
  1454. result.tm_isdst = -1;
  1455. }
  1456. else
  1457. {
  1458. time_t now = static_cast <time_t> (seconds);
  1459. #if JUCE_WINDOWS
  1460. #ifdef USE_NEW_SECURE_TIME_FNS
  1461. if (now >= 0 && now <= 0x793406fff)
  1462. localtime_s (&result, &now);
  1463. else
  1464. zeromem (&result, sizeof (result));
  1465. #else
  1466. result = *localtime (&now);
  1467. #endif
  1468. #else
  1469. // more thread-safe
  1470. localtime_r (&now, &result);
  1471. #endif
  1472. }
  1473. return result;
  1474. }
  1475. static int extendedModulo (const int64 value, const int modulo) throw()
  1476. {
  1477. return (int) (value >= 0 ? (value % modulo)
  1478. : (value - ((value / modulo) + 1) * modulo));
  1479. }
  1480. static uint32 lastMSCounterValue = 0;
  1481. }
  1482. Time::Time() throw()
  1483. : millisSinceEpoch (0)
  1484. {
  1485. }
  1486. Time::Time (const Time& other) throw()
  1487. : millisSinceEpoch (other.millisSinceEpoch)
  1488. {
  1489. }
  1490. Time::Time (const int64 ms) throw()
  1491. : millisSinceEpoch (ms)
  1492. {
  1493. }
  1494. Time::Time (const int year,
  1495. const int month,
  1496. const int day,
  1497. const int hours,
  1498. const int minutes,
  1499. const int seconds,
  1500. const int milliseconds,
  1501. const bool useLocalTime) throw()
  1502. {
  1503. jassert (year > 100); // year must be a 4-digit version
  1504. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1505. {
  1506. // use extended maths for dates beyond 1970 to 2037..
  1507. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1508. : 0;
  1509. const int a = (13 - month) / 12;
  1510. const int y = year + 4800 - a;
  1511. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1512. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1513. - 32045;
  1514. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1515. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1516. + milliseconds;
  1517. }
  1518. else
  1519. {
  1520. struct tm t;
  1521. t.tm_year = year - 1900;
  1522. t.tm_mon = month;
  1523. t.tm_mday = day;
  1524. t.tm_hour = hours;
  1525. t.tm_min = minutes;
  1526. t.tm_sec = seconds;
  1527. t.tm_isdst = -1;
  1528. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1529. if (millisSinceEpoch < 0)
  1530. millisSinceEpoch = 0;
  1531. else
  1532. millisSinceEpoch += milliseconds;
  1533. }
  1534. }
  1535. Time::~Time() throw()
  1536. {
  1537. }
  1538. Time& Time::operator= (const Time& other) throw()
  1539. {
  1540. millisSinceEpoch = other.millisSinceEpoch;
  1541. return *this;
  1542. }
  1543. int64 Time::currentTimeMillis() throw()
  1544. {
  1545. static uint32 lastCounterResult = 0xffffffff;
  1546. static int64 correction = 0;
  1547. const uint32 now = getMillisecondCounter();
  1548. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1549. if (now < lastCounterResult)
  1550. {
  1551. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1552. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1553. {
  1554. // get the time once using normal library calls, and store the difference needed to
  1555. // turn the millisecond counter into a real time.
  1556. #if JUCE_WINDOWS
  1557. struct _timeb t;
  1558. #ifdef USE_NEW_SECURE_TIME_FNS
  1559. _ftime_s (&t);
  1560. #else
  1561. _ftime (&t);
  1562. #endif
  1563. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1564. #else
  1565. struct timeval tv;
  1566. struct timezone tz;
  1567. gettimeofday (&tv, &tz);
  1568. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1569. #endif
  1570. }
  1571. }
  1572. lastCounterResult = now;
  1573. return correction + now;
  1574. }
  1575. uint32 juce_millisecondsSinceStartup() throw();
  1576. uint32 Time::getMillisecondCounter() throw()
  1577. {
  1578. const uint32 now = juce_millisecondsSinceStartup();
  1579. if (now < TimeHelpers::lastMSCounterValue)
  1580. {
  1581. // in multi-threaded apps this might be called concurrently, so
  1582. // make sure that our last counter value only increases and doesn't
  1583. // go backwards..
  1584. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1585. TimeHelpers::lastMSCounterValue = now;
  1586. }
  1587. else
  1588. {
  1589. TimeHelpers::lastMSCounterValue = now;
  1590. }
  1591. return now;
  1592. }
  1593. uint32 Time::getApproximateMillisecondCounter() throw()
  1594. {
  1595. jassert (TimeHelpers::lastMSCounterValue != 0);
  1596. return TimeHelpers::lastMSCounterValue;
  1597. }
  1598. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1599. {
  1600. for (;;)
  1601. {
  1602. const uint32 now = getMillisecondCounter();
  1603. if (now >= targetTime)
  1604. break;
  1605. const int toWait = targetTime - now;
  1606. if (toWait > 2)
  1607. {
  1608. Thread::sleep (jmin (20, toWait >> 1));
  1609. }
  1610. else
  1611. {
  1612. // xxx should consider using mutex_pause on the mac as it apparently
  1613. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1614. for (int i = 10; --i >= 0;)
  1615. Thread::yield();
  1616. }
  1617. }
  1618. }
  1619. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1620. {
  1621. return ticks / (double) getHighResolutionTicksPerSecond();
  1622. }
  1623. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1624. {
  1625. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1626. }
  1627. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1628. {
  1629. return Time (currentTimeMillis());
  1630. }
  1631. const String Time::toString (const bool includeDate,
  1632. const bool includeTime,
  1633. const bool includeSeconds,
  1634. const bool use24HourClock) const throw()
  1635. {
  1636. String result;
  1637. if (includeDate)
  1638. {
  1639. result << getDayOfMonth() << ' '
  1640. << getMonthName (true) << ' '
  1641. << getYear();
  1642. if (includeTime)
  1643. result << ' ';
  1644. }
  1645. if (includeTime)
  1646. {
  1647. const int mins = getMinutes();
  1648. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1649. << (mins < 10 ? ":0" : ":") << mins;
  1650. if (includeSeconds)
  1651. {
  1652. const int secs = getSeconds();
  1653. result << (secs < 10 ? ":0" : ":") << secs;
  1654. }
  1655. if (! use24HourClock)
  1656. result << (isAfternoon() ? "pm" : "am");
  1657. }
  1658. return result.trimEnd();
  1659. }
  1660. const String Time::formatted (const String& format) const throw()
  1661. {
  1662. String buffer;
  1663. int bufferSize = 128;
  1664. buffer.preallocateStorage (bufferSize);
  1665. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1666. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1667. {
  1668. bufferSize += 128;
  1669. buffer.preallocateStorage (bufferSize);
  1670. }
  1671. return buffer;
  1672. }
  1673. int Time::getYear() const throw()
  1674. {
  1675. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1676. }
  1677. int Time::getMonth() const throw()
  1678. {
  1679. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1680. }
  1681. int Time::getDayOfMonth() const throw()
  1682. {
  1683. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1684. }
  1685. int Time::getDayOfWeek() const throw()
  1686. {
  1687. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1688. }
  1689. int Time::getHours() const throw()
  1690. {
  1691. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1692. }
  1693. int Time::getHoursInAmPmFormat() const throw()
  1694. {
  1695. const int hours = getHours();
  1696. if (hours == 0)
  1697. return 12;
  1698. else if (hours <= 12)
  1699. return hours;
  1700. else
  1701. return hours - 12;
  1702. }
  1703. bool Time::isAfternoon() const throw()
  1704. {
  1705. return getHours() >= 12;
  1706. }
  1707. int Time::getMinutes() const throw()
  1708. {
  1709. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1710. }
  1711. int Time::getSeconds() const throw()
  1712. {
  1713. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1714. }
  1715. int Time::getMilliseconds() const throw()
  1716. {
  1717. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1718. }
  1719. bool Time::isDaylightSavingTime() const throw()
  1720. {
  1721. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1722. }
  1723. const String Time::getTimeZone() const throw()
  1724. {
  1725. String zone[2];
  1726. #if JUCE_WINDOWS
  1727. _tzset();
  1728. #ifdef USE_NEW_SECURE_TIME_FNS
  1729. {
  1730. char name [128];
  1731. size_t length;
  1732. for (int i = 0; i < 2; ++i)
  1733. {
  1734. zeromem (name, sizeof (name));
  1735. _get_tzname (&length, name, 127, i);
  1736. zone[i] = name;
  1737. }
  1738. }
  1739. #else
  1740. const char** const zonePtr = (const char**) _tzname;
  1741. zone[0] = zonePtr[0];
  1742. zone[1] = zonePtr[1];
  1743. #endif
  1744. #else
  1745. tzset();
  1746. const char** const zonePtr = (const char**) tzname;
  1747. zone[0] = zonePtr[0];
  1748. zone[1] = zonePtr[1];
  1749. #endif
  1750. if (isDaylightSavingTime())
  1751. {
  1752. zone[0] = zone[1];
  1753. if (zone[0].length() > 3
  1754. && zone[0].containsIgnoreCase ("daylight")
  1755. && zone[0].contains ("GMT"))
  1756. zone[0] = "BST";
  1757. }
  1758. return zone[0].substring (0, 3);
  1759. }
  1760. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1761. {
  1762. return getMonthName (getMonth(), threeLetterVersion);
  1763. }
  1764. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1765. {
  1766. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1767. }
  1768. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1769. {
  1770. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1771. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1772. monthNumber %= 12;
  1773. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1774. : longMonthNames [monthNumber]);
  1775. }
  1776. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1777. {
  1778. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1779. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1780. day %= 7;
  1781. return TRANS (threeLetterVersion ? shortDayNames [day]
  1782. : longDayNames [day]);
  1783. }
  1784. END_JUCE_NAMESPACE
  1785. /*** End of inlined file: juce_Time.cpp ***/
  1786. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1787. BEGIN_JUCE_NAMESPACE
  1788. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1789. #endif
  1790. #if JUCE_WINDOWS
  1791. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1792. #endif
  1793. #if JUCE_DEBUG
  1794. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1795. #endif
  1796. #if JUCE_DEBUG
  1797. namespace SimpleUnitTests
  1798. {
  1799. template <typename Type>
  1800. class AtomicTester
  1801. {
  1802. public:
  1803. AtomicTester() {}
  1804. static void testInteger()
  1805. {
  1806. Atomic<Type> a, b;
  1807. a.set ((Type) 10);
  1808. a += (Type) 15;
  1809. a.memoryBarrier();
  1810. a -= (Type) 5;
  1811. ++a; ++a; --a;
  1812. a.memoryBarrier();
  1813. testFloat();
  1814. }
  1815. static void testFloat()
  1816. {
  1817. Atomic<Type> a, b;
  1818. a = (Type) 21;
  1819. a.memoryBarrier();
  1820. /* These are some simple test cases to check the atomics - let me know
  1821. if any of these assertions fail on your system!
  1822. */
  1823. jassert (a.get() == (Type) 21);
  1824. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1825. jassert (a.get() == (Type) 21);
  1826. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1827. jassert (a.get() == (Type) 101);
  1828. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1829. jassert (a.get() == (Type) 101);
  1830. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1831. jassert (a.get() == (Type) 200);
  1832. jassert (a.exchange ((Type) 300) == (Type) 200);
  1833. jassert (a.get() == (Type) 300);
  1834. b = a;
  1835. jassert (b.get() == a.get());
  1836. }
  1837. };
  1838. static void runBasicTests()
  1839. {
  1840. // Some simple test code, to keep an eye on things and make sure these functions
  1841. // work ok on all platforms. Let me know if any of these assertions fail on your system!
  1842. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1843. static_jassert (sizeof (int8) == 1);
  1844. static_jassert (sizeof (uint8) == 1);
  1845. static_jassert (sizeof (int16) == 2);
  1846. static_jassert (sizeof (uint16) == 2);
  1847. static_jassert (sizeof (int32) == 4);
  1848. static_jassert (sizeof (uint32) == 4);
  1849. static_jassert (sizeof (int64) == 8);
  1850. static_jassert (sizeof (uint64) == 8);
  1851. char a1[7];
  1852. jassert (numElementsInArray(a1) == 7);
  1853. int a2[3];
  1854. jassert (numElementsInArray(a2) == 3);
  1855. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1856. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1857. jassert (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1858. // Some quick stream tests..
  1859. int randomInt = Random::getSystemRandom().nextInt();
  1860. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1861. double randomDouble = Random::getSystemRandom().nextDouble();
  1862. String randomString;
  1863. for (int i = 50; --i >= 0;)
  1864. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1865. MemoryOutputStream mo;
  1866. mo.writeInt (randomInt);
  1867. mo.writeIntBigEndian (randomInt);
  1868. mo.writeCompressedInt (randomInt);
  1869. mo.writeString (randomString);
  1870. mo.writeInt64 (randomInt64);
  1871. mo.writeInt64BigEndian (randomInt64);
  1872. mo.writeDouble (randomDouble);
  1873. mo.writeDoubleBigEndian (randomDouble);
  1874. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1875. jassert (mi.readInt() == randomInt);
  1876. jassert (mi.readIntBigEndian() == randomInt);
  1877. jassert (mi.readCompressedInt() == randomInt);
  1878. jassert (mi.readString() == randomString);
  1879. jassert (mi.readInt64() == randomInt64);
  1880. jassert (mi.readInt64BigEndian() == randomInt64);
  1881. jassert (mi.readDouble() == randomDouble);
  1882. jassert (mi.readDoubleBigEndian() == randomDouble);
  1883. AtomicTester <int>::testInteger();
  1884. AtomicTester <unsigned int>::testInteger();
  1885. AtomicTester <int32>::testInteger();
  1886. AtomicTester <uint32>::testInteger();
  1887. AtomicTester <long>::testInteger();
  1888. AtomicTester <void*>::testInteger();
  1889. AtomicTester <int*>::testInteger();
  1890. AtomicTester <float>::testFloat();
  1891. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1892. AtomicTester <int64>::testInteger();
  1893. AtomicTester <uint64>::testInteger();
  1894. AtomicTester <double>::testFloat();
  1895. #endif
  1896. }
  1897. }
  1898. #endif
  1899. static bool juceInitialisedNonGUI = false;
  1900. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1901. {
  1902. if (! juceInitialisedNonGUI)
  1903. {
  1904. juceInitialisedNonGUI = true;
  1905. JUCE_AUTORELEASEPOOL
  1906. #if JUCE_DEBUG
  1907. SimpleUnitTests::runBasicTests();
  1908. #endif
  1909. DBG (SystemStats::getJUCEVersion());
  1910. SystemStats::initialiseStats();
  1911. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1912. }
  1913. }
  1914. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1915. {
  1916. if (juceInitialisedNonGUI)
  1917. {
  1918. juceInitialisedNonGUI = false;
  1919. JUCE_AUTORELEASEPOOL
  1920. LocalisedStrings::setCurrentMappings (0);
  1921. Thread::stopAllThreads (3000);
  1922. #if JUCE_WINDOWS
  1923. juce_shutdownWin32Sockets();
  1924. #endif
  1925. #if JUCE_DEBUG
  1926. juce_CheckForDanglingStreams();
  1927. #endif
  1928. }
  1929. }
  1930. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1931. void juce_setCurrentThreadName (const String& name);
  1932. static bool juceInitialisedGUI = false;
  1933. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1934. {
  1935. if (! juceInitialisedGUI)
  1936. {
  1937. juceInitialisedGUI = true;
  1938. JUCE_AUTORELEASEPOOL
  1939. initialiseJuce_NonGUI();
  1940. MessageManager::getInstance();
  1941. LookAndFeel::setDefaultLookAndFeel (0);
  1942. juce_setCurrentThreadName ("Juce Message Thread");
  1943. #if JUCE_DEBUG
  1944. // This section is just for catching people who mess up their project settings and
  1945. // turn RTTI off..
  1946. try
  1947. {
  1948. TextButton tb (String::empty);
  1949. Component* c = &tb;
  1950. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1951. c = dynamic_cast <Button*> (c);
  1952. }
  1953. catch (...)
  1954. {
  1955. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1956. jassertfalse;
  1957. }
  1958. #endif
  1959. }
  1960. }
  1961. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1962. {
  1963. if (juceInitialisedGUI)
  1964. {
  1965. juceInitialisedGUI = false;
  1966. JUCE_AUTORELEASEPOOL
  1967. DeletedAtShutdown::deleteAll();
  1968. LookAndFeel::clearDefaultLookAndFeel();
  1969. delete MessageManager::getInstance();
  1970. shutdownJuce_NonGUI();
  1971. }
  1972. }
  1973. #endif
  1974. END_JUCE_NAMESPACE
  1975. /*** End of inlined file: juce_Initialisation.cpp ***/
  1976. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1977. BEGIN_JUCE_NAMESPACE
  1978. BigInteger::BigInteger()
  1979. : numValues (4),
  1980. highestBit (-1),
  1981. negative (false)
  1982. {
  1983. values.calloc (numValues + 1);
  1984. }
  1985. BigInteger::BigInteger (const int value)
  1986. : numValues (4),
  1987. highestBit (31),
  1988. negative (value < 0)
  1989. {
  1990. values.calloc (numValues + 1);
  1991. values[0] = abs (value);
  1992. highestBit = getHighestBit();
  1993. }
  1994. BigInteger::BigInteger (int64 value)
  1995. : numValues (4),
  1996. highestBit (63),
  1997. negative (value < 0)
  1998. {
  1999. values.calloc (numValues + 1);
  2000. if (value < 0)
  2001. value = -value;
  2002. values[0] = (unsigned int) value;
  2003. values[1] = (unsigned int) (value >> 32);
  2004. highestBit = getHighestBit();
  2005. }
  2006. BigInteger::BigInteger (const unsigned int value)
  2007. : numValues (4),
  2008. highestBit (31),
  2009. negative (false)
  2010. {
  2011. values.calloc (numValues + 1);
  2012. values[0] = value;
  2013. highestBit = getHighestBit();
  2014. }
  2015. BigInteger::BigInteger (const BigInteger& other)
  2016. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  2017. highestBit (other.getHighestBit()),
  2018. negative (other.negative)
  2019. {
  2020. values.malloc (numValues + 1);
  2021. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2022. }
  2023. BigInteger::~BigInteger()
  2024. {
  2025. }
  2026. void BigInteger::swapWith (BigInteger& other) throw()
  2027. {
  2028. values.swapWith (other.values);
  2029. swapVariables (numValues, other.numValues);
  2030. swapVariables (highestBit, other.highestBit);
  2031. swapVariables (negative, other.negative);
  2032. }
  2033. BigInteger& BigInteger::operator= (const BigInteger& other)
  2034. {
  2035. if (this != &other)
  2036. {
  2037. highestBit = other.getHighestBit();
  2038. numValues = jmax (4, (highestBit >> 5) + 1);
  2039. negative = other.negative;
  2040. values.malloc (numValues + 1);
  2041. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2042. }
  2043. return *this;
  2044. }
  2045. void BigInteger::ensureSize (const int numVals)
  2046. {
  2047. if (numVals + 2 >= numValues)
  2048. {
  2049. int oldSize = numValues;
  2050. numValues = ((numVals + 2) * 3) / 2;
  2051. values.realloc (numValues + 1);
  2052. while (oldSize < numValues)
  2053. values [oldSize++] = 0;
  2054. }
  2055. }
  2056. bool BigInteger::operator[] (const int bit) const throw()
  2057. {
  2058. return bit <= highestBit && bit >= 0
  2059. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2060. }
  2061. int BigInteger::toInteger() const throw()
  2062. {
  2063. const int n = (int) (values[0] & 0x7fffffff);
  2064. return negative ? -n : n;
  2065. }
  2066. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2067. {
  2068. BigInteger r;
  2069. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2070. r.ensureSize (numBits >> 5);
  2071. r.highestBit = numBits;
  2072. int i = 0;
  2073. while (numBits > 0)
  2074. {
  2075. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2076. numBits -= 32;
  2077. startBit += 32;
  2078. }
  2079. r.highestBit = r.getHighestBit();
  2080. return r;
  2081. }
  2082. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2083. {
  2084. if (numBits > 32)
  2085. {
  2086. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2087. numBits = 32;
  2088. }
  2089. numBits = jmin (numBits, highestBit + 1 - startBit);
  2090. if (numBits <= 0)
  2091. return 0;
  2092. const int pos = startBit >> 5;
  2093. const int offset = startBit & 31;
  2094. const int endSpace = 32 - numBits;
  2095. uint32 n = ((uint32) values [pos]) >> offset;
  2096. if (offset > endSpace)
  2097. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2098. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2099. }
  2100. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2101. {
  2102. if (numBits > 32)
  2103. {
  2104. jassertfalse;
  2105. numBits = 32;
  2106. }
  2107. for (int i = 0; i < numBits; ++i)
  2108. {
  2109. setBit (startBit + i, (valueToSet & 1) != 0);
  2110. valueToSet >>= 1;
  2111. }
  2112. }
  2113. void BigInteger::clear()
  2114. {
  2115. if (numValues > 16)
  2116. {
  2117. numValues = 4;
  2118. values.calloc (numValues + 1);
  2119. }
  2120. else
  2121. {
  2122. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2123. }
  2124. highestBit = -1;
  2125. negative = false;
  2126. }
  2127. void BigInteger::setBit (const int bit)
  2128. {
  2129. if (bit >= 0)
  2130. {
  2131. if (bit > highestBit)
  2132. {
  2133. ensureSize (bit >> 5);
  2134. highestBit = bit;
  2135. }
  2136. values [bit >> 5] |= (1 << (bit & 31));
  2137. }
  2138. }
  2139. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2140. {
  2141. if (shouldBeSet)
  2142. setBit (bit);
  2143. else
  2144. clearBit (bit);
  2145. }
  2146. void BigInteger::clearBit (const int bit) throw()
  2147. {
  2148. if (bit >= 0 && bit <= highestBit)
  2149. values [bit >> 5] &= ~(1 << (bit & 31));
  2150. }
  2151. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2152. {
  2153. while (--numBits >= 0)
  2154. setBit (startBit++, shouldBeSet);
  2155. }
  2156. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2157. {
  2158. if (bit >= 0)
  2159. shiftBits (1, bit);
  2160. setBit (bit, shouldBeSet);
  2161. }
  2162. bool BigInteger::isZero() const throw()
  2163. {
  2164. return getHighestBit() < 0;
  2165. }
  2166. bool BigInteger::isOne() const throw()
  2167. {
  2168. return getHighestBit() == 0 && ! negative;
  2169. }
  2170. bool BigInteger::isNegative() const throw()
  2171. {
  2172. return negative && ! isZero();
  2173. }
  2174. void BigInteger::setNegative (const bool neg) throw()
  2175. {
  2176. negative = neg;
  2177. }
  2178. void BigInteger::negate() throw()
  2179. {
  2180. negative = (! negative) && ! isZero();
  2181. }
  2182. int BigInteger::countNumberOfSetBits() const throw()
  2183. {
  2184. int total = 0;
  2185. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2186. {
  2187. unsigned int n = values[i];
  2188. if (n == 0xffffffff)
  2189. {
  2190. total += 32;
  2191. }
  2192. else
  2193. {
  2194. while (n != 0)
  2195. {
  2196. total += (n & 1);
  2197. n >>= 1;
  2198. }
  2199. }
  2200. }
  2201. return total;
  2202. }
  2203. int BigInteger::getHighestBit() const throw()
  2204. {
  2205. for (int i = highestBit + 1; --i >= 0;)
  2206. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2207. return i;
  2208. return -1;
  2209. }
  2210. int BigInteger::findNextSetBit (int i) const throw()
  2211. {
  2212. for (; i <= highestBit; ++i)
  2213. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2214. return i;
  2215. return -1;
  2216. }
  2217. int BigInteger::findNextClearBit (int i) const throw()
  2218. {
  2219. for (; i <= highestBit; ++i)
  2220. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2221. break;
  2222. return i;
  2223. }
  2224. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2225. {
  2226. if (other.isNegative())
  2227. return operator-= (-other);
  2228. if (isNegative())
  2229. {
  2230. if (compareAbsolute (other) < 0)
  2231. {
  2232. BigInteger temp (*this);
  2233. temp.negate();
  2234. *this = other;
  2235. operator-= (temp);
  2236. }
  2237. else
  2238. {
  2239. negate();
  2240. operator-= (other);
  2241. negate();
  2242. }
  2243. }
  2244. else
  2245. {
  2246. if (other.highestBit > highestBit)
  2247. highestBit = other.highestBit;
  2248. ++highestBit;
  2249. const int numInts = (highestBit >> 5) + 1;
  2250. ensureSize (numInts);
  2251. int64 remainder = 0;
  2252. for (int i = 0; i <= numInts; ++i)
  2253. {
  2254. if (i < numValues)
  2255. remainder += values[i];
  2256. if (i < other.numValues)
  2257. remainder += other.values[i];
  2258. values[i] = (unsigned int) remainder;
  2259. remainder >>= 32;
  2260. }
  2261. jassert (remainder == 0);
  2262. highestBit = getHighestBit();
  2263. }
  2264. return *this;
  2265. }
  2266. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2267. {
  2268. if (other.isNegative())
  2269. return operator+= (-other);
  2270. if (! isNegative())
  2271. {
  2272. if (compareAbsolute (other) < 0)
  2273. {
  2274. BigInteger temp (other);
  2275. swapWith (temp);
  2276. operator-= (temp);
  2277. negate();
  2278. return *this;
  2279. }
  2280. }
  2281. else
  2282. {
  2283. negate();
  2284. operator+= (other);
  2285. negate();
  2286. return *this;
  2287. }
  2288. const int numInts = (highestBit >> 5) + 1;
  2289. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2290. int64 amountToSubtract = 0;
  2291. for (int i = 0; i <= numInts; ++i)
  2292. {
  2293. if (i <= maxOtherInts)
  2294. amountToSubtract += (int64) other.values[i];
  2295. if (values[i] >= amountToSubtract)
  2296. {
  2297. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2298. amountToSubtract = 0;
  2299. }
  2300. else
  2301. {
  2302. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2303. values[i] = (unsigned int) n;
  2304. amountToSubtract = 1;
  2305. }
  2306. }
  2307. return *this;
  2308. }
  2309. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2310. {
  2311. BigInteger total;
  2312. highestBit = getHighestBit();
  2313. const bool wasNegative = isNegative();
  2314. setNegative (false);
  2315. for (int i = 0; i <= highestBit; ++i)
  2316. {
  2317. if (operator[](i))
  2318. {
  2319. BigInteger n (other);
  2320. n.setNegative (false);
  2321. n <<= i;
  2322. total += n;
  2323. }
  2324. }
  2325. total.setNegative (wasNegative ^ other.isNegative());
  2326. swapWith (total);
  2327. return *this;
  2328. }
  2329. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2330. {
  2331. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2332. const int divHB = divisor.getHighestBit();
  2333. const int ourHB = getHighestBit();
  2334. if (divHB < 0 || ourHB < 0)
  2335. {
  2336. // division by zero
  2337. remainder.clear();
  2338. clear();
  2339. }
  2340. else
  2341. {
  2342. const bool wasNegative = isNegative();
  2343. swapWith (remainder);
  2344. remainder.setNegative (false);
  2345. clear();
  2346. BigInteger temp (divisor);
  2347. temp.setNegative (false);
  2348. int leftShift = ourHB - divHB;
  2349. temp <<= leftShift;
  2350. while (leftShift >= 0)
  2351. {
  2352. if (remainder.compareAbsolute (temp) >= 0)
  2353. {
  2354. remainder -= temp;
  2355. setBit (leftShift);
  2356. }
  2357. if (--leftShift >= 0)
  2358. temp >>= 1;
  2359. }
  2360. negative = wasNegative ^ divisor.isNegative();
  2361. remainder.setNegative (wasNegative);
  2362. }
  2363. }
  2364. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2365. {
  2366. BigInteger remainder;
  2367. divideBy (other, remainder);
  2368. return *this;
  2369. }
  2370. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2371. {
  2372. // this operation doesn't take into account negative values..
  2373. jassert (isNegative() == other.isNegative());
  2374. if (other.highestBit >= 0)
  2375. {
  2376. ensureSize (other.highestBit >> 5);
  2377. int n = (other.highestBit >> 5) + 1;
  2378. while (--n >= 0)
  2379. values[n] |= other.values[n];
  2380. if (other.highestBit > highestBit)
  2381. highestBit = other.highestBit;
  2382. highestBit = getHighestBit();
  2383. }
  2384. return *this;
  2385. }
  2386. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2387. {
  2388. // this operation doesn't take into account negative values..
  2389. jassert (isNegative() == other.isNegative());
  2390. int n = numValues;
  2391. while (n > other.numValues)
  2392. values[--n] = 0;
  2393. while (--n >= 0)
  2394. values[n] &= other.values[n];
  2395. if (other.highestBit < highestBit)
  2396. highestBit = other.highestBit;
  2397. highestBit = getHighestBit();
  2398. return *this;
  2399. }
  2400. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2401. {
  2402. // this operation will only work with the absolute values
  2403. jassert (isNegative() == other.isNegative());
  2404. if (other.highestBit >= 0)
  2405. {
  2406. ensureSize (other.highestBit >> 5);
  2407. int n = (other.highestBit >> 5) + 1;
  2408. while (--n >= 0)
  2409. values[n] ^= other.values[n];
  2410. if (other.highestBit > highestBit)
  2411. highestBit = other.highestBit;
  2412. highestBit = getHighestBit();
  2413. }
  2414. return *this;
  2415. }
  2416. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2417. {
  2418. BigInteger remainder;
  2419. divideBy (divisor, remainder);
  2420. swapWith (remainder);
  2421. return *this;
  2422. }
  2423. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2424. {
  2425. shiftBits (numBitsToShift, 0);
  2426. return *this;
  2427. }
  2428. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2429. {
  2430. return operator<<= (-numBitsToShift);
  2431. }
  2432. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2433. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2434. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2435. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2436. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2437. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2438. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2439. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2440. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2441. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2442. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2443. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2444. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2445. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2446. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2447. int BigInteger::compare (const BigInteger& other) const throw()
  2448. {
  2449. if (isNegative() == other.isNegative())
  2450. {
  2451. const int absComp = compareAbsolute (other);
  2452. return isNegative() ? -absComp : absComp;
  2453. }
  2454. else
  2455. {
  2456. return isNegative() ? -1 : 1;
  2457. }
  2458. }
  2459. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2460. {
  2461. const int h1 = getHighestBit();
  2462. const int h2 = other.getHighestBit();
  2463. if (h1 > h2)
  2464. return 1;
  2465. else if (h1 < h2)
  2466. return -1;
  2467. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2468. if (values[i] != other.values[i])
  2469. return (values[i] > other.values[i]) ? 1 : -1;
  2470. return 0;
  2471. }
  2472. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2473. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2474. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2475. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2476. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2477. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2478. void BigInteger::shiftBits (int bits, const int startBit)
  2479. {
  2480. if (highestBit < 0)
  2481. return;
  2482. if (startBit > 0)
  2483. {
  2484. if (bits < 0)
  2485. {
  2486. // right shift
  2487. for (int i = startBit; i <= highestBit; ++i)
  2488. setBit (i, operator[] (i - bits));
  2489. highestBit = getHighestBit();
  2490. }
  2491. else if (bits > 0)
  2492. {
  2493. // left shift
  2494. for (int i = highestBit + 1; --i >= startBit;)
  2495. setBit (i + bits, operator[] (i));
  2496. while (--bits >= 0)
  2497. clearBit (bits + startBit);
  2498. }
  2499. }
  2500. else
  2501. {
  2502. if (bits < 0)
  2503. {
  2504. // right shift
  2505. bits = -bits;
  2506. if (bits > highestBit)
  2507. {
  2508. clear();
  2509. }
  2510. else
  2511. {
  2512. const int wordsToMove = bits >> 5;
  2513. int top = 1 + (highestBit >> 5) - wordsToMove;
  2514. highestBit -= bits;
  2515. if (wordsToMove > 0)
  2516. {
  2517. int i;
  2518. for (i = 0; i < top; ++i)
  2519. values [i] = values [i + wordsToMove];
  2520. for (i = 0; i < wordsToMove; ++i)
  2521. values [top + i] = 0;
  2522. bits &= 31;
  2523. }
  2524. if (bits != 0)
  2525. {
  2526. const int invBits = 32 - bits;
  2527. --top;
  2528. for (int i = 0; i < top; ++i)
  2529. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2530. values[top] = (values[top] >> bits);
  2531. }
  2532. highestBit = getHighestBit();
  2533. }
  2534. }
  2535. else if (bits > 0)
  2536. {
  2537. // left shift
  2538. ensureSize (((highestBit + bits) >> 5) + 1);
  2539. const int wordsToMove = bits >> 5;
  2540. int top = 1 + (highestBit >> 5);
  2541. highestBit += bits;
  2542. if (wordsToMove > 0)
  2543. {
  2544. int i;
  2545. for (i = top; --i >= 0;)
  2546. values [i + wordsToMove] = values [i];
  2547. for (i = 0; i < wordsToMove; ++i)
  2548. values [i] = 0;
  2549. bits &= 31;
  2550. }
  2551. if (bits != 0)
  2552. {
  2553. const int invBits = 32 - bits;
  2554. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2555. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2556. values [wordsToMove] = values [wordsToMove] << bits;
  2557. }
  2558. highestBit = getHighestBit();
  2559. }
  2560. }
  2561. }
  2562. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2563. {
  2564. while (! m->isZero())
  2565. {
  2566. if (n->compareAbsolute (*m) > 0)
  2567. swapVariables (m, n);
  2568. *m -= *n;
  2569. }
  2570. return *n;
  2571. }
  2572. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2573. {
  2574. BigInteger m (*this);
  2575. while (! n.isZero())
  2576. {
  2577. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2578. return simpleGCD (&m, &n);
  2579. BigInteger temp1 (m), temp2;
  2580. temp1.divideBy (n, temp2);
  2581. m = n;
  2582. n = temp2;
  2583. }
  2584. return m;
  2585. }
  2586. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2587. {
  2588. BigInteger exp (exponent);
  2589. exp %= modulus;
  2590. BigInteger value (1);
  2591. swapWith (value);
  2592. value %= modulus;
  2593. while (! exp.isZero())
  2594. {
  2595. if (exp [0])
  2596. {
  2597. operator*= (value);
  2598. operator%= (modulus);
  2599. }
  2600. value *= value;
  2601. value %= modulus;
  2602. exp >>= 1;
  2603. }
  2604. }
  2605. void BigInteger::inverseModulo (const BigInteger& modulus)
  2606. {
  2607. if (modulus.isOne() || modulus.isNegative())
  2608. {
  2609. clear();
  2610. return;
  2611. }
  2612. if (isNegative() || compareAbsolute (modulus) >= 0)
  2613. operator%= (modulus);
  2614. if (isOne())
  2615. return;
  2616. if (! (*this)[0])
  2617. {
  2618. // not invertible
  2619. clear();
  2620. return;
  2621. }
  2622. BigInteger a1 (modulus);
  2623. BigInteger a2 (*this);
  2624. BigInteger b1 (modulus);
  2625. BigInteger b2 (1);
  2626. while (! a2.isOne())
  2627. {
  2628. BigInteger temp1, temp2, multiplier (a1);
  2629. multiplier.divideBy (a2, temp1);
  2630. temp1 = a2;
  2631. temp1 *= multiplier;
  2632. temp2 = a1;
  2633. temp2 -= temp1;
  2634. a1 = a2;
  2635. a2 = temp2;
  2636. temp1 = b2;
  2637. temp1 *= multiplier;
  2638. temp2 = b1;
  2639. temp2 -= temp1;
  2640. b1 = b2;
  2641. b2 = temp2;
  2642. }
  2643. while (b2.isNegative())
  2644. b2 += modulus;
  2645. b2 %= modulus;
  2646. swapWith (b2);
  2647. }
  2648. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2649. {
  2650. return stream << value.toString (10);
  2651. }
  2652. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2653. {
  2654. String s;
  2655. BigInteger v (*this);
  2656. if (base == 2 || base == 8 || base == 16)
  2657. {
  2658. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2659. static const char* const hexDigits = "0123456789abcdef";
  2660. for (;;)
  2661. {
  2662. const int remainder = v.getBitRangeAsInt (0, bits);
  2663. v >>= bits;
  2664. if (remainder == 0 && v.isZero())
  2665. break;
  2666. s = String::charToString (hexDigits [remainder]) + s;
  2667. }
  2668. }
  2669. else if (base == 10)
  2670. {
  2671. const BigInteger ten (10);
  2672. BigInteger remainder;
  2673. for (;;)
  2674. {
  2675. v.divideBy (ten, remainder);
  2676. if (remainder.isZero() && v.isZero())
  2677. break;
  2678. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2679. }
  2680. }
  2681. else
  2682. {
  2683. jassertfalse; // can't do the specified base!
  2684. return String::empty;
  2685. }
  2686. s = s.paddedLeft ('0', minimumNumCharacters);
  2687. return isNegative() ? "-" + s : s;
  2688. }
  2689. void BigInteger::parseString (const String& text, const int base)
  2690. {
  2691. clear();
  2692. const juce_wchar* t = text;
  2693. if (base == 2 || base == 8 || base == 16)
  2694. {
  2695. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2696. for (;;)
  2697. {
  2698. const juce_wchar c = *t++;
  2699. const int digit = CharacterFunctions::getHexDigitValue (c);
  2700. if (((unsigned int) digit) < (unsigned int) base)
  2701. {
  2702. operator<<= (bits);
  2703. operator+= (digit);
  2704. }
  2705. else if (c == 0)
  2706. {
  2707. break;
  2708. }
  2709. }
  2710. }
  2711. else if (base == 10)
  2712. {
  2713. const BigInteger ten ((unsigned int) 10);
  2714. for (;;)
  2715. {
  2716. const juce_wchar c = *t++;
  2717. if (c >= '0' && c <= '9')
  2718. {
  2719. operator*= (ten);
  2720. operator+= ((int) (c - '0'));
  2721. }
  2722. else if (c == 0)
  2723. {
  2724. break;
  2725. }
  2726. }
  2727. }
  2728. setNegative (text.trimStart().startsWithChar ('-'));
  2729. }
  2730. const MemoryBlock BigInteger::toMemoryBlock() const
  2731. {
  2732. const int numBytes = (getHighestBit() + 8) >> 3;
  2733. MemoryBlock mb ((size_t) numBytes);
  2734. for (int i = 0; i < numBytes; ++i)
  2735. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2736. return mb;
  2737. }
  2738. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2739. {
  2740. clear();
  2741. for (int i = (int) data.getSize(); --i >= 0;)
  2742. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2743. }
  2744. END_JUCE_NAMESPACE
  2745. /*** End of inlined file: juce_BigInteger.cpp ***/
  2746. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2747. BEGIN_JUCE_NAMESPACE
  2748. MemoryBlock::MemoryBlock() throw()
  2749. : size (0)
  2750. {
  2751. }
  2752. MemoryBlock::MemoryBlock (const size_t initialSize,
  2753. const bool initialiseToZero) throw()
  2754. {
  2755. if (initialSize > 0)
  2756. {
  2757. size = initialSize;
  2758. data.allocate (initialSize, initialiseToZero);
  2759. }
  2760. else
  2761. {
  2762. size = 0;
  2763. }
  2764. }
  2765. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2766. : size (other.size)
  2767. {
  2768. if (size > 0)
  2769. {
  2770. jassert (other.data != 0);
  2771. data.malloc (size);
  2772. memcpy (data, other.data, size);
  2773. }
  2774. }
  2775. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2776. const size_t sizeInBytes) throw()
  2777. : size (jmax ((size_t) 0, sizeInBytes))
  2778. {
  2779. jassert (sizeInBytes >= 0);
  2780. if (size > 0)
  2781. {
  2782. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2783. data.malloc (size);
  2784. if (dataToInitialiseFrom != 0)
  2785. memcpy (data, dataToInitialiseFrom, size);
  2786. }
  2787. }
  2788. MemoryBlock::~MemoryBlock() throw()
  2789. {
  2790. jassert (size >= 0); // should never happen
  2791. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2792. }
  2793. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2794. {
  2795. if (this != &other)
  2796. {
  2797. setSize (other.size, false);
  2798. memcpy (data, other.data, size);
  2799. }
  2800. return *this;
  2801. }
  2802. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2803. {
  2804. return matches (other.data, other.size);
  2805. }
  2806. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2807. {
  2808. return ! operator== (other);
  2809. }
  2810. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2811. {
  2812. return size == dataSize
  2813. && memcmp (data, dataToCompare, size) == 0;
  2814. }
  2815. // this will resize the block to this size
  2816. void MemoryBlock::setSize (const size_t newSize,
  2817. const bool initialiseToZero) throw()
  2818. {
  2819. if (size != newSize)
  2820. {
  2821. if (newSize <= 0)
  2822. {
  2823. data.free();
  2824. size = 0;
  2825. }
  2826. else
  2827. {
  2828. if (data != 0)
  2829. {
  2830. data.realloc (newSize);
  2831. if (initialiseToZero && (newSize > size))
  2832. zeromem (data + size, newSize - size);
  2833. }
  2834. else
  2835. {
  2836. data.allocate (newSize, initialiseToZero);
  2837. }
  2838. size = newSize;
  2839. }
  2840. }
  2841. }
  2842. void MemoryBlock::ensureSize (const size_t minimumSize,
  2843. const bool initialiseToZero) throw()
  2844. {
  2845. if (size < minimumSize)
  2846. setSize (minimumSize, initialiseToZero);
  2847. }
  2848. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2849. {
  2850. swapVariables (size, other.size);
  2851. data.swapWith (other.data);
  2852. }
  2853. void MemoryBlock::fillWith (const uint8 value) throw()
  2854. {
  2855. memset (data, (int) value, size);
  2856. }
  2857. void MemoryBlock::append (const void* const srcData,
  2858. const size_t numBytes) throw()
  2859. {
  2860. if (numBytes > 0)
  2861. {
  2862. const size_t oldSize = size;
  2863. setSize (size + numBytes);
  2864. memcpy (data + oldSize, srcData, numBytes);
  2865. }
  2866. }
  2867. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2868. {
  2869. const char* d = static_cast<const char*> (src);
  2870. if (offset < 0)
  2871. {
  2872. d -= offset;
  2873. num -= offset;
  2874. offset = 0;
  2875. }
  2876. if (offset + num > size)
  2877. num = size - offset;
  2878. if (num > 0)
  2879. memcpy (data + offset, d, num);
  2880. }
  2881. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2882. {
  2883. char* d = static_cast<char*> (dst);
  2884. if (offset < 0)
  2885. {
  2886. zeromem (d, -offset);
  2887. d -= offset;
  2888. num += offset;
  2889. offset = 0;
  2890. }
  2891. if (offset + num > size)
  2892. {
  2893. const size_t newNum = size - offset;
  2894. zeromem (d + newNum, num - newNum);
  2895. num = newNum;
  2896. }
  2897. if (num > 0)
  2898. memcpy (d, data + offset, num);
  2899. }
  2900. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2901. {
  2902. if (startByte < 0)
  2903. {
  2904. numBytesToRemove += startByte;
  2905. startByte = 0;
  2906. }
  2907. if (startByte + numBytesToRemove >= size)
  2908. {
  2909. setSize (startByte);
  2910. }
  2911. else if (numBytesToRemove > 0)
  2912. {
  2913. memmove (data + startByte,
  2914. data + startByte + numBytesToRemove,
  2915. size - (startByte + numBytesToRemove));
  2916. setSize (size - numBytesToRemove);
  2917. }
  2918. }
  2919. const String MemoryBlock::toString() const throw()
  2920. {
  2921. return String (static_cast <const char*> (getData()), size);
  2922. }
  2923. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2924. {
  2925. int res = 0;
  2926. size_t byte = bitRangeStart >> 3;
  2927. int offsetInByte = (int) bitRangeStart & 7;
  2928. size_t bitsSoFar = 0;
  2929. while (numBits > 0 && (size_t) byte < size)
  2930. {
  2931. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2932. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2933. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2934. bitsSoFar += bitsThisTime;
  2935. numBits -= bitsThisTime;
  2936. ++byte;
  2937. offsetInByte = 0;
  2938. }
  2939. return res;
  2940. }
  2941. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2942. {
  2943. size_t byte = bitRangeStart >> 3;
  2944. int offsetInByte = (int) bitRangeStart & 7;
  2945. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2946. while (numBits > 0 && (size_t) byte < size)
  2947. {
  2948. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2949. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2950. const unsigned int tempBits = bitsToSet << offsetInByte;
  2951. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2952. ++byte;
  2953. numBits -= bitsThisTime;
  2954. bitsToSet >>= bitsThisTime;
  2955. mask >>= bitsThisTime;
  2956. offsetInByte = 0;
  2957. }
  2958. }
  2959. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2960. {
  2961. ensureSize (hex.length() >> 1);
  2962. char* dest = data;
  2963. int i = 0;
  2964. for (;;)
  2965. {
  2966. int byte = 0;
  2967. for (int loop = 2; --loop >= 0;)
  2968. {
  2969. byte <<= 4;
  2970. for (;;)
  2971. {
  2972. const juce_wchar c = hex [i++];
  2973. if (c >= '0' && c <= '9')
  2974. {
  2975. byte |= c - '0';
  2976. break;
  2977. }
  2978. else if (c >= 'a' && c <= 'z')
  2979. {
  2980. byte |= c - ('a' - 10);
  2981. break;
  2982. }
  2983. else if (c >= 'A' && c <= 'Z')
  2984. {
  2985. byte |= c - ('A' - 10);
  2986. break;
  2987. }
  2988. else if (c == 0)
  2989. {
  2990. setSize (static_cast <size_t> (dest - data));
  2991. return;
  2992. }
  2993. }
  2994. }
  2995. *dest++ = (char) byte;
  2996. }
  2997. }
  2998. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2999. const String MemoryBlock::toBase64Encoding() const throw()
  3000. {
  3001. const size_t numChars = ((size << 3) + 5) / 6;
  3002. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3003. const int initialLen = destString.length();
  3004. destString.preallocateStorage (initialLen + 2 + numChars);
  3005. juce_wchar* d = destString;
  3006. d += initialLen;
  3007. *d++ = '.';
  3008. for (size_t i = 0; i < numChars; ++i)
  3009. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3010. *d++ = 0;
  3011. return destString;
  3012. }
  3013. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  3014. {
  3015. const int startPos = s.indexOfChar ('.') + 1;
  3016. if (startPos <= 0)
  3017. return false;
  3018. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3019. setSize (numBytesNeeded, true);
  3020. const int numChars = s.length() - startPos;
  3021. const juce_wchar* srcChars = s;
  3022. srcChars += startPos;
  3023. int pos = 0;
  3024. for (int i = 0; i < numChars; ++i)
  3025. {
  3026. const char c = (char) srcChars[i];
  3027. for (int j = 0; j < 64; ++j)
  3028. {
  3029. if (encodingTable[j] == c)
  3030. {
  3031. setBitRange (pos, 6, j);
  3032. pos += 6;
  3033. break;
  3034. }
  3035. }
  3036. }
  3037. return true;
  3038. }
  3039. END_JUCE_NAMESPACE
  3040. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3041. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3042. BEGIN_JUCE_NAMESPACE
  3043. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  3044. : properties (ignoreCaseOfKeyNames),
  3045. fallbackProperties (0),
  3046. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3047. {
  3048. }
  3049. PropertySet::PropertySet (const PropertySet& other) throw()
  3050. : properties (other.properties),
  3051. fallbackProperties (other.fallbackProperties),
  3052. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3053. {
  3054. }
  3055. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  3056. {
  3057. properties = other.properties;
  3058. fallbackProperties = other.fallbackProperties;
  3059. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3060. propertyChanged();
  3061. return *this;
  3062. }
  3063. PropertySet::~PropertySet()
  3064. {
  3065. }
  3066. void PropertySet::clear()
  3067. {
  3068. const ScopedLock sl (lock);
  3069. if (properties.size() > 0)
  3070. {
  3071. properties.clear();
  3072. propertyChanged();
  3073. }
  3074. }
  3075. const String PropertySet::getValue (const String& keyName,
  3076. const String& defaultValue) const throw()
  3077. {
  3078. const ScopedLock sl (lock);
  3079. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3080. if (index >= 0)
  3081. return properties.getAllValues() [index];
  3082. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3083. : defaultValue;
  3084. }
  3085. int PropertySet::getIntValue (const String& keyName,
  3086. const int defaultValue) const throw()
  3087. {
  3088. const ScopedLock sl (lock);
  3089. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3090. if (index >= 0)
  3091. return properties.getAllValues() [index].getIntValue();
  3092. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3093. : defaultValue;
  3094. }
  3095. double PropertySet::getDoubleValue (const String& keyName,
  3096. const double defaultValue) const throw()
  3097. {
  3098. const ScopedLock sl (lock);
  3099. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3100. if (index >= 0)
  3101. return properties.getAllValues()[index].getDoubleValue();
  3102. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3103. : defaultValue;
  3104. }
  3105. bool PropertySet::getBoolValue (const String& keyName,
  3106. const bool defaultValue) const throw()
  3107. {
  3108. const ScopedLock sl (lock);
  3109. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3110. if (index >= 0)
  3111. return properties.getAllValues() [index].getIntValue() != 0;
  3112. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3113. : defaultValue;
  3114. }
  3115. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3116. {
  3117. XmlDocument doc (getValue (keyName));
  3118. return doc.getDocumentElement();
  3119. }
  3120. void PropertySet::setValue (const String& keyName,
  3121. const String& value) throw()
  3122. {
  3123. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3124. if (keyName.isNotEmpty())
  3125. {
  3126. const ScopedLock sl (lock);
  3127. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3128. if (index < 0 || properties.getAllValues() [index] != value)
  3129. {
  3130. properties.set (keyName, value);
  3131. propertyChanged();
  3132. }
  3133. }
  3134. }
  3135. void PropertySet::removeValue (const String& keyName) throw()
  3136. {
  3137. if (keyName.isNotEmpty())
  3138. {
  3139. const ScopedLock sl (lock);
  3140. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3141. if (index >= 0)
  3142. {
  3143. properties.remove (keyName);
  3144. propertyChanged();
  3145. }
  3146. }
  3147. }
  3148. void PropertySet::setValue (const String& keyName, const int value) throw()
  3149. {
  3150. setValue (keyName, String (value));
  3151. }
  3152. void PropertySet::setValue (const String& keyName, const double value) throw()
  3153. {
  3154. setValue (keyName, String (value));
  3155. }
  3156. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3157. {
  3158. setValue (keyName, String (value ? "1" : "0"));
  3159. }
  3160. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3161. {
  3162. setValue (keyName, (xml == 0) ? String::empty
  3163. : xml->createDocument (String::empty, true));
  3164. }
  3165. bool PropertySet::containsKey (const String& keyName) const throw()
  3166. {
  3167. const ScopedLock sl (lock);
  3168. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3169. }
  3170. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3171. {
  3172. const ScopedLock sl (lock);
  3173. fallbackProperties = fallbackProperties_;
  3174. }
  3175. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3176. {
  3177. const ScopedLock sl (lock);
  3178. XmlElement* const xml = new XmlElement (nodeName);
  3179. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3180. {
  3181. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3182. e->setAttribute ("name", properties.getAllKeys()[i]);
  3183. e->setAttribute ("val", properties.getAllValues()[i]);
  3184. }
  3185. return xml;
  3186. }
  3187. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3188. {
  3189. const ScopedLock sl (lock);
  3190. clear();
  3191. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3192. {
  3193. if (e->hasAttribute ("name")
  3194. && e->hasAttribute ("val"))
  3195. {
  3196. properties.set (e->getStringAttribute ("name"),
  3197. e->getStringAttribute ("val"));
  3198. }
  3199. }
  3200. if (properties.size() > 0)
  3201. propertyChanged();
  3202. }
  3203. void PropertySet::propertyChanged()
  3204. {
  3205. }
  3206. END_JUCE_NAMESPACE
  3207. /*** End of inlined file: juce_PropertySet.cpp ***/
  3208. /*** Start of inlined file: juce_Identifier.cpp ***/
  3209. BEGIN_JUCE_NAMESPACE
  3210. StringPool& Identifier::getPool()
  3211. {
  3212. static StringPool pool;
  3213. return pool;
  3214. }
  3215. Identifier::Identifier() throw()
  3216. : name (0)
  3217. {
  3218. }
  3219. Identifier::Identifier (const Identifier& other) throw()
  3220. : name (other.name)
  3221. {
  3222. }
  3223. Identifier& Identifier::operator= (const Identifier& other) throw()
  3224. {
  3225. name = other.name;
  3226. return *this;
  3227. }
  3228. Identifier::Identifier (const String& name_)
  3229. : name (Identifier::getPool().getPooledString (name_))
  3230. {
  3231. /* An Identifier string must be suitable for use as a script variable or XML
  3232. attribute, so it can only contain this limited set of characters.. */
  3233. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3234. }
  3235. Identifier::Identifier (const char* const name_)
  3236. : name (Identifier::getPool().getPooledString (name_))
  3237. {
  3238. /* An Identifier string must be suitable for use as a script variable or XML
  3239. attribute, so it can only contain this limited set of characters.. */
  3240. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3241. }
  3242. Identifier::~Identifier()
  3243. {
  3244. }
  3245. END_JUCE_NAMESPACE
  3246. /*** End of inlined file: juce_Identifier.cpp ***/
  3247. /*** Start of inlined file: juce_Variant.cpp ***/
  3248. BEGIN_JUCE_NAMESPACE
  3249. class var::VariantType
  3250. {
  3251. public:
  3252. VariantType() {}
  3253. virtual ~VariantType() {}
  3254. virtual int toInt (const ValueUnion&) const { return 0; }
  3255. virtual double toDouble (const ValueUnion&) const { return 0; }
  3256. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3257. virtual bool toBool (const ValueUnion&) const { return false; }
  3258. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3259. virtual bool isVoid() const throw() { return false; }
  3260. virtual bool isInt() const throw() { return false; }
  3261. virtual bool isBool() const throw() { return false; }
  3262. virtual bool isDouble() const throw() { return false; }
  3263. virtual bool isString() const throw() { return false; }
  3264. virtual bool isObject() const throw() { return false; }
  3265. virtual bool isMethod() const throw() { return false; }
  3266. virtual void cleanUp (ValueUnion&) const throw() {}
  3267. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3268. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3269. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3270. };
  3271. class var::VariantType_Void : public var::VariantType
  3272. {
  3273. public:
  3274. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3275. bool isVoid() const throw() { return true; }
  3276. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3277. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3278. };
  3279. class var::VariantType_Int : public var::VariantType
  3280. {
  3281. public:
  3282. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3283. int toInt (const ValueUnion& data) const { return data.intValue; };
  3284. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3285. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3286. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3287. bool isInt() const throw() { return true; }
  3288. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3289. {
  3290. return otherType.toInt (otherData) == data.intValue;
  3291. }
  3292. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3293. {
  3294. output.writeCompressedInt (5);
  3295. output.writeByte (1);
  3296. output.writeInt (data.intValue);
  3297. }
  3298. };
  3299. class var::VariantType_Double : public var::VariantType
  3300. {
  3301. public:
  3302. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3303. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3304. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3305. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3306. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3307. bool isDouble() const throw() { return true; }
  3308. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3309. {
  3310. return otherType.toDouble (otherData) == data.doubleValue;
  3311. }
  3312. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3313. {
  3314. output.writeCompressedInt (9);
  3315. output.writeByte (4);
  3316. output.writeDouble (data.doubleValue);
  3317. }
  3318. };
  3319. class var::VariantType_Bool : public var::VariantType
  3320. {
  3321. public:
  3322. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3323. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3324. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3325. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3326. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3327. bool isBool() const throw() { return true; }
  3328. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3329. {
  3330. return otherType.toBool (otherData) == data.boolValue;
  3331. }
  3332. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3333. {
  3334. output.writeCompressedInt (1);
  3335. output.writeByte (data.boolValue ? 2 : 3);
  3336. }
  3337. };
  3338. class var::VariantType_String : public var::VariantType
  3339. {
  3340. public:
  3341. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3342. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3343. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3344. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3345. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3346. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3347. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3348. || data.stringValue->trim().equalsIgnoreCase ("true")
  3349. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3350. bool isString() const throw() { return true; }
  3351. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3352. {
  3353. return otherType.toString (otherData) == *data.stringValue;
  3354. }
  3355. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3356. {
  3357. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3358. output.writeCompressedInt (len + 1);
  3359. output.writeByte (5);
  3360. HeapBlock<char> temp (len);
  3361. data.stringValue->copyToUTF8 (temp, len);
  3362. output.write (temp, len);
  3363. }
  3364. };
  3365. class var::VariantType_Object : public var::VariantType
  3366. {
  3367. public:
  3368. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3369. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3370. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3371. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3372. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3373. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3374. bool isObject() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toObject (otherData) == data.objectValue;
  3378. }
  3379. void writeToStream (const ValueUnion&, OutputStream& output) const
  3380. {
  3381. jassertfalse; // Can't write an object to a stream!
  3382. output.writeCompressedInt (0);
  3383. }
  3384. };
  3385. class var::VariantType_Method : public var::VariantType
  3386. {
  3387. public:
  3388. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3389. const String toString (const ValueUnion&) const { return "Method"; }
  3390. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3391. bool isMethod() const throw() { return true; }
  3392. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3393. {
  3394. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3395. }
  3396. void writeToStream (const ValueUnion&, OutputStream& output) const
  3397. {
  3398. jassertfalse; // Can't write a method to a stream!
  3399. output.writeCompressedInt (0);
  3400. }
  3401. };
  3402. var::var() throw()
  3403. : type (VariantType_Void::getInstance())
  3404. {
  3405. }
  3406. var::~var() throw()
  3407. {
  3408. type->cleanUp (value);
  3409. }
  3410. const var var::null;
  3411. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3412. {
  3413. type->createCopy (value, valueToCopy.value);
  3414. }
  3415. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3416. {
  3417. value.intValue = value_;
  3418. }
  3419. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3420. {
  3421. value.boolValue = value_;
  3422. }
  3423. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3424. {
  3425. value.doubleValue = value_;
  3426. }
  3427. var::var (const String& value_) : type (VariantType_String::getInstance())
  3428. {
  3429. value.stringValue = new String (value_);
  3430. }
  3431. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3432. {
  3433. value.stringValue = new String (value_);
  3434. }
  3435. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3436. {
  3437. value.stringValue = new String (value_);
  3438. }
  3439. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3440. {
  3441. value.objectValue = object;
  3442. if (object != 0)
  3443. object->incReferenceCount();
  3444. }
  3445. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3446. {
  3447. value.methodValue = method_;
  3448. }
  3449. bool var::isVoid() const throw() { return type->isVoid(); }
  3450. bool var::isInt() const throw() { return type->isInt(); }
  3451. bool var::isBool() const throw() { return type->isBool(); }
  3452. bool var::isDouble() const throw() { return type->isDouble(); }
  3453. bool var::isString() const throw() { return type->isString(); }
  3454. bool var::isObject() const throw() { return type->isObject(); }
  3455. bool var::isMethod() const throw() { return type->isMethod(); }
  3456. var::operator int() const { return type->toInt (value); }
  3457. var::operator bool() const { return type->toBool (value); }
  3458. var::operator float() const { return (float) type->toDouble (value); }
  3459. var::operator double() const { return type->toDouble (value); }
  3460. const String var::toString() const { return type->toString (value); }
  3461. var::operator const String() const { return type->toString (value); }
  3462. DynamicObject* var::getObject() const { return type->toObject (value); }
  3463. void var::swapWith (var& other) throw()
  3464. {
  3465. swapVariables (type, other.type);
  3466. swapVariables (value, other.value);
  3467. }
  3468. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3469. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3470. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3471. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3472. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3473. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3474. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3475. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3476. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3477. bool var::equals (const var& other) const throw()
  3478. {
  3479. return type->equals (value, other.value, *other.type);
  3480. }
  3481. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3482. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3483. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3484. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3485. void var::writeToStream (OutputStream& output) const
  3486. {
  3487. type->writeToStream (value, output);
  3488. }
  3489. const var var::readFromStream (InputStream& input)
  3490. {
  3491. const int numBytes = input.readCompressedInt();
  3492. if (numBytes > 0)
  3493. {
  3494. switch (input.readByte())
  3495. {
  3496. case 1: return var (input.readInt());
  3497. case 2: return var (true);
  3498. case 3: return var (false);
  3499. case 4: return var (input.readDouble());
  3500. case 5:
  3501. {
  3502. MemoryOutputStream mo;
  3503. mo.writeFromInputStream (input, numBytes - 1);
  3504. return var (mo.toUTF8());
  3505. }
  3506. default: input.skipNextBytes (numBytes - 1); break;
  3507. }
  3508. }
  3509. return var::null;
  3510. }
  3511. const var var::operator[] (const Identifier& propertyName) const
  3512. {
  3513. DynamicObject* const o = getObject();
  3514. return o != 0 ? o->getProperty (propertyName) : var::null;
  3515. }
  3516. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3517. {
  3518. DynamicObject* const o = getObject();
  3519. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3520. }
  3521. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3522. {
  3523. if (isMethod())
  3524. {
  3525. DynamicObject* const target = targetObject.getObject();
  3526. if (target != 0)
  3527. return (target->*(value.methodValue)) (arguments, numArguments);
  3528. }
  3529. return var::null;
  3530. }
  3531. const var var::call (const Identifier& method) const
  3532. {
  3533. return invoke (method, 0, 0);
  3534. }
  3535. const var var::call (const Identifier& method, const var& arg1) const
  3536. {
  3537. return invoke (method, &arg1, 1);
  3538. }
  3539. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3540. {
  3541. var args[] = { arg1, arg2 };
  3542. return invoke (method, args, 2);
  3543. }
  3544. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3545. {
  3546. var args[] = { arg1, arg2, arg3 };
  3547. return invoke (method, args, 3);
  3548. }
  3549. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3550. {
  3551. var args[] = { arg1, arg2, arg3, arg4 };
  3552. return invoke (method, args, 4);
  3553. }
  3554. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3555. {
  3556. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3557. return invoke (method, args, 5);
  3558. }
  3559. END_JUCE_NAMESPACE
  3560. /*** End of inlined file: juce_Variant.cpp ***/
  3561. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3562. BEGIN_JUCE_NAMESPACE
  3563. NamedValueSet::NamedValue::NamedValue() throw()
  3564. {
  3565. }
  3566. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3567. : name (name_), value (value_)
  3568. {
  3569. }
  3570. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3571. {
  3572. return name == other.name && value == other.value;
  3573. }
  3574. NamedValueSet::NamedValueSet() throw()
  3575. {
  3576. }
  3577. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3578. : values (other.values)
  3579. {
  3580. }
  3581. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3582. {
  3583. values = other.values;
  3584. return *this;
  3585. }
  3586. NamedValueSet::~NamedValueSet()
  3587. {
  3588. }
  3589. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3590. {
  3591. return values == other.values;
  3592. }
  3593. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3594. {
  3595. return ! operator== (other);
  3596. }
  3597. int NamedValueSet::size() const throw()
  3598. {
  3599. return values.size();
  3600. }
  3601. const var& NamedValueSet::operator[] (const Identifier& name) const
  3602. {
  3603. for (int i = values.size(); --i >= 0;)
  3604. {
  3605. const NamedValue& v = values.getReference(i);
  3606. if (v.name == name)
  3607. return v.value;
  3608. }
  3609. return var::null;
  3610. }
  3611. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3612. {
  3613. const var* v = getItem (name);
  3614. return v != 0 ? *v : defaultReturnValue;
  3615. }
  3616. var* NamedValueSet::getItem (const Identifier& name) const
  3617. {
  3618. for (int i = values.size(); --i >= 0;)
  3619. {
  3620. NamedValue& v = values.getReference(i);
  3621. if (v.name == name)
  3622. return &(v.value);
  3623. }
  3624. return 0;
  3625. }
  3626. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3627. {
  3628. for (int i = values.size(); --i >= 0;)
  3629. {
  3630. NamedValue& v = values.getReference(i);
  3631. if (v.name == name)
  3632. {
  3633. if (v.value == newValue)
  3634. return false;
  3635. v.value = newValue;
  3636. return true;
  3637. }
  3638. }
  3639. values.add (NamedValue (name, newValue));
  3640. return true;
  3641. }
  3642. bool NamedValueSet::contains (const Identifier& name) const
  3643. {
  3644. return getItem (name) != 0;
  3645. }
  3646. bool NamedValueSet::remove (const Identifier& name)
  3647. {
  3648. for (int i = values.size(); --i >= 0;)
  3649. {
  3650. if (values.getReference(i).name == name)
  3651. {
  3652. values.remove (i);
  3653. return true;
  3654. }
  3655. }
  3656. return false;
  3657. }
  3658. const Identifier NamedValueSet::getName (const int index) const
  3659. {
  3660. jassert (((unsigned int) index) < (unsigned int) values.size());
  3661. return values [index].name;
  3662. }
  3663. const var NamedValueSet::getValueAt (const int index) const
  3664. {
  3665. jassert (((unsigned int) index) < (unsigned int) values.size());
  3666. return values [index].value;
  3667. }
  3668. void NamedValueSet::clear()
  3669. {
  3670. values.clear();
  3671. }
  3672. END_JUCE_NAMESPACE
  3673. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3674. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3675. BEGIN_JUCE_NAMESPACE
  3676. DynamicObject::DynamicObject()
  3677. {
  3678. }
  3679. DynamicObject::~DynamicObject()
  3680. {
  3681. }
  3682. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3683. {
  3684. var* const v = properties.getItem (propertyName);
  3685. return v != 0 && ! v->isMethod();
  3686. }
  3687. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3688. {
  3689. return properties [propertyName];
  3690. }
  3691. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3692. {
  3693. properties.set (propertyName, newValue);
  3694. }
  3695. void DynamicObject::removeProperty (const Identifier& propertyName)
  3696. {
  3697. properties.remove (propertyName);
  3698. }
  3699. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3700. {
  3701. return getProperty (methodName).isMethod();
  3702. }
  3703. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3704. const var* parameters,
  3705. int numParameters)
  3706. {
  3707. return properties [methodName].invoke (var (this), parameters, numParameters);
  3708. }
  3709. void DynamicObject::setMethod (const Identifier& name,
  3710. var::MethodFunction methodFunction)
  3711. {
  3712. properties.set (name, var (methodFunction));
  3713. }
  3714. void DynamicObject::clear()
  3715. {
  3716. properties.clear();
  3717. }
  3718. END_JUCE_NAMESPACE
  3719. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3720. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3721. BEGIN_JUCE_NAMESPACE
  3722. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3723. {
  3724. jassert (keyData != 0);
  3725. jassert (keyBytes > 0);
  3726. static const uint32 initialPValues [18] =
  3727. {
  3728. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3729. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3730. 0x9216d5d9, 0x8979fb1b
  3731. };
  3732. static const uint32 initialSValues [4 * 256] =
  3733. {
  3734. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3735. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3736. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3737. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3738. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3739. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3740. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3741. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3742. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3743. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3744. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3745. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3746. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3747. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3748. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3749. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3750. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3751. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3752. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3753. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3754. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3755. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3756. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3757. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3758. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3759. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3760. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3761. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3762. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3763. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3764. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3765. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3766. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3767. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3768. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3769. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3770. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3771. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3772. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3773. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3774. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3775. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3776. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3777. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3778. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3779. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3780. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3781. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3782. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3783. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3784. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3785. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3786. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3787. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3788. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3789. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3790. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3791. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3792. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3793. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3794. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3795. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3796. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3797. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3798. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3799. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3800. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3801. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3802. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3803. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3804. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3805. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3806. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3807. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3808. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3809. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3810. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3811. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3812. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3813. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3814. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3815. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3816. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3817. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3818. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3819. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3820. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3821. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3822. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3823. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3824. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3825. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3826. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3827. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3828. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3829. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3830. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3831. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3832. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3833. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3834. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3835. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3836. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3837. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3838. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3839. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3840. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3841. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3842. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3843. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3844. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3845. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3846. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3847. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3848. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3849. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3850. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3851. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3852. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3853. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3854. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3855. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3856. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3857. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3858. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3859. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3860. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3861. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3862. };
  3863. memcpy (p, initialPValues, sizeof (p));
  3864. int i, j = 0;
  3865. for (i = 4; --i >= 0;)
  3866. {
  3867. s[i].malloc (256);
  3868. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3869. }
  3870. for (i = 0; i < 18; ++i)
  3871. {
  3872. uint32 d = 0;
  3873. for (int k = 0; k < 4; ++k)
  3874. {
  3875. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3876. if (++j >= keyBytes)
  3877. j = 0;
  3878. }
  3879. p[i] = initialPValues[i] ^ d;
  3880. }
  3881. uint32 l = 0, r = 0;
  3882. for (i = 0; i < 18; i += 2)
  3883. {
  3884. encrypt (l, r);
  3885. p[i] = l;
  3886. p[i + 1] = r;
  3887. }
  3888. for (i = 0; i < 4; ++i)
  3889. {
  3890. for (j = 0; j < 256; j += 2)
  3891. {
  3892. encrypt (l, r);
  3893. s[i][j] = l;
  3894. s[i][j + 1] = r;
  3895. }
  3896. }
  3897. }
  3898. BlowFish::BlowFish (const BlowFish& other)
  3899. {
  3900. for (int i = 4; --i >= 0;)
  3901. s[i].malloc (256);
  3902. operator= (other);
  3903. }
  3904. BlowFish& BlowFish::operator= (const BlowFish& other)
  3905. {
  3906. memcpy (p, other.p, sizeof (p));
  3907. for (int i = 4; --i >= 0;)
  3908. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3909. return *this;
  3910. }
  3911. BlowFish::~BlowFish()
  3912. {
  3913. }
  3914. uint32 BlowFish::F (const uint32 x) const throw()
  3915. {
  3916. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3917. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3918. }
  3919. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3920. {
  3921. uint32 l = data1;
  3922. uint32 r = data2;
  3923. for (int i = 0; i < 16; ++i)
  3924. {
  3925. l ^= p[i];
  3926. r ^= F(l);
  3927. swapVariables (l, r);
  3928. }
  3929. data1 = r ^ p[17];
  3930. data2 = l ^ p[16];
  3931. }
  3932. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3933. {
  3934. uint32 l = data1;
  3935. uint32 r = data2;
  3936. for (int i = 17; i > 1; --i)
  3937. {
  3938. l ^= p[i];
  3939. r ^= F(l);
  3940. swapVariables (l, r);
  3941. }
  3942. data1 = r ^ p[0];
  3943. data2 = l ^ p[1];
  3944. }
  3945. END_JUCE_NAMESPACE
  3946. /*** End of inlined file: juce_BlowFish.cpp ***/
  3947. /*** Start of inlined file: juce_MD5.cpp ***/
  3948. BEGIN_JUCE_NAMESPACE
  3949. MD5::MD5()
  3950. {
  3951. zerostruct (result);
  3952. }
  3953. MD5::MD5 (const MD5& other)
  3954. {
  3955. memcpy (result, other.result, sizeof (result));
  3956. }
  3957. MD5& MD5::operator= (const MD5& other)
  3958. {
  3959. memcpy (result, other.result, sizeof (result));
  3960. return *this;
  3961. }
  3962. MD5::MD5 (const MemoryBlock& data)
  3963. {
  3964. ProcessContext context;
  3965. context.processBlock (data.getData(), data.getSize());
  3966. context.finish (result);
  3967. }
  3968. MD5::MD5 (const void* data, const size_t numBytes)
  3969. {
  3970. ProcessContext context;
  3971. context.processBlock (data, numBytes);
  3972. context.finish (result);
  3973. }
  3974. MD5::MD5 (const String& text)
  3975. {
  3976. ProcessContext context;
  3977. const int len = text.length();
  3978. const juce_wchar* const t = text;
  3979. for (int i = 0; i < len; ++i)
  3980. {
  3981. // force the string into integer-sized unicode characters, to try to make it
  3982. // get the same results on all platforms + compilers.
  3983. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3984. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3985. }
  3986. context.finish (result);
  3987. }
  3988. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3989. {
  3990. ProcessContext context;
  3991. if (numBytesToRead < 0)
  3992. numBytesToRead = std::numeric_limits<int64>::max();
  3993. while (numBytesToRead > 0)
  3994. {
  3995. uint8 tempBuffer [512];
  3996. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3997. if (bytesRead <= 0)
  3998. break;
  3999. numBytesToRead -= bytesRead;
  4000. context.processBlock (tempBuffer, bytesRead);
  4001. }
  4002. context.finish (result);
  4003. }
  4004. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4005. {
  4006. processStream (input, numBytesToRead);
  4007. }
  4008. MD5::MD5 (const File& file)
  4009. {
  4010. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4011. if (fin != 0)
  4012. processStream (*fin, -1);
  4013. else
  4014. zerostruct (result);
  4015. }
  4016. MD5::~MD5()
  4017. {
  4018. }
  4019. namespace MD5Functions
  4020. {
  4021. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4022. {
  4023. for (int i = 0; i < (numBytes >> 2); ++i)
  4024. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4025. }
  4026. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4027. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4028. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4029. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4030. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4031. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4032. {
  4033. a += F (b, c, d) + x + ac;
  4034. a = rotateLeft (a, s) + b;
  4035. }
  4036. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4037. {
  4038. a += G (b, c, d) + x + ac;
  4039. a = rotateLeft (a, s) + b;
  4040. }
  4041. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4042. {
  4043. a += H (b, c, d) + x + ac;
  4044. a = rotateLeft (a, s) + b;
  4045. }
  4046. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4047. {
  4048. a += I (b, c, d) + x + ac;
  4049. a = rotateLeft (a, s) + b;
  4050. }
  4051. }
  4052. MD5::ProcessContext::ProcessContext()
  4053. {
  4054. state[0] = 0x67452301;
  4055. state[1] = 0xefcdab89;
  4056. state[2] = 0x98badcfe;
  4057. state[3] = 0x10325476;
  4058. count[0] = 0;
  4059. count[1] = 0;
  4060. }
  4061. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4062. {
  4063. int bufferPos = ((count[0] >> 3) & 0x3F);
  4064. count[0] += (uint32) (dataSize << 3);
  4065. if (count[0] < ((uint32) dataSize << 3))
  4066. count[1]++;
  4067. count[1] += (uint32) (dataSize >> 29);
  4068. const size_t spaceLeft = 64 - bufferPos;
  4069. size_t i = 0;
  4070. if (dataSize >= spaceLeft)
  4071. {
  4072. memcpy (buffer + bufferPos, data, spaceLeft);
  4073. transform (buffer);
  4074. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4075. transform (static_cast <const char*> (data) + i);
  4076. bufferPos = 0;
  4077. }
  4078. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4079. }
  4080. void MD5::ProcessContext::finish (void* const result)
  4081. {
  4082. unsigned char encodedLength[8];
  4083. MD5Functions::encode (encodedLength, count, 8);
  4084. // Pad out to 56 mod 64.
  4085. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4086. const int paddingLength = (index < 56) ? (56 - index)
  4087. : (120 - index);
  4088. uint8 paddingBuffer [64];
  4089. zeromem (paddingBuffer, paddingLength);
  4090. paddingBuffer [0] = 0x80;
  4091. processBlock (paddingBuffer, paddingLength);
  4092. processBlock (encodedLength, 8);
  4093. MD5Functions::encode (result, state, 16);
  4094. zerostruct (buffer);
  4095. }
  4096. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4097. {
  4098. using namespace MD5Functions;
  4099. uint32 a = state[0];
  4100. uint32 b = state[1];
  4101. uint32 c = state[2];
  4102. uint32 d = state[3];
  4103. uint32 x[16];
  4104. encode (x, bufferToTransform, 64);
  4105. enum Constants
  4106. {
  4107. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4108. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4109. };
  4110. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4111. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4112. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4113. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4114. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4115. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4116. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4117. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4118. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4119. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4120. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4121. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4122. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4123. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4124. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4125. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4126. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4127. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4128. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4129. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4130. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4131. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4132. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4133. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4134. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4135. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4136. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4137. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4138. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4139. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4140. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4141. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4142. state[0] += a;
  4143. state[1] += b;
  4144. state[2] += c;
  4145. state[3] += d;
  4146. zerostruct (x);
  4147. }
  4148. const MemoryBlock MD5::getRawChecksumData() const
  4149. {
  4150. return MemoryBlock (result, sizeof (result));
  4151. }
  4152. const String MD5::toHexString() const
  4153. {
  4154. return String::toHexString (result, sizeof (result), 0);
  4155. }
  4156. bool MD5::operator== (const MD5& other) const
  4157. {
  4158. return memcmp (result, other.result, sizeof (result)) == 0;
  4159. }
  4160. bool MD5::operator!= (const MD5& other) const
  4161. {
  4162. return ! operator== (other);
  4163. }
  4164. END_JUCE_NAMESPACE
  4165. /*** End of inlined file: juce_MD5.cpp ***/
  4166. /*** Start of inlined file: juce_Primes.cpp ***/
  4167. BEGIN_JUCE_NAMESPACE
  4168. namespace PrimesHelpers
  4169. {
  4170. static void createSmallSieve (const int numBits, BigInteger& result)
  4171. {
  4172. result.setBit (numBits);
  4173. result.clearBit (numBits); // to enlarge the array
  4174. result.setBit (0);
  4175. int n = 2;
  4176. do
  4177. {
  4178. for (int i = n + n; i < numBits; i += n)
  4179. result.setBit (i);
  4180. n = result.findNextClearBit (n + 1);
  4181. }
  4182. while (n <= (numBits >> 1));
  4183. }
  4184. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4185. const BigInteger& smallSieve, const int smallSieveSize)
  4186. {
  4187. jassert (! base[0]); // must be even!
  4188. result.setBit (numBits);
  4189. result.clearBit (numBits); // to enlarge the array
  4190. int index = smallSieve.findNextClearBit (0);
  4191. do
  4192. {
  4193. const int prime = (index << 1) + 1;
  4194. BigInteger r (base), remainder;
  4195. r.divideBy (prime, remainder);
  4196. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4197. if (r.isZero())
  4198. i += prime;
  4199. if ((i & 1) == 0)
  4200. i += prime;
  4201. i = (i - 1) >> 1;
  4202. while (i < numBits)
  4203. {
  4204. result.setBit (i);
  4205. i += prime;
  4206. }
  4207. index = smallSieve.findNextClearBit (index + 1);
  4208. }
  4209. while (index < smallSieveSize);
  4210. }
  4211. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4212. const int numBits, BigInteger& result, const int certainty)
  4213. {
  4214. for (int i = 0; i < numBits; ++i)
  4215. {
  4216. if (! sieve[i])
  4217. {
  4218. result = base + (unsigned int) ((i << 1) + 1);
  4219. if (Primes::isProbablyPrime (result, certainty))
  4220. return true;
  4221. }
  4222. }
  4223. return false;
  4224. }
  4225. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4226. {
  4227. const BigInteger one (1), two (2);
  4228. const BigInteger nMinusOne (n - one);
  4229. BigInteger d (nMinusOne);
  4230. const int s = d.findNextSetBit (0);
  4231. d >>= s;
  4232. BigInteger smallPrimes;
  4233. int numBitsInSmallPrimes = 0;
  4234. for (;;)
  4235. {
  4236. numBitsInSmallPrimes += 256;
  4237. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4238. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4239. if (numPrimesFound > iterations + 1)
  4240. break;
  4241. }
  4242. int smallPrime = 2;
  4243. while (--iterations >= 0)
  4244. {
  4245. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4246. BigInteger r (smallPrime);
  4247. r.exponentModulo (d, n);
  4248. if (r != one && r != nMinusOne)
  4249. {
  4250. for (int j = 0; j < s; ++j)
  4251. {
  4252. r.exponentModulo (two, n);
  4253. if (r == nMinusOne)
  4254. break;
  4255. }
  4256. if (r != nMinusOne)
  4257. return false;
  4258. }
  4259. }
  4260. return true;
  4261. }
  4262. }
  4263. const BigInteger Primes::createProbablePrime (const int bitLength,
  4264. const int certainty,
  4265. const int* randomSeeds,
  4266. int numRandomSeeds)
  4267. {
  4268. using namespace PrimesHelpers;
  4269. int defaultSeeds [16];
  4270. if (numRandomSeeds <= 0)
  4271. {
  4272. randomSeeds = defaultSeeds;
  4273. numRandomSeeds = numElementsInArray (defaultSeeds);
  4274. Random r (0);
  4275. for (int j = 10; --j >= 0;)
  4276. {
  4277. r.setSeedRandomly();
  4278. for (int i = numRandomSeeds; --i >= 0;)
  4279. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4280. }
  4281. }
  4282. BigInteger smallSieve;
  4283. const int smallSieveSize = 15000;
  4284. createSmallSieve (smallSieveSize, smallSieve);
  4285. BigInteger p;
  4286. for (int i = numRandomSeeds; --i >= 0;)
  4287. {
  4288. BigInteger p2;
  4289. Random r (randomSeeds[i]);
  4290. r.fillBitsRandomly (p2, 0, bitLength);
  4291. p ^= p2;
  4292. }
  4293. p.setBit (bitLength - 1);
  4294. p.clearBit (0);
  4295. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4296. while (p.getHighestBit() < bitLength)
  4297. {
  4298. p += 2 * searchLen;
  4299. BigInteger sieve;
  4300. bigSieve (p, searchLen, sieve,
  4301. smallSieve, smallSieveSize);
  4302. BigInteger candidate;
  4303. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4304. return candidate;
  4305. }
  4306. jassertfalse;
  4307. return BigInteger();
  4308. }
  4309. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4310. {
  4311. using namespace PrimesHelpers;
  4312. if (! number[0])
  4313. return false;
  4314. if (number.getHighestBit() <= 10)
  4315. {
  4316. const int num = number.getBitRangeAsInt (0, 10);
  4317. for (int i = num / 2; --i > 1;)
  4318. if (num % i == 0)
  4319. return false;
  4320. return true;
  4321. }
  4322. else
  4323. {
  4324. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4325. return false;
  4326. return passesMillerRabin (number, certainty);
  4327. }
  4328. }
  4329. END_JUCE_NAMESPACE
  4330. /*** End of inlined file: juce_Primes.cpp ***/
  4331. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4332. BEGIN_JUCE_NAMESPACE
  4333. RSAKey::RSAKey()
  4334. {
  4335. }
  4336. RSAKey::RSAKey (const String& s)
  4337. {
  4338. if (s.containsChar (','))
  4339. {
  4340. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4341. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4342. }
  4343. else
  4344. {
  4345. // the string needs to be two hex numbers, comma-separated..
  4346. jassertfalse;
  4347. }
  4348. }
  4349. RSAKey::~RSAKey()
  4350. {
  4351. }
  4352. bool RSAKey::operator== (const RSAKey& other) const throw()
  4353. {
  4354. return part1 == other.part1 && part2 == other.part2;
  4355. }
  4356. bool RSAKey::operator!= (const RSAKey& other) const throw()
  4357. {
  4358. return ! operator== (other);
  4359. }
  4360. const String RSAKey::toString() const
  4361. {
  4362. return part1.toString (16) + "," + part2.toString (16);
  4363. }
  4364. bool RSAKey::applyToValue (BigInteger& value) const
  4365. {
  4366. if (part1.isZero() || part2.isZero() || value <= 0)
  4367. {
  4368. jassertfalse; // using an uninitialised key
  4369. value.clear();
  4370. return false;
  4371. }
  4372. BigInteger result;
  4373. while (! value.isZero())
  4374. {
  4375. result *= part2;
  4376. BigInteger remainder;
  4377. value.divideBy (part2, remainder);
  4378. remainder.exponentModulo (part1, part2);
  4379. result += remainder;
  4380. }
  4381. value.swapWith (result);
  4382. return true;
  4383. }
  4384. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4385. {
  4386. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4387. // are fast to divide + multiply
  4388. for (int i = 2; i <= 65536; i *= 2)
  4389. {
  4390. const BigInteger e (1 + i);
  4391. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4392. return e;
  4393. }
  4394. BigInteger e (4);
  4395. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4396. ++e;
  4397. return e;
  4398. }
  4399. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4400. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4401. {
  4402. jassert (numBits > 16); // not much point using less than this..
  4403. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  4404. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  4405. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  4406. const BigInteger n (p * q);
  4407. const BigInteger m (--p * --q);
  4408. const BigInteger e (findBestCommonDivisor (p, q));
  4409. BigInteger d (e);
  4410. d.inverseModulo (m);
  4411. publicKey.part1 = e;
  4412. publicKey.part2 = n;
  4413. privateKey.part1 = d;
  4414. privateKey.part2 = n;
  4415. }
  4416. END_JUCE_NAMESPACE
  4417. /*** End of inlined file: juce_RSAKey.cpp ***/
  4418. /*** Start of inlined file: juce_InputStream.cpp ***/
  4419. BEGIN_JUCE_NAMESPACE
  4420. char InputStream::readByte()
  4421. {
  4422. char temp = 0;
  4423. read (&temp, 1);
  4424. return temp;
  4425. }
  4426. bool InputStream::readBool()
  4427. {
  4428. return readByte() != 0;
  4429. }
  4430. short InputStream::readShort()
  4431. {
  4432. char temp[2];
  4433. if (read (temp, 2) == 2)
  4434. return (short) ByteOrder::littleEndianShort (temp);
  4435. return 0;
  4436. }
  4437. short InputStream::readShortBigEndian()
  4438. {
  4439. char temp[2];
  4440. if (read (temp, 2) == 2)
  4441. return (short) ByteOrder::bigEndianShort (temp);
  4442. return 0;
  4443. }
  4444. int InputStream::readInt()
  4445. {
  4446. char temp[4];
  4447. if (read (temp, 4) == 4)
  4448. return (int) ByteOrder::littleEndianInt (temp);
  4449. return 0;
  4450. }
  4451. int InputStream::readIntBigEndian()
  4452. {
  4453. char temp[4];
  4454. if (read (temp, 4) == 4)
  4455. return (int) ByteOrder::bigEndianInt (temp);
  4456. return 0;
  4457. }
  4458. int InputStream::readCompressedInt()
  4459. {
  4460. const unsigned char sizeByte = readByte();
  4461. if (sizeByte == 0)
  4462. return 0;
  4463. const int numBytes = (sizeByte & 0x7f);
  4464. if (numBytes > 4)
  4465. {
  4466. jassertfalse; // trying to read corrupt data - this method must only be used
  4467. // to read data that was written by OutputStream::writeCompressedInt()
  4468. return 0;
  4469. }
  4470. char bytes[4] = { 0, 0, 0, 0 };
  4471. if (read (bytes, numBytes) != numBytes)
  4472. return 0;
  4473. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4474. return (sizeByte >> 7) ? -num : num;
  4475. }
  4476. int64 InputStream::readInt64()
  4477. {
  4478. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4479. if (read (n.asBytes, 8) == 8)
  4480. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4481. return 0;
  4482. }
  4483. int64 InputStream::readInt64BigEndian()
  4484. {
  4485. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4486. if (read (n.asBytes, 8) == 8)
  4487. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4488. return 0;
  4489. }
  4490. float InputStream::readFloat()
  4491. {
  4492. // the union below relies on these types being the same size...
  4493. static_jassert (sizeof (int32) == sizeof (float));
  4494. union { int32 asInt; float asFloat; } n;
  4495. n.asInt = (int32) readInt();
  4496. return n.asFloat;
  4497. }
  4498. float InputStream::readFloatBigEndian()
  4499. {
  4500. union { int32 asInt; float asFloat; } n;
  4501. n.asInt = (int32) readIntBigEndian();
  4502. return n.asFloat;
  4503. }
  4504. double InputStream::readDouble()
  4505. {
  4506. union { int64 asInt; double asDouble; } n;
  4507. n.asInt = readInt64();
  4508. return n.asDouble;
  4509. }
  4510. double InputStream::readDoubleBigEndian()
  4511. {
  4512. union { int64 asInt; double asDouble; } n;
  4513. n.asInt = readInt64BigEndian();
  4514. return n.asDouble;
  4515. }
  4516. const String InputStream::readString()
  4517. {
  4518. MemoryBlock buffer (256);
  4519. char* data = static_cast<char*> (buffer.getData());
  4520. size_t i = 0;
  4521. while ((data[i] = readByte()) != 0)
  4522. {
  4523. if (++i >= buffer.getSize())
  4524. {
  4525. buffer.setSize (buffer.getSize() + 512);
  4526. data = static_cast<char*> (buffer.getData());
  4527. }
  4528. }
  4529. return String::fromUTF8 (data, (int) i);
  4530. }
  4531. const String InputStream::readNextLine()
  4532. {
  4533. MemoryBlock buffer (256);
  4534. char* data = static_cast<char*> (buffer.getData());
  4535. size_t i = 0;
  4536. while ((data[i] = readByte()) != 0)
  4537. {
  4538. if (data[i] == '\n')
  4539. break;
  4540. if (data[i] == '\r')
  4541. {
  4542. const int64 lastPos = getPosition();
  4543. if (readByte() != '\n')
  4544. setPosition (lastPos);
  4545. break;
  4546. }
  4547. if (++i >= buffer.getSize())
  4548. {
  4549. buffer.setSize (buffer.getSize() + 512);
  4550. data = static_cast<char*> (buffer.getData());
  4551. }
  4552. }
  4553. return String::fromUTF8 (data, (int) i);
  4554. }
  4555. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4556. {
  4557. MemoryOutputStream mo (block, true);
  4558. return mo.writeFromInputStream (*this, numBytes);
  4559. }
  4560. const String InputStream::readEntireStreamAsString()
  4561. {
  4562. MemoryOutputStream mo;
  4563. mo.writeFromInputStream (*this, -1);
  4564. return mo.toString();
  4565. }
  4566. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4567. {
  4568. if (numBytesToSkip > 0)
  4569. {
  4570. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4571. HeapBlock<char> temp (skipBufferSize);
  4572. while (numBytesToSkip > 0 && ! isExhausted())
  4573. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4574. }
  4575. }
  4576. END_JUCE_NAMESPACE
  4577. /*** End of inlined file: juce_InputStream.cpp ***/
  4578. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4579. BEGIN_JUCE_NAMESPACE
  4580. #if JUCE_DEBUG
  4581. static CriticalSection activeStreamLock;
  4582. static Array<void*> activeStreams;
  4583. void juce_CheckForDanglingStreams()
  4584. {
  4585. /*
  4586. It's always a bad idea to leak any object, but if you're leaking output
  4587. streams, then there's a good chance that you're failing to flush a file
  4588. to disk properly, which could result in corrupted data and other similar
  4589. nastiness..
  4590. */
  4591. jassert (activeStreams.size() == 0);
  4592. };
  4593. #endif
  4594. OutputStream::OutputStream()
  4595. {
  4596. #if JUCE_DEBUG
  4597. const ScopedLock sl (activeStreamLock);
  4598. activeStreams.add (this);
  4599. #endif
  4600. }
  4601. OutputStream::~OutputStream()
  4602. {
  4603. #if JUCE_DEBUG
  4604. const ScopedLock sl (activeStreamLock);
  4605. activeStreams.removeValue (this);
  4606. #endif
  4607. }
  4608. void OutputStream::writeBool (const bool b)
  4609. {
  4610. writeByte (b ? (char) 1
  4611. : (char) 0);
  4612. }
  4613. void OutputStream::writeByte (char byte)
  4614. {
  4615. write (&byte, 1);
  4616. }
  4617. void OutputStream::writeShort (short value)
  4618. {
  4619. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4620. write (&v, 2);
  4621. }
  4622. void OutputStream::writeShortBigEndian (short value)
  4623. {
  4624. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4625. write (&v, 2);
  4626. }
  4627. void OutputStream::writeInt (int value)
  4628. {
  4629. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4630. write (&v, 4);
  4631. }
  4632. void OutputStream::writeIntBigEndian (int value)
  4633. {
  4634. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4635. write (&v, 4);
  4636. }
  4637. void OutputStream::writeCompressedInt (int value)
  4638. {
  4639. unsigned int un = (value < 0) ? (unsigned int) -value
  4640. : (unsigned int) value;
  4641. uint8 data[5];
  4642. int num = 0;
  4643. while (un > 0)
  4644. {
  4645. data[++num] = (uint8) un;
  4646. un >>= 8;
  4647. }
  4648. data[0] = (uint8) num;
  4649. if (value < 0)
  4650. data[0] |= 0x80;
  4651. write (data, num + 1);
  4652. }
  4653. void OutputStream::writeInt64 (int64 value)
  4654. {
  4655. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4656. write (&v, 8);
  4657. }
  4658. void OutputStream::writeInt64BigEndian (int64 value)
  4659. {
  4660. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4661. write (&v, 8);
  4662. }
  4663. void OutputStream::writeFloat (float value)
  4664. {
  4665. union { int asInt; float asFloat; } n;
  4666. n.asFloat = value;
  4667. writeInt (n.asInt);
  4668. }
  4669. void OutputStream::writeFloatBigEndian (float value)
  4670. {
  4671. union { int asInt; float asFloat; } n;
  4672. n.asFloat = value;
  4673. writeIntBigEndian (n.asInt);
  4674. }
  4675. void OutputStream::writeDouble (double value)
  4676. {
  4677. union { int64 asInt; double asDouble; } n;
  4678. n.asDouble = value;
  4679. writeInt64 (n.asInt);
  4680. }
  4681. void OutputStream::writeDoubleBigEndian (double value)
  4682. {
  4683. union { int64 asInt; double asDouble; } n;
  4684. n.asDouble = value;
  4685. writeInt64BigEndian (n.asInt);
  4686. }
  4687. void OutputStream::writeString (const String& text)
  4688. {
  4689. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4690. // if lots of large, persistent strings were to be written to streams).
  4691. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4692. HeapBlock<char> temp (numBytes);
  4693. text.copyToUTF8 (temp, numBytes);
  4694. write (temp, numBytes);
  4695. }
  4696. void OutputStream::writeText (const String& text, const bool asUnicode,
  4697. const bool writeUnicodeHeaderBytes)
  4698. {
  4699. if (asUnicode)
  4700. {
  4701. if (writeUnicodeHeaderBytes)
  4702. write ("\x0ff\x0fe", 2);
  4703. const juce_wchar* src = text;
  4704. bool lastCharWasReturn = false;
  4705. while (*src != 0)
  4706. {
  4707. if (*src == L'\n' && ! lastCharWasReturn)
  4708. writeShort ((short) L'\r');
  4709. lastCharWasReturn = (*src == L'\r');
  4710. writeShort ((short) *src++);
  4711. }
  4712. }
  4713. else
  4714. {
  4715. const char* src = text.toUTF8();
  4716. const char* t = src;
  4717. for (;;)
  4718. {
  4719. if (*t == '\n')
  4720. {
  4721. if (t > src)
  4722. write (src, (int) (t - src));
  4723. write ("\r\n", 2);
  4724. src = t + 1;
  4725. }
  4726. else if (*t == '\r')
  4727. {
  4728. if (t[1] == '\n')
  4729. ++t;
  4730. }
  4731. else if (*t == 0)
  4732. {
  4733. if (t > src)
  4734. write (src, (int) (t - src));
  4735. break;
  4736. }
  4737. ++t;
  4738. }
  4739. }
  4740. }
  4741. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4742. {
  4743. if (numBytesToWrite < 0)
  4744. numBytesToWrite = std::numeric_limits<int64>::max();
  4745. int numWritten = 0;
  4746. while (numBytesToWrite > 0 && ! source.isExhausted())
  4747. {
  4748. char buffer [8192];
  4749. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4750. if (num <= 0)
  4751. break;
  4752. write (buffer, num);
  4753. numBytesToWrite -= num;
  4754. numWritten += num;
  4755. }
  4756. return numWritten;
  4757. }
  4758. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4759. {
  4760. return stream << String (number);
  4761. }
  4762. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4763. {
  4764. return stream << String (number);
  4765. }
  4766. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4767. {
  4768. stream.writeByte (character);
  4769. return stream;
  4770. }
  4771. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4772. {
  4773. stream.write (text, (int) strlen (text));
  4774. return stream;
  4775. }
  4776. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4777. {
  4778. stream.write (data.getData(), (int) data.getSize());
  4779. return stream;
  4780. }
  4781. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4782. {
  4783. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4784. if (in != 0)
  4785. stream.writeFromInputStream (*in, -1);
  4786. return stream;
  4787. }
  4788. END_JUCE_NAMESPACE
  4789. /*** End of inlined file: juce_OutputStream.cpp ***/
  4790. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4791. BEGIN_JUCE_NAMESPACE
  4792. DirectoryIterator::DirectoryIterator (const File& directory,
  4793. bool isRecursive_,
  4794. const String& wildCard_,
  4795. const int whatToLookFor_)
  4796. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  4797. wildCard (wildCard_),
  4798. path (File::addTrailingSeparator (directory.getFullPathName())),
  4799. index (-1),
  4800. totalNumFiles (-1),
  4801. whatToLookFor (whatToLookFor_),
  4802. isRecursive (isRecursive_)
  4803. {
  4804. // you have to specify the type of files you're looking for!
  4805. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4806. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4807. }
  4808. DirectoryIterator::~DirectoryIterator()
  4809. {
  4810. }
  4811. bool DirectoryIterator::next()
  4812. {
  4813. return next (0, 0, 0, 0, 0, 0);
  4814. }
  4815. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4816. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4817. {
  4818. if (subIterator != 0)
  4819. {
  4820. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4821. return true;
  4822. subIterator = 0;
  4823. }
  4824. String filename;
  4825. bool isDirectory, isHidden;
  4826. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4827. {
  4828. ++index;
  4829. if (! filename.containsOnly ("."))
  4830. {
  4831. const File fileFound (path + filename, 0);
  4832. bool matches = false;
  4833. if (isDirectory)
  4834. {
  4835. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4836. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4837. matches = (whatToLookFor & File::findDirectories) != 0;
  4838. }
  4839. else
  4840. {
  4841. matches = (whatToLookFor & File::findFiles) != 0;
  4842. }
  4843. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4844. if (matches && isRecursive)
  4845. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4846. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4847. matches = ! isHidden;
  4848. if (matches)
  4849. {
  4850. currentFile = fileFound;
  4851. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4852. if (isDirResult != 0) *isDirResult = isDirectory;
  4853. return true;
  4854. }
  4855. else if (subIterator != 0)
  4856. {
  4857. return next();
  4858. }
  4859. }
  4860. }
  4861. return false;
  4862. }
  4863. const File DirectoryIterator::getFile() const
  4864. {
  4865. if (subIterator != 0)
  4866. return subIterator->getFile();
  4867. return currentFile;
  4868. }
  4869. float DirectoryIterator::getEstimatedProgress() const
  4870. {
  4871. if (totalNumFiles < 0)
  4872. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4873. if (totalNumFiles <= 0)
  4874. return 0.0f;
  4875. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4876. : (float) index;
  4877. return detailedIndex / totalNumFiles;
  4878. }
  4879. END_JUCE_NAMESPACE
  4880. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4881. /*** Start of inlined file: juce_File.cpp ***/
  4882. #if ! JUCE_WINDOWS
  4883. #include <pwd.h>
  4884. #endif
  4885. BEGIN_JUCE_NAMESPACE
  4886. File::File (const String& fullPathName)
  4887. : fullPath (parseAbsolutePath (fullPathName))
  4888. {
  4889. }
  4890. File::File (const String& path, int)
  4891. : fullPath (path)
  4892. {
  4893. }
  4894. const File File::createFileWithoutCheckingPath (const String& path)
  4895. {
  4896. return File (path, 0);
  4897. }
  4898. File::File (const File& other)
  4899. : fullPath (other.fullPath)
  4900. {
  4901. }
  4902. File& File::operator= (const String& newPath)
  4903. {
  4904. fullPath = parseAbsolutePath (newPath);
  4905. return *this;
  4906. }
  4907. File& File::operator= (const File& other)
  4908. {
  4909. fullPath = other.fullPath;
  4910. return *this;
  4911. }
  4912. const File File::nonexistent;
  4913. const String File::parseAbsolutePath (const String& p)
  4914. {
  4915. if (p.isEmpty())
  4916. return String::empty;
  4917. #if JUCE_WINDOWS
  4918. // Windows..
  4919. String path (p.replaceCharacter ('/', '\\'));
  4920. if (path.startsWithChar (File::separator))
  4921. {
  4922. if (path[1] != File::separator)
  4923. {
  4924. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4925. If you're trying to parse a string that may be either a relative path or an absolute path,
  4926. you MUST provide a context against which the partial path can be evaluated - you can do
  4927. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4928. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4929. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4930. */
  4931. jassertfalse;
  4932. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4933. }
  4934. }
  4935. else if (! path.containsChar (':'))
  4936. {
  4937. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4938. If you're trying to parse a string that may be either a relative path or an absolute path,
  4939. you MUST provide a context against which the partial path can be evaluated - you can do
  4940. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4941. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4942. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4943. */
  4944. jassertfalse;
  4945. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4946. }
  4947. #else
  4948. // Mac or Linux..
  4949. String path (p.replaceCharacter ('\\', '/'));
  4950. if (path.startsWithChar ('~'))
  4951. {
  4952. if (path[1] == File::separator || path[1] == 0)
  4953. {
  4954. // expand a name of the form "~/abc"
  4955. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4956. + path.substring (1);
  4957. }
  4958. else
  4959. {
  4960. // expand a name of type "~dave/abc"
  4961. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4962. struct passwd* const pw = getpwnam (userName.toUTF8());
  4963. if (pw != 0)
  4964. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4965. }
  4966. }
  4967. else if (! path.startsWithChar (File::separator))
  4968. {
  4969. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4970. If you're trying to parse a string that may be either a relative path or an absolute path,
  4971. you MUST provide a context against which the partial path can be evaluated - you can do
  4972. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4973. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4974. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4975. */
  4976. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4977. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4978. }
  4979. #endif
  4980. return path.trimCharactersAtEnd (separatorString);
  4981. }
  4982. const String File::addTrailingSeparator (const String& path)
  4983. {
  4984. return path.endsWithChar (File::separator) ? path
  4985. : path + File::separator;
  4986. }
  4987. #if JUCE_LINUX
  4988. #define NAMES_ARE_CASE_SENSITIVE 1
  4989. #endif
  4990. bool File::areFileNamesCaseSensitive()
  4991. {
  4992. #if NAMES_ARE_CASE_SENSITIVE
  4993. return true;
  4994. #else
  4995. return false;
  4996. #endif
  4997. }
  4998. bool File::operator== (const File& other) const
  4999. {
  5000. #if NAMES_ARE_CASE_SENSITIVE
  5001. return fullPath == other.fullPath;
  5002. #else
  5003. return fullPath.equalsIgnoreCase (other.fullPath);
  5004. #endif
  5005. }
  5006. bool File::operator!= (const File& other) const
  5007. {
  5008. return ! operator== (other);
  5009. }
  5010. bool File::operator< (const File& other) const
  5011. {
  5012. #if NAMES_ARE_CASE_SENSITIVE
  5013. return fullPath < other.fullPath;
  5014. #else
  5015. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5016. #endif
  5017. }
  5018. bool File::operator> (const File& other) const
  5019. {
  5020. #if NAMES_ARE_CASE_SENSITIVE
  5021. return fullPath > other.fullPath;
  5022. #else
  5023. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5024. #endif
  5025. }
  5026. bool File::setReadOnly (const bool shouldBeReadOnly,
  5027. const bool applyRecursively) const
  5028. {
  5029. bool worked = true;
  5030. if (applyRecursively && isDirectory())
  5031. {
  5032. Array <File> subFiles;
  5033. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5034. for (int i = subFiles.size(); --i >= 0;)
  5035. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5036. }
  5037. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5038. }
  5039. bool File::deleteRecursively() const
  5040. {
  5041. bool worked = true;
  5042. if (isDirectory())
  5043. {
  5044. Array<File> subFiles;
  5045. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5046. for (int i = subFiles.size(); --i >= 0;)
  5047. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5048. }
  5049. return deleteFile() && worked;
  5050. }
  5051. bool File::moveFileTo (const File& newFile) const
  5052. {
  5053. if (newFile.fullPath == fullPath)
  5054. return true;
  5055. #if ! NAMES_ARE_CASE_SENSITIVE
  5056. if (*this != newFile)
  5057. #endif
  5058. if (! newFile.deleteFile())
  5059. return false;
  5060. return moveInternal (newFile);
  5061. }
  5062. bool File::copyFileTo (const File& newFile) const
  5063. {
  5064. return (*this == newFile)
  5065. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5066. }
  5067. bool File::copyDirectoryTo (const File& newDirectory) const
  5068. {
  5069. if (isDirectory() && newDirectory.createDirectory())
  5070. {
  5071. Array<File> subFiles;
  5072. findChildFiles (subFiles, File::findFiles, false);
  5073. int i;
  5074. for (i = 0; i < subFiles.size(); ++i)
  5075. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5076. return false;
  5077. subFiles.clear();
  5078. findChildFiles (subFiles, File::findDirectories, false);
  5079. for (i = 0; i < subFiles.size(); ++i)
  5080. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5081. return false;
  5082. return true;
  5083. }
  5084. return false;
  5085. }
  5086. const String File::getPathUpToLastSlash() const
  5087. {
  5088. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5089. if (lastSlash > 0)
  5090. return fullPath.substring (0, lastSlash);
  5091. else if (lastSlash == 0)
  5092. return separatorString;
  5093. else
  5094. return fullPath;
  5095. }
  5096. const File File::getParentDirectory() const
  5097. {
  5098. return File (getPathUpToLastSlash(), (int) 0);
  5099. }
  5100. const String File::getFileName() const
  5101. {
  5102. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5103. }
  5104. int File::hashCode() const
  5105. {
  5106. return fullPath.hashCode();
  5107. }
  5108. int64 File::hashCode64() const
  5109. {
  5110. return fullPath.hashCode64();
  5111. }
  5112. const String File::getFileNameWithoutExtension() const
  5113. {
  5114. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5115. const int lastDot = fullPath.lastIndexOfChar ('.');
  5116. if (lastDot > lastSlash)
  5117. return fullPath.substring (lastSlash, lastDot);
  5118. else
  5119. return fullPath.substring (lastSlash);
  5120. }
  5121. bool File::isAChildOf (const File& potentialParent) const
  5122. {
  5123. if (potentialParent == File::nonexistent)
  5124. return false;
  5125. const String ourPath (getPathUpToLastSlash());
  5126. #if NAMES_ARE_CASE_SENSITIVE
  5127. if (potentialParent.fullPath == ourPath)
  5128. #else
  5129. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5130. #endif
  5131. {
  5132. return true;
  5133. }
  5134. else if (potentialParent.fullPath.length() >= ourPath.length())
  5135. {
  5136. return false;
  5137. }
  5138. else
  5139. {
  5140. return getParentDirectory().isAChildOf (potentialParent);
  5141. }
  5142. }
  5143. bool File::isAbsolutePath (const String& path)
  5144. {
  5145. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5146. #if JUCE_WINDOWS
  5147. || (path.isNotEmpty() && path[1] == ':');
  5148. #else
  5149. || path.startsWithChar ('~');
  5150. #endif
  5151. }
  5152. const File File::getChildFile (String relativePath) const
  5153. {
  5154. if (isAbsolutePath (relativePath))
  5155. {
  5156. // the path is really absolute..
  5157. return File (relativePath);
  5158. }
  5159. else
  5160. {
  5161. // it's relative, so remove any ../ or ./ bits at the start.
  5162. String path (fullPath);
  5163. if (relativePath[0] == '.')
  5164. {
  5165. #if JUCE_WINDOWS
  5166. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5167. #else
  5168. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5169. #endif
  5170. while (relativePath[0] == '.')
  5171. {
  5172. if (relativePath[1] == '.')
  5173. {
  5174. if (relativePath [2] == 0 || relativePath[2] == separator)
  5175. {
  5176. const int lastSlash = path.lastIndexOfChar (separator);
  5177. if (lastSlash >= 0)
  5178. path = path.substring (0, lastSlash);
  5179. relativePath = relativePath.substring (3);
  5180. }
  5181. else
  5182. {
  5183. break;
  5184. }
  5185. }
  5186. else if (relativePath[1] == separator)
  5187. {
  5188. relativePath = relativePath.substring (2);
  5189. }
  5190. else
  5191. {
  5192. break;
  5193. }
  5194. }
  5195. }
  5196. return File (addTrailingSeparator (path) + relativePath);
  5197. }
  5198. }
  5199. const File File::getSiblingFile (const String& fileName) const
  5200. {
  5201. return getParentDirectory().getChildFile (fileName);
  5202. }
  5203. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5204. {
  5205. if (bytes == 1)
  5206. {
  5207. return "1 byte";
  5208. }
  5209. else if (bytes < 1024)
  5210. {
  5211. return String ((int) bytes) + " bytes";
  5212. }
  5213. else if (bytes < 1024 * 1024)
  5214. {
  5215. return String (bytes / 1024.0, 1) + " KB";
  5216. }
  5217. else if (bytes < 1024 * 1024 * 1024)
  5218. {
  5219. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5220. }
  5221. else
  5222. {
  5223. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5224. }
  5225. }
  5226. bool File::create() const
  5227. {
  5228. if (exists())
  5229. return true;
  5230. {
  5231. const File parentDir (getParentDirectory());
  5232. if (parentDir == *this || ! parentDir.createDirectory())
  5233. return false;
  5234. FileOutputStream fo (*this, 8);
  5235. }
  5236. return exists();
  5237. }
  5238. bool File::createDirectory() const
  5239. {
  5240. if (! isDirectory())
  5241. {
  5242. const File parentDir (getParentDirectory());
  5243. if (parentDir == *this || ! parentDir.createDirectory())
  5244. return false;
  5245. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5246. return isDirectory();
  5247. }
  5248. return true;
  5249. }
  5250. const Time File::getCreationTime() const
  5251. {
  5252. int64 m, a, c;
  5253. getFileTimesInternal (m, a, c);
  5254. return Time (c);
  5255. }
  5256. const Time File::getLastModificationTime() const
  5257. {
  5258. int64 m, a, c;
  5259. getFileTimesInternal (m, a, c);
  5260. return Time (m);
  5261. }
  5262. const Time File::getLastAccessTime() const
  5263. {
  5264. int64 m, a, c;
  5265. getFileTimesInternal (m, a, c);
  5266. return Time (a);
  5267. }
  5268. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5269. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5270. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5271. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5272. {
  5273. if (! existsAsFile())
  5274. return false;
  5275. FileInputStream in (*this);
  5276. return getSize() == in.readIntoMemoryBlock (destBlock);
  5277. }
  5278. const String File::loadFileAsString() const
  5279. {
  5280. if (! existsAsFile())
  5281. return String::empty;
  5282. FileInputStream in (*this);
  5283. return in.readEntireStreamAsString();
  5284. }
  5285. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5286. {
  5287. return (whatToLookFor & (isDir ? findDirectories
  5288. : findFiles)) != 0
  5289. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5290. }
  5291. int File::findChildFiles (Array<File>& results,
  5292. const int whatToLookFor,
  5293. const bool searchRecursively,
  5294. const String& wildCardPattern) const
  5295. {
  5296. // you have to specify the type of files you're looking for!
  5297. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5298. int total = 0;
  5299. if (isDirectory())
  5300. {
  5301. // find child files or directories in this directory first..
  5302. String path (addTrailingSeparator (fullPath)), filename;
  5303. bool itemIsDirectory, itemIsHidden;
  5304. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5305. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5306. {
  5307. if (! filename.containsOnly ("."))
  5308. {
  5309. const File fileFound (path + filename, 0);
  5310. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5311. {
  5312. results.add (fileFound);
  5313. ++total;
  5314. }
  5315. if (searchRecursively && itemIsDirectory
  5316. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5317. {
  5318. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5319. }
  5320. }
  5321. }
  5322. }
  5323. return total;
  5324. }
  5325. int File::getNumberOfChildFiles (const int whatToLookFor,
  5326. const String& wildCardPattern) const
  5327. {
  5328. // you have to specify the type of files you're looking for!
  5329. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5330. int count = 0;
  5331. if (isDirectory())
  5332. {
  5333. String filename;
  5334. bool itemIsDirectory, itemIsHidden;
  5335. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5336. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5337. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5338. && ! filename.containsOnly ("."))
  5339. ++count;
  5340. }
  5341. else
  5342. {
  5343. // trying to search for files inside a non-directory?
  5344. jassertfalse;
  5345. }
  5346. return count;
  5347. }
  5348. bool File::containsSubDirectories() const
  5349. {
  5350. if (isDirectory())
  5351. {
  5352. String filename;
  5353. bool itemIsDirectory;
  5354. DirectoryIterator::NativeIterator i (*this, "*");
  5355. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5356. if (itemIsDirectory)
  5357. return true;
  5358. }
  5359. return false;
  5360. }
  5361. const File File::getNonexistentChildFile (const String& prefix_,
  5362. const String& suffix,
  5363. bool putNumbersInBrackets) const
  5364. {
  5365. File f (getChildFile (prefix_ + suffix));
  5366. if (f.exists())
  5367. {
  5368. int num = 2;
  5369. String prefix (prefix_);
  5370. // remove any bracketed numbers that may already be on the end..
  5371. if (prefix.trim().endsWithChar (')'))
  5372. {
  5373. putNumbersInBrackets = true;
  5374. const int openBracks = prefix.lastIndexOfChar ('(');
  5375. const int closeBracks = prefix.lastIndexOfChar (')');
  5376. if (openBracks > 0
  5377. && closeBracks > openBracks
  5378. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5379. {
  5380. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5381. prefix = prefix.substring (0, openBracks);
  5382. }
  5383. }
  5384. // also use brackets if it ends in a digit.
  5385. putNumbersInBrackets = putNumbersInBrackets
  5386. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5387. do
  5388. {
  5389. if (putNumbersInBrackets)
  5390. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5391. else
  5392. f = getChildFile (prefix + String (num++) + suffix);
  5393. } while (f.exists());
  5394. }
  5395. return f;
  5396. }
  5397. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5398. {
  5399. if (exists())
  5400. {
  5401. return getParentDirectory()
  5402. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5403. getFileExtension(),
  5404. putNumbersInBrackets);
  5405. }
  5406. else
  5407. {
  5408. return *this;
  5409. }
  5410. }
  5411. const String File::getFileExtension() const
  5412. {
  5413. String ext;
  5414. if (! isDirectory())
  5415. {
  5416. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5417. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5418. ext = fullPath.substring (indexOfDot);
  5419. }
  5420. return ext;
  5421. }
  5422. bool File::hasFileExtension (const String& possibleSuffix) const
  5423. {
  5424. if (possibleSuffix.isEmpty())
  5425. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5426. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5427. if (semicolon >= 0)
  5428. {
  5429. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5430. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5431. }
  5432. else
  5433. {
  5434. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5435. {
  5436. if (possibleSuffix.startsWithChar ('.'))
  5437. return true;
  5438. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5439. if (dotPos >= 0)
  5440. return fullPath [dotPos] == '.';
  5441. }
  5442. }
  5443. return false;
  5444. }
  5445. const File File::withFileExtension (const String& newExtension) const
  5446. {
  5447. if (fullPath.isEmpty())
  5448. return File::nonexistent;
  5449. String filePart (getFileName());
  5450. int i = filePart.lastIndexOfChar ('.');
  5451. if (i >= 0)
  5452. filePart = filePart.substring (0, i);
  5453. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5454. filePart << '.';
  5455. return getSiblingFile (filePart + newExtension);
  5456. }
  5457. bool File::startAsProcess (const String& parameters) const
  5458. {
  5459. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5460. }
  5461. FileInputStream* File::createInputStream() const
  5462. {
  5463. if (existsAsFile())
  5464. return new FileInputStream (*this);
  5465. return 0;
  5466. }
  5467. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5468. {
  5469. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5470. if (out->failedToOpen())
  5471. return 0;
  5472. return out.release();
  5473. }
  5474. bool File::appendData (const void* const dataToAppend,
  5475. const int numberOfBytes) const
  5476. {
  5477. if (numberOfBytes > 0)
  5478. {
  5479. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5480. if (out == 0)
  5481. return false;
  5482. out->write (dataToAppend, numberOfBytes);
  5483. }
  5484. return true;
  5485. }
  5486. bool File::replaceWithData (const void* const dataToWrite,
  5487. const int numberOfBytes) const
  5488. {
  5489. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5490. if (numberOfBytes <= 0)
  5491. return deleteFile();
  5492. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5493. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5494. return tempFile.overwriteTargetFileWithTemporary();
  5495. }
  5496. bool File::appendText (const String& text,
  5497. const bool asUnicode,
  5498. const bool writeUnicodeHeaderBytes) const
  5499. {
  5500. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5501. if (out != 0)
  5502. {
  5503. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5504. return true;
  5505. }
  5506. return false;
  5507. }
  5508. bool File::replaceWithText (const String& textToWrite,
  5509. const bool asUnicode,
  5510. const bool writeUnicodeHeaderBytes) const
  5511. {
  5512. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5513. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5514. return tempFile.overwriteTargetFileWithTemporary();
  5515. }
  5516. bool File::hasIdenticalContentTo (const File& other) const
  5517. {
  5518. if (other == *this)
  5519. return true;
  5520. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  5521. {
  5522. FileInputStream in1 (*this), in2 (other);
  5523. const int bufferSize = 4096;
  5524. HeapBlock <char> buffer1, buffer2;
  5525. buffer1.malloc (bufferSize);
  5526. buffer2.malloc (bufferSize);
  5527. for (;;)
  5528. {
  5529. const int num1 = in1.read (buffer1, bufferSize);
  5530. const int num2 = in2.read (buffer2, bufferSize);
  5531. if (num1 != num2)
  5532. break;
  5533. if (num1 <= 0)
  5534. return true;
  5535. if (memcmp (buffer1, buffer2, num1) != 0)
  5536. break;
  5537. }
  5538. }
  5539. return false;
  5540. }
  5541. const String File::createLegalPathName (const String& original)
  5542. {
  5543. String s (original);
  5544. String start;
  5545. if (s[1] == ':')
  5546. {
  5547. start = s.substring (0, 2);
  5548. s = s.substring (2);
  5549. }
  5550. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5551. .substring (0, 1024);
  5552. }
  5553. const String File::createLegalFileName (const String& original)
  5554. {
  5555. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5556. const int maxLength = 128; // only the length of the filename, not the whole path
  5557. const int len = s.length();
  5558. if (len > maxLength)
  5559. {
  5560. const int lastDot = s.lastIndexOfChar ('.');
  5561. if (lastDot > jmax (0, len - 12))
  5562. {
  5563. s = s.substring (0, maxLength - (len - lastDot))
  5564. + s.substring (lastDot);
  5565. }
  5566. else
  5567. {
  5568. s = s.substring (0, maxLength);
  5569. }
  5570. }
  5571. return s;
  5572. }
  5573. const String File::getRelativePathFrom (const File& dir) const
  5574. {
  5575. String thisPath (fullPath);
  5576. {
  5577. int len = thisPath.length();
  5578. while (--len >= 0 && thisPath [len] == File::separator)
  5579. thisPath [len] = 0;
  5580. }
  5581. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5582. : dir.fullPath));
  5583. const int len = jmin (thisPath.length(), dirPath.length());
  5584. int commonBitLength = 0;
  5585. for (int i = 0; i < len; ++i)
  5586. {
  5587. #if NAMES_ARE_CASE_SENSITIVE
  5588. if (thisPath[i] != dirPath[i])
  5589. #else
  5590. if (CharacterFunctions::toLowerCase (thisPath[i])
  5591. != CharacterFunctions::toLowerCase (dirPath[i]))
  5592. #endif
  5593. {
  5594. break;
  5595. }
  5596. ++commonBitLength;
  5597. }
  5598. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5599. --commonBitLength;
  5600. // if the only common bit is the root, then just return the full path..
  5601. if (commonBitLength <= 0
  5602. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5603. return fullPath;
  5604. thisPath = thisPath.substring (commonBitLength);
  5605. dirPath = dirPath.substring (commonBitLength);
  5606. while (dirPath.isNotEmpty())
  5607. {
  5608. #if JUCE_WINDOWS
  5609. thisPath = "..\\" + thisPath;
  5610. #else
  5611. thisPath = "../" + thisPath;
  5612. #endif
  5613. const int sep = dirPath.indexOfChar (separator);
  5614. if (sep >= 0)
  5615. dirPath = dirPath.substring (sep + 1);
  5616. else
  5617. dirPath = String::empty;
  5618. }
  5619. return thisPath;
  5620. }
  5621. const File File::createTempFile (const String& fileNameEnding)
  5622. {
  5623. const File tempFile (getSpecialLocation (tempDirectory)
  5624. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5625. .withFileExtension (fileNameEnding));
  5626. if (tempFile.exists())
  5627. return createTempFile (fileNameEnding);
  5628. else
  5629. return tempFile;
  5630. }
  5631. END_JUCE_NAMESPACE
  5632. /*** End of inlined file: juce_File.cpp ***/
  5633. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5634. BEGIN_JUCE_NAMESPACE
  5635. void* juce_fileOpen (const File& file, bool forWriting);
  5636. void juce_fileClose (void* handle);
  5637. int juce_fileRead (void* handle, void* buffer, int size);
  5638. int64 juce_fileSetPosition (void* handle, int64 pos);
  5639. FileInputStream::FileInputStream (const File& f)
  5640. : file (f),
  5641. currentPosition (0),
  5642. needToSeek (true)
  5643. {
  5644. totalSize = f.getSize();
  5645. fileHandle = juce_fileOpen (f, false);
  5646. }
  5647. FileInputStream::~FileInputStream()
  5648. {
  5649. juce_fileClose (fileHandle);
  5650. }
  5651. int64 FileInputStream::getTotalLength()
  5652. {
  5653. return totalSize;
  5654. }
  5655. int FileInputStream::read (void* buffer, int bytesToRead)
  5656. {
  5657. int num = 0;
  5658. if (needToSeek)
  5659. {
  5660. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5661. return 0;
  5662. needToSeek = false;
  5663. }
  5664. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5665. currentPosition += num;
  5666. return num;
  5667. }
  5668. bool FileInputStream::isExhausted()
  5669. {
  5670. return currentPosition >= totalSize;
  5671. }
  5672. int64 FileInputStream::getPosition()
  5673. {
  5674. return currentPosition;
  5675. }
  5676. bool FileInputStream::setPosition (int64 pos)
  5677. {
  5678. pos = jlimit ((int64) 0, totalSize, pos);
  5679. needToSeek |= (currentPosition != pos);
  5680. currentPosition = pos;
  5681. return true;
  5682. }
  5683. END_JUCE_NAMESPACE
  5684. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5685. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5686. BEGIN_JUCE_NAMESPACE
  5687. void* juce_fileOpen (const File& file, bool forWriting);
  5688. void juce_fileClose (void* handle);
  5689. int juce_fileWrite (void* handle, const void* buffer, int size);
  5690. int64 juce_fileSetPosition (void* handle, int64 pos);
  5691. FileOutputStream::FileOutputStream (const File& f,
  5692. const int bufferSize_)
  5693. : file (f),
  5694. bufferSize (bufferSize_),
  5695. bytesInBuffer (0)
  5696. {
  5697. fileHandle = juce_fileOpen (f, true);
  5698. if (fileHandle != 0)
  5699. {
  5700. currentPosition = getPositionInternal();
  5701. if (currentPosition < 0)
  5702. {
  5703. jassertfalse;
  5704. juce_fileClose (fileHandle);
  5705. fileHandle = 0;
  5706. }
  5707. }
  5708. buffer.malloc (jmax (bufferSize_, 16));
  5709. }
  5710. FileOutputStream::~FileOutputStream()
  5711. {
  5712. flush();
  5713. juce_fileClose (fileHandle);
  5714. }
  5715. int64 FileOutputStream::getPosition()
  5716. {
  5717. return currentPosition;
  5718. }
  5719. bool FileOutputStream::setPosition (int64 newPosition)
  5720. {
  5721. if (newPosition != currentPosition)
  5722. {
  5723. flush();
  5724. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5725. }
  5726. return newPosition == currentPosition;
  5727. }
  5728. void FileOutputStream::flush()
  5729. {
  5730. if (bytesInBuffer > 0)
  5731. {
  5732. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5733. bytesInBuffer = 0;
  5734. }
  5735. flushInternal();
  5736. }
  5737. bool FileOutputStream::write (const void* const src, const int numBytes)
  5738. {
  5739. if (bytesInBuffer + numBytes < bufferSize)
  5740. {
  5741. memcpy (buffer + bytesInBuffer, src, numBytes);
  5742. bytesInBuffer += numBytes;
  5743. currentPosition += numBytes;
  5744. }
  5745. else
  5746. {
  5747. if (bytesInBuffer > 0)
  5748. {
  5749. // flush the reservoir
  5750. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5751. bytesInBuffer = 0;
  5752. if (! wroteOk)
  5753. return false;
  5754. }
  5755. if (numBytes < bufferSize)
  5756. {
  5757. memcpy (buffer + bytesInBuffer, src, numBytes);
  5758. bytesInBuffer += numBytes;
  5759. currentPosition += numBytes;
  5760. }
  5761. else
  5762. {
  5763. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5764. currentPosition += bytesWritten;
  5765. return bytesWritten == numBytes;
  5766. }
  5767. }
  5768. return true;
  5769. }
  5770. END_JUCE_NAMESPACE
  5771. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5772. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5773. BEGIN_JUCE_NAMESPACE
  5774. FileSearchPath::FileSearchPath()
  5775. {
  5776. }
  5777. FileSearchPath::FileSearchPath (const String& path)
  5778. {
  5779. init (path);
  5780. }
  5781. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5782. : directories (other.directories)
  5783. {
  5784. }
  5785. FileSearchPath::~FileSearchPath()
  5786. {
  5787. }
  5788. FileSearchPath& FileSearchPath::operator= (const String& path)
  5789. {
  5790. init (path);
  5791. return *this;
  5792. }
  5793. void FileSearchPath::init (const String& path)
  5794. {
  5795. directories.clear();
  5796. directories.addTokens (path, ";", "\"");
  5797. directories.trim();
  5798. directories.removeEmptyStrings();
  5799. for (int i = directories.size(); --i >= 0;)
  5800. directories.set (i, directories[i].unquoted());
  5801. }
  5802. int FileSearchPath::getNumPaths() const
  5803. {
  5804. return directories.size();
  5805. }
  5806. const File FileSearchPath::operator[] (const int index) const
  5807. {
  5808. return File (directories [index]);
  5809. }
  5810. const String FileSearchPath::toString() const
  5811. {
  5812. StringArray directories2 (directories);
  5813. for (int i = directories2.size(); --i >= 0;)
  5814. if (directories2[i].containsChar (';'))
  5815. directories2.set (i, directories2[i].quoted());
  5816. return directories2.joinIntoString (";");
  5817. }
  5818. void FileSearchPath::add (const File& dir, const int insertIndex)
  5819. {
  5820. directories.insert (insertIndex, dir.getFullPathName());
  5821. }
  5822. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5823. {
  5824. for (int i = 0; i < directories.size(); ++i)
  5825. if (File (directories[i]) == dir)
  5826. return;
  5827. add (dir);
  5828. }
  5829. void FileSearchPath::remove (const int index)
  5830. {
  5831. directories.remove (index);
  5832. }
  5833. void FileSearchPath::addPath (const FileSearchPath& other)
  5834. {
  5835. for (int i = 0; i < other.getNumPaths(); ++i)
  5836. addIfNotAlreadyThere (other[i]);
  5837. }
  5838. void FileSearchPath::removeRedundantPaths()
  5839. {
  5840. for (int i = directories.size(); --i >= 0;)
  5841. {
  5842. const File d1 (directories[i]);
  5843. for (int j = directories.size(); --j >= 0;)
  5844. {
  5845. const File d2 (directories[j]);
  5846. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5847. {
  5848. directories.remove (i);
  5849. break;
  5850. }
  5851. }
  5852. }
  5853. }
  5854. void FileSearchPath::removeNonExistentPaths()
  5855. {
  5856. for (int i = directories.size(); --i >= 0;)
  5857. if (! File (directories[i]).isDirectory())
  5858. directories.remove (i);
  5859. }
  5860. int FileSearchPath::findChildFiles (Array<File>& results,
  5861. const int whatToLookFor,
  5862. const bool searchRecursively,
  5863. const String& wildCardPattern) const
  5864. {
  5865. int total = 0;
  5866. for (int i = 0; i < directories.size(); ++i)
  5867. total += operator[] (i).findChildFiles (results,
  5868. whatToLookFor,
  5869. searchRecursively,
  5870. wildCardPattern);
  5871. return total;
  5872. }
  5873. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5874. const bool checkRecursively) const
  5875. {
  5876. for (int i = directories.size(); --i >= 0;)
  5877. {
  5878. const File d (directories[i]);
  5879. if (checkRecursively)
  5880. {
  5881. if (fileToCheck.isAChildOf (d))
  5882. return true;
  5883. }
  5884. else
  5885. {
  5886. if (fileToCheck.getParentDirectory() == d)
  5887. return true;
  5888. }
  5889. }
  5890. return false;
  5891. }
  5892. END_JUCE_NAMESPACE
  5893. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5894. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5895. BEGIN_JUCE_NAMESPACE
  5896. NamedPipe::NamedPipe()
  5897. : internal (0)
  5898. {
  5899. }
  5900. NamedPipe::~NamedPipe()
  5901. {
  5902. close();
  5903. }
  5904. bool NamedPipe::openExisting (const String& pipeName)
  5905. {
  5906. currentPipeName = pipeName;
  5907. return openInternal (pipeName, false);
  5908. }
  5909. bool NamedPipe::createNewPipe (const String& pipeName)
  5910. {
  5911. currentPipeName = pipeName;
  5912. return openInternal (pipeName, true);
  5913. }
  5914. bool NamedPipe::isOpen() const
  5915. {
  5916. return internal != 0;
  5917. }
  5918. const String NamedPipe::getName() const
  5919. {
  5920. return currentPipeName;
  5921. }
  5922. // other methods for this class are implemented in the platform-specific files
  5923. END_JUCE_NAMESPACE
  5924. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5925. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5926. BEGIN_JUCE_NAMESPACE
  5927. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5928. {
  5929. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5930. "temp_" + String (Random::getSystemRandom().nextInt()),
  5931. suffix,
  5932. optionFlags);
  5933. }
  5934. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5935. : targetFile (targetFile_)
  5936. {
  5937. // If you use this constructor, you need to give it a valid target file!
  5938. jassert (targetFile != File::nonexistent);
  5939. createTempFile (targetFile.getParentDirectory(),
  5940. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5941. targetFile.getFileExtension(),
  5942. optionFlags);
  5943. }
  5944. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5945. const String& suffix, const int optionFlags)
  5946. {
  5947. if ((optionFlags & useHiddenFile) != 0)
  5948. name = "." + name;
  5949. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5950. }
  5951. TemporaryFile::~TemporaryFile()
  5952. {
  5953. // Have a few attempts at deleting the file before giving up..
  5954. for (int i = 5; --i >= 0;)
  5955. {
  5956. if (temporaryFile.deleteFile())
  5957. return;
  5958. Thread::sleep (50);
  5959. }
  5960. // Failed to delete our temporary file! Check that you've deleted all the
  5961. // file output streams that were using it!
  5962. jassertfalse;
  5963. }
  5964. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5965. {
  5966. // This method only works if you created this object with the constructor
  5967. // that takes a target file!
  5968. jassert (targetFile != File::nonexistent);
  5969. if (temporaryFile.exists())
  5970. {
  5971. // Have a few attempts at overwriting the file before giving up..
  5972. for (int i = 5; --i >= 0;)
  5973. {
  5974. if (temporaryFile.moveFileTo (targetFile))
  5975. return true;
  5976. Thread::sleep (100);
  5977. }
  5978. }
  5979. else
  5980. {
  5981. // There's no temporary file to use. If your write failed, you should
  5982. // probably check, and not bother calling this method.
  5983. jassertfalse;
  5984. }
  5985. return false;
  5986. }
  5987. END_JUCE_NAMESPACE
  5988. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5989. /*** Start of inlined file: juce_Socket.cpp ***/
  5990. #if JUCE_WINDOWS
  5991. #include <winsock2.h>
  5992. #if JUCE_MSVC
  5993. #pragma warning (push)
  5994. #pragma warning (disable : 4127 4389 4018)
  5995. #endif
  5996. #else
  5997. #if JUCE_LINUX
  5998. #include <sys/types.h>
  5999. #include <sys/socket.h>
  6000. #include <sys/errno.h>
  6001. #include <unistd.h>
  6002. #include <netinet/in.h>
  6003. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6004. #include <CoreServices/CoreServices.h>
  6005. #endif
  6006. #include <fcntl.h>
  6007. #include <netdb.h>
  6008. #include <arpa/inet.h>
  6009. #include <netinet/tcp.h>
  6010. #endif
  6011. BEGIN_JUCE_NAMESPACE
  6012. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6013. typedef socklen_t juce_socklen_t;
  6014. #else
  6015. typedef int juce_socklen_t;
  6016. #endif
  6017. #if JUCE_WINDOWS
  6018. namespace SocketHelpers
  6019. {
  6020. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6021. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6022. }
  6023. static void initWin32Sockets()
  6024. {
  6025. static CriticalSection lock;
  6026. const ScopedLock sl (lock);
  6027. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6028. {
  6029. WSADATA wsaData;
  6030. const WORD wVersionRequested = MAKEWORD (1, 1);
  6031. WSAStartup (wVersionRequested, &wsaData);
  6032. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6033. }
  6034. }
  6035. void juce_shutdownWin32Sockets()
  6036. {
  6037. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6038. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6039. }
  6040. #endif
  6041. namespace SocketHelpers
  6042. {
  6043. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6044. {
  6045. const int sndBufSize = 65536;
  6046. const int rcvBufSize = 65536;
  6047. const int one = 1;
  6048. return handle > 0
  6049. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6050. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6051. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6052. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6053. }
  6054. static bool bindSocketToPort (const int handle, const int port) throw()
  6055. {
  6056. if (handle <= 0 || port <= 0)
  6057. return false;
  6058. struct sockaddr_in servTmpAddr;
  6059. zerostruct (servTmpAddr);
  6060. servTmpAddr.sin_family = PF_INET;
  6061. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6062. servTmpAddr.sin_port = htons ((uint16) port);
  6063. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6064. }
  6065. static int readSocket (const int handle,
  6066. void* const destBuffer, const int maxBytesToRead,
  6067. bool volatile& connected,
  6068. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6069. {
  6070. int bytesRead = 0;
  6071. while (bytesRead < maxBytesToRead)
  6072. {
  6073. int bytesThisTime;
  6074. #if JUCE_WINDOWS
  6075. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6076. #else
  6077. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6078. && errno == EINTR
  6079. && connected)
  6080. {
  6081. }
  6082. #endif
  6083. if (bytesThisTime <= 0 || ! connected)
  6084. {
  6085. if (bytesRead == 0)
  6086. bytesRead = -1;
  6087. break;
  6088. }
  6089. bytesRead += bytesThisTime;
  6090. if (! blockUntilSpecifiedAmountHasArrived)
  6091. break;
  6092. }
  6093. return bytesRead;
  6094. }
  6095. static int waitForReadiness (const int handle, const bool forReading,
  6096. const int timeoutMsecs) throw()
  6097. {
  6098. struct timeval timeout;
  6099. struct timeval* timeoutp;
  6100. if (timeoutMsecs >= 0)
  6101. {
  6102. timeout.tv_sec = timeoutMsecs / 1000;
  6103. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6104. timeoutp = &timeout;
  6105. }
  6106. else
  6107. {
  6108. timeoutp = 0;
  6109. }
  6110. fd_set rset, wset;
  6111. FD_ZERO (&rset);
  6112. FD_SET (handle, &rset);
  6113. FD_ZERO (&wset);
  6114. FD_SET (handle, &wset);
  6115. fd_set* const prset = forReading ? &rset : 0;
  6116. fd_set* const pwset = forReading ? 0 : &wset;
  6117. #if JUCE_WINDOWS
  6118. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6119. return -1;
  6120. #else
  6121. {
  6122. int result;
  6123. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6124. && errno == EINTR)
  6125. {
  6126. }
  6127. if (result < 0)
  6128. return -1;
  6129. }
  6130. #endif
  6131. {
  6132. int opt;
  6133. juce_socklen_t len = sizeof (opt);
  6134. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6135. || opt != 0)
  6136. return -1;
  6137. }
  6138. if ((forReading && FD_ISSET (handle, &rset))
  6139. || ((! forReading) && FD_ISSET (handle, &wset)))
  6140. return 1;
  6141. return 0;
  6142. }
  6143. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6144. {
  6145. #if JUCE_WINDOWS
  6146. u_long nonBlocking = shouldBlock ? 0 : 1;
  6147. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6148. return false;
  6149. #else
  6150. int socketFlags = fcntl (handle, F_GETFL, 0);
  6151. if (socketFlags == -1)
  6152. return false;
  6153. if (shouldBlock)
  6154. socketFlags &= ~O_NONBLOCK;
  6155. else
  6156. socketFlags |= O_NONBLOCK;
  6157. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6158. return false;
  6159. #endif
  6160. return true;
  6161. }
  6162. static bool connectSocket (int volatile& handle,
  6163. const bool isDatagram,
  6164. void** serverAddress,
  6165. const String& hostName,
  6166. const int portNumber,
  6167. const int timeOutMillisecs) throw()
  6168. {
  6169. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6170. if (hostEnt == 0)
  6171. return false;
  6172. struct in_addr targetAddress;
  6173. memcpy (&targetAddress.s_addr,
  6174. *(hostEnt->h_addr_list),
  6175. sizeof (targetAddress.s_addr));
  6176. struct sockaddr_in servTmpAddr;
  6177. zerostruct (servTmpAddr);
  6178. servTmpAddr.sin_family = PF_INET;
  6179. servTmpAddr.sin_addr = targetAddress;
  6180. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6181. if (handle < 0)
  6182. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6183. if (handle < 0)
  6184. return false;
  6185. if (isDatagram)
  6186. {
  6187. *serverAddress = new struct sockaddr_in();
  6188. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6189. return true;
  6190. }
  6191. setSocketBlockingState (handle, false);
  6192. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6193. if (result < 0)
  6194. {
  6195. #if JUCE_WINDOWS
  6196. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6197. #else
  6198. if (errno == EINPROGRESS)
  6199. #endif
  6200. {
  6201. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6202. {
  6203. setSocketBlockingState (handle, true);
  6204. return false;
  6205. }
  6206. }
  6207. }
  6208. setSocketBlockingState (handle, true);
  6209. resetSocketOptions (handle, false, false);
  6210. return true;
  6211. }
  6212. }
  6213. StreamingSocket::StreamingSocket()
  6214. : portNumber (0),
  6215. handle (-1),
  6216. connected (false),
  6217. isListener (false)
  6218. {
  6219. #if JUCE_WINDOWS
  6220. initWin32Sockets();
  6221. #endif
  6222. }
  6223. StreamingSocket::StreamingSocket (const String& hostName_,
  6224. const int portNumber_,
  6225. const int handle_)
  6226. : hostName (hostName_),
  6227. portNumber (portNumber_),
  6228. handle (handle_),
  6229. connected (true),
  6230. isListener (false)
  6231. {
  6232. #if JUCE_WINDOWS
  6233. initWin32Sockets();
  6234. #endif
  6235. SocketHelpers::resetSocketOptions (handle_, false, false);
  6236. }
  6237. StreamingSocket::~StreamingSocket()
  6238. {
  6239. close();
  6240. }
  6241. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6242. {
  6243. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6244. : -1;
  6245. }
  6246. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6247. {
  6248. if (isListener || ! connected)
  6249. return -1;
  6250. #if JUCE_WINDOWS
  6251. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6252. #else
  6253. int result;
  6254. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6255. && errno == EINTR)
  6256. {
  6257. }
  6258. return result;
  6259. #endif
  6260. }
  6261. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6262. const int timeoutMsecs) const
  6263. {
  6264. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6265. : -1;
  6266. }
  6267. bool StreamingSocket::bindToPort (const int port)
  6268. {
  6269. return SocketHelpers::bindSocketToPort (handle, port);
  6270. }
  6271. bool StreamingSocket::connect (const String& remoteHostName,
  6272. const int remotePortNumber,
  6273. const int timeOutMillisecs)
  6274. {
  6275. if (isListener)
  6276. {
  6277. jassertfalse; // a listener socket can't connect to another one!
  6278. return false;
  6279. }
  6280. if (connected)
  6281. close();
  6282. hostName = remoteHostName;
  6283. portNumber = remotePortNumber;
  6284. isListener = false;
  6285. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  6286. remotePortNumber, timeOutMillisecs);
  6287. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  6288. {
  6289. close();
  6290. return false;
  6291. }
  6292. return true;
  6293. }
  6294. void StreamingSocket::close()
  6295. {
  6296. #if JUCE_WINDOWS
  6297. if (handle != SOCKET_ERROR || connected)
  6298. closesocket (handle);
  6299. connected = false;
  6300. #else
  6301. if (connected)
  6302. {
  6303. connected = false;
  6304. if (isListener)
  6305. {
  6306. // need to do this to interrupt the accept() function..
  6307. StreamingSocket temp;
  6308. temp.connect ("localhost", portNumber, 1000);
  6309. }
  6310. }
  6311. if (handle != -1)
  6312. ::close (handle);
  6313. #endif
  6314. hostName = String::empty;
  6315. portNumber = 0;
  6316. handle = -1;
  6317. isListener = false;
  6318. }
  6319. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6320. {
  6321. if (connected)
  6322. close();
  6323. hostName = "listener";
  6324. portNumber = newPortNumber;
  6325. isListener = true;
  6326. struct sockaddr_in servTmpAddr;
  6327. zerostruct (servTmpAddr);
  6328. servTmpAddr.sin_family = PF_INET;
  6329. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6330. if (localHostName.isNotEmpty())
  6331. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6332. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6333. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6334. if (handle < 0)
  6335. return false;
  6336. const int reuse = 1;
  6337. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6338. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6339. || listen (handle, SOMAXCONN) < 0)
  6340. {
  6341. close();
  6342. return false;
  6343. }
  6344. connected = true;
  6345. return true;
  6346. }
  6347. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6348. {
  6349. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6350. // prepare this socket as a listener.
  6351. if (connected && isListener)
  6352. {
  6353. struct sockaddr address;
  6354. juce_socklen_t len = sizeof (sockaddr);
  6355. const int newSocket = (int) accept (handle, &address, &len);
  6356. if (newSocket >= 0 && connected)
  6357. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6358. portNumber, newSocket);
  6359. }
  6360. return 0;
  6361. }
  6362. bool StreamingSocket::isLocal() const throw()
  6363. {
  6364. return hostName == "127.0.0.1";
  6365. }
  6366. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6367. : portNumber (0),
  6368. handle (-1),
  6369. connected (true),
  6370. allowBroadcast (allowBroadcast_),
  6371. serverAddress (0)
  6372. {
  6373. #if JUCE_WINDOWS
  6374. initWin32Sockets();
  6375. #endif
  6376. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6377. bindToPort (localPortNumber);
  6378. }
  6379. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6380. const int handle_, const int localPortNumber)
  6381. : hostName (hostName_),
  6382. portNumber (portNumber_),
  6383. handle (handle_),
  6384. connected (true),
  6385. allowBroadcast (false),
  6386. serverAddress (0)
  6387. {
  6388. #if JUCE_WINDOWS
  6389. initWin32Sockets();
  6390. #endif
  6391. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  6392. bindToPort (localPortNumber);
  6393. }
  6394. DatagramSocket::~DatagramSocket()
  6395. {
  6396. close();
  6397. delete ((struct sockaddr_in*) serverAddress);
  6398. serverAddress = 0;
  6399. }
  6400. void DatagramSocket::close()
  6401. {
  6402. #if JUCE_WINDOWS
  6403. closesocket (handle);
  6404. connected = false;
  6405. #else
  6406. connected = false;
  6407. ::close (handle);
  6408. #endif
  6409. hostName = String::empty;
  6410. portNumber = 0;
  6411. handle = -1;
  6412. }
  6413. bool DatagramSocket::bindToPort (const int port)
  6414. {
  6415. return SocketHelpers::bindSocketToPort (handle, port);
  6416. }
  6417. bool DatagramSocket::connect (const String& remoteHostName,
  6418. const int remotePortNumber,
  6419. const int timeOutMillisecs)
  6420. {
  6421. if (connected)
  6422. close();
  6423. hostName = remoteHostName;
  6424. portNumber = remotePortNumber;
  6425. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  6426. remoteHostName, remotePortNumber,
  6427. timeOutMillisecs);
  6428. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  6429. {
  6430. close();
  6431. return false;
  6432. }
  6433. return true;
  6434. }
  6435. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6436. {
  6437. struct sockaddr address;
  6438. juce_socklen_t len = sizeof (sockaddr);
  6439. while (waitUntilReady (true, -1) == 1)
  6440. {
  6441. char buf[1];
  6442. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6443. {
  6444. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6445. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6446. -1, -1);
  6447. }
  6448. }
  6449. return 0;
  6450. }
  6451. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6452. const int timeoutMsecs) const
  6453. {
  6454. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6455. : -1;
  6456. }
  6457. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6458. {
  6459. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6460. : -1;
  6461. }
  6462. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6463. {
  6464. // You need to call connect() first to set the server address..
  6465. jassert (serverAddress != 0 && connected);
  6466. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6467. numBytesToWrite, 0,
  6468. (const struct sockaddr*) serverAddress,
  6469. sizeof (struct sockaddr_in))
  6470. : -1;
  6471. }
  6472. bool DatagramSocket::isLocal() const throw()
  6473. {
  6474. return hostName == "127.0.0.1";
  6475. }
  6476. #if JUCE_MSVC
  6477. #pragma warning (pop)
  6478. #endif
  6479. END_JUCE_NAMESPACE
  6480. /*** End of inlined file: juce_Socket.cpp ***/
  6481. /*** Start of inlined file: juce_URL.cpp ***/
  6482. BEGIN_JUCE_NAMESPACE
  6483. URL::URL()
  6484. {
  6485. }
  6486. URL::URL (const String& url_)
  6487. : url (url_)
  6488. {
  6489. int i = url.indexOfChar ('?');
  6490. if (i >= 0)
  6491. {
  6492. do
  6493. {
  6494. const int nextAmp = url.indexOfChar (i + 1, '&');
  6495. const int equalsPos = url.indexOfChar (i + 1, '=');
  6496. if (equalsPos > i + 1)
  6497. {
  6498. if (nextAmp < 0)
  6499. {
  6500. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6501. removeEscapeChars (url.substring (equalsPos + 1)));
  6502. }
  6503. else if (nextAmp > 0 && equalsPos < nextAmp)
  6504. {
  6505. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6506. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6507. }
  6508. }
  6509. i = nextAmp;
  6510. }
  6511. while (i >= 0);
  6512. url = url.upToFirstOccurrenceOf ("?", false, false);
  6513. }
  6514. }
  6515. URL::URL (const URL& other)
  6516. : url (other.url),
  6517. postData (other.postData),
  6518. parameters (other.parameters),
  6519. filesToUpload (other.filesToUpload),
  6520. mimeTypes (other.mimeTypes)
  6521. {
  6522. }
  6523. URL& URL::operator= (const URL& other)
  6524. {
  6525. url = other.url;
  6526. postData = other.postData;
  6527. parameters = other.parameters;
  6528. filesToUpload = other.filesToUpload;
  6529. mimeTypes = other.mimeTypes;
  6530. return *this;
  6531. }
  6532. URL::~URL()
  6533. {
  6534. }
  6535. static const String getMangledParameters (const StringPairArray& parameters)
  6536. {
  6537. String p;
  6538. for (int i = 0; i < parameters.size(); ++i)
  6539. {
  6540. if (i > 0)
  6541. p += '&';
  6542. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6543. << '='
  6544. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6545. }
  6546. return p;
  6547. }
  6548. const String URL::toString (const bool includeGetParameters) const
  6549. {
  6550. if (includeGetParameters && parameters.size() > 0)
  6551. return url + "?" + getMangledParameters (parameters);
  6552. else
  6553. return url;
  6554. }
  6555. bool URL::isWellFormed() const
  6556. {
  6557. //xxx TODO
  6558. return url.isNotEmpty();
  6559. }
  6560. static int findStartOfDomain (const String& url)
  6561. {
  6562. int i = 0;
  6563. while (CharacterFunctions::isLetterOrDigit (url[i])
  6564. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6565. ++i;
  6566. return url[i] == ':' ? i + 1 : 0;
  6567. }
  6568. const String URL::getDomain() const
  6569. {
  6570. int start = findStartOfDomain (url);
  6571. while (url[start] == '/')
  6572. ++start;
  6573. const int end1 = url.indexOfChar (start, '/');
  6574. const int end2 = url.indexOfChar (start, ':');
  6575. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6576. : jmin (end1, end2);
  6577. return url.substring (start, end);
  6578. }
  6579. const String URL::getSubPath() const
  6580. {
  6581. int start = findStartOfDomain (url);
  6582. while (url[start] == '/')
  6583. ++start;
  6584. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6585. return startOfPath <= 0 ? String::empty
  6586. : url.substring (startOfPath);
  6587. }
  6588. const String URL::getScheme() const
  6589. {
  6590. return url.substring (0, findStartOfDomain (url) - 1);
  6591. }
  6592. const URL URL::withNewSubPath (const String& newPath) const
  6593. {
  6594. int start = findStartOfDomain (url);
  6595. while (url[start] == '/')
  6596. ++start;
  6597. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6598. URL u (*this);
  6599. if (startOfPath > 0)
  6600. u.url = url.substring (0, startOfPath);
  6601. if (! u.url.endsWithChar ('/'))
  6602. u.url << '/';
  6603. if (newPath.startsWithChar ('/'))
  6604. u.url << newPath.substring (1);
  6605. else
  6606. u.url << newPath;
  6607. return u;
  6608. }
  6609. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6610. {
  6611. if (possibleURL.startsWithIgnoreCase ("http:")
  6612. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6613. return true;
  6614. if (possibleURL.startsWithIgnoreCase ("file:")
  6615. || possibleURL.containsChar ('@')
  6616. || possibleURL.endsWithChar ('.')
  6617. || (! possibleURL.containsChar ('.')))
  6618. return false;
  6619. if (possibleURL.startsWithIgnoreCase ("www.")
  6620. && possibleURL.substring (5).containsChar ('.'))
  6621. return true;
  6622. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6623. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6624. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6625. return true;
  6626. return false;
  6627. }
  6628. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6629. {
  6630. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6631. return atSign > 0
  6632. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6633. && (! possibleEmailAddress.endsWithChar ('.'));
  6634. }
  6635. void* juce_openInternetFile (const String& url,
  6636. const String& headers,
  6637. const MemoryBlock& optionalPostData,
  6638. const bool isPost,
  6639. URL::OpenStreamProgressCallback* callback,
  6640. void* callbackContext,
  6641. int timeOutMs);
  6642. void juce_closeInternetFile (void* handle);
  6643. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6644. int juce_seekInInternetFile (void* handle, int newPosition);
  6645. int64 juce_getInternetFileContentLength (void* handle);
  6646. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  6647. class WebInputStream : public InputStream
  6648. {
  6649. public:
  6650. WebInputStream (const URL& url,
  6651. const bool isPost_,
  6652. URL::OpenStreamProgressCallback* const progressCallback_,
  6653. void* const progressCallbackContext_,
  6654. const String& extraHeaders,
  6655. const int timeOutMs_,
  6656. StringPairArray* const responseHeaders)
  6657. : position (0),
  6658. finished (false),
  6659. isPost (isPost_),
  6660. progressCallback (progressCallback_),
  6661. progressCallbackContext (progressCallbackContext_),
  6662. timeOutMs (timeOutMs_)
  6663. {
  6664. server = url.toString (! isPost);
  6665. if (isPost_)
  6666. createHeadersAndPostData (url);
  6667. headers += extraHeaders;
  6668. if (! headers.endsWithChar ('\n'))
  6669. headers << "\r\n";
  6670. handle = juce_openInternetFile (server, headers, postData, isPost,
  6671. progressCallback_, progressCallbackContext_,
  6672. timeOutMs);
  6673. if (responseHeaders != 0)
  6674. juce_getInternetFileHeaders (handle, *responseHeaders);
  6675. }
  6676. ~WebInputStream()
  6677. {
  6678. juce_closeInternetFile (handle);
  6679. }
  6680. bool isError() const { return handle == 0; }
  6681. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6682. bool isExhausted() { return finished; }
  6683. int64 getPosition() { return position; }
  6684. int read (void* dest, int bytes)
  6685. {
  6686. if (finished || isError())
  6687. {
  6688. return 0;
  6689. }
  6690. else
  6691. {
  6692. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6693. position += bytesRead;
  6694. if (bytesRead == 0)
  6695. finished = true;
  6696. return bytesRead;
  6697. }
  6698. }
  6699. bool setPosition (int64 wantedPos)
  6700. {
  6701. if (wantedPos != position)
  6702. {
  6703. finished = false;
  6704. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6705. if (actualPos == wantedPos)
  6706. {
  6707. position = wantedPos;
  6708. }
  6709. else
  6710. {
  6711. if (wantedPos < position)
  6712. {
  6713. juce_closeInternetFile (handle);
  6714. position = 0;
  6715. finished = false;
  6716. handle = juce_openInternetFile (server, headers, postData, isPost,
  6717. progressCallback, progressCallbackContext,
  6718. timeOutMs);
  6719. }
  6720. skipNextBytes (wantedPos - position);
  6721. }
  6722. }
  6723. return true;
  6724. }
  6725. juce_UseDebuggingNewOperator
  6726. private:
  6727. String server, headers;
  6728. MemoryBlock postData;
  6729. int64 position;
  6730. bool finished;
  6731. const bool isPost;
  6732. void* handle;
  6733. URL::OpenStreamProgressCallback* const progressCallback;
  6734. void* const progressCallbackContext;
  6735. const int timeOutMs;
  6736. void createHeadersAndPostData (const URL& url)
  6737. {
  6738. MemoryOutputStream data (postData, false);
  6739. if (url.getFilesToUpload().size() > 0)
  6740. {
  6741. // need to upload some files, so do it as multi-part...
  6742. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6743. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6744. data << "--" << boundary;
  6745. int i;
  6746. for (i = 0; i < url.getParameters().size(); ++i)
  6747. {
  6748. data << "\r\nContent-Disposition: form-data; name=\""
  6749. << url.getParameters().getAllKeys() [i]
  6750. << "\"\r\n\r\n"
  6751. << url.getParameters().getAllValues() [i]
  6752. << "\r\n--"
  6753. << boundary;
  6754. }
  6755. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6756. {
  6757. const File file (url.getFilesToUpload().getAllValues() [i]);
  6758. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6759. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6760. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6761. const String mimeType (url.getMimeTypesOfUploadFiles()
  6762. .getValue (paramName, String::empty));
  6763. if (mimeType.isNotEmpty())
  6764. data << "Content-Type: " << mimeType << "\r\n";
  6765. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6766. << file << "\r\n--" << boundary;
  6767. }
  6768. data << "--\r\n";
  6769. data.flush();
  6770. }
  6771. else
  6772. {
  6773. data << getMangledParameters (url.getParameters())
  6774. << url.getPostData();
  6775. data.flush();
  6776. // just a short text attachment, so use simple url encoding..
  6777. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6778. + String ((unsigned int) postData.getSize())
  6779. + "\r\n";
  6780. }
  6781. }
  6782. WebInputStream (const WebInputStream&);
  6783. WebInputStream& operator= (const WebInputStream&);
  6784. };
  6785. InputStream* URL::createInputStream (const bool usePostCommand,
  6786. OpenStreamProgressCallback* const progressCallback,
  6787. void* const progressCallbackContext,
  6788. const String& extraHeaders,
  6789. const int timeOutMs,
  6790. StringPairArray* const responseHeaders) const
  6791. {
  6792. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6793. progressCallback, progressCallbackContext,
  6794. extraHeaders, timeOutMs, responseHeaders));
  6795. return wi->isError() ? 0 : wi.release();
  6796. }
  6797. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6798. const bool usePostCommand) const
  6799. {
  6800. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6801. if (in != 0)
  6802. {
  6803. in->readIntoMemoryBlock (destData);
  6804. return true;
  6805. }
  6806. return false;
  6807. }
  6808. const String URL::readEntireTextStream (const bool usePostCommand) const
  6809. {
  6810. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6811. if (in != 0)
  6812. return in->readEntireStreamAsString();
  6813. return String::empty;
  6814. }
  6815. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6816. {
  6817. XmlDocument doc (readEntireTextStream (usePostCommand));
  6818. return doc.getDocumentElement();
  6819. }
  6820. const URL URL::withParameter (const String& parameterName,
  6821. const String& parameterValue) const
  6822. {
  6823. URL u (*this);
  6824. u.parameters.set (parameterName, parameterValue);
  6825. return u;
  6826. }
  6827. const URL URL::withFileToUpload (const String& parameterName,
  6828. const File& fileToUpload,
  6829. const String& mimeType) const
  6830. {
  6831. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6832. URL u (*this);
  6833. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6834. u.mimeTypes.set (parameterName, mimeType);
  6835. return u;
  6836. }
  6837. const URL URL::withPOSTData (const String& postData_) const
  6838. {
  6839. URL u (*this);
  6840. u.postData = postData_;
  6841. return u;
  6842. }
  6843. const StringPairArray& URL::getParameters() const
  6844. {
  6845. return parameters;
  6846. }
  6847. const StringPairArray& URL::getFilesToUpload() const
  6848. {
  6849. return filesToUpload;
  6850. }
  6851. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6852. {
  6853. return mimeTypes;
  6854. }
  6855. const String URL::removeEscapeChars (const String& s)
  6856. {
  6857. String result (s.replaceCharacter ('+', ' '));
  6858. int nextPercent = 0;
  6859. for (;;)
  6860. {
  6861. nextPercent = result.indexOfChar (nextPercent, '%');
  6862. if (nextPercent < 0)
  6863. break;
  6864. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6865. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6866. ++nextPercent;
  6867. }
  6868. return result;
  6869. }
  6870. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6871. {
  6872. String result;
  6873. result.preallocateStorage (s.length() + 8);
  6874. const char* utf8 = s.toUTF8();
  6875. const char* legalChars = isParameter ? "_-.*!'()"
  6876. : "_-$.*!'(),";
  6877. while (*utf8 != 0)
  6878. {
  6879. const char c = *utf8++;
  6880. if (CharacterFunctions::isLetterOrDigit (c)
  6881. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6882. {
  6883. result << c;
  6884. }
  6885. else
  6886. {
  6887. const int v = (int) (uint8) c;
  6888. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6889. }
  6890. }
  6891. return result;
  6892. }
  6893. bool URL::launchInDefaultBrowser() const
  6894. {
  6895. String u (toString (true));
  6896. if (u.containsChar ('@') && ! u.containsChar (':'))
  6897. u = "mailto:" + u;
  6898. return PlatformUtilities::openDocument (u, String::empty);
  6899. }
  6900. END_JUCE_NAMESPACE
  6901. /*** End of inlined file: juce_URL.cpp ***/
  6902. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6903. BEGIN_JUCE_NAMESPACE
  6904. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6905. const int bufferSize_,
  6906. const bool deleteSourceWhenDestroyed)
  6907. : source (source_),
  6908. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6909. bufferSize (jmax (256, bufferSize_)),
  6910. position (source_->getPosition()),
  6911. lastReadPos (0),
  6912. bufferOverlap (128)
  6913. {
  6914. const int sourceSize = (int) source_->getTotalLength();
  6915. if (sourceSize >= 0)
  6916. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6917. bufferStart = position;
  6918. buffer.malloc (bufferSize);
  6919. }
  6920. BufferedInputStream::~BufferedInputStream()
  6921. {
  6922. }
  6923. int64 BufferedInputStream::getTotalLength()
  6924. {
  6925. return source->getTotalLength();
  6926. }
  6927. int64 BufferedInputStream::getPosition()
  6928. {
  6929. return position;
  6930. }
  6931. bool BufferedInputStream::setPosition (int64 newPosition)
  6932. {
  6933. position = jmax ((int64) 0, newPosition);
  6934. return true;
  6935. }
  6936. bool BufferedInputStream::isExhausted()
  6937. {
  6938. return (position >= lastReadPos)
  6939. && source->isExhausted();
  6940. }
  6941. void BufferedInputStream::ensureBuffered()
  6942. {
  6943. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6944. if (position < bufferStart || position >= bufferEndOverlap)
  6945. {
  6946. int bytesRead;
  6947. if (position < lastReadPos
  6948. && position >= bufferEndOverlap
  6949. && position >= bufferStart)
  6950. {
  6951. const int bytesToKeep = (int) (lastReadPos - position);
  6952. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6953. bufferStart = position;
  6954. bytesRead = source->read (buffer + bytesToKeep,
  6955. bufferSize - bytesToKeep);
  6956. lastReadPos += bytesRead;
  6957. bytesRead += bytesToKeep;
  6958. }
  6959. else
  6960. {
  6961. bufferStart = position;
  6962. source->setPosition (bufferStart);
  6963. bytesRead = source->read (buffer, bufferSize);
  6964. lastReadPos = bufferStart + bytesRead;
  6965. }
  6966. while (bytesRead < bufferSize)
  6967. buffer [bytesRead++] = 0;
  6968. }
  6969. }
  6970. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6971. {
  6972. if (position >= bufferStart
  6973. && position + maxBytesToRead <= lastReadPos)
  6974. {
  6975. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6976. position += maxBytesToRead;
  6977. return maxBytesToRead;
  6978. }
  6979. else
  6980. {
  6981. if (position < bufferStart || position >= lastReadPos)
  6982. ensureBuffered();
  6983. int bytesRead = 0;
  6984. while (maxBytesToRead > 0)
  6985. {
  6986. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6987. if (bytesAvailable > 0)
  6988. {
  6989. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6990. maxBytesToRead -= bytesAvailable;
  6991. bytesRead += bytesAvailable;
  6992. position += bytesAvailable;
  6993. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6994. }
  6995. const int64 oldLastReadPos = lastReadPos;
  6996. ensureBuffered();
  6997. if (oldLastReadPos == lastReadPos)
  6998. break; // if ensureBuffered() failed to read any more data, bail out
  6999. if (isExhausted())
  7000. break;
  7001. }
  7002. return bytesRead;
  7003. }
  7004. }
  7005. const String BufferedInputStream::readString()
  7006. {
  7007. if (position >= bufferStart
  7008. && position < lastReadPos)
  7009. {
  7010. const int maxChars = (int) (lastReadPos - position);
  7011. const char* const src = buffer + (int) (position - bufferStart);
  7012. for (int i = 0; i < maxChars; ++i)
  7013. {
  7014. if (src[i] == 0)
  7015. {
  7016. position += i + 1;
  7017. return String::fromUTF8 (src, i);
  7018. }
  7019. }
  7020. }
  7021. return InputStream::readString();
  7022. }
  7023. END_JUCE_NAMESPACE
  7024. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7025. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7026. BEGIN_JUCE_NAMESPACE
  7027. FileInputSource::FileInputSource (const File& file_)
  7028. : file (file_)
  7029. {
  7030. }
  7031. FileInputSource::~FileInputSource()
  7032. {
  7033. }
  7034. InputStream* FileInputSource::createInputStream()
  7035. {
  7036. return file.createInputStream();
  7037. }
  7038. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7039. {
  7040. return file.getSiblingFile (relatedItemPath).createInputStream();
  7041. }
  7042. int64 FileInputSource::hashCode() const
  7043. {
  7044. return file.hashCode();
  7045. }
  7046. END_JUCE_NAMESPACE
  7047. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7048. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7049. BEGIN_JUCE_NAMESPACE
  7050. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7051. const size_t sourceDataSize,
  7052. const bool keepInternalCopy)
  7053. : data (static_cast <const char*> (sourceData)),
  7054. dataSize (sourceDataSize),
  7055. position (0)
  7056. {
  7057. if (keepInternalCopy)
  7058. {
  7059. internalCopy.append (data, sourceDataSize);
  7060. data = static_cast <const char*> (internalCopy.getData());
  7061. }
  7062. }
  7063. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7064. const bool keepInternalCopy)
  7065. : data (static_cast <const char*> (sourceData.getData())),
  7066. dataSize (sourceData.getSize()),
  7067. position (0)
  7068. {
  7069. if (keepInternalCopy)
  7070. {
  7071. internalCopy = sourceData;
  7072. data = static_cast <const char*> (internalCopy.getData());
  7073. }
  7074. }
  7075. MemoryInputStream::~MemoryInputStream()
  7076. {
  7077. }
  7078. int64 MemoryInputStream::getTotalLength()
  7079. {
  7080. return dataSize;
  7081. }
  7082. int MemoryInputStream::read (void* const buffer, const int howMany)
  7083. {
  7084. jassert (howMany >= 0);
  7085. const int num = jmin (howMany, (int) (dataSize - position));
  7086. memcpy (buffer, data + position, num);
  7087. position += num;
  7088. return (int) num;
  7089. }
  7090. bool MemoryInputStream::isExhausted()
  7091. {
  7092. return (position >= dataSize);
  7093. }
  7094. bool MemoryInputStream::setPosition (const int64 pos)
  7095. {
  7096. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7097. return true;
  7098. }
  7099. int64 MemoryInputStream::getPosition()
  7100. {
  7101. return position;
  7102. }
  7103. END_JUCE_NAMESPACE
  7104. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7105. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7106. BEGIN_JUCE_NAMESPACE
  7107. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  7108. : data (internalBlock),
  7109. position (0),
  7110. size (0)
  7111. {
  7112. internalBlock.setSize (initialSize, false);
  7113. }
  7114. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  7115. const bool appendToExistingBlockContent)
  7116. : data (memoryBlockToWriteTo),
  7117. position (0),
  7118. size (0)
  7119. {
  7120. if (appendToExistingBlockContent)
  7121. position = size = memoryBlockToWriteTo.getSize();
  7122. }
  7123. MemoryOutputStream::~MemoryOutputStream()
  7124. {
  7125. flush();
  7126. }
  7127. void MemoryOutputStream::flush()
  7128. {
  7129. if (&data != &internalBlock)
  7130. data.setSize (size, false);
  7131. }
  7132. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  7133. {
  7134. data.ensureSize (bytesToPreallocate + 1);
  7135. }
  7136. void MemoryOutputStream::reset() throw()
  7137. {
  7138. position = 0;
  7139. size = 0;
  7140. }
  7141. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7142. {
  7143. if (howMany > 0)
  7144. {
  7145. const size_t storageNeeded = position + howMany;
  7146. if (storageNeeded >= data.getSize())
  7147. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  7148. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  7149. position += howMany;
  7150. size = jmax (size, position);
  7151. }
  7152. return true;
  7153. }
  7154. const void* MemoryOutputStream::getData() const throw()
  7155. {
  7156. void* const d = data.getData();
  7157. if (data.getSize() > size)
  7158. static_cast <char*> (d) [size] = 0;
  7159. return d;
  7160. }
  7161. bool MemoryOutputStream::setPosition (int64 newPosition)
  7162. {
  7163. if (newPosition <= (int64) size)
  7164. {
  7165. // ok to seek backwards
  7166. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7167. return true;
  7168. }
  7169. else
  7170. {
  7171. // trying to make it bigger isn't a good thing to do..
  7172. return false;
  7173. }
  7174. }
  7175. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  7176. {
  7177. // before writing from an input, see if we can preallocate to make it more efficient..
  7178. int64 availableData = source.getTotalLength() - source.getPosition();
  7179. if (availableData > 0)
  7180. {
  7181. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  7182. availableData = maxNumBytesToWrite;
  7183. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  7184. }
  7185. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  7186. }
  7187. const String MemoryOutputStream::toUTF8() const
  7188. {
  7189. return String (static_cast <const char*> (getData()), getDataSize());
  7190. }
  7191. const String MemoryOutputStream::toString() const
  7192. {
  7193. return String::createStringFromData (getData(), getDataSize());
  7194. }
  7195. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  7196. {
  7197. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  7198. return stream;
  7199. }
  7200. END_JUCE_NAMESPACE
  7201. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7202. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7203. BEGIN_JUCE_NAMESPACE
  7204. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7205. const int64 startPositionInSourceStream_,
  7206. const int64 lengthOfSourceStream_,
  7207. const bool deleteSourceWhenDestroyed)
  7208. : source (sourceStream),
  7209. startPositionInSourceStream (startPositionInSourceStream_),
  7210. lengthOfSourceStream (lengthOfSourceStream_)
  7211. {
  7212. if (deleteSourceWhenDestroyed)
  7213. sourceToDelete = source;
  7214. setPosition (0);
  7215. }
  7216. SubregionStream::~SubregionStream()
  7217. {
  7218. }
  7219. int64 SubregionStream::getTotalLength()
  7220. {
  7221. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7222. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7223. : srcLen;
  7224. }
  7225. int64 SubregionStream::getPosition()
  7226. {
  7227. return source->getPosition() - startPositionInSourceStream;
  7228. }
  7229. bool SubregionStream::setPosition (int64 newPosition)
  7230. {
  7231. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7232. }
  7233. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7234. {
  7235. if (lengthOfSourceStream < 0)
  7236. {
  7237. return source->read (destBuffer, maxBytesToRead);
  7238. }
  7239. else
  7240. {
  7241. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7242. if (maxBytesToRead <= 0)
  7243. return 0;
  7244. return source->read (destBuffer, maxBytesToRead);
  7245. }
  7246. }
  7247. bool SubregionStream::isExhausted()
  7248. {
  7249. if (lengthOfSourceStream >= 0)
  7250. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7251. else
  7252. return source->isExhausted();
  7253. }
  7254. END_JUCE_NAMESPACE
  7255. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7256. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7257. BEGIN_JUCE_NAMESPACE
  7258. PerformanceCounter::PerformanceCounter (const String& name_,
  7259. int runsPerPrintout,
  7260. const File& loggingFile)
  7261. : name (name_),
  7262. numRuns (0),
  7263. runsPerPrint (runsPerPrintout),
  7264. totalTime (0),
  7265. outputFile (loggingFile)
  7266. {
  7267. if (outputFile != File::nonexistent)
  7268. {
  7269. String s ("**** Counter for \"");
  7270. s << name_ << "\" started at: "
  7271. << Time::getCurrentTime().toString (true, true)
  7272. << "\r\n";
  7273. outputFile.appendText (s, false, false);
  7274. }
  7275. }
  7276. PerformanceCounter::~PerformanceCounter()
  7277. {
  7278. printStatistics();
  7279. }
  7280. void PerformanceCounter::start()
  7281. {
  7282. started = Time::getHighResolutionTicks();
  7283. }
  7284. void PerformanceCounter::stop()
  7285. {
  7286. const int64 now = Time::getHighResolutionTicks();
  7287. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7288. if (++numRuns == runsPerPrint)
  7289. printStatistics();
  7290. }
  7291. void PerformanceCounter::printStatistics()
  7292. {
  7293. if (numRuns > 0)
  7294. {
  7295. String s ("Performance count for \"");
  7296. s << name << "\" - average over " << numRuns << " run(s) = ";
  7297. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7298. if (micros > 10000)
  7299. s << (micros/1000) << " millisecs";
  7300. else
  7301. s << micros << " microsecs";
  7302. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7303. Logger::outputDebugString (s);
  7304. s << "\r\n";
  7305. if (outputFile != File::nonexistent)
  7306. outputFile.appendText (s, false, false);
  7307. numRuns = 0;
  7308. totalTime = 0;
  7309. }
  7310. }
  7311. END_JUCE_NAMESPACE
  7312. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7313. /*** Start of inlined file: juce_Uuid.cpp ***/
  7314. BEGIN_JUCE_NAMESPACE
  7315. Uuid::Uuid()
  7316. {
  7317. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7318. // to make it very very unlikely that two UUIDs will ever be the same..
  7319. static int64 macAddresses[2];
  7320. static bool hasCheckedMacAddresses = false;
  7321. if (! hasCheckedMacAddresses)
  7322. {
  7323. hasCheckedMacAddresses = true;
  7324. SystemStats::getMACAddresses (macAddresses, 2);
  7325. }
  7326. value.asInt64[0] = macAddresses[0];
  7327. value.asInt64[1] = macAddresses[1];
  7328. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7329. // whose seed will carry over between calls to this method.
  7330. Random r (macAddresses[0] ^ macAddresses[1]
  7331. ^ Random::getSystemRandom().nextInt64());
  7332. for (int i = 4; --i >= 0;)
  7333. {
  7334. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7335. value.asInt[i] ^= r.nextInt();
  7336. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7337. }
  7338. }
  7339. Uuid::~Uuid() throw()
  7340. {
  7341. }
  7342. Uuid::Uuid (const Uuid& other)
  7343. : value (other.value)
  7344. {
  7345. }
  7346. Uuid& Uuid::operator= (const Uuid& other)
  7347. {
  7348. value = other.value;
  7349. return *this;
  7350. }
  7351. bool Uuid::operator== (const Uuid& other) const
  7352. {
  7353. return value.asInt64[0] == other.value.asInt64[0]
  7354. && value.asInt64[1] == other.value.asInt64[1];
  7355. }
  7356. bool Uuid::operator!= (const Uuid& other) const
  7357. {
  7358. return ! operator== (other);
  7359. }
  7360. bool Uuid::isNull() const throw()
  7361. {
  7362. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7363. }
  7364. const String Uuid::toString() const
  7365. {
  7366. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7367. }
  7368. Uuid::Uuid (const String& uuidString)
  7369. {
  7370. operator= (uuidString);
  7371. }
  7372. Uuid& Uuid::operator= (const String& uuidString)
  7373. {
  7374. MemoryBlock mb;
  7375. mb.loadFromHexString (uuidString);
  7376. mb.ensureSize (sizeof (value.asBytes), true);
  7377. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7378. return *this;
  7379. }
  7380. Uuid::Uuid (const uint8* const rawData)
  7381. {
  7382. operator= (rawData);
  7383. }
  7384. Uuid& Uuid::operator= (const uint8* const rawData)
  7385. {
  7386. if (rawData != 0)
  7387. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7388. else
  7389. zeromem (value.asBytes, sizeof (value.asBytes));
  7390. return *this;
  7391. }
  7392. END_JUCE_NAMESPACE
  7393. /*** End of inlined file: juce_Uuid.cpp ***/
  7394. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7395. BEGIN_JUCE_NAMESPACE
  7396. class ZipFile::ZipEntryInfo
  7397. {
  7398. public:
  7399. ZipFile::ZipEntry entry;
  7400. int streamOffset;
  7401. int compressedSize;
  7402. bool compressed;
  7403. };
  7404. class ZipFile::ZipInputStream : public InputStream
  7405. {
  7406. public:
  7407. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7408. : file (file_),
  7409. zipEntryInfo (zei),
  7410. pos (0),
  7411. headerSize (0),
  7412. inputStream (0)
  7413. {
  7414. inputStream = file_.inputStream;
  7415. if (file_.inputSource != 0)
  7416. {
  7417. inputStream = file.inputSource->createInputStream();
  7418. }
  7419. else
  7420. {
  7421. #if JUCE_DEBUG
  7422. file_.numOpenStreams++;
  7423. #endif
  7424. }
  7425. char buffer [30];
  7426. if (inputStream != 0
  7427. && inputStream->setPosition (zei.streamOffset)
  7428. && inputStream->read (buffer, 30) == 30
  7429. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7430. {
  7431. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7432. + ByteOrder::littleEndianShort (buffer + 28);
  7433. }
  7434. }
  7435. ~ZipInputStream()
  7436. {
  7437. #if JUCE_DEBUG
  7438. if (inputStream != 0 && inputStream == file.inputStream)
  7439. file.numOpenStreams--;
  7440. #endif
  7441. if (inputStream != file.inputStream)
  7442. delete inputStream;
  7443. }
  7444. int64 getTotalLength()
  7445. {
  7446. return zipEntryInfo.compressedSize;
  7447. }
  7448. int read (void* buffer, int howMany)
  7449. {
  7450. if (headerSize <= 0)
  7451. return 0;
  7452. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7453. if (inputStream == 0)
  7454. return 0;
  7455. int num;
  7456. if (inputStream == file.inputStream)
  7457. {
  7458. const ScopedLock sl (file.lock);
  7459. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7460. num = inputStream->read (buffer, howMany);
  7461. }
  7462. else
  7463. {
  7464. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7465. num = inputStream->read (buffer, howMany);
  7466. }
  7467. pos += num;
  7468. return num;
  7469. }
  7470. bool isExhausted()
  7471. {
  7472. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7473. }
  7474. int64 getPosition()
  7475. {
  7476. return pos;
  7477. }
  7478. bool setPosition (int64 newPos)
  7479. {
  7480. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7481. return true;
  7482. }
  7483. private:
  7484. ZipFile& file;
  7485. ZipEntryInfo zipEntryInfo;
  7486. int64 pos;
  7487. int headerSize;
  7488. InputStream* inputStream;
  7489. ZipInputStream (const ZipInputStream&);
  7490. ZipInputStream& operator= (const ZipInputStream&);
  7491. };
  7492. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  7493. : inputStream (source_)
  7494. #if JUCE_DEBUG
  7495. , numOpenStreams (0)
  7496. #endif
  7497. {
  7498. if (deleteStreamWhenDestroyed)
  7499. streamToDelete = inputStream;
  7500. init();
  7501. }
  7502. ZipFile::ZipFile (const File& file)
  7503. : inputStream (0)
  7504. #if JUCE_DEBUG
  7505. , numOpenStreams (0)
  7506. #endif
  7507. {
  7508. inputSource = new FileInputSource (file);
  7509. init();
  7510. }
  7511. ZipFile::ZipFile (InputSource* const inputSource_)
  7512. : inputStream (0),
  7513. inputSource (inputSource_)
  7514. #if JUCE_DEBUG
  7515. , numOpenStreams (0)
  7516. #endif
  7517. {
  7518. init();
  7519. }
  7520. ZipFile::~ZipFile()
  7521. {
  7522. #if JUCE_DEBUG
  7523. entries.clear();
  7524. // If you hit this assertion, it means you've created a stream to read
  7525. // one of the items in the zipfile, but you've forgotten to delete that
  7526. // stream object before deleting the file.. Streams can't be kept open
  7527. // after the file is deleted because they need to share the input
  7528. // stream that the file uses to read itself.
  7529. jassert (numOpenStreams == 0);
  7530. #endif
  7531. }
  7532. int ZipFile::getNumEntries() const throw()
  7533. {
  7534. return entries.size();
  7535. }
  7536. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7537. {
  7538. ZipEntryInfo* const zei = entries [index];
  7539. return zei != 0 ? &(zei->entry) : 0;
  7540. }
  7541. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7542. {
  7543. for (int i = 0; i < entries.size(); ++i)
  7544. if (entries.getUnchecked (i)->entry.filename == fileName)
  7545. return i;
  7546. return -1;
  7547. }
  7548. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7549. {
  7550. return getEntry (getIndexOfFileName (fileName));
  7551. }
  7552. InputStream* ZipFile::createStreamForEntry (const int index)
  7553. {
  7554. ZipEntryInfo* const zei = entries[index];
  7555. InputStream* stream = 0;
  7556. if (zei != 0)
  7557. {
  7558. stream = new ZipInputStream (*this, *zei);
  7559. if (zei->compressed)
  7560. {
  7561. stream = new GZIPDecompressorInputStream (stream, true, true,
  7562. zei->entry.uncompressedSize);
  7563. // (much faster to unzip in big blocks using a buffer..)
  7564. stream = new BufferedInputStream (stream, 32768, true);
  7565. }
  7566. }
  7567. return stream;
  7568. }
  7569. class ZipFile::ZipFilenameComparator
  7570. {
  7571. public:
  7572. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7573. {
  7574. return first->entry.filename.compare (second->entry.filename);
  7575. }
  7576. };
  7577. void ZipFile::sortEntriesByFilename()
  7578. {
  7579. ZipFilenameComparator sorter;
  7580. entries.sort (sorter);
  7581. }
  7582. void ZipFile::init()
  7583. {
  7584. ScopedPointer <InputStream> toDelete;
  7585. InputStream* in = inputStream;
  7586. if (inputSource != 0)
  7587. {
  7588. in = inputSource->createInputStream();
  7589. toDelete = in;
  7590. }
  7591. if (in != 0)
  7592. {
  7593. int numEntries = 0;
  7594. int pos = findEndOfZipEntryTable (in, numEntries);
  7595. if (pos >= 0 && pos < in->getTotalLength())
  7596. {
  7597. const int size = (int) (in->getTotalLength() - pos);
  7598. in->setPosition (pos);
  7599. MemoryBlock headerData;
  7600. if (in->readIntoMemoryBlock (headerData, size) == size)
  7601. {
  7602. pos = 0;
  7603. for (int i = 0; i < numEntries; ++i)
  7604. {
  7605. if (pos + 46 > size)
  7606. break;
  7607. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7608. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7609. if (pos + 46 + fileNameLen > size)
  7610. break;
  7611. ZipEntryInfo* const zei = new ZipEntryInfo();
  7612. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7613. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7614. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7615. const int year = 1980 + (date >> 9);
  7616. const int month = ((date >> 5) & 15) - 1;
  7617. const int day = date & 31;
  7618. const int hours = time >> 11;
  7619. const int minutes = (time >> 5) & 63;
  7620. const int seconds = (time & 31) << 1;
  7621. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7622. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7623. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7624. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7625. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7626. entries.add (zei);
  7627. pos += 46 + fileNameLen
  7628. + ByteOrder::littleEndianShort (buffer + 30)
  7629. + ByteOrder::littleEndianShort (buffer + 32);
  7630. }
  7631. }
  7632. }
  7633. }
  7634. }
  7635. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7636. {
  7637. BufferedInputStream in (input, 8192, false);
  7638. in.setPosition (in.getTotalLength());
  7639. int64 pos = in.getPosition();
  7640. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7641. char buffer [32];
  7642. zeromem (buffer, sizeof (buffer));
  7643. while (pos > lowestPos)
  7644. {
  7645. in.setPosition (pos - 22);
  7646. pos = in.getPosition();
  7647. memcpy (buffer + 22, buffer, 4);
  7648. if (in.read (buffer, 22) != 22)
  7649. return 0;
  7650. for (int i = 0; i < 22; ++i)
  7651. {
  7652. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7653. {
  7654. in.setPosition (pos + i);
  7655. in.read (buffer, 22);
  7656. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7657. return ByteOrder::littleEndianInt (buffer + 16);
  7658. }
  7659. }
  7660. }
  7661. return 0;
  7662. }
  7663. void ZipFile::uncompressTo (const File& targetDirectory,
  7664. const bool shouldOverwriteFiles)
  7665. {
  7666. for (int i = 0; i < entries.size(); ++i)
  7667. {
  7668. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7669. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7670. if (zei.filename.endsWithChar ('/'))
  7671. {
  7672. targetFile.createDirectory(); // (entry is a directory, not a file)
  7673. }
  7674. else
  7675. {
  7676. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7677. if (in != 0)
  7678. {
  7679. if (shouldOverwriteFiles)
  7680. targetFile.deleteFile();
  7681. if ((! targetFile.exists())
  7682. && targetFile.getParentDirectory().createDirectory())
  7683. {
  7684. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7685. if (out != 0)
  7686. {
  7687. out->writeFromInputStream (*in, -1);
  7688. out = 0;
  7689. targetFile.setCreationTime (zei.fileTime);
  7690. targetFile.setLastModificationTime (zei.fileTime);
  7691. targetFile.setLastAccessTime (zei.fileTime);
  7692. }
  7693. }
  7694. }
  7695. }
  7696. }
  7697. }
  7698. END_JUCE_NAMESPACE
  7699. /*** End of inlined file: juce_ZipFile.cpp ***/
  7700. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7701. #if JUCE_MSVC
  7702. #pragma warning (push)
  7703. #pragma warning (disable: 4514 4996)
  7704. #endif
  7705. #include <cwctype>
  7706. #include <cctype>
  7707. #include <ctime>
  7708. BEGIN_JUCE_NAMESPACE
  7709. int CharacterFunctions::length (const char* const s) throw()
  7710. {
  7711. return (int) strlen (s);
  7712. }
  7713. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7714. {
  7715. return (int) wcslen (s);
  7716. }
  7717. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7718. {
  7719. strncpy (dest, src, maxChars);
  7720. }
  7721. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7722. {
  7723. wcsncpy (dest, src, maxChars);
  7724. }
  7725. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7726. {
  7727. mbstowcs (dest, src, maxChars);
  7728. }
  7729. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7730. {
  7731. wcstombs (dest, src, maxChars);
  7732. }
  7733. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7734. {
  7735. return (int) wcstombs (0, src, 0);
  7736. }
  7737. void CharacterFunctions::append (char* dest, const char* src) throw()
  7738. {
  7739. strcat (dest, src);
  7740. }
  7741. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7742. {
  7743. wcscat (dest, src);
  7744. }
  7745. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7746. {
  7747. return strcmp (s1, s2);
  7748. }
  7749. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7750. {
  7751. jassert (s1 != 0 && s2 != 0);
  7752. return wcscmp (s1, s2);
  7753. }
  7754. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7755. {
  7756. jassert (s1 != 0 && s2 != 0);
  7757. return strncmp (s1, s2, maxChars);
  7758. }
  7759. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7760. {
  7761. jassert (s1 != 0 && s2 != 0);
  7762. return wcsncmp (s1, s2, maxChars);
  7763. }
  7764. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7765. {
  7766. jassert (s1 != 0 && s2 != 0);
  7767. for (;;)
  7768. {
  7769. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7770. if (diff != 0)
  7771. return diff;
  7772. else if (*s1 == 0)
  7773. break;
  7774. ++s1;
  7775. ++s2;
  7776. }
  7777. return 0;
  7778. }
  7779. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7780. {
  7781. return -compare (s2, s1);
  7782. }
  7783. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7784. {
  7785. jassert (s1 != 0 && s2 != 0);
  7786. #if JUCE_WINDOWS
  7787. return stricmp (s1, s2);
  7788. #else
  7789. return strcasecmp (s1, s2);
  7790. #endif
  7791. }
  7792. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7793. {
  7794. jassert (s1 != 0 && s2 != 0);
  7795. #if JUCE_WINDOWS
  7796. return _wcsicmp (s1, s2);
  7797. #else
  7798. for (;;)
  7799. {
  7800. if (*s1 != *s2)
  7801. {
  7802. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7803. if (diff != 0)
  7804. return diff < 0 ? -1 : 1;
  7805. }
  7806. else if (*s1 == 0)
  7807. break;
  7808. ++s1;
  7809. ++s2;
  7810. }
  7811. return 0;
  7812. #endif
  7813. }
  7814. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7815. {
  7816. jassert (s1 != 0 && s2 != 0);
  7817. for (;;)
  7818. {
  7819. if (*s1 != *s2)
  7820. {
  7821. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7822. if (diff != 0)
  7823. return diff < 0 ? -1 : 1;
  7824. }
  7825. else if (*s1 == 0)
  7826. break;
  7827. ++s1;
  7828. ++s2;
  7829. }
  7830. return 0;
  7831. }
  7832. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7833. {
  7834. jassert (s1 != 0 && s2 != 0);
  7835. #if JUCE_WINDOWS
  7836. return strnicmp (s1, s2, maxChars);
  7837. #else
  7838. return strncasecmp (s1, s2, maxChars);
  7839. #endif
  7840. }
  7841. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7842. {
  7843. jassert (s1 != 0 && s2 != 0);
  7844. #if JUCE_WINDOWS
  7845. return _wcsnicmp (s1, s2, maxChars);
  7846. #else
  7847. while (--maxChars >= 0)
  7848. {
  7849. if (*s1 != *s2)
  7850. {
  7851. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7852. if (diff != 0)
  7853. return diff < 0 ? -1 : 1;
  7854. }
  7855. else if (*s1 == 0)
  7856. break;
  7857. ++s1;
  7858. ++s2;
  7859. }
  7860. return 0;
  7861. #endif
  7862. }
  7863. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7864. {
  7865. return strstr (haystack, needle);
  7866. }
  7867. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7868. {
  7869. return wcsstr (haystack, needle);
  7870. }
  7871. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7872. {
  7873. if (haystack != 0)
  7874. {
  7875. int i = 0;
  7876. if (ignoreCase)
  7877. {
  7878. const char n1 = toLowerCase (needle);
  7879. const char n2 = toUpperCase (needle);
  7880. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7881. {
  7882. while (haystack[i] != 0)
  7883. {
  7884. if (haystack[i] == n1 || haystack[i] == n2)
  7885. return i;
  7886. ++i;
  7887. }
  7888. return -1;
  7889. }
  7890. jassert (n1 == needle);
  7891. }
  7892. while (haystack[i] != 0)
  7893. {
  7894. if (haystack[i] == needle)
  7895. return i;
  7896. ++i;
  7897. }
  7898. }
  7899. return -1;
  7900. }
  7901. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7902. {
  7903. if (haystack != 0)
  7904. {
  7905. int i = 0;
  7906. if (ignoreCase)
  7907. {
  7908. const juce_wchar n1 = toLowerCase (needle);
  7909. const juce_wchar n2 = toUpperCase (needle);
  7910. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7911. {
  7912. while (haystack[i] != 0)
  7913. {
  7914. if (haystack[i] == n1 || haystack[i] == n2)
  7915. return i;
  7916. ++i;
  7917. }
  7918. return -1;
  7919. }
  7920. jassert (n1 == needle);
  7921. }
  7922. while (haystack[i] != 0)
  7923. {
  7924. if (haystack[i] == needle)
  7925. return i;
  7926. ++i;
  7927. }
  7928. }
  7929. return -1;
  7930. }
  7931. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7932. {
  7933. jassert (haystack != 0);
  7934. int i = 0;
  7935. while (haystack[i] != 0)
  7936. {
  7937. if (haystack[i] == needle)
  7938. return i;
  7939. ++i;
  7940. }
  7941. return -1;
  7942. }
  7943. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7944. {
  7945. jassert (haystack != 0);
  7946. int i = 0;
  7947. while (haystack[i] != 0)
  7948. {
  7949. if (haystack[i] == needle)
  7950. return i;
  7951. ++i;
  7952. }
  7953. return -1;
  7954. }
  7955. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7956. {
  7957. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7958. }
  7959. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7960. {
  7961. if (allowedChars == 0)
  7962. return 0;
  7963. int i = 0;
  7964. for (;;)
  7965. {
  7966. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7967. break;
  7968. ++i;
  7969. }
  7970. return i;
  7971. }
  7972. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7973. {
  7974. return (int) strftime (dest, maxChars, format, tm);
  7975. }
  7976. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7977. {
  7978. return (int) wcsftime (dest, maxChars, format, tm);
  7979. }
  7980. int CharacterFunctions::getIntValue (const char* const s) throw()
  7981. {
  7982. return atoi (s);
  7983. }
  7984. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7985. {
  7986. #if JUCE_WINDOWS
  7987. return _wtoi (s);
  7988. #else
  7989. int v = 0;
  7990. while (isWhitespace (*s))
  7991. ++s;
  7992. const bool isNeg = *s == '-';
  7993. if (isNeg)
  7994. ++s;
  7995. for (;;)
  7996. {
  7997. const wchar_t c = *s++;
  7998. if (c >= '0' && c <= '9')
  7999. v = v * 10 + (int) (c - '0');
  8000. else
  8001. break;
  8002. }
  8003. return isNeg ? -v : v;
  8004. #endif
  8005. }
  8006. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8007. {
  8008. #if JUCE_LINUX
  8009. return atoll (s);
  8010. #elif JUCE_WINDOWS
  8011. return _atoi64 (s);
  8012. #else
  8013. int64 v = 0;
  8014. while (isWhitespace (*s))
  8015. ++s;
  8016. const bool isNeg = *s == '-';
  8017. if (isNeg)
  8018. ++s;
  8019. for (;;)
  8020. {
  8021. const char c = *s++;
  8022. if (c >= '0' && c <= '9')
  8023. v = v * 10 + (int64) (c - '0');
  8024. else
  8025. break;
  8026. }
  8027. return isNeg ? -v : v;
  8028. #endif
  8029. }
  8030. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8031. {
  8032. #if JUCE_WINDOWS
  8033. return _wtoi64 (s);
  8034. #else
  8035. int64 v = 0;
  8036. while (isWhitespace (*s))
  8037. ++s;
  8038. const bool isNeg = *s == '-';
  8039. if (isNeg)
  8040. ++s;
  8041. for (;;)
  8042. {
  8043. const juce_wchar c = *s++;
  8044. if (c >= '0' && c <= '9')
  8045. v = v * 10 + (int64) (c - '0');
  8046. else
  8047. break;
  8048. }
  8049. return isNeg ? -v : v;
  8050. #endif
  8051. }
  8052. static double juce_mulexp10 (const double value, int exponent) throw()
  8053. {
  8054. if (exponent == 0)
  8055. return value;
  8056. if (value == 0)
  8057. return 0;
  8058. const bool negative = (exponent < 0);
  8059. if (negative)
  8060. exponent = -exponent;
  8061. double result = 1.0, power = 10.0;
  8062. for (int bit = 1; exponent != 0; bit <<= 1)
  8063. {
  8064. if ((exponent & bit) != 0)
  8065. {
  8066. exponent ^= bit;
  8067. result *= power;
  8068. if (exponent == 0)
  8069. break;
  8070. }
  8071. power *= power;
  8072. }
  8073. return negative ? (value / result) : (value * result);
  8074. }
  8075. template <class CharType>
  8076. double juce_atof (const CharType* const original) throw()
  8077. {
  8078. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8079. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8080. int exponent = 0, decPointIndex = 0, digit = 0;
  8081. int lastDigit = 0, numSignificantDigits = 0;
  8082. bool isNegative = false, digitsFound = false;
  8083. const int maxSignificantDigits = 15 + 2;
  8084. const CharType* s = original;
  8085. while (CharacterFunctions::isWhitespace (*s))
  8086. ++s;
  8087. switch (*s)
  8088. {
  8089. case '-': isNegative = true; // fall-through..
  8090. case '+': ++s;
  8091. }
  8092. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8093. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8094. for (;;)
  8095. {
  8096. if (CharacterFunctions::isDigit (*s))
  8097. {
  8098. lastDigit = digit;
  8099. digit = *s++ - '0';
  8100. digitsFound = true;
  8101. if (decPointIndex != 0)
  8102. exponentAdjustment[1]++;
  8103. if (numSignificantDigits == 0 && digit == 0)
  8104. continue;
  8105. if (++numSignificantDigits > maxSignificantDigits)
  8106. {
  8107. if (digit > 5)
  8108. ++accumulator [decPointIndex];
  8109. else if (digit == 5 && (lastDigit & 1) != 0)
  8110. ++accumulator [decPointIndex];
  8111. if (decPointIndex > 0)
  8112. exponentAdjustment[1]--;
  8113. else
  8114. exponentAdjustment[0]++;
  8115. while (CharacterFunctions::isDigit (*s))
  8116. {
  8117. ++s;
  8118. if (decPointIndex == 0)
  8119. exponentAdjustment[0]++;
  8120. }
  8121. }
  8122. else
  8123. {
  8124. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8125. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8126. {
  8127. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8128. + accumulator [decPointIndex];
  8129. accumulator [decPointIndex] = 0;
  8130. exponentAccumulator [decPointIndex] = 0;
  8131. }
  8132. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8133. exponentAccumulator [decPointIndex]++;
  8134. }
  8135. }
  8136. else if (decPointIndex == 0 && *s == '.')
  8137. {
  8138. ++s;
  8139. decPointIndex = 1;
  8140. if (numSignificantDigits > maxSignificantDigits)
  8141. {
  8142. while (CharacterFunctions::isDigit (*s))
  8143. ++s;
  8144. break;
  8145. }
  8146. }
  8147. else
  8148. {
  8149. break;
  8150. }
  8151. }
  8152. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8153. if (decPointIndex != 0)
  8154. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8155. if ((*s == 'e' || *s == 'E') && digitsFound)
  8156. {
  8157. bool negativeExponent = false;
  8158. switch (*++s)
  8159. {
  8160. case '-': negativeExponent = true; // fall-through..
  8161. case '+': ++s;
  8162. }
  8163. while (CharacterFunctions::isDigit (*s))
  8164. exponent = (exponent * 10) + (*s++ - '0');
  8165. if (negativeExponent)
  8166. exponent = -exponent;
  8167. }
  8168. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8169. if (decPointIndex != 0)
  8170. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8171. return isNegative ? -r : r;
  8172. }
  8173. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8174. {
  8175. return juce_atof <char> (s);
  8176. }
  8177. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8178. {
  8179. return juce_atof <juce_wchar> (s);
  8180. }
  8181. char CharacterFunctions::toUpperCase (const char character) throw()
  8182. {
  8183. return (char) toupper (character);
  8184. }
  8185. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8186. {
  8187. return towupper (character);
  8188. }
  8189. void CharacterFunctions::toUpperCase (char* s) throw()
  8190. {
  8191. #if JUCE_WINDOWS
  8192. strupr (s);
  8193. #else
  8194. while (*s != 0)
  8195. {
  8196. *s = toUpperCase (*s);
  8197. ++s;
  8198. }
  8199. #endif
  8200. }
  8201. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8202. {
  8203. #if JUCE_WINDOWS
  8204. _wcsupr (s);
  8205. #else
  8206. while (*s != 0)
  8207. {
  8208. *s = toUpperCase (*s);
  8209. ++s;
  8210. }
  8211. #endif
  8212. }
  8213. bool CharacterFunctions::isUpperCase (const char character) throw()
  8214. {
  8215. return isupper (character) != 0;
  8216. }
  8217. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8218. {
  8219. #if JUCE_WINDOWS
  8220. return iswupper (character) != 0;
  8221. #else
  8222. return toLowerCase (character) != character;
  8223. #endif
  8224. }
  8225. char CharacterFunctions::toLowerCase (const char character) throw()
  8226. {
  8227. return (char) tolower (character);
  8228. }
  8229. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8230. {
  8231. return towlower (character);
  8232. }
  8233. void CharacterFunctions::toLowerCase (char* s) throw()
  8234. {
  8235. #if JUCE_WINDOWS
  8236. strlwr (s);
  8237. #else
  8238. while (*s != 0)
  8239. {
  8240. *s = toLowerCase (*s);
  8241. ++s;
  8242. }
  8243. #endif
  8244. }
  8245. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8246. {
  8247. #if JUCE_WINDOWS
  8248. _wcslwr (s);
  8249. #else
  8250. while (*s != 0)
  8251. {
  8252. *s = toLowerCase (*s);
  8253. ++s;
  8254. }
  8255. #endif
  8256. }
  8257. bool CharacterFunctions::isLowerCase (const char character) throw()
  8258. {
  8259. return islower (character) != 0;
  8260. }
  8261. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8262. {
  8263. #if JUCE_WINDOWS
  8264. return iswlower (character) != 0;
  8265. #else
  8266. return toUpperCase (character) != character;
  8267. #endif
  8268. }
  8269. bool CharacterFunctions::isWhitespace (const char character) throw()
  8270. {
  8271. return character == ' ' || (character <= 13 && character >= 9);
  8272. }
  8273. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8274. {
  8275. return iswspace (character) != 0;
  8276. }
  8277. bool CharacterFunctions::isDigit (const char character) throw()
  8278. {
  8279. return (character >= '0' && character <= '9');
  8280. }
  8281. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8282. {
  8283. return iswdigit (character) != 0;
  8284. }
  8285. bool CharacterFunctions::isLetter (const char character) throw()
  8286. {
  8287. return (character >= 'a' && character <= 'z')
  8288. || (character >= 'A' && character <= 'Z');
  8289. }
  8290. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8291. {
  8292. return iswalpha (character) != 0;
  8293. }
  8294. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8295. {
  8296. return (character >= 'a' && character <= 'z')
  8297. || (character >= 'A' && character <= 'Z')
  8298. || (character >= '0' && character <= '9');
  8299. }
  8300. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8301. {
  8302. return iswalnum (character) != 0;
  8303. }
  8304. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8305. {
  8306. unsigned int d = digit - '0';
  8307. if (d < (unsigned int) 10)
  8308. return (int) d;
  8309. d += (unsigned int) ('0' - 'a');
  8310. if (d < (unsigned int) 6)
  8311. return (int) d + 10;
  8312. d += (unsigned int) ('a' - 'A');
  8313. if (d < (unsigned int) 6)
  8314. return (int) d + 10;
  8315. return -1;
  8316. }
  8317. #if JUCE_MSVC
  8318. #pragma warning (pop)
  8319. #endif
  8320. END_JUCE_NAMESPACE
  8321. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8322. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8323. BEGIN_JUCE_NAMESPACE
  8324. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8325. {
  8326. loadFromText (fileContents);
  8327. }
  8328. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8329. {
  8330. loadFromText (fileToLoad.loadFileAsString());
  8331. }
  8332. LocalisedStrings::~LocalisedStrings()
  8333. {
  8334. }
  8335. const String LocalisedStrings::translate (const String& text) const
  8336. {
  8337. return translations.getValue (text, text);
  8338. }
  8339. static int findCloseQuote (const String& text, int startPos)
  8340. {
  8341. juce_wchar lastChar = 0;
  8342. for (;;)
  8343. {
  8344. const juce_wchar c = text [startPos];
  8345. if (c == 0 || (c == '"' && lastChar != '\\'))
  8346. break;
  8347. lastChar = c;
  8348. ++startPos;
  8349. }
  8350. return startPos;
  8351. }
  8352. static const String unescapeString (const String& s)
  8353. {
  8354. return s.replace ("\\\"", "\"")
  8355. .replace ("\\\'", "\'")
  8356. .replace ("\\t", "\t")
  8357. .replace ("\\r", "\r")
  8358. .replace ("\\n", "\n");
  8359. }
  8360. void LocalisedStrings::loadFromText (const String& fileContents)
  8361. {
  8362. StringArray lines;
  8363. lines.addLines (fileContents);
  8364. for (int i = 0; i < lines.size(); ++i)
  8365. {
  8366. String line (lines[i].trim());
  8367. if (line.startsWithChar ('"'))
  8368. {
  8369. int closeQuote = findCloseQuote (line, 1);
  8370. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8371. if (originalText.isNotEmpty())
  8372. {
  8373. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8374. closeQuote = findCloseQuote (line, openingQuote + 1);
  8375. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8376. if (newText.isNotEmpty())
  8377. translations.set (originalText, newText);
  8378. }
  8379. }
  8380. else if (line.startsWithIgnoreCase ("language:"))
  8381. {
  8382. languageName = line.substring (9).trim();
  8383. }
  8384. else if (line.startsWithIgnoreCase ("countries:"))
  8385. {
  8386. countryCodes.addTokens (line.substring (10).trim(), true);
  8387. countryCodes.trim();
  8388. countryCodes.removeEmptyStrings();
  8389. }
  8390. }
  8391. }
  8392. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8393. {
  8394. translations.setIgnoresCase (shouldIgnoreCase);
  8395. }
  8396. static CriticalSection currentMappingsLock;
  8397. static LocalisedStrings* currentMappings = 0;
  8398. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8399. {
  8400. const ScopedLock sl (currentMappingsLock);
  8401. delete currentMappings;
  8402. currentMappings = newTranslations;
  8403. }
  8404. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8405. {
  8406. return currentMappings;
  8407. }
  8408. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8409. {
  8410. const ScopedLock sl (currentMappingsLock);
  8411. if (currentMappings != 0)
  8412. return currentMappings->translate (text);
  8413. return text;
  8414. }
  8415. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8416. {
  8417. return translateWithCurrentMappings (String (text));
  8418. }
  8419. END_JUCE_NAMESPACE
  8420. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8421. /*** Start of inlined file: juce_String.cpp ***/
  8422. #if JUCE_MSVC
  8423. #pragma warning (push)
  8424. #pragma warning (disable: 4514)
  8425. #endif
  8426. #include <locale>
  8427. BEGIN_JUCE_NAMESPACE
  8428. #if JUCE_MSVC
  8429. #pragma warning (pop)
  8430. #endif
  8431. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8432. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8433. #endif
  8434. class StringHolder
  8435. {
  8436. public:
  8437. StringHolder()
  8438. : refCount (0x3fffffff), allocatedNumChars (0)
  8439. {
  8440. text[0] = 0;
  8441. }
  8442. static juce_wchar* createUninitialised (const size_t numChars)
  8443. {
  8444. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8445. s->refCount.value = 0;
  8446. s->allocatedNumChars = numChars;
  8447. return &(s->text[0]);
  8448. }
  8449. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8450. {
  8451. juce_wchar* const dest = createUninitialised (numChars);
  8452. copyChars (dest, src, numChars);
  8453. return dest;
  8454. }
  8455. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8456. {
  8457. juce_wchar* const dest = createUninitialised (numChars);
  8458. CharacterFunctions::copy (dest, src, (int) numChars);
  8459. dest [numChars] = 0;
  8460. return dest;
  8461. }
  8462. static inline juce_wchar* getEmpty() throw()
  8463. {
  8464. return &(empty.text[0]);
  8465. }
  8466. static void retain (juce_wchar* const text) throw()
  8467. {
  8468. ++(bufferFromText (text)->refCount);
  8469. }
  8470. static inline void release (StringHolder* const b) throw()
  8471. {
  8472. if (--(b->refCount) == -1 && b != &empty)
  8473. delete[] reinterpret_cast <char*> (b);
  8474. }
  8475. static void release (juce_wchar* const text) throw()
  8476. {
  8477. release (bufferFromText (text));
  8478. }
  8479. static juce_wchar* makeUnique (juce_wchar* const text)
  8480. {
  8481. StringHolder* const b = bufferFromText (text);
  8482. if (b->refCount.get() <= 0)
  8483. return text;
  8484. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8485. release (b);
  8486. return newText;
  8487. }
  8488. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8489. {
  8490. StringHolder* const b = bufferFromText (text);
  8491. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8492. return text;
  8493. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8494. copyChars (newText, text, b->allocatedNumChars);
  8495. release (b);
  8496. return newText;
  8497. }
  8498. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8499. {
  8500. return bufferFromText (text)->allocatedNumChars;
  8501. }
  8502. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8503. {
  8504. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8505. dest [numChars] = 0;
  8506. }
  8507. Atomic<int> refCount;
  8508. size_t allocatedNumChars;
  8509. juce_wchar text[1];
  8510. static StringHolder empty;
  8511. private:
  8512. static inline StringHolder* bufferFromText (void* const text) throw()
  8513. {
  8514. // (Can't use offsetof() here because of warnings about this not being a POD)
  8515. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8516. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8517. }
  8518. };
  8519. StringHolder StringHolder::empty;
  8520. const String String::empty;
  8521. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8522. {
  8523. jassert (t[numChars] == 0); // must have a null terminator
  8524. text = StringHolder::createCopy (t, numChars);
  8525. }
  8526. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8527. {
  8528. if (numExtraChars > 0)
  8529. {
  8530. const int oldLen = length();
  8531. const int newTotalLen = oldLen + numExtraChars;
  8532. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8533. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8534. }
  8535. }
  8536. void String::preallocateStorage (const size_t numChars)
  8537. {
  8538. text = StringHolder::makeUniqueWithSize (text, numChars);
  8539. }
  8540. String::String() throw()
  8541. : text (StringHolder::getEmpty())
  8542. {
  8543. }
  8544. String::~String() throw()
  8545. {
  8546. StringHolder::release (text);
  8547. }
  8548. String::String (const String& other) throw()
  8549. : text (other.text)
  8550. {
  8551. StringHolder::retain (text);
  8552. }
  8553. void String::swapWith (String& other) throw()
  8554. {
  8555. swapVariables (text, other.text);
  8556. }
  8557. String& String::operator= (const String& other) throw()
  8558. {
  8559. juce_wchar* const newText = other.text;
  8560. StringHolder::retain (newText);
  8561. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8562. return *this;
  8563. }
  8564. String::String (const size_t numChars, const int /*dummyVariable*/)
  8565. : text (StringHolder::createUninitialised (numChars))
  8566. {
  8567. }
  8568. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8569. {
  8570. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8571. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8572. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8573. }
  8574. String::String (const char* const t)
  8575. {
  8576. if (t != 0 && *t != 0)
  8577. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8578. else
  8579. text = StringHolder::getEmpty();
  8580. }
  8581. String::String (const juce_wchar* const t)
  8582. {
  8583. if (t != 0 && *t != 0)
  8584. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8585. else
  8586. text = StringHolder::getEmpty();
  8587. }
  8588. String::String (const char* const t, const size_t maxChars)
  8589. {
  8590. int i;
  8591. for (i = 0; (size_t) i < maxChars; ++i)
  8592. if (t[i] == 0)
  8593. break;
  8594. if (i > 0)
  8595. text = StringHolder::createCopy (t, i);
  8596. else
  8597. text = StringHolder::getEmpty();
  8598. }
  8599. String::String (const juce_wchar* const t, const size_t maxChars)
  8600. {
  8601. int i;
  8602. for (i = 0; (size_t) i < maxChars; ++i)
  8603. if (t[i] == 0)
  8604. break;
  8605. if (i > 0)
  8606. text = StringHolder::createCopy (t, i);
  8607. else
  8608. text = StringHolder::getEmpty();
  8609. }
  8610. const String String::charToString (const juce_wchar character)
  8611. {
  8612. String result ((size_t) 1, (int) 0);
  8613. result.text[0] = character;
  8614. result.text[1] = 0;
  8615. return result;
  8616. }
  8617. namespace NumberToStringConverters
  8618. {
  8619. // pass in a pointer to the END of a buffer..
  8620. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8621. {
  8622. *--t = 0;
  8623. int64 v = (n >= 0) ? n : -n;
  8624. do
  8625. {
  8626. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8627. v /= 10;
  8628. } while (v > 0);
  8629. if (n < 0)
  8630. *--t = '-';
  8631. return t;
  8632. }
  8633. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8634. {
  8635. *--t = 0;
  8636. do
  8637. {
  8638. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8639. v /= 10;
  8640. } while (v > 0);
  8641. return t;
  8642. }
  8643. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8644. {
  8645. if (n == (int) 0x80000000) // (would cause an overflow)
  8646. return int64ToString (t, n);
  8647. *--t = 0;
  8648. int v = abs (n);
  8649. do
  8650. {
  8651. *--t = (juce_wchar) ('0' + (v % 10));
  8652. v /= 10;
  8653. } while (v > 0);
  8654. if (n < 0)
  8655. *--t = '-';
  8656. return t;
  8657. }
  8658. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8659. {
  8660. *--t = 0;
  8661. do
  8662. {
  8663. *--t = (juce_wchar) ('0' + (v % 10));
  8664. v /= 10;
  8665. } while (v > 0);
  8666. return t;
  8667. }
  8668. static juce_wchar getDecimalPoint()
  8669. {
  8670. #if JUCE_WINDOWS && _MSC_VER < 1400
  8671. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8672. #else
  8673. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8674. #endif
  8675. return dp;
  8676. }
  8677. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8678. {
  8679. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8680. {
  8681. juce_wchar* const end = buffer + numChars;
  8682. juce_wchar* t = end;
  8683. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8684. *--t = (juce_wchar) 0;
  8685. while (numDecPlaces >= 0 || v > 0)
  8686. {
  8687. if (numDecPlaces == 0)
  8688. *--t = getDecimalPoint();
  8689. *--t = (juce_wchar) ('0' + (v % 10));
  8690. v /= 10;
  8691. --numDecPlaces;
  8692. }
  8693. if (n < 0)
  8694. *--t = '-';
  8695. len = end - t - 1;
  8696. return t;
  8697. }
  8698. else
  8699. {
  8700. #if JUCE_WINDOWS
  8701. #if _MSC_VER <= 1400
  8702. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8703. #else
  8704. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8705. #endif
  8706. #else
  8707. len = swprintf (buffer, numChars, L"%.9g", n);
  8708. #endif
  8709. return buffer;
  8710. }
  8711. }
  8712. }
  8713. String::String (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. createInternal (start, end - start - 1);
  8719. }
  8720. String::String (const unsigned int number)
  8721. {
  8722. juce_wchar buffer [16];
  8723. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8724. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8725. createInternal (start, end - start - 1);
  8726. }
  8727. String::String (const short number)
  8728. {
  8729. juce_wchar buffer [16];
  8730. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8731. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8732. createInternal (start, end - start - 1);
  8733. }
  8734. String::String (const unsigned short number)
  8735. {
  8736. juce_wchar buffer [16];
  8737. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8738. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8739. createInternal (start, end - start - 1);
  8740. }
  8741. String::String (const int64 number)
  8742. {
  8743. juce_wchar buffer [32];
  8744. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8745. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8746. createInternal (start, end - start - 1);
  8747. }
  8748. String::String (const uint64 number)
  8749. {
  8750. juce_wchar buffer [32];
  8751. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8752. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8753. createInternal (start, end - start - 1);
  8754. }
  8755. String::String (const float number, const int numberOfDecimalPlaces)
  8756. {
  8757. juce_wchar buffer [48];
  8758. size_t len;
  8759. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8760. createInternal (start, len);
  8761. }
  8762. String::String (const double number, const int numberOfDecimalPlaces)
  8763. {
  8764. juce_wchar buffer [48];
  8765. size_t len;
  8766. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8767. createInternal (start, len);
  8768. }
  8769. int String::length() const throw()
  8770. {
  8771. return CharacterFunctions::length (text);
  8772. }
  8773. int String::hashCode() const throw()
  8774. {
  8775. const juce_wchar* t = text;
  8776. int result = 0;
  8777. while (*t != (juce_wchar) 0)
  8778. result = 31 * result + *t++;
  8779. return result;
  8780. }
  8781. int64 String::hashCode64() const throw()
  8782. {
  8783. const juce_wchar* t = text;
  8784. int64 result = 0;
  8785. while (*t != (juce_wchar) 0)
  8786. result = 101 * result + *t++;
  8787. return result;
  8788. }
  8789. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  8790. {
  8791. return string1.compare (string2) == 0;
  8792. }
  8793. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  8794. {
  8795. return string1.compare (string2) == 0;
  8796. }
  8797. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  8798. {
  8799. return string1.compare (string2) == 0;
  8800. }
  8801. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  8802. {
  8803. return string1.compare (string2) != 0;
  8804. }
  8805. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  8806. {
  8807. return string1.compare (string2) != 0;
  8808. }
  8809. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  8810. {
  8811. return string1.compare (string2) != 0;
  8812. }
  8813. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  8814. {
  8815. return string1.compare (string2) > 0;
  8816. }
  8817. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  8818. {
  8819. return string1.compare (string2) < 0;
  8820. }
  8821. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  8822. {
  8823. return string1.compare (string2) >= 0;
  8824. }
  8825. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  8826. {
  8827. return string1.compare (string2) <= 0;
  8828. }
  8829. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8830. {
  8831. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8832. : isEmpty();
  8833. }
  8834. bool String::equalsIgnoreCase (const char* t) const throw()
  8835. {
  8836. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8837. : isEmpty();
  8838. }
  8839. bool String::equalsIgnoreCase (const String& other) const throw()
  8840. {
  8841. return text == other.text
  8842. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8843. }
  8844. int String::compare (const String& other) const throw()
  8845. {
  8846. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8847. }
  8848. int String::compare (const char* other) const throw()
  8849. {
  8850. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8851. }
  8852. int String::compare (const juce_wchar* other) const throw()
  8853. {
  8854. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8855. }
  8856. int String::compareIgnoreCase (const String& other) const throw()
  8857. {
  8858. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8859. }
  8860. int String::compareLexicographically (const String& other) const throw()
  8861. {
  8862. const juce_wchar* s1 = text;
  8863. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8864. ++s1;
  8865. const juce_wchar* s2 = other.text;
  8866. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8867. ++s2;
  8868. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8869. }
  8870. String& String::operator+= (const juce_wchar* const t)
  8871. {
  8872. if (t != 0)
  8873. appendInternal (t, CharacterFunctions::length (t));
  8874. return *this;
  8875. }
  8876. String& String::operator+= (const String& other)
  8877. {
  8878. if (isEmpty())
  8879. operator= (other);
  8880. else
  8881. appendInternal (other.text, other.length());
  8882. return *this;
  8883. }
  8884. String& String::operator+= (const char ch)
  8885. {
  8886. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8887. return operator+= (static_cast <const juce_wchar*> (asString));
  8888. }
  8889. String& String::operator+= (const juce_wchar ch)
  8890. {
  8891. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8892. return operator+= (static_cast <const juce_wchar*> (asString));
  8893. }
  8894. String& String::operator+= (const int number)
  8895. {
  8896. juce_wchar buffer [16];
  8897. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8898. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8899. appendInternal (start, (int) (end - start));
  8900. return *this;
  8901. }
  8902. String& String::operator+= (const unsigned int number)
  8903. {
  8904. juce_wchar buffer [16];
  8905. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8906. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8907. appendInternal (start, (int) (end - start));
  8908. return *this;
  8909. }
  8910. void String::append (const juce_wchar* const other, const int howMany)
  8911. {
  8912. if (howMany > 0)
  8913. {
  8914. int i;
  8915. for (i = 0; i < howMany; ++i)
  8916. if (other[i] == 0)
  8917. break;
  8918. appendInternal (other, i);
  8919. }
  8920. }
  8921. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  8922. {
  8923. String s (string1);
  8924. return s += string2;
  8925. }
  8926. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  8927. {
  8928. String s (string1);
  8929. return s += string2;
  8930. }
  8931. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  8932. {
  8933. return String::charToString (string1) + string2;
  8934. }
  8935. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  8936. {
  8937. return String::charToString (string1) + string2;
  8938. }
  8939. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  8940. {
  8941. return string1 += string2;
  8942. }
  8943. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  8944. {
  8945. return string1 += string2;
  8946. }
  8947. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  8948. {
  8949. return string1 += string2;
  8950. }
  8951. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  8952. {
  8953. return string1 += string2;
  8954. }
  8955. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  8956. {
  8957. return string1 += string2;
  8958. }
  8959. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  8960. {
  8961. return string1 += characterToAppend;
  8962. }
  8963. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  8964. {
  8965. return string1 += characterToAppend;
  8966. }
  8967. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  8968. {
  8969. return string1 += string2;
  8970. }
  8971. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  8972. {
  8973. return string1 += string2;
  8974. }
  8975. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  8976. {
  8977. return string1 += string2;
  8978. }
  8979. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  8980. {
  8981. return string1 += (int) number;
  8982. }
  8983. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  8984. {
  8985. return string1 += number;
  8986. }
  8987. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  8988. {
  8989. return string1 += number;
  8990. }
  8991. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  8992. {
  8993. return string1 += (int) number;
  8994. }
  8995. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  8996. {
  8997. return string1 += (unsigned int) number;
  8998. }
  8999. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9000. {
  9001. return string1 += String (number);
  9002. }
  9003. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9004. {
  9005. return string1 += String (number);
  9006. }
  9007. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9008. {
  9009. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9010. // if lots of large, persistent strings were to be written to streams).
  9011. const int numBytes = text.getNumBytesAsUTF8();
  9012. HeapBlock<char> temp (numBytes + 1);
  9013. text.copyToUTF8 (temp, numBytes + 1);
  9014. stream.write (temp, numBytes);
  9015. return stream;
  9016. }
  9017. int String::indexOfChar (const juce_wchar character) const throw()
  9018. {
  9019. const juce_wchar* t = text;
  9020. for (;;)
  9021. {
  9022. if (*t == character)
  9023. return (int) (t - text);
  9024. if (*t++ == 0)
  9025. return -1;
  9026. }
  9027. }
  9028. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9029. {
  9030. for (int i = length(); --i >= 0;)
  9031. if (text[i] == character)
  9032. return i;
  9033. return -1;
  9034. }
  9035. int String::indexOf (const String& t) const throw()
  9036. {
  9037. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9038. return r == 0 ? -1 : (int) (r - text);
  9039. }
  9040. int String::indexOfChar (const int startIndex,
  9041. const juce_wchar character) const throw()
  9042. {
  9043. if (startIndex > 0 && startIndex >= length())
  9044. return -1;
  9045. const juce_wchar* t = text + jmax (0, startIndex);
  9046. for (;;)
  9047. {
  9048. if (*t == character)
  9049. return (int) (t - text);
  9050. if (*t == 0)
  9051. return -1;
  9052. ++t;
  9053. }
  9054. }
  9055. int String::indexOfAnyOf (const String& charactersToLookFor,
  9056. const int startIndex,
  9057. const bool ignoreCase) const throw()
  9058. {
  9059. if (startIndex > 0 && startIndex >= length())
  9060. return -1;
  9061. const juce_wchar* t = text + jmax (0, startIndex);
  9062. while (*t != 0)
  9063. {
  9064. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9065. return (int) (t - text);
  9066. ++t;
  9067. }
  9068. return -1;
  9069. }
  9070. int String::indexOf (const int startIndex, const String& other) const throw()
  9071. {
  9072. if (startIndex > 0 && startIndex >= length())
  9073. return -1;
  9074. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9075. return found == 0 ? -1 : (int) (found - text);
  9076. }
  9077. int String::indexOfIgnoreCase (const String& other) const throw()
  9078. {
  9079. if (other.isNotEmpty())
  9080. {
  9081. const int len = other.length();
  9082. const int end = length() - len;
  9083. for (int i = 0; i <= end; ++i)
  9084. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9085. return i;
  9086. }
  9087. return -1;
  9088. }
  9089. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9090. {
  9091. if (other.isNotEmpty())
  9092. {
  9093. const int len = other.length();
  9094. const int end = length() - len;
  9095. for (int i = jmax (0, startIndex); i <= end; ++i)
  9096. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9097. return i;
  9098. }
  9099. return -1;
  9100. }
  9101. int String::lastIndexOf (const String& other) const throw()
  9102. {
  9103. if (other.isNotEmpty())
  9104. {
  9105. const int len = other.length();
  9106. int i = length() - len;
  9107. if (i >= 0)
  9108. {
  9109. const juce_wchar* n = text + i;
  9110. while (i >= 0)
  9111. {
  9112. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9113. return i;
  9114. --i;
  9115. }
  9116. }
  9117. }
  9118. return -1;
  9119. }
  9120. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9121. {
  9122. if (other.isNotEmpty())
  9123. {
  9124. const int len = other.length();
  9125. int i = length() - len;
  9126. if (i >= 0)
  9127. {
  9128. const juce_wchar* n = text + i;
  9129. while (i >= 0)
  9130. {
  9131. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9132. return i;
  9133. --i;
  9134. }
  9135. }
  9136. }
  9137. return -1;
  9138. }
  9139. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9140. {
  9141. for (int i = length(); --i >= 0;)
  9142. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9143. return i;
  9144. return -1;
  9145. }
  9146. bool String::contains (const String& other) const throw()
  9147. {
  9148. return indexOf (other) >= 0;
  9149. }
  9150. bool String::containsChar (const juce_wchar character) const throw()
  9151. {
  9152. const juce_wchar* t = text;
  9153. for (;;)
  9154. {
  9155. if (*t == 0)
  9156. return false;
  9157. if (*t == character)
  9158. return true;
  9159. ++t;
  9160. }
  9161. }
  9162. bool String::containsIgnoreCase (const String& t) const throw()
  9163. {
  9164. return indexOfIgnoreCase (t) >= 0;
  9165. }
  9166. int String::indexOfWholeWord (const String& word) const throw()
  9167. {
  9168. if (word.isNotEmpty())
  9169. {
  9170. const int wordLen = word.length();
  9171. const int end = length() - wordLen;
  9172. const juce_wchar* t = text;
  9173. for (int i = 0; i <= end; ++i)
  9174. {
  9175. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9176. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9177. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9178. {
  9179. return i;
  9180. }
  9181. ++t;
  9182. }
  9183. }
  9184. return -1;
  9185. }
  9186. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9187. {
  9188. if (word.isNotEmpty())
  9189. {
  9190. const int wordLen = word.length();
  9191. const int end = length() - wordLen;
  9192. const juce_wchar* t = text;
  9193. for (int i = 0; i <= end; ++i)
  9194. {
  9195. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9196. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9197. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9198. {
  9199. return i;
  9200. }
  9201. ++t;
  9202. }
  9203. }
  9204. return -1;
  9205. }
  9206. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9207. {
  9208. return indexOfWholeWord (wordToLookFor) >= 0;
  9209. }
  9210. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9211. {
  9212. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9213. }
  9214. static int indexOfMatch (const juce_wchar* const wildcard,
  9215. const juce_wchar* const test,
  9216. const bool ignoreCase) throw()
  9217. {
  9218. int start = 0;
  9219. while (test [start] != 0)
  9220. {
  9221. int i = 0;
  9222. for (;;)
  9223. {
  9224. const juce_wchar wc = wildcard [i];
  9225. const juce_wchar c = test [i + start];
  9226. if (wc == c
  9227. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9228. || (wc == '?' && c != 0))
  9229. {
  9230. if (wc == 0)
  9231. return start;
  9232. ++i;
  9233. }
  9234. else
  9235. {
  9236. if (wc == '*' && (wildcard [i + 1] == 0
  9237. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9238. {
  9239. return start;
  9240. }
  9241. break;
  9242. }
  9243. }
  9244. ++start;
  9245. }
  9246. return -1;
  9247. }
  9248. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9249. {
  9250. int i = 0;
  9251. for (;;)
  9252. {
  9253. const juce_wchar wc = wildcard.text [i];
  9254. const juce_wchar c = text [i];
  9255. if (wc == c
  9256. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9257. || (wc == '?' && c != 0))
  9258. {
  9259. if (wc == 0)
  9260. return true;
  9261. ++i;
  9262. }
  9263. else
  9264. {
  9265. return wc == '*' && (wildcard [i + 1] == 0
  9266. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9267. }
  9268. }
  9269. }
  9270. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9271. {
  9272. const int len = stringToRepeat.length();
  9273. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9274. juce_wchar* n = result.text;
  9275. *n = 0;
  9276. while (--numberOfTimesToRepeat >= 0)
  9277. {
  9278. StringHolder::copyChars (n, stringToRepeat.text, len);
  9279. n += len;
  9280. }
  9281. return result;
  9282. }
  9283. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9284. {
  9285. jassert (padCharacter != 0);
  9286. const int len = length();
  9287. if (len >= minimumLength || padCharacter == 0)
  9288. return *this;
  9289. String result ((size_t) minimumLength + 1, (int) 0);
  9290. juce_wchar* n = result.text;
  9291. minimumLength -= len;
  9292. while (--minimumLength >= 0)
  9293. *n++ = padCharacter;
  9294. StringHolder::copyChars (n, text, len);
  9295. return result;
  9296. }
  9297. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9298. {
  9299. jassert (padCharacter != 0);
  9300. const int len = length();
  9301. if (len >= minimumLength || padCharacter == 0)
  9302. return *this;
  9303. String result (*this, (size_t) minimumLength);
  9304. juce_wchar* n = result.text + len;
  9305. minimumLength -= len;
  9306. while (--minimumLength >= 0)
  9307. *n++ = padCharacter;
  9308. *n = 0;
  9309. return result;
  9310. }
  9311. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9312. {
  9313. if (index < 0)
  9314. {
  9315. // a negative index to replace from?
  9316. jassertfalse;
  9317. index = 0;
  9318. }
  9319. if (numCharsToReplace < 0)
  9320. {
  9321. // replacing a negative number of characters?
  9322. numCharsToReplace = 0;
  9323. jassertfalse;
  9324. }
  9325. const int len = length();
  9326. if (index + numCharsToReplace > len)
  9327. {
  9328. if (index > len)
  9329. {
  9330. // replacing beyond the end of the string?
  9331. index = len;
  9332. jassertfalse;
  9333. }
  9334. numCharsToReplace = len - index;
  9335. }
  9336. const int newStringLen = stringToInsert.length();
  9337. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9338. if (newTotalLen <= 0)
  9339. return String::empty;
  9340. String result ((size_t) newTotalLen, (int) 0);
  9341. StringHolder::copyChars (result.text, text, index);
  9342. if (newStringLen > 0)
  9343. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9344. const int endStringLen = newTotalLen - (index + newStringLen);
  9345. if (endStringLen > 0)
  9346. StringHolder::copyChars (result.text + (index + newStringLen),
  9347. text + (index + numCharsToReplace),
  9348. endStringLen);
  9349. return result;
  9350. }
  9351. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9352. {
  9353. const int stringToReplaceLen = stringToReplace.length();
  9354. const int stringToInsertLen = stringToInsert.length();
  9355. int i = 0;
  9356. String result (*this);
  9357. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9358. : result.indexOf (i, stringToReplace))) >= 0)
  9359. {
  9360. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9361. i += stringToInsertLen;
  9362. }
  9363. return result;
  9364. }
  9365. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9366. {
  9367. const int index = indexOfChar (charToReplace);
  9368. if (index < 0)
  9369. return *this;
  9370. String result (*this, size_t());
  9371. juce_wchar* t = result.text + index;
  9372. while (*t != 0)
  9373. {
  9374. if (*t == charToReplace)
  9375. *t = charToInsert;
  9376. ++t;
  9377. }
  9378. return result;
  9379. }
  9380. const String String::replaceCharacters (const String& charactersToReplace,
  9381. const String& charactersToInsertInstead) const
  9382. {
  9383. String result (*this, size_t());
  9384. juce_wchar* t = result.text;
  9385. const int len2 = charactersToInsertInstead.length();
  9386. // the two strings passed in are supposed to be the same length!
  9387. jassert (len2 == charactersToReplace.length());
  9388. while (*t != 0)
  9389. {
  9390. const int index = charactersToReplace.indexOfChar (*t);
  9391. if (((unsigned int) index) < (unsigned int) len2)
  9392. *t = charactersToInsertInstead [index];
  9393. ++t;
  9394. }
  9395. return result;
  9396. }
  9397. bool String::startsWith (const String& other) const throw()
  9398. {
  9399. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9400. }
  9401. bool String::startsWithIgnoreCase (const String& other) const throw()
  9402. {
  9403. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9404. }
  9405. bool String::startsWithChar (const juce_wchar character) const throw()
  9406. {
  9407. jassert (character != 0); // strings can't contain a null character!
  9408. return text[0] == character;
  9409. }
  9410. bool String::endsWithChar (const juce_wchar character) const throw()
  9411. {
  9412. jassert (character != 0); // strings can't contain a null character!
  9413. return text[0] != 0
  9414. && text [length() - 1] == character;
  9415. }
  9416. bool String::endsWith (const String& other) const throw()
  9417. {
  9418. const int thisLen = length();
  9419. const int otherLen = other.length();
  9420. return thisLen >= otherLen
  9421. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9422. }
  9423. bool String::endsWithIgnoreCase (const String& other) const throw()
  9424. {
  9425. const int thisLen = length();
  9426. const int otherLen = other.length();
  9427. return thisLen >= otherLen
  9428. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9429. }
  9430. const String String::toUpperCase() const
  9431. {
  9432. String result (*this, size_t());
  9433. CharacterFunctions::toUpperCase (result.text);
  9434. return result;
  9435. }
  9436. const String String::toLowerCase() const
  9437. {
  9438. String result (*this, size_t());
  9439. CharacterFunctions::toLowerCase (result.text);
  9440. return result;
  9441. }
  9442. juce_wchar& String::operator[] (const int index)
  9443. {
  9444. jassert (((unsigned int) index) <= (unsigned int) length());
  9445. text = StringHolder::makeUnique (text);
  9446. return text [index];
  9447. }
  9448. juce_wchar String::getLastCharacter() const throw()
  9449. {
  9450. return isEmpty() ? juce_wchar() : text [length() - 1];
  9451. }
  9452. const String String::substring (int start, int end) const
  9453. {
  9454. if (start < 0)
  9455. start = 0;
  9456. else if (end <= start)
  9457. return empty;
  9458. int len = 0;
  9459. while (len <= end && text [len] != 0)
  9460. ++len;
  9461. if (end >= len)
  9462. {
  9463. if (start == 0)
  9464. return *this;
  9465. end = len;
  9466. }
  9467. return String (text + start, end - start);
  9468. }
  9469. const String String::substring (const int start) const
  9470. {
  9471. if (start <= 0)
  9472. return *this;
  9473. const int len = length();
  9474. if (start >= len)
  9475. return empty;
  9476. return String (text + start, len - start);
  9477. }
  9478. const String String::dropLastCharacters (const int numberToDrop) const
  9479. {
  9480. return String (text, jmax (0, length() - numberToDrop));
  9481. }
  9482. const String String::getLastCharacters (const int numCharacters) const
  9483. {
  9484. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9485. }
  9486. const String String::fromFirstOccurrenceOf (const String& sub,
  9487. const bool includeSubString,
  9488. const bool ignoreCase) const
  9489. {
  9490. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9491. : indexOf (sub);
  9492. if (i < 0)
  9493. return empty;
  9494. return substring (includeSubString ? i : i + sub.length());
  9495. }
  9496. const String String::fromLastOccurrenceOf (const String& sub,
  9497. const bool includeSubString,
  9498. const bool ignoreCase) const
  9499. {
  9500. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9501. : lastIndexOf (sub);
  9502. if (i < 0)
  9503. return *this;
  9504. return substring (includeSubString ? i : i + sub.length());
  9505. }
  9506. const String String::upToFirstOccurrenceOf (const String& sub,
  9507. const bool includeSubString,
  9508. const bool ignoreCase) const
  9509. {
  9510. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9511. : indexOf (sub);
  9512. if (i < 0)
  9513. return *this;
  9514. return substring (0, includeSubString ? i + sub.length() : i);
  9515. }
  9516. const String String::upToLastOccurrenceOf (const String& sub,
  9517. const bool includeSubString,
  9518. const bool ignoreCase) const
  9519. {
  9520. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9521. : lastIndexOf (sub);
  9522. if (i < 0)
  9523. return *this;
  9524. return substring (0, includeSubString ? i + sub.length() : i);
  9525. }
  9526. bool String::isQuotedString() const
  9527. {
  9528. const String trimmed (trimStart());
  9529. return trimmed[0] == '"'
  9530. || trimmed[0] == '\'';
  9531. }
  9532. const String String::unquoted() const
  9533. {
  9534. String s (*this);
  9535. if (s.text[0] == '"' || s.text[0] == '\'')
  9536. s = s.substring (1);
  9537. const int lastCharIndex = s.length() - 1;
  9538. if (lastCharIndex >= 0
  9539. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9540. s [lastCharIndex] = 0;
  9541. return s;
  9542. }
  9543. const String String::quoted (const juce_wchar quoteCharacter) const
  9544. {
  9545. if (isEmpty())
  9546. return charToString (quoteCharacter) + quoteCharacter;
  9547. String t (*this);
  9548. if (! t.startsWithChar (quoteCharacter))
  9549. t = charToString (quoteCharacter) + t;
  9550. if (! t.endsWithChar (quoteCharacter))
  9551. t += quoteCharacter;
  9552. return t;
  9553. }
  9554. const String String::trim() const
  9555. {
  9556. if (isEmpty())
  9557. return empty;
  9558. int start = 0;
  9559. while (CharacterFunctions::isWhitespace (text [start]))
  9560. ++start;
  9561. const int len = length();
  9562. int end = len - 1;
  9563. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9564. --end;
  9565. ++end;
  9566. if (end <= start)
  9567. return empty;
  9568. else if (start > 0 || end < len)
  9569. return String (text + start, end - start);
  9570. return *this;
  9571. }
  9572. const String String::trimStart() const
  9573. {
  9574. if (isEmpty())
  9575. return empty;
  9576. const juce_wchar* t = text;
  9577. while (CharacterFunctions::isWhitespace (*t))
  9578. ++t;
  9579. if (t == text)
  9580. return *this;
  9581. return String (t);
  9582. }
  9583. const String String::trimEnd() const
  9584. {
  9585. if (isEmpty())
  9586. return empty;
  9587. const juce_wchar* endT = text + (length() - 1);
  9588. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9589. --endT;
  9590. return String (text, (int) (++endT - text));
  9591. }
  9592. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9593. {
  9594. const juce_wchar* t = text;
  9595. while (charactersToTrim.containsChar (*t))
  9596. ++t;
  9597. return t == text ? *this : String (t);
  9598. }
  9599. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9600. {
  9601. if (isEmpty())
  9602. return empty;
  9603. const int len = length();
  9604. const juce_wchar* endT = text + (len - 1);
  9605. int numToRemove = 0;
  9606. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9607. {
  9608. ++numToRemove;
  9609. --endT;
  9610. }
  9611. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9612. }
  9613. const String String::retainCharacters (const String& charactersToRetain) const
  9614. {
  9615. if (isEmpty())
  9616. return empty;
  9617. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9618. juce_wchar* dst = result.text;
  9619. const juce_wchar* src = text;
  9620. while (*src != 0)
  9621. {
  9622. if (charactersToRetain.containsChar (*src))
  9623. *dst++ = *src;
  9624. ++src;
  9625. }
  9626. *dst = 0;
  9627. return result;
  9628. }
  9629. const String String::removeCharacters (const String& charactersToRemove) const
  9630. {
  9631. if (isEmpty())
  9632. return empty;
  9633. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9634. juce_wchar* dst = result.text;
  9635. const juce_wchar* src = text;
  9636. while (*src != 0)
  9637. {
  9638. if (! charactersToRemove.containsChar (*src))
  9639. *dst++ = *src;
  9640. ++src;
  9641. }
  9642. *dst = 0;
  9643. return result;
  9644. }
  9645. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9646. {
  9647. int i = 0;
  9648. for (;;)
  9649. {
  9650. if (! permittedCharacters.containsChar (text[i]))
  9651. break;
  9652. ++i;
  9653. }
  9654. return substring (0, i);
  9655. }
  9656. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9657. {
  9658. const juce_wchar* const t = text;
  9659. int i = 0;
  9660. while (t[i] != 0)
  9661. {
  9662. if (charactersToStopAt.containsChar (t[i]))
  9663. return String (text, i);
  9664. ++i;
  9665. }
  9666. return empty;
  9667. }
  9668. bool String::containsOnly (const String& chars) const throw()
  9669. {
  9670. const juce_wchar* t = text;
  9671. while (*t != 0)
  9672. if (! chars.containsChar (*t++))
  9673. return false;
  9674. return true;
  9675. }
  9676. bool String::containsAnyOf (const String& chars) const throw()
  9677. {
  9678. const juce_wchar* t = text;
  9679. while (*t != 0)
  9680. if (chars.containsChar (*t++))
  9681. return true;
  9682. return false;
  9683. }
  9684. bool String::containsNonWhitespaceChars() const throw()
  9685. {
  9686. const juce_wchar* t = text;
  9687. while (*t != 0)
  9688. if (! CharacterFunctions::isWhitespace (*t++))
  9689. return true;
  9690. return false;
  9691. }
  9692. const String String::formatted (const juce_wchar* const pf, ... )
  9693. {
  9694. jassert (pf != 0);
  9695. va_list args;
  9696. va_start (args, pf);
  9697. size_t bufferSize = 256;
  9698. String result (bufferSize, (int) 0);
  9699. result.text[0] = 0;
  9700. for (;;)
  9701. {
  9702. #if JUCE_LINUX && JUCE_64BIT
  9703. va_list tempArgs;
  9704. va_copy (tempArgs, args);
  9705. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9706. va_end (tempArgs);
  9707. #elif JUCE_WINDOWS
  9708. #if JUCE_MSVC
  9709. #pragma warning (push)
  9710. #pragma warning (disable: 4996)
  9711. #endif
  9712. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9713. #if JUCE_MSVC
  9714. #pragma warning (pop)
  9715. #endif
  9716. #else
  9717. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9718. #endif
  9719. if (num > 0)
  9720. return result;
  9721. bufferSize += 256;
  9722. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9723. break; // returns -1 because of an error rather than because it needs more space.
  9724. result.preallocateStorage (bufferSize);
  9725. }
  9726. return empty;
  9727. }
  9728. int String::getIntValue() const throw()
  9729. {
  9730. return CharacterFunctions::getIntValue (text);
  9731. }
  9732. int String::getTrailingIntValue() const throw()
  9733. {
  9734. int n = 0;
  9735. int mult = 1;
  9736. const juce_wchar* t = text + length();
  9737. while (--t >= text)
  9738. {
  9739. const juce_wchar c = *t;
  9740. if (! CharacterFunctions::isDigit (c))
  9741. {
  9742. if (c == '-')
  9743. n = -n;
  9744. break;
  9745. }
  9746. n += mult * (c - '0');
  9747. mult *= 10;
  9748. }
  9749. return n;
  9750. }
  9751. int64 String::getLargeIntValue() const throw()
  9752. {
  9753. return CharacterFunctions::getInt64Value (text);
  9754. }
  9755. float String::getFloatValue() const throw()
  9756. {
  9757. return (float) CharacterFunctions::getDoubleValue (text);
  9758. }
  9759. double String::getDoubleValue() const throw()
  9760. {
  9761. return CharacterFunctions::getDoubleValue (text);
  9762. }
  9763. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  9764. const String String::toHexString (const int number)
  9765. {
  9766. juce_wchar buffer[32];
  9767. juce_wchar* const end = buffer + 32;
  9768. juce_wchar* t = end;
  9769. *--t = 0;
  9770. unsigned int v = (unsigned int) number;
  9771. do
  9772. {
  9773. *--t = hexDigits [v & 15];
  9774. v >>= 4;
  9775. } while (v != 0);
  9776. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9777. }
  9778. const String String::toHexString (const int64 number)
  9779. {
  9780. juce_wchar buffer[32];
  9781. juce_wchar* const end = buffer + 32;
  9782. juce_wchar* t = end;
  9783. *--t = 0;
  9784. uint64 v = (uint64) number;
  9785. do
  9786. {
  9787. *--t = hexDigits [(int) (v & 15)];
  9788. v >>= 4;
  9789. } while (v != 0);
  9790. return String (t, (int) (((char*) end) - (char*) t));
  9791. }
  9792. const String String::toHexString (const short number)
  9793. {
  9794. return toHexString ((int) (unsigned short) number);
  9795. }
  9796. const String String::toHexString (const unsigned char* data,
  9797. const int size,
  9798. const int groupSize)
  9799. {
  9800. if (size <= 0)
  9801. return empty;
  9802. int numChars = (size * 2) + 2;
  9803. if (groupSize > 0)
  9804. numChars += size / groupSize;
  9805. String s ((size_t) numChars, (int) 0);
  9806. juce_wchar* d = s.text;
  9807. for (int i = 0; i < size; ++i)
  9808. {
  9809. *d++ = hexDigits [(*data) >> 4];
  9810. *d++ = hexDigits [(*data) & 0xf];
  9811. ++data;
  9812. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9813. *d++ = ' ';
  9814. }
  9815. *d = 0;
  9816. return s;
  9817. }
  9818. int String::getHexValue32() const throw()
  9819. {
  9820. int result = 0;
  9821. const juce_wchar* c = text;
  9822. for (;;)
  9823. {
  9824. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9825. if (hexValue >= 0)
  9826. result = (result << 4) | hexValue;
  9827. else if (*c == 0)
  9828. break;
  9829. ++c;
  9830. }
  9831. return result;
  9832. }
  9833. int64 String::getHexValue64() const throw()
  9834. {
  9835. int64 result = 0;
  9836. const juce_wchar* c = text;
  9837. for (;;)
  9838. {
  9839. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9840. if (hexValue >= 0)
  9841. result = (result << 4) | hexValue;
  9842. else if (*c == 0)
  9843. break;
  9844. ++c;
  9845. }
  9846. return result;
  9847. }
  9848. const String String::createStringFromData (const void* const data_, const int size)
  9849. {
  9850. const char* const data = static_cast <const char*> (data_);
  9851. if (size <= 0 || data == 0)
  9852. {
  9853. return empty;
  9854. }
  9855. else if (size < 2)
  9856. {
  9857. return charToString (data[0]);
  9858. }
  9859. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9860. || (data[0] == (char)-1 && data[1] == (char)-2))
  9861. {
  9862. // assume it's 16-bit unicode
  9863. const bool bigEndian = (data[0] == (char)-2);
  9864. const int numChars = size / 2 - 1;
  9865. String result;
  9866. result.preallocateStorage (numChars + 2);
  9867. const uint16* const src = (const uint16*) (data + 2);
  9868. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9869. if (bigEndian)
  9870. {
  9871. for (int i = 0; i < numChars; ++i)
  9872. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9873. }
  9874. else
  9875. {
  9876. for (int i = 0; i < numChars; ++i)
  9877. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9878. }
  9879. dst [numChars] = 0;
  9880. return result;
  9881. }
  9882. else
  9883. {
  9884. return String::fromUTF8 (data, size);
  9885. }
  9886. }
  9887. const char* String::toUTF8() const
  9888. {
  9889. if (isEmpty())
  9890. {
  9891. return reinterpret_cast <const char*> (text);
  9892. }
  9893. else
  9894. {
  9895. const int currentLen = length() + 1;
  9896. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9897. String* const mutableThis = const_cast <String*> (this);
  9898. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9899. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9900. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  9901. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  9902. #endif
  9903. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9904. return otherCopy;
  9905. }
  9906. }
  9907. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9908. {
  9909. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9910. int num = 0, index = 0;
  9911. for (;;)
  9912. {
  9913. const uint32 c = (uint32) text [index++];
  9914. if (c >= 0x80)
  9915. {
  9916. int numExtraBytes = 1;
  9917. if (c >= 0x800)
  9918. {
  9919. ++numExtraBytes;
  9920. if (c >= 0x10000)
  9921. {
  9922. ++numExtraBytes;
  9923. if (c >= 0x200000)
  9924. {
  9925. ++numExtraBytes;
  9926. if (c >= 0x4000000)
  9927. ++numExtraBytes;
  9928. }
  9929. }
  9930. }
  9931. if (buffer != 0)
  9932. {
  9933. if (num + numExtraBytes >= maxBufferSizeBytes)
  9934. {
  9935. buffer [num++] = 0;
  9936. break;
  9937. }
  9938. else
  9939. {
  9940. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9941. while (--numExtraBytes >= 0)
  9942. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9943. }
  9944. }
  9945. else
  9946. {
  9947. num += numExtraBytes + 1;
  9948. }
  9949. }
  9950. else
  9951. {
  9952. if (buffer != 0)
  9953. {
  9954. if (num + 1 >= maxBufferSizeBytes)
  9955. {
  9956. buffer [num++] = 0;
  9957. break;
  9958. }
  9959. buffer [num] = (uint8) c;
  9960. }
  9961. ++num;
  9962. }
  9963. if (c == 0)
  9964. break;
  9965. }
  9966. return num;
  9967. }
  9968. int String::getNumBytesAsUTF8() const throw()
  9969. {
  9970. int num = 0;
  9971. const juce_wchar* t = text;
  9972. for (;;)
  9973. {
  9974. const uint32 c = (uint32) *t;
  9975. if (c >= 0x80)
  9976. {
  9977. ++num;
  9978. if (c >= 0x800)
  9979. {
  9980. ++num;
  9981. if (c >= 0x10000)
  9982. {
  9983. ++num;
  9984. if (c >= 0x200000)
  9985. {
  9986. ++num;
  9987. if (c >= 0x4000000)
  9988. ++num;
  9989. }
  9990. }
  9991. }
  9992. }
  9993. else if (c == 0)
  9994. break;
  9995. ++num;
  9996. ++t;
  9997. }
  9998. return num;
  9999. }
  10000. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10001. {
  10002. if (buffer == 0)
  10003. return empty;
  10004. if (bufferSizeBytes < 0)
  10005. bufferSizeBytes = std::numeric_limits<int>::max();
  10006. size_t numBytes;
  10007. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10008. if (buffer [numBytes] == 0)
  10009. break;
  10010. String result ((size_t) numBytes + 1, (int) 0);
  10011. juce_wchar* dest = result.text;
  10012. size_t i = 0;
  10013. while (i < numBytes)
  10014. {
  10015. const char c = buffer [i++];
  10016. if (c < 0)
  10017. {
  10018. unsigned int mask = 0x7f;
  10019. int bit = 0x40;
  10020. int numExtraValues = 0;
  10021. while (bit != 0 && (c & bit) != 0)
  10022. {
  10023. bit >>= 1;
  10024. mask >>= 1;
  10025. ++numExtraValues;
  10026. }
  10027. int n = (mask & (unsigned char) c);
  10028. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10029. {
  10030. const char nextByte = buffer[i];
  10031. if ((nextByte & 0xc0) != 0x80)
  10032. break;
  10033. n <<= 6;
  10034. n |= (nextByte & 0x3f);
  10035. ++i;
  10036. }
  10037. *dest++ = (juce_wchar) n;
  10038. }
  10039. else
  10040. {
  10041. *dest++ = (juce_wchar) c;
  10042. }
  10043. }
  10044. *dest = 0;
  10045. return result;
  10046. }
  10047. const char* String::toCString() const
  10048. {
  10049. if (isEmpty())
  10050. {
  10051. return reinterpret_cast <const char*> (text);
  10052. }
  10053. else
  10054. {
  10055. const int len = length();
  10056. String* const mutableThis = const_cast <String*> (this);
  10057. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10058. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10059. CharacterFunctions::copy (otherCopy, text, len);
  10060. otherCopy [len] = 0;
  10061. return otherCopy;
  10062. }
  10063. }
  10064. #if JUCE_MSVC
  10065. #pragma warning (push)
  10066. #pragma warning (disable: 4514 4996)
  10067. #endif
  10068. int String::getNumBytesAsCString() const throw()
  10069. {
  10070. return (int) wcstombs (0, text, 0);
  10071. }
  10072. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10073. {
  10074. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10075. if (destBuffer != 0 && numBytes >= 0)
  10076. destBuffer [numBytes] = 0;
  10077. return numBytes;
  10078. }
  10079. #if JUCE_MSVC
  10080. #pragma warning (pop)
  10081. #endif
  10082. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  10083. {
  10084. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  10085. }
  10086. String::Concatenator::Concatenator (String& stringToAppendTo)
  10087. : result (stringToAppendTo),
  10088. nextIndex (stringToAppendTo.length())
  10089. {
  10090. }
  10091. String::Concatenator::~Concatenator()
  10092. {
  10093. }
  10094. void String::Concatenator::append (const String& s)
  10095. {
  10096. const int len = s.length();
  10097. if (len > 0)
  10098. {
  10099. result.preallocateStorage (nextIndex + len);
  10100. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10101. nextIndex += len;
  10102. }
  10103. }
  10104. END_JUCE_NAMESPACE
  10105. /*** End of inlined file: juce_String.cpp ***/
  10106. /*** Start of inlined file: juce_StringArray.cpp ***/
  10107. BEGIN_JUCE_NAMESPACE
  10108. StringArray::StringArray() throw()
  10109. {
  10110. }
  10111. StringArray::StringArray (const StringArray& other)
  10112. : strings (other.strings)
  10113. {
  10114. }
  10115. StringArray::StringArray (const String& firstValue)
  10116. {
  10117. strings.add (firstValue);
  10118. }
  10119. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10120. const int numberOfStrings)
  10121. {
  10122. for (int i = 0; i < numberOfStrings; ++i)
  10123. strings.add (initialStrings [i]);
  10124. }
  10125. StringArray::StringArray (const char* const* const initialStrings,
  10126. const int numberOfStrings)
  10127. {
  10128. for (int i = 0; i < numberOfStrings; ++i)
  10129. strings.add (initialStrings [i]);
  10130. }
  10131. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10132. {
  10133. int i = 0;
  10134. while (initialStrings[i] != 0)
  10135. strings.add (initialStrings [i++]);
  10136. }
  10137. StringArray::StringArray (const char* const* const initialStrings)
  10138. {
  10139. int i = 0;
  10140. while (initialStrings[i] != 0)
  10141. strings.add (initialStrings [i++]);
  10142. }
  10143. StringArray& StringArray::operator= (const StringArray& other)
  10144. {
  10145. strings = other.strings;
  10146. return *this;
  10147. }
  10148. StringArray::~StringArray()
  10149. {
  10150. }
  10151. bool StringArray::operator== (const StringArray& other) const throw()
  10152. {
  10153. if (other.size() != size())
  10154. return false;
  10155. for (int i = size(); --i >= 0;)
  10156. if (other.strings.getReference(i) != strings.getReference(i))
  10157. return false;
  10158. return true;
  10159. }
  10160. bool StringArray::operator!= (const StringArray& other) const throw()
  10161. {
  10162. return ! operator== (other);
  10163. }
  10164. void StringArray::clear()
  10165. {
  10166. strings.clear();
  10167. }
  10168. const String& StringArray::operator[] (const int index) const throw()
  10169. {
  10170. if (((unsigned int) index) < (unsigned int) strings.size())
  10171. return strings.getReference (index);
  10172. return String::empty;
  10173. }
  10174. String& StringArray::getReference (const int index) throw()
  10175. {
  10176. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10177. return strings.getReference (index);
  10178. }
  10179. void StringArray::add (const String& newString)
  10180. {
  10181. strings.add (newString);
  10182. }
  10183. void StringArray::insert (const int index, const String& newString)
  10184. {
  10185. strings.insert (index, newString);
  10186. }
  10187. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10188. {
  10189. if (! contains (newString, ignoreCase))
  10190. add (newString);
  10191. }
  10192. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10193. {
  10194. if (startIndex < 0)
  10195. {
  10196. jassertfalse;
  10197. startIndex = 0;
  10198. }
  10199. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10200. numElementsToAdd = otherArray.size() - startIndex;
  10201. while (--numElementsToAdd >= 0)
  10202. strings.add (otherArray.strings.getReference (startIndex++));
  10203. }
  10204. void StringArray::set (const int index, const String& newString)
  10205. {
  10206. strings.set (index, newString);
  10207. }
  10208. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10209. {
  10210. if (ignoreCase)
  10211. {
  10212. for (int i = size(); --i >= 0;)
  10213. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10214. return true;
  10215. }
  10216. else
  10217. {
  10218. for (int i = size(); --i >= 0;)
  10219. if (stringToLookFor == strings.getReference(i))
  10220. return true;
  10221. }
  10222. return false;
  10223. }
  10224. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10225. {
  10226. if (i < 0)
  10227. i = 0;
  10228. const int numElements = size();
  10229. if (ignoreCase)
  10230. {
  10231. while (i < numElements)
  10232. {
  10233. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10234. return i;
  10235. ++i;
  10236. }
  10237. }
  10238. else
  10239. {
  10240. while (i < numElements)
  10241. {
  10242. if (stringToLookFor == strings.getReference (i))
  10243. return i;
  10244. ++i;
  10245. }
  10246. }
  10247. return -1;
  10248. }
  10249. void StringArray::remove (const int index)
  10250. {
  10251. strings.remove (index);
  10252. }
  10253. void StringArray::removeString (const String& stringToRemove,
  10254. const bool ignoreCase)
  10255. {
  10256. if (ignoreCase)
  10257. {
  10258. for (int i = size(); --i >= 0;)
  10259. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10260. strings.remove (i);
  10261. }
  10262. else
  10263. {
  10264. for (int i = size(); --i >= 0;)
  10265. if (stringToRemove == strings.getReference (i))
  10266. strings.remove (i);
  10267. }
  10268. }
  10269. void StringArray::removeRange (int startIndex, int numberToRemove)
  10270. {
  10271. strings.removeRange (startIndex, numberToRemove);
  10272. }
  10273. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10274. {
  10275. if (removeWhitespaceStrings)
  10276. {
  10277. for (int i = size(); --i >= 0;)
  10278. if (! strings.getReference(i).containsNonWhitespaceChars())
  10279. strings.remove (i);
  10280. }
  10281. else
  10282. {
  10283. for (int i = size(); --i >= 0;)
  10284. if (strings.getReference(i).isEmpty())
  10285. strings.remove (i);
  10286. }
  10287. }
  10288. void StringArray::trim()
  10289. {
  10290. for (int i = size(); --i >= 0;)
  10291. {
  10292. String& s = strings.getReference(i);
  10293. s = s.trim();
  10294. }
  10295. }
  10296. class InternalStringArrayComparator_CaseSensitive
  10297. {
  10298. public:
  10299. static int compareElements (String& first, String& second) { return first.compare (second); }
  10300. };
  10301. class InternalStringArrayComparator_CaseInsensitive
  10302. {
  10303. public:
  10304. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10305. };
  10306. void StringArray::sort (const bool ignoreCase)
  10307. {
  10308. if (ignoreCase)
  10309. {
  10310. InternalStringArrayComparator_CaseInsensitive comp;
  10311. strings.sort (comp);
  10312. }
  10313. else
  10314. {
  10315. InternalStringArrayComparator_CaseSensitive comp;
  10316. strings.sort (comp);
  10317. }
  10318. }
  10319. void StringArray::move (const int currentIndex, int newIndex) throw()
  10320. {
  10321. strings.move (currentIndex, newIndex);
  10322. }
  10323. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10324. {
  10325. const int last = (numberToJoin < 0) ? size()
  10326. : jmin (size(), start + numberToJoin);
  10327. if (start < 0)
  10328. start = 0;
  10329. if (start >= last)
  10330. return String::empty;
  10331. if (start == last - 1)
  10332. return strings.getReference (start);
  10333. const int separatorLen = separator.length();
  10334. int charsNeeded = separatorLen * (last - start - 1);
  10335. for (int i = start; i < last; ++i)
  10336. charsNeeded += strings.getReference(i).length();
  10337. String result;
  10338. result.preallocateStorage (charsNeeded);
  10339. juce_wchar* dest = result;
  10340. while (start < last)
  10341. {
  10342. const String& s = strings.getReference (start);
  10343. const int len = s.length();
  10344. if (len > 0)
  10345. {
  10346. s.copyToUnicode (dest, len);
  10347. dest += len;
  10348. }
  10349. if (++start < last && separatorLen > 0)
  10350. {
  10351. separator.copyToUnicode (dest, separatorLen);
  10352. dest += separatorLen;
  10353. }
  10354. }
  10355. *dest = 0;
  10356. return result;
  10357. }
  10358. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10359. {
  10360. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10361. }
  10362. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10363. {
  10364. int num = 0;
  10365. if (text.isNotEmpty())
  10366. {
  10367. bool insideQuotes = false;
  10368. juce_wchar currentQuoteChar = 0;
  10369. int i = 0;
  10370. int tokenStart = 0;
  10371. for (;;)
  10372. {
  10373. const juce_wchar c = text[i];
  10374. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10375. if (! isBreak)
  10376. {
  10377. if (quoteCharacters.containsChar (c))
  10378. {
  10379. if (insideQuotes)
  10380. {
  10381. // only break out of quotes-mode if we find a matching quote to the
  10382. // one that we opened with..
  10383. if (currentQuoteChar == c)
  10384. insideQuotes = false;
  10385. }
  10386. else
  10387. {
  10388. insideQuotes = true;
  10389. currentQuoteChar = c;
  10390. }
  10391. }
  10392. }
  10393. else
  10394. {
  10395. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10396. ++num;
  10397. tokenStart = i + 1;
  10398. }
  10399. if (c == 0)
  10400. break;
  10401. ++i;
  10402. }
  10403. }
  10404. return num;
  10405. }
  10406. int StringArray::addLines (const String& sourceText)
  10407. {
  10408. int numLines = 0;
  10409. const juce_wchar* text = sourceText;
  10410. while (*text != 0)
  10411. {
  10412. const juce_wchar* const startOfLine = text;
  10413. while (*text != 0)
  10414. {
  10415. if (*text == '\r')
  10416. {
  10417. ++text;
  10418. if (*text == '\n')
  10419. ++text;
  10420. break;
  10421. }
  10422. if (*text == '\n')
  10423. {
  10424. ++text;
  10425. break;
  10426. }
  10427. ++text;
  10428. }
  10429. const juce_wchar* endOfLine = text;
  10430. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10431. --endOfLine;
  10432. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10433. --endOfLine;
  10434. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10435. ++numLines;
  10436. }
  10437. return numLines;
  10438. }
  10439. void StringArray::removeDuplicates (const bool ignoreCase)
  10440. {
  10441. for (int i = 0; i < size() - 1; ++i)
  10442. {
  10443. const String s (strings.getReference(i));
  10444. int nextIndex = i + 1;
  10445. for (;;)
  10446. {
  10447. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10448. if (nextIndex < 0)
  10449. break;
  10450. strings.remove (nextIndex);
  10451. }
  10452. }
  10453. }
  10454. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10455. const bool appendNumberToFirstInstance,
  10456. const juce_wchar* preNumberString,
  10457. const juce_wchar* postNumberString)
  10458. {
  10459. if (preNumberString == 0)
  10460. preNumberString = L" (";
  10461. if (postNumberString == 0)
  10462. postNumberString = L")";
  10463. for (int i = 0; i < size() - 1; ++i)
  10464. {
  10465. String& s = strings.getReference(i);
  10466. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10467. if (nextIndex >= 0)
  10468. {
  10469. const String original (s);
  10470. int number = 0;
  10471. if (appendNumberToFirstInstance)
  10472. s = original + preNumberString + String (++number) + postNumberString;
  10473. else
  10474. ++number;
  10475. while (nextIndex >= 0)
  10476. {
  10477. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10478. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10479. }
  10480. }
  10481. }
  10482. }
  10483. void StringArray::minimiseStorageOverheads()
  10484. {
  10485. strings.minimiseStorageOverheads();
  10486. }
  10487. END_JUCE_NAMESPACE
  10488. /*** End of inlined file: juce_StringArray.cpp ***/
  10489. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10490. BEGIN_JUCE_NAMESPACE
  10491. StringPairArray::StringPairArray (const bool ignoreCase_)
  10492. : ignoreCase (ignoreCase_)
  10493. {
  10494. }
  10495. StringPairArray::StringPairArray (const StringPairArray& other)
  10496. : keys (other.keys),
  10497. values (other.values),
  10498. ignoreCase (other.ignoreCase)
  10499. {
  10500. }
  10501. StringPairArray::~StringPairArray()
  10502. {
  10503. }
  10504. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10505. {
  10506. keys = other.keys;
  10507. values = other.values;
  10508. return *this;
  10509. }
  10510. bool StringPairArray::operator== (const StringPairArray& other) const
  10511. {
  10512. for (int i = keys.size(); --i >= 0;)
  10513. if (other [keys[i]] != values[i])
  10514. return false;
  10515. return true;
  10516. }
  10517. bool StringPairArray::operator!= (const StringPairArray& other) const
  10518. {
  10519. return ! operator== (other);
  10520. }
  10521. const String& StringPairArray::operator[] (const String& key) const
  10522. {
  10523. return values [keys.indexOf (key, ignoreCase)];
  10524. }
  10525. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10526. {
  10527. const int i = keys.indexOf (key, ignoreCase);
  10528. if (i >= 0)
  10529. return values[i];
  10530. return defaultReturnValue;
  10531. }
  10532. void StringPairArray::set (const String& key, const String& value)
  10533. {
  10534. const int i = keys.indexOf (key, ignoreCase);
  10535. if (i >= 0)
  10536. {
  10537. values.set (i, value);
  10538. }
  10539. else
  10540. {
  10541. keys.add (key);
  10542. values.add (value);
  10543. }
  10544. }
  10545. void StringPairArray::addArray (const StringPairArray& other)
  10546. {
  10547. for (int i = 0; i < other.size(); ++i)
  10548. set (other.keys[i], other.values[i]);
  10549. }
  10550. void StringPairArray::clear()
  10551. {
  10552. keys.clear();
  10553. values.clear();
  10554. }
  10555. void StringPairArray::remove (const String& key)
  10556. {
  10557. remove (keys.indexOf (key, ignoreCase));
  10558. }
  10559. void StringPairArray::remove (const int index)
  10560. {
  10561. keys.remove (index);
  10562. values.remove (index);
  10563. }
  10564. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10565. {
  10566. ignoreCase = shouldIgnoreCase;
  10567. }
  10568. const String StringPairArray::getDescription() const
  10569. {
  10570. String s;
  10571. for (int i = 0; i < keys.size(); ++i)
  10572. {
  10573. s << keys[i] << " = " << values[i];
  10574. if (i < keys.size())
  10575. s << ", ";
  10576. }
  10577. return s;
  10578. }
  10579. void StringPairArray::minimiseStorageOverheads()
  10580. {
  10581. keys.minimiseStorageOverheads();
  10582. values.minimiseStorageOverheads();
  10583. }
  10584. END_JUCE_NAMESPACE
  10585. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10586. /*** Start of inlined file: juce_StringPool.cpp ***/
  10587. BEGIN_JUCE_NAMESPACE
  10588. StringPool::StringPool() throw() {}
  10589. StringPool::~StringPool() {}
  10590. template <class StringType>
  10591. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  10592. {
  10593. int start = 0;
  10594. int end = strings.size();
  10595. for (;;)
  10596. {
  10597. if (start >= end)
  10598. {
  10599. jassert (start <= end);
  10600. strings.insert (start, newString);
  10601. return strings.getReference (start);
  10602. }
  10603. else
  10604. {
  10605. const String& startString = strings.getReference (start);
  10606. if (startString == newString)
  10607. return startString;
  10608. const int halfway = (start + end) >> 1;
  10609. if (halfway == start)
  10610. {
  10611. if (startString.compare (newString) < 0)
  10612. ++start;
  10613. strings.insert (start, newString);
  10614. return strings.getReference (start);
  10615. }
  10616. const int comp = strings.getReference (halfway).compare (newString);
  10617. if (comp == 0)
  10618. return strings.getReference (halfway);
  10619. else if (comp < 0)
  10620. start = halfway;
  10621. else
  10622. end = halfway;
  10623. }
  10624. }
  10625. }
  10626. const juce_wchar* StringPool::getPooledString (const String& s)
  10627. {
  10628. if (s.isEmpty())
  10629. return String::empty;
  10630. return getPooledStringFromArray (strings, s);
  10631. }
  10632. const juce_wchar* StringPool::getPooledString (const char* const s)
  10633. {
  10634. if (s == 0 || *s == 0)
  10635. return String::empty;
  10636. return getPooledStringFromArray (strings, s);
  10637. }
  10638. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  10639. {
  10640. if (s == 0 || *s == 0)
  10641. return String::empty;
  10642. return getPooledStringFromArray (strings, s);
  10643. }
  10644. int StringPool::size() const throw()
  10645. {
  10646. return strings.size();
  10647. }
  10648. const juce_wchar* StringPool::operator[] (const int index) const throw()
  10649. {
  10650. return strings [index];
  10651. }
  10652. END_JUCE_NAMESPACE
  10653. /*** End of inlined file: juce_StringPool.cpp ***/
  10654. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10655. BEGIN_JUCE_NAMESPACE
  10656. XmlDocument::XmlDocument (const String& documentText)
  10657. : originalText (documentText),
  10658. ignoreEmptyTextElements (true)
  10659. {
  10660. }
  10661. XmlDocument::XmlDocument (const File& file)
  10662. : ignoreEmptyTextElements (true)
  10663. {
  10664. inputSource = new FileInputSource (file);
  10665. }
  10666. XmlDocument::~XmlDocument()
  10667. {
  10668. }
  10669. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10670. {
  10671. inputSource = newSource;
  10672. }
  10673. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10674. {
  10675. ignoreEmptyTextElements = shouldBeIgnored;
  10676. }
  10677. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10678. {
  10679. return CharacterFunctions::isLetterOrDigit (c)
  10680. || c == '_' || c == '-' || c == ':' || c == '.';
  10681. }
  10682. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10683. {
  10684. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10685. : isXmlIdentifierCharSlow (c);
  10686. }
  10687. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10688. {
  10689. String textToParse (originalText);
  10690. if (textToParse.isEmpty() && inputSource != 0)
  10691. {
  10692. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10693. if (in != 0)
  10694. {
  10695. MemoryOutputStream data;
  10696. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  10697. textToParse = data.toString();
  10698. if (! onlyReadOuterDocumentElement)
  10699. originalText = textToParse;
  10700. }
  10701. }
  10702. input = textToParse;
  10703. lastError = String::empty;
  10704. errorOccurred = false;
  10705. outOfData = false;
  10706. needToLoadDTD = true;
  10707. for (int i = 0; i < 128; ++i)
  10708. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10709. if (textToParse.isEmpty())
  10710. {
  10711. lastError = "not enough input";
  10712. }
  10713. else
  10714. {
  10715. skipHeader();
  10716. if (input != 0)
  10717. {
  10718. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10719. if (! errorOccurred)
  10720. return result.release();
  10721. }
  10722. else
  10723. {
  10724. lastError = "incorrect xml header";
  10725. }
  10726. }
  10727. return 0;
  10728. }
  10729. const String& XmlDocument::getLastParseError() const throw()
  10730. {
  10731. return lastError;
  10732. }
  10733. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10734. {
  10735. lastError = desc;
  10736. errorOccurred = ! carryOn;
  10737. }
  10738. const String XmlDocument::getFileContents (const String& filename) const
  10739. {
  10740. if (inputSource != 0)
  10741. {
  10742. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10743. if (in != 0)
  10744. return in->readEntireStreamAsString();
  10745. }
  10746. return String::empty;
  10747. }
  10748. juce_wchar XmlDocument::readNextChar() throw()
  10749. {
  10750. if (*input != 0)
  10751. {
  10752. return *input++;
  10753. }
  10754. else
  10755. {
  10756. outOfData = true;
  10757. return 0;
  10758. }
  10759. }
  10760. int XmlDocument::findNextTokenLength() throw()
  10761. {
  10762. int len = 0;
  10763. juce_wchar c = *input;
  10764. while (isXmlIdentifierChar (c))
  10765. c = input [++len];
  10766. return len;
  10767. }
  10768. void XmlDocument::skipHeader()
  10769. {
  10770. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  10771. if (found != 0)
  10772. {
  10773. input = found;
  10774. input = CharacterFunctions::find (input, JUCE_T("?>"));
  10775. if (input == 0)
  10776. return;
  10777. input += 2;
  10778. }
  10779. skipNextWhiteSpace();
  10780. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  10781. if (docType == 0)
  10782. return;
  10783. input = docType + 9;
  10784. int n = 1;
  10785. while (n > 0)
  10786. {
  10787. const juce_wchar c = readNextChar();
  10788. if (outOfData)
  10789. return;
  10790. if (c == '<')
  10791. ++n;
  10792. else if (c == '>')
  10793. --n;
  10794. }
  10795. docType += 9;
  10796. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10797. }
  10798. void XmlDocument::skipNextWhiteSpace()
  10799. {
  10800. for (;;)
  10801. {
  10802. juce_wchar c = *input;
  10803. while (CharacterFunctions::isWhitespace (c))
  10804. c = *++input;
  10805. if (c == 0)
  10806. {
  10807. outOfData = true;
  10808. break;
  10809. }
  10810. else if (c == '<')
  10811. {
  10812. if (input[1] == '!'
  10813. && input[2] == '-'
  10814. && input[3] == '-')
  10815. {
  10816. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  10817. if (closeComment == 0)
  10818. {
  10819. outOfData = true;
  10820. break;
  10821. }
  10822. input = closeComment + 3;
  10823. continue;
  10824. }
  10825. else if (input[1] == '?')
  10826. {
  10827. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  10828. if (closeBracket == 0)
  10829. {
  10830. outOfData = true;
  10831. break;
  10832. }
  10833. input = closeBracket + 2;
  10834. continue;
  10835. }
  10836. }
  10837. break;
  10838. }
  10839. }
  10840. void XmlDocument::readQuotedString (String& result)
  10841. {
  10842. const juce_wchar quote = readNextChar();
  10843. while (! outOfData)
  10844. {
  10845. const juce_wchar c = readNextChar();
  10846. if (c == quote)
  10847. break;
  10848. if (c == '&')
  10849. {
  10850. --input;
  10851. readEntity (result);
  10852. }
  10853. else
  10854. {
  10855. --input;
  10856. const juce_wchar* const start = input;
  10857. for (;;)
  10858. {
  10859. const juce_wchar character = *input;
  10860. if (character == quote)
  10861. {
  10862. result.append (start, (int) (input - start));
  10863. ++input;
  10864. return;
  10865. }
  10866. else if (character == '&')
  10867. {
  10868. result.append (start, (int) (input - start));
  10869. break;
  10870. }
  10871. else if (character == 0)
  10872. {
  10873. outOfData = true;
  10874. setLastError ("unmatched quotes", false);
  10875. break;
  10876. }
  10877. ++input;
  10878. }
  10879. }
  10880. }
  10881. }
  10882. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10883. {
  10884. XmlElement* node = 0;
  10885. skipNextWhiteSpace();
  10886. if (outOfData)
  10887. return 0;
  10888. input = CharacterFunctions::find (input, JUCE_T("<"));
  10889. if (input != 0)
  10890. {
  10891. ++input;
  10892. int tagLen = findNextTokenLength();
  10893. if (tagLen == 0)
  10894. {
  10895. // no tag name - but allow for a gap after the '<' before giving an error
  10896. skipNextWhiteSpace();
  10897. tagLen = findNextTokenLength();
  10898. if (tagLen == 0)
  10899. {
  10900. setLastError ("tag name missing", false);
  10901. return node;
  10902. }
  10903. }
  10904. node = new XmlElement (String (input, tagLen));
  10905. input += tagLen;
  10906. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10907. // look for attributes
  10908. for (;;)
  10909. {
  10910. skipNextWhiteSpace();
  10911. const juce_wchar c = *input;
  10912. // empty tag..
  10913. if (c == '/' && input[1] == '>')
  10914. {
  10915. input += 2;
  10916. break;
  10917. }
  10918. // parse the guts of the element..
  10919. if (c == '>')
  10920. {
  10921. ++input;
  10922. skipNextWhiteSpace();
  10923. if (alsoParseSubElements)
  10924. readChildElements (node);
  10925. break;
  10926. }
  10927. // get an attribute..
  10928. if (isXmlIdentifierChar (c))
  10929. {
  10930. const int attNameLen = findNextTokenLength();
  10931. if (attNameLen > 0)
  10932. {
  10933. const juce_wchar* attNameStart = input;
  10934. input += attNameLen;
  10935. skipNextWhiteSpace();
  10936. if (readNextChar() == '=')
  10937. {
  10938. skipNextWhiteSpace();
  10939. const juce_wchar nextChar = *input;
  10940. if (nextChar == '"' || nextChar == '\'')
  10941. {
  10942. XmlElement::XmlAttributeNode* const newAtt
  10943. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10944. String::empty);
  10945. readQuotedString (newAtt->value);
  10946. if (lastAttribute == 0)
  10947. node->attributes = newAtt;
  10948. else
  10949. lastAttribute->next = newAtt;
  10950. lastAttribute = newAtt;
  10951. continue;
  10952. }
  10953. }
  10954. }
  10955. }
  10956. else
  10957. {
  10958. if (! outOfData)
  10959. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10960. }
  10961. break;
  10962. }
  10963. }
  10964. return node;
  10965. }
  10966. void XmlDocument::readChildElements (XmlElement* parent)
  10967. {
  10968. XmlElement* lastChildNode = 0;
  10969. for (;;)
  10970. {
  10971. skipNextWhiteSpace();
  10972. if (outOfData)
  10973. {
  10974. setLastError ("unmatched tags", false);
  10975. break;
  10976. }
  10977. if (*input == '<')
  10978. {
  10979. if (input[1] == '/')
  10980. {
  10981. // our close tag..
  10982. input = CharacterFunctions::find (input, JUCE_T(">"));
  10983. ++input;
  10984. break;
  10985. }
  10986. else if (input[1] == '!'
  10987. && input[2] == '['
  10988. && input[3] == 'C'
  10989. && input[4] == 'D'
  10990. && input[5] == 'A'
  10991. && input[6] == 'T'
  10992. && input[7] == 'A'
  10993. && input[8] == '[')
  10994. {
  10995. input += 9;
  10996. const juce_wchar* const inputStart = input;
  10997. int len = 0;
  10998. for (;;)
  10999. {
  11000. if (*input == 0)
  11001. {
  11002. setLastError ("unterminated CDATA section", false);
  11003. outOfData = true;
  11004. break;
  11005. }
  11006. else if (input[0] == ']'
  11007. && input[1] == ']'
  11008. && input[2] == '>')
  11009. {
  11010. input += 3;
  11011. break;
  11012. }
  11013. ++input;
  11014. ++len;
  11015. }
  11016. XmlElement* const e = new XmlElement ((int) 0);
  11017. e->setText (String (inputStart, len));
  11018. if (lastChildNode != 0)
  11019. lastChildNode->nextElement = e;
  11020. else
  11021. parent->addChildElement (e);
  11022. lastChildNode = e;
  11023. }
  11024. else
  11025. {
  11026. // this is some other element, so parse and add it..
  11027. XmlElement* const n = readNextElement (true);
  11028. if (n != 0)
  11029. {
  11030. if (lastChildNode == 0)
  11031. parent->addChildElement (n);
  11032. else
  11033. lastChildNode->nextElement = n;
  11034. lastChildNode = n;
  11035. }
  11036. else
  11037. {
  11038. return;
  11039. }
  11040. }
  11041. }
  11042. else
  11043. {
  11044. // read character block..
  11045. XmlElement* const e = new XmlElement ((int)0);
  11046. if (lastChildNode != 0)
  11047. lastChildNode->nextElement = e;
  11048. else
  11049. parent->addChildElement (e);
  11050. lastChildNode = e;
  11051. String textElementContent;
  11052. for (;;)
  11053. {
  11054. const juce_wchar c = *input;
  11055. if (c == '<')
  11056. break;
  11057. if (c == 0)
  11058. {
  11059. setLastError ("unmatched tags", false);
  11060. outOfData = true;
  11061. return;
  11062. }
  11063. if (c == '&')
  11064. {
  11065. String entity;
  11066. readEntity (entity);
  11067. if (entity.startsWithChar ('<') && entity [1] != 0)
  11068. {
  11069. const juce_wchar* const oldInput = input;
  11070. const bool oldOutOfData = outOfData;
  11071. input = entity;
  11072. outOfData = false;
  11073. for (;;)
  11074. {
  11075. XmlElement* const n = readNextElement (true);
  11076. if (n == 0)
  11077. break;
  11078. if (lastChildNode == 0)
  11079. parent->addChildElement (n);
  11080. else
  11081. lastChildNode->nextElement = n;
  11082. lastChildNode = n;
  11083. }
  11084. input = oldInput;
  11085. outOfData = oldOutOfData;
  11086. }
  11087. else
  11088. {
  11089. textElementContent += entity;
  11090. }
  11091. }
  11092. else
  11093. {
  11094. const juce_wchar* start = input;
  11095. int len = 0;
  11096. for (;;)
  11097. {
  11098. const juce_wchar nextChar = *input;
  11099. if (nextChar == '<' || nextChar == '&')
  11100. {
  11101. break;
  11102. }
  11103. else if (nextChar == 0)
  11104. {
  11105. setLastError ("unmatched tags", false);
  11106. outOfData = true;
  11107. return;
  11108. }
  11109. ++input;
  11110. ++len;
  11111. }
  11112. textElementContent.append (start, len);
  11113. }
  11114. }
  11115. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11116. : textElementContent.isNotEmpty())
  11117. e->setText (textElementContent);
  11118. }
  11119. }
  11120. }
  11121. void XmlDocument::readEntity (String& result)
  11122. {
  11123. // skip over the ampersand
  11124. ++input;
  11125. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11126. {
  11127. input += 4;
  11128. result += '&';
  11129. }
  11130. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11131. {
  11132. input += 5;
  11133. result += '"';
  11134. }
  11135. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11136. {
  11137. input += 5;
  11138. result += '\'';
  11139. }
  11140. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11141. {
  11142. input += 3;
  11143. result += '<';
  11144. }
  11145. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11146. {
  11147. input += 3;
  11148. result += '>';
  11149. }
  11150. else if (*input == '#')
  11151. {
  11152. int charCode = 0;
  11153. ++input;
  11154. if (*input == 'x' || *input == 'X')
  11155. {
  11156. ++input;
  11157. int numChars = 0;
  11158. while (input[0] != ';')
  11159. {
  11160. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11161. if (hexValue < 0 || ++numChars > 8)
  11162. {
  11163. setLastError ("illegal escape sequence", true);
  11164. break;
  11165. }
  11166. charCode = (charCode << 4) | hexValue;
  11167. ++input;
  11168. }
  11169. ++input;
  11170. }
  11171. else if (input[0] >= '0' && input[0] <= '9')
  11172. {
  11173. int numChars = 0;
  11174. while (input[0] != ';')
  11175. {
  11176. if (++numChars > 12)
  11177. {
  11178. setLastError ("illegal escape sequence", true);
  11179. break;
  11180. }
  11181. charCode = charCode * 10 + (input[0] - '0');
  11182. ++input;
  11183. }
  11184. ++input;
  11185. }
  11186. else
  11187. {
  11188. setLastError ("illegal escape sequence", true);
  11189. result += '&';
  11190. return;
  11191. }
  11192. result << (juce_wchar) charCode;
  11193. }
  11194. else
  11195. {
  11196. const juce_wchar* const entityNameStart = input;
  11197. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11198. if (closingSemiColon == 0)
  11199. {
  11200. outOfData = true;
  11201. result += '&';
  11202. }
  11203. else
  11204. {
  11205. input = closingSemiColon + 1;
  11206. result += expandExternalEntity (String (entityNameStart,
  11207. (int) (closingSemiColon - entityNameStart)));
  11208. }
  11209. }
  11210. }
  11211. const String XmlDocument::expandEntity (const String& ent)
  11212. {
  11213. if (ent.equalsIgnoreCase ("amp"))
  11214. return String::charToString ('&');
  11215. if (ent.equalsIgnoreCase ("quot"))
  11216. return String::charToString ('"');
  11217. if (ent.equalsIgnoreCase ("apos"))
  11218. return String::charToString ('\'');
  11219. if (ent.equalsIgnoreCase ("lt"))
  11220. return String::charToString ('<');
  11221. if (ent.equalsIgnoreCase ("gt"))
  11222. return String::charToString ('>');
  11223. if (ent[0] == '#')
  11224. {
  11225. if (ent[1] == 'x' || ent[1] == 'X')
  11226. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11227. if (ent[1] >= '0' && ent[1] <= '9')
  11228. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11229. setLastError ("illegal escape sequence", false);
  11230. return String::charToString ('&');
  11231. }
  11232. return expandExternalEntity (ent);
  11233. }
  11234. const String XmlDocument::expandExternalEntity (const String& entity)
  11235. {
  11236. if (needToLoadDTD)
  11237. {
  11238. if (dtdText.isNotEmpty())
  11239. {
  11240. dtdText = dtdText.trimCharactersAtEnd (">");
  11241. tokenisedDTD.addTokens (dtdText, true);
  11242. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11243. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11244. {
  11245. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11246. tokenisedDTD.clear();
  11247. tokenisedDTD.addTokens (getFileContents (fn), true);
  11248. }
  11249. else
  11250. {
  11251. tokenisedDTD.clear();
  11252. const int openBracket = dtdText.indexOfChar ('[');
  11253. if (openBracket > 0)
  11254. {
  11255. const int closeBracket = dtdText.lastIndexOfChar (']');
  11256. if (closeBracket > openBracket)
  11257. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11258. closeBracket), true);
  11259. }
  11260. }
  11261. for (int i = tokenisedDTD.size(); --i >= 0;)
  11262. {
  11263. if (tokenisedDTD[i].startsWithChar ('%')
  11264. && tokenisedDTD[i].endsWithChar (';'))
  11265. {
  11266. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11267. StringArray newToks;
  11268. newToks.addTokens (parsed, true);
  11269. tokenisedDTD.remove (i);
  11270. for (int j = newToks.size(); --j >= 0;)
  11271. tokenisedDTD.insert (i, newToks[j]);
  11272. }
  11273. }
  11274. }
  11275. needToLoadDTD = false;
  11276. }
  11277. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11278. {
  11279. if (tokenisedDTD[i] == entity)
  11280. {
  11281. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11282. {
  11283. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11284. // check for sub-entities..
  11285. int ampersand = ent.indexOfChar ('&');
  11286. while (ampersand >= 0)
  11287. {
  11288. const int semiColon = ent.indexOf (i + 1, ";");
  11289. if (semiColon < 0)
  11290. {
  11291. setLastError ("entity without terminating semi-colon", false);
  11292. break;
  11293. }
  11294. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11295. ent = ent.substring (0, ampersand)
  11296. + resolved
  11297. + ent.substring (semiColon + 1);
  11298. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11299. }
  11300. return ent;
  11301. }
  11302. }
  11303. }
  11304. setLastError ("unknown entity", true);
  11305. return entity;
  11306. }
  11307. const String XmlDocument::getParameterEntity (const String& entity)
  11308. {
  11309. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11310. {
  11311. if (tokenisedDTD[i] == entity)
  11312. {
  11313. if (tokenisedDTD [i - 1] == "%"
  11314. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11315. {
  11316. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11317. if (ent.equalsIgnoreCase ("system"))
  11318. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11319. else
  11320. return ent.trim().unquoted();
  11321. }
  11322. }
  11323. }
  11324. return entity;
  11325. }
  11326. END_JUCE_NAMESPACE
  11327. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11328. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11329. BEGIN_JUCE_NAMESPACE
  11330. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11331. : name (other.name),
  11332. value (other.value),
  11333. next (0)
  11334. {
  11335. }
  11336. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11337. : name (name_),
  11338. value (value_),
  11339. next (0)
  11340. {
  11341. }
  11342. XmlElement::XmlElement (const String& tagName_) throw()
  11343. : tagName (tagName_),
  11344. firstChildElement (0),
  11345. nextElement (0),
  11346. attributes (0)
  11347. {
  11348. // the tag name mustn't be empty, or it'll look like a text element!
  11349. jassert (tagName_.containsNonWhitespaceChars())
  11350. // The tag can't contain spaces or other characters that would create invalid XML!
  11351. jassert (! tagName_.containsAnyOf (" <>/&"));
  11352. }
  11353. XmlElement::XmlElement (int /*dummy*/) throw()
  11354. : firstChildElement (0),
  11355. nextElement (0),
  11356. attributes (0)
  11357. {
  11358. }
  11359. XmlElement::XmlElement (const XmlElement& other)
  11360. : tagName (other.tagName),
  11361. firstChildElement (0),
  11362. nextElement (0),
  11363. attributes (0)
  11364. {
  11365. copyChildrenAndAttributesFrom (other);
  11366. }
  11367. XmlElement& XmlElement::operator= (const XmlElement& other)
  11368. {
  11369. if (this != &other)
  11370. {
  11371. removeAllAttributes();
  11372. deleteAllChildElements();
  11373. tagName = other.tagName;
  11374. copyChildrenAndAttributesFrom (other);
  11375. }
  11376. return *this;
  11377. }
  11378. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  11379. {
  11380. XmlElement* child = other.firstChildElement;
  11381. XmlElement* lastChild = 0;
  11382. while (child != 0)
  11383. {
  11384. XmlElement* const copiedChild = new XmlElement (*child);
  11385. if (lastChild != 0)
  11386. lastChild->nextElement = copiedChild;
  11387. else
  11388. firstChildElement = copiedChild;
  11389. lastChild = copiedChild;
  11390. child = child->nextElement;
  11391. }
  11392. const XmlAttributeNode* att = other.attributes;
  11393. XmlAttributeNode* lastAtt = 0;
  11394. while (att != 0)
  11395. {
  11396. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11397. if (lastAtt != 0)
  11398. lastAtt->next = newAtt;
  11399. else
  11400. attributes = newAtt;
  11401. lastAtt = newAtt;
  11402. att = att->next;
  11403. }
  11404. }
  11405. XmlElement::~XmlElement() throw()
  11406. {
  11407. XmlElement* child = firstChildElement;
  11408. while (child != 0)
  11409. {
  11410. XmlElement* const nextChild = child->nextElement;
  11411. delete child;
  11412. child = nextChild;
  11413. }
  11414. XmlAttributeNode* att = attributes;
  11415. while (att != 0)
  11416. {
  11417. XmlAttributeNode* const nextAtt = att->next;
  11418. delete att;
  11419. att = nextAtt;
  11420. }
  11421. }
  11422. namespace XmlOutputFunctions
  11423. {
  11424. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11425. {
  11426. if ((character >= 'a' && character <= 'z')
  11427. || (character >= 'A' && character <= 'Z')
  11428. || (character >= '0' && character <= '9'))
  11429. return true;
  11430. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  11431. do
  11432. {
  11433. if (((juce_wchar) (uint8) *t) == character)
  11434. return true;
  11435. }
  11436. while (*++t != 0);
  11437. return false;
  11438. }
  11439. static void generateLegalCharConstants()
  11440. {
  11441. uint8 n[32];
  11442. zerostruct (n);
  11443. for (int i = 0; i < 256; ++i)
  11444. if (isLegalXmlCharSlow (i))
  11445. n[i >> 3] |= (1 << (i & 7));
  11446. String s;
  11447. for (int i = 0; i < 32; ++i)
  11448. s << (int) n[i] << ", ";
  11449. DBG (s);
  11450. }*/
  11451. static bool isLegalXmlChar (const uint32 c) throw()
  11452. {
  11453. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  11454. return c < sizeof (legalChars) * 8
  11455. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11456. }
  11457. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11458. {
  11459. const juce_wchar* t = text;
  11460. for (;;)
  11461. {
  11462. const juce_wchar character = *t++;
  11463. if (character == 0)
  11464. {
  11465. break;
  11466. }
  11467. else if (isLegalXmlChar ((uint32) character))
  11468. {
  11469. outputStream << (char) character;
  11470. }
  11471. else
  11472. {
  11473. switch (character)
  11474. {
  11475. case '&': outputStream << "&amp;"; break;
  11476. case '"': outputStream << "&quot;"; break;
  11477. case '>': outputStream << "&gt;"; break;
  11478. case '<': outputStream << "&lt;"; break;
  11479. case '\n':
  11480. if (changeNewLines)
  11481. outputStream << "&#10;";
  11482. else
  11483. outputStream << (char) character;
  11484. break;
  11485. case '\r':
  11486. if (changeNewLines)
  11487. outputStream << "&#13;";
  11488. else
  11489. outputStream << (char) character;
  11490. break;
  11491. default:
  11492. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11493. break;
  11494. }
  11495. }
  11496. }
  11497. }
  11498. static void writeSpaces (OutputStream& out, int numSpaces)
  11499. {
  11500. if (numSpaces > 0)
  11501. {
  11502. const char* const blanks = " ";
  11503. const int blankSize = (int) sizeof (blanks) - 1;
  11504. while (numSpaces > blankSize)
  11505. {
  11506. out.write (blanks, blankSize);
  11507. numSpaces -= blankSize;
  11508. }
  11509. out.write (blanks, numSpaces);
  11510. }
  11511. }
  11512. }
  11513. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11514. const int indentationLevel,
  11515. const int lineWrapLength) const
  11516. {
  11517. using namespace XmlOutputFunctions;
  11518. writeSpaces (outputStream, indentationLevel);
  11519. if (! isTextElement())
  11520. {
  11521. outputStream.writeByte ('<');
  11522. outputStream << tagName;
  11523. const int attIndent = indentationLevel + tagName.length() + 1;
  11524. int lineLen = 0;
  11525. const XmlAttributeNode* att = attributes;
  11526. while (att != 0)
  11527. {
  11528. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11529. {
  11530. outputStream.write ("\r\n", 2);
  11531. writeSpaces (outputStream, attIndent);
  11532. lineLen = 0;
  11533. }
  11534. const int64 startPos = outputStream.getPosition();
  11535. outputStream.writeByte (' ');
  11536. outputStream << att->name;
  11537. outputStream.write ("=\"", 2);
  11538. escapeIllegalXmlChars (outputStream, att->value, true);
  11539. outputStream.writeByte ('"');
  11540. lineLen += (int) (outputStream.getPosition() - startPos);
  11541. att = att->next;
  11542. }
  11543. if (firstChildElement != 0)
  11544. {
  11545. XmlElement* child = firstChildElement;
  11546. if (child->nextElement == 0 && child->isTextElement())
  11547. {
  11548. outputStream.writeByte ('>');
  11549. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11550. }
  11551. else
  11552. {
  11553. if (indentationLevel >= 0)
  11554. outputStream.write (">\r\n", 3);
  11555. else
  11556. outputStream.writeByte ('>');
  11557. bool lastWasTextNode = false;
  11558. while (child != 0)
  11559. {
  11560. if (child->isTextElement())
  11561. {
  11562. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11563. writeSpaces (outputStream, indentationLevel + 2);
  11564. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11565. lastWasTextNode = true;
  11566. }
  11567. else
  11568. {
  11569. if (indentationLevel >= 0)
  11570. {
  11571. if (lastWasTextNode)
  11572. outputStream.write ("\r\n", 2);
  11573. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11574. }
  11575. else
  11576. {
  11577. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11578. }
  11579. lastWasTextNode = false;
  11580. }
  11581. child = child->nextElement;
  11582. }
  11583. if (indentationLevel >= 0)
  11584. {
  11585. if (lastWasTextNode)
  11586. outputStream.write ("\r\n", 2);
  11587. writeSpaces (outputStream, indentationLevel);
  11588. }
  11589. }
  11590. outputStream.write ("</", 2);
  11591. outputStream << tagName;
  11592. if (indentationLevel >= 0)
  11593. outputStream.write (">\r\n", 3);
  11594. else
  11595. outputStream.writeByte ('>');
  11596. }
  11597. else
  11598. {
  11599. if (indentationLevel >= 0)
  11600. outputStream.write ("/>\r\n", 4);
  11601. else
  11602. outputStream.write ("/>", 2);
  11603. }
  11604. }
  11605. else
  11606. {
  11607. if (indentationLevel >= 0)
  11608. writeSpaces (outputStream, indentationLevel + 2);
  11609. escapeIllegalXmlChars (outputStream, getText(), false);
  11610. }
  11611. }
  11612. const String XmlElement::createDocument (const String& dtdToUse,
  11613. const bool allOnOneLine,
  11614. const bool includeXmlHeader,
  11615. const String& encodingType,
  11616. const int lineWrapLength) const
  11617. {
  11618. MemoryOutputStream mem (2048);
  11619. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11620. return mem.toUTF8();
  11621. }
  11622. void XmlElement::writeToStream (OutputStream& output,
  11623. const String& dtdToUse,
  11624. const bool allOnOneLine,
  11625. const bool includeXmlHeader,
  11626. const String& encodingType,
  11627. const int lineWrapLength) const
  11628. {
  11629. if (includeXmlHeader)
  11630. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11631. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11632. if (dtdToUse.isNotEmpty())
  11633. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11634. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11635. }
  11636. bool XmlElement::writeToFile (const File& file,
  11637. const String& dtdToUse,
  11638. const String& encodingType,
  11639. const int lineWrapLength) const
  11640. {
  11641. if (file.hasWriteAccess())
  11642. {
  11643. TemporaryFile tempFile (file);
  11644. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11645. if (out != 0)
  11646. {
  11647. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11648. out = 0;
  11649. return tempFile.overwriteTargetFileWithTemporary();
  11650. }
  11651. }
  11652. return false;
  11653. }
  11654. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11655. {
  11656. #if JUCE_DEBUG
  11657. // if debugging, check that the case is actually the same, because
  11658. // valid xml is case-sensitive, and although this lets it pass, it's
  11659. // better not to..
  11660. if (tagName.equalsIgnoreCase (tagNameWanted))
  11661. {
  11662. jassert (tagName == tagNameWanted);
  11663. return true;
  11664. }
  11665. else
  11666. {
  11667. return false;
  11668. }
  11669. #else
  11670. return tagName.equalsIgnoreCase (tagNameWanted);
  11671. #endif
  11672. }
  11673. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11674. {
  11675. XmlElement* e = nextElement;
  11676. while (e != 0 && ! e->hasTagName (requiredTagName))
  11677. e = e->nextElement;
  11678. return e;
  11679. }
  11680. int XmlElement::getNumAttributes() const throw()
  11681. {
  11682. const XmlAttributeNode* att = attributes;
  11683. int count = 0;
  11684. while (att != 0)
  11685. {
  11686. att = att->next;
  11687. ++count;
  11688. }
  11689. return count;
  11690. }
  11691. const String& XmlElement::getAttributeName (const int index) const throw()
  11692. {
  11693. const XmlAttributeNode* att = attributes;
  11694. int count = 0;
  11695. while (att != 0)
  11696. {
  11697. if (count == index)
  11698. return att->name;
  11699. att = att->next;
  11700. ++count;
  11701. }
  11702. return String::empty;
  11703. }
  11704. const String& XmlElement::getAttributeValue (const int index) const throw()
  11705. {
  11706. const XmlAttributeNode* att = attributes;
  11707. int count = 0;
  11708. while (att != 0)
  11709. {
  11710. if (count == index)
  11711. return att->value;
  11712. att = att->next;
  11713. ++count;
  11714. }
  11715. return String::empty;
  11716. }
  11717. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11718. {
  11719. const XmlAttributeNode* att = attributes;
  11720. while (att != 0)
  11721. {
  11722. if (att->name.equalsIgnoreCase (attributeName))
  11723. return true;
  11724. att = att->next;
  11725. }
  11726. return false;
  11727. }
  11728. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11729. {
  11730. const XmlAttributeNode* att = attributes;
  11731. while (att != 0)
  11732. {
  11733. if (att->name.equalsIgnoreCase (attributeName))
  11734. return att->value;
  11735. att = att->next;
  11736. }
  11737. return String::empty;
  11738. }
  11739. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11740. {
  11741. const XmlAttributeNode* att = attributes;
  11742. while (att != 0)
  11743. {
  11744. if (att->name.equalsIgnoreCase (attributeName))
  11745. return att->value;
  11746. att = att->next;
  11747. }
  11748. return defaultReturnValue;
  11749. }
  11750. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11751. {
  11752. const XmlAttributeNode* att = attributes;
  11753. while (att != 0)
  11754. {
  11755. if (att->name.equalsIgnoreCase (attributeName))
  11756. return att->value.getIntValue();
  11757. att = att->next;
  11758. }
  11759. return defaultReturnValue;
  11760. }
  11761. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11762. {
  11763. const XmlAttributeNode* att = attributes;
  11764. while (att != 0)
  11765. {
  11766. if (att->name.equalsIgnoreCase (attributeName))
  11767. return att->value.getDoubleValue();
  11768. att = att->next;
  11769. }
  11770. return defaultReturnValue;
  11771. }
  11772. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11773. {
  11774. const XmlAttributeNode* att = attributes;
  11775. while (att != 0)
  11776. {
  11777. if (att->name.equalsIgnoreCase (attributeName))
  11778. {
  11779. juce_wchar firstChar = att->value[0];
  11780. if (CharacterFunctions::isWhitespace (firstChar))
  11781. firstChar = att->value.trimStart() [0];
  11782. return firstChar == '1'
  11783. || firstChar == 't'
  11784. || firstChar == 'y'
  11785. || firstChar == 'T'
  11786. || firstChar == 'Y';
  11787. }
  11788. att = att->next;
  11789. }
  11790. return defaultReturnValue;
  11791. }
  11792. bool XmlElement::compareAttribute (const String& attributeName,
  11793. const String& stringToCompareAgainst,
  11794. const bool ignoreCase) const throw()
  11795. {
  11796. const XmlAttributeNode* att = attributes;
  11797. while (att != 0)
  11798. {
  11799. if (att->name.equalsIgnoreCase (attributeName))
  11800. {
  11801. if (ignoreCase)
  11802. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11803. else
  11804. return att->value == stringToCompareAgainst;
  11805. }
  11806. att = att->next;
  11807. }
  11808. return false;
  11809. }
  11810. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11811. {
  11812. #if JUCE_DEBUG
  11813. // check the identifier being passed in is legal..
  11814. const juce_wchar* t = attributeName;
  11815. while (*t != 0)
  11816. {
  11817. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11818. || *t == '_'
  11819. || *t == '-'
  11820. || *t == ':');
  11821. ++t;
  11822. }
  11823. #endif
  11824. if (attributes == 0)
  11825. {
  11826. attributes = new XmlAttributeNode (attributeName, value);
  11827. }
  11828. else
  11829. {
  11830. XmlAttributeNode* att = attributes;
  11831. for (;;)
  11832. {
  11833. if (att->name.equalsIgnoreCase (attributeName))
  11834. {
  11835. att->value = value;
  11836. break;
  11837. }
  11838. else if (att->next == 0)
  11839. {
  11840. att->next = new XmlAttributeNode (attributeName, value);
  11841. break;
  11842. }
  11843. att = att->next;
  11844. }
  11845. }
  11846. }
  11847. void XmlElement::setAttribute (const String& attributeName, const int number)
  11848. {
  11849. setAttribute (attributeName, String (number));
  11850. }
  11851. void XmlElement::setAttribute (const String& attributeName, const double number)
  11852. {
  11853. setAttribute (attributeName, String (number));
  11854. }
  11855. void XmlElement::removeAttribute (const String& attributeName) throw()
  11856. {
  11857. XmlAttributeNode* att = attributes;
  11858. XmlAttributeNode* lastAtt = 0;
  11859. while (att != 0)
  11860. {
  11861. if (att->name.equalsIgnoreCase (attributeName))
  11862. {
  11863. if (lastAtt == 0)
  11864. attributes = att->next;
  11865. else
  11866. lastAtt->next = att->next;
  11867. delete att;
  11868. break;
  11869. }
  11870. lastAtt = att;
  11871. att = att->next;
  11872. }
  11873. }
  11874. void XmlElement::removeAllAttributes() throw()
  11875. {
  11876. while (attributes != 0)
  11877. {
  11878. XmlAttributeNode* const nextAtt = attributes->next;
  11879. delete attributes;
  11880. attributes = nextAtt;
  11881. }
  11882. }
  11883. int XmlElement::getNumChildElements() const throw()
  11884. {
  11885. int count = 0;
  11886. const XmlElement* child = firstChildElement;
  11887. while (child != 0)
  11888. {
  11889. ++count;
  11890. child = child->nextElement;
  11891. }
  11892. return count;
  11893. }
  11894. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11895. {
  11896. int count = 0;
  11897. XmlElement* child = firstChildElement;
  11898. while (child != 0 && count < index)
  11899. {
  11900. child = child->nextElement;
  11901. ++count;
  11902. }
  11903. return child;
  11904. }
  11905. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11906. {
  11907. XmlElement* child = firstChildElement;
  11908. while (child != 0)
  11909. {
  11910. if (child->hasTagName (childName))
  11911. break;
  11912. child = child->nextElement;
  11913. }
  11914. return child;
  11915. }
  11916. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11917. {
  11918. if (newNode != 0)
  11919. {
  11920. if (firstChildElement == 0)
  11921. {
  11922. firstChildElement = newNode;
  11923. }
  11924. else
  11925. {
  11926. XmlElement* child = firstChildElement;
  11927. while (child->nextElement != 0)
  11928. child = child->nextElement;
  11929. child->nextElement = newNode;
  11930. // if this is non-zero, then something's probably
  11931. // gone wrong..
  11932. jassert (newNode->nextElement == 0);
  11933. }
  11934. }
  11935. }
  11936. void XmlElement::insertChildElement (XmlElement* const newNode,
  11937. int indexToInsertAt) throw()
  11938. {
  11939. if (newNode != 0)
  11940. {
  11941. removeChildElement (newNode, false);
  11942. if (indexToInsertAt == 0)
  11943. {
  11944. newNode->nextElement = firstChildElement;
  11945. firstChildElement = newNode;
  11946. }
  11947. else
  11948. {
  11949. if (firstChildElement == 0)
  11950. {
  11951. firstChildElement = newNode;
  11952. }
  11953. else
  11954. {
  11955. if (indexToInsertAt < 0)
  11956. indexToInsertAt = std::numeric_limits<int>::max();
  11957. XmlElement* child = firstChildElement;
  11958. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11959. child = child->nextElement;
  11960. newNode->nextElement = child->nextElement;
  11961. child->nextElement = newNode;
  11962. }
  11963. }
  11964. }
  11965. }
  11966. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11967. {
  11968. XmlElement* const newElement = new XmlElement (childTagName);
  11969. addChildElement (newElement);
  11970. return newElement;
  11971. }
  11972. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11973. XmlElement* const newNode) throw()
  11974. {
  11975. if (newNode != 0)
  11976. {
  11977. XmlElement* child = firstChildElement;
  11978. XmlElement* previousNode = 0;
  11979. while (child != 0)
  11980. {
  11981. if (child == currentChildElement)
  11982. {
  11983. if (child != newNode)
  11984. {
  11985. if (previousNode == 0)
  11986. firstChildElement = newNode;
  11987. else
  11988. previousNode->nextElement = newNode;
  11989. newNode->nextElement = child->nextElement;
  11990. delete child;
  11991. }
  11992. return true;
  11993. }
  11994. previousNode = child;
  11995. child = child->nextElement;
  11996. }
  11997. }
  11998. return false;
  11999. }
  12000. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12001. const bool shouldDeleteTheChild) throw()
  12002. {
  12003. if (childToRemove != 0)
  12004. {
  12005. if (firstChildElement == childToRemove)
  12006. {
  12007. firstChildElement = childToRemove->nextElement;
  12008. childToRemove->nextElement = 0;
  12009. }
  12010. else
  12011. {
  12012. XmlElement* child = firstChildElement;
  12013. XmlElement* last = 0;
  12014. while (child != 0)
  12015. {
  12016. if (child == childToRemove)
  12017. {
  12018. if (last == 0)
  12019. firstChildElement = child->nextElement;
  12020. else
  12021. last->nextElement = child->nextElement;
  12022. childToRemove->nextElement = 0;
  12023. break;
  12024. }
  12025. last = child;
  12026. child = child->nextElement;
  12027. }
  12028. }
  12029. if (shouldDeleteTheChild)
  12030. delete childToRemove;
  12031. }
  12032. }
  12033. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12034. const bool ignoreOrderOfAttributes) const throw()
  12035. {
  12036. if (this != other)
  12037. {
  12038. if (other == 0 || tagName != other->tagName)
  12039. {
  12040. return false;
  12041. }
  12042. if (ignoreOrderOfAttributes)
  12043. {
  12044. int totalAtts = 0;
  12045. const XmlAttributeNode* att = attributes;
  12046. while (att != 0)
  12047. {
  12048. if (! other->compareAttribute (att->name, att->value))
  12049. return false;
  12050. att = att->next;
  12051. ++totalAtts;
  12052. }
  12053. if (totalAtts != other->getNumAttributes())
  12054. return false;
  12055. }
  12056. else
  12057. {
  12058. const XmlAttributeNode* thisAtt = attributes;
  12059. const XmlAttributeNode* otherAtt = other->attributes;
  12060. for (;;)
  12061. {
  12062. if (thisAtt == 0 || otherAtt == 0)
  12063. {
  12064. if (thisAtt == otherAtt) // both 0, so it's a match
  12065. break;
  12066. return false;
  12067. }
  12068. if (thisAtt->name != otherAtt->name
  12069. || thisAtt->value != otherAtt->value)
  12070. {
  12071. return false;
  12072. }
  12073. thisAtt = thisAtt->next;
  12074. otherAtt = otherAtt->next;
  12075. }
  12076. }
  12077. const XmlElement* thisChild = firstChildElement;
  12078. const XmlElement* otherChild = other->firstChildElement;
  12079. for (;;)
  12080. {
  12081. if (thisChild == 0 || otherChild == 0)
  12082. {
  12083. if (thisChild == otherChild) // both 0, so it's a match
  12084. break;
  12085. return false;
  12086. }
  12087. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12088. return false;
  12089. thisChild = thisChild->nextElement;
  12090. otherChild = otherChild->nextElement;
  12091. }
  12092. }
  12093. return true;
  12094. }
  12095. void XmlElement::deleteAllChildElements() throw()
  12096. {
  12097. while (firstChildElement != 0)
  12098. {
  12099. XmlElement* const nextChild = firstChildElement->nextElement;
  12100. delete firstChildElement;
  12101. firstChildElement = nextChild;
  12102. }
  12103. }
  12104. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12105. {
  12106. XmlElement* child = firstChildElement;
  12107. while (child != 0)
  12108. {
  12109. if (child->hasTagName (name))
  12110. {
  12111. XmlElement* const nextChild = child->nextElement;
  12112. removeChildElement (child, true);
  12113. child = nextChild;
  12114. }
  12115. else
  12116. {
  12117. child = child->nextElement;
  12118. }
  12119. }
  12120. }
  12121. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12122. {
  12123. const XmlElement* child = firstChildElement;
  12124. while (child != 0)
  12125. {
  12126. if (child == possibleChild)
  12127. return true;
  12128. child = child->nextElement;
  12129. }
  12130. return false;
  12131. }
  12132. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12133. {
  12134. if (this == elementToLookFor || elementToLookFor == 0)
  12135. return 0;
  12136. XmlElement* child = firstChildElement;
  12137. while (child != 0)
  12138. {
  12139. if (elementToLookFor == child)
  12140. return this;
  12141. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12142. if (found != 0)
  12143. return found;
  12144. child = child->nextElement;
  12145. }
  12146. return 0;
  12147. }
  12148. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12149. {
  12150. XmlElement* e = firstChildElement;
  12151. while (e != 0)
  12152. {
  12153. *elems++ = e;
  12154. e = e->nextElement;
  12155. }
  12156. }
  12157. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12158. {
  12159. XmlElement* e = firstChildElement = elems[0];
  12160. for (int i = 1; i < num; ++i)
  12161. {
  12162. e->nextElement = elems[i];
  12163. e = e->nextElement;
  12164. }
  12165. e->nextElement = 0;
  12166. }
  12167. bool XmlElement::isTextElement() const throw()
  12168. {
  12169. return tagName.isEmpty();
  12170. }
  12171. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12172. const String& XmlElement::getText() const throw()
  12173. {
  12174. jassert (isTextElement()); // you're trying to get the text from an element that
  12175. // isn't actually a text element.. If this contains text sub-nodes, you
  12176. // probably want to use getAllSubText instead.
  12177. return getStringAttribute (juce_xmltextContentAttributeName);
  12178. }
  12179. void XmlElement::setText (const String& newText)
  12180. {
  12181. if (isTextElement())
  12182. setAttribute (juce_xmltextContentAttributeName, newText);
  12183. else
  12184. jassertfalse; // you can only change the text in a text element, not a normal one.
  12185. }
  12186. const String XmlElement::getAllSubText() const
  12187. {
  12188. String result;
  12189. String::Concatenator concatenator (result);
  12190. const XmlElement* child = firstChildElement;
  12191. while (child != 0)
  12192. {
  12193. if (child->isTextElement())
  12194. concatenator.append (child->getText());
  12195. child = child->nextElement;
  12196. }
  12197. return result;
  12198. }
  12199. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12200. const String& defaultReturnValue) const
  12201. {
  12202. const XmlElement* const child = getChildByName (childTagName);
  12203. if (child != 0)
  12204. return child->getAllSubText();
  12205. return defaultReturnValue;
  12206. }
  12207. XmlElement* XmlElement::createTextElement (const String& text)
  12208. {
  12209. XmlElement* const e = new XmlElement ((int) 0);
  12210. e->setAttribute (juce_xmltextContentAttributeName, text);
  12211. return e;
  12212. }
  12213. void XmlElement::addTextElement (const String& text)
  12214. {
  12215. addChildElement (createTextElement (text));
  12216. }
  12217. void XmlElement::deleteAllTextElements() throw()
  12218. {
  12219. XmlElement* child = firstChildElement;
  12220. while (child != 0)
  12221. {
  12222. XmlElement* const next = child->nextElement;
  12223. if (child->isTextElement())
  12224. removeChildElement (child, true);
  12225. child = next;
  12226. }
  12227. }
  12228. END_JUCE_NAMESPACE
  12229. /*** End of inlined file: juce_XmlElement.cpp ***/
  12230. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12231. BEGIN_JUCE_NAMESPACE
  12232. ReadWriteLock::ReadWriteLock() throw()
  12233. : numWaitingWriters (0),
  12234. numWriters (0),
  12235. writerThreadId (0)
  12236. {
  12237. }
  12238. ReadWriteLock::~ReadWriteLock() throw()
  12239. {
  12240. jassert (readerThreads.size() == 0);
  12241. jassert (numWriters == 0);
  12242. }
  12243. void ReadWriteLock::enterRead() const throw()
  12244. {
  12245. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12246. const ScopedLock sl (accessLock);
  12247. for (;;)
  12248. {
  12249. jassert (readerThreads.size() % 2 == 0);
  12250. int i;
  12251. for (i = 0; i < readerThreads.size(); i += 2)
  12252. if (readerThreads.getUnchecked(i) == threadId)
  12253. break;
  12254. if (i < readerThreads.size()
  12255. || numWriters + numWaitingWriters == 0
  12256. || (threadId == writerThreadId && numWriters > 0))
  12257. {
  12258. if (i < readerThreads.size())
  12259. {
  12260. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12261. }
  12262. else
  12263. {
  12264. readerThreads.add (threadId);
  12265. readerThreads.add ((Thread::ThreadID) 1);
  12266. }
  12267. return;
  12268. }
  12269. const ScopedUnlock ul (accessLock);
  12270. waitEvent.wait (100);
  12271. }
  12272. }
  12273. void ReadWriteLock::exitRead() const throw()
  12274. {
  12275. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12276. const ScopedLock sl (accessLock);
  12277. for (int i = 0; i < readerThreads.size(); i += 2)
  12278. {
  12279. if (readerThreads.getUnchecked(i) == threadId)
  12280. {
  12281. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12282. if (newCount == 0)
  12283. {
  12284. readerThreads.removeRange (i, 2);
  12285. waitEvent.signal();
  12286. }
  12287. else
  12288. {
  12289. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12290. }
  12291. return;
  12292. }
  12293. }
  12294. jassertfalse; // unlocking a lock that wasn't locked..
  12295. }
  12296. void ReadWriteLock::enterWrite() const throw()
  12297. {
  12298. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12299. const ScopedLock sl (accessLock);
  12300. for (;;)
  12301. {
  12302. if (readerThreads.size() + numWriters == 0
  12303. || threadId == writerThreadId
  12304. || (readerThreads.size() == 2
  12305. && readerThreads.getUnchecked(0) == threadId))
  12306. {
  12307. writerThreadId = threadId;
  12308. ++numWriters;
  12309. break;
  12310. }
  12311. ++numWaitingWriters;
  12312. accessLock.exit();
  12313. waitEvent.wait (100);
  12314. accessLock.enter();
  12315. --numWaitingWriters;
  12316. }
  12317. }
  12318. bool ReadWriteLock::tryEnterWrite() const throw()
  12319. {
  12320. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12321. const ScopedLock sl (accessLock);
  12322. if (readerThreads.size() + numWriters == 0
  12323. || threadId == writerThreadId
  12324. || (readerThreads.size() == 2
  12325. && readerThreads.getUnchecked(0) == threadId))
  12326. {
  12327. writerThreadId = threadId;
  12328. ++numWriters;
  12329. return true;
  12330. }
  12331. return false;
  12332. }
  12333. void ReadWriteLock::exitWrite() const throw()
  12334. {
  12335. const ScopedLock sl (accessLock);
  12336. // check this thread actually had the lock..
  12337. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12338. if (--numWriters == 0)
  12339. {
  12340. writerThreadId = 0;
  12341. waitEvent.signal();
  12342. }
  12343. }
  12344. END_JUCE_NAMESPACE
  12345. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12346. /*** Start of inlined file: juce_Thread.cpp ***/
  12347. BEGIN_JUCE_NAMESPACE
  12348. // these functions are implemented in the platform-specific code.
  12349. void* juce_createThread (void* userData);
  12350. void juce_killThread (void* handle);
  12351. bool juce_setThreadPriority (void* handle, int priority);
  12352. void juce_setCurrentThreadName (const String& name);
  12353. #if JUCE_WINDOWS
  12354. void juce_CloseThreadHandle (void* handle);
  12355. #endif
  12356. void Thread::threadEntryPoint (Thread* const thread)
  12357. {
  12358. {
  12359. const ScopedLock sl (runningThreadsLock);
  12360. runningThreads.add (thread);
  12361. }
  12362. JUCE_TRY
  12363. {
  12364. thread->threadId_ = Thread::getCurrentThreadId();
  12365. if (thread->threadName_.isNotEmpty())
  12366. juce_setCurrentThreadName (thread->threadName_);
  12367. if (thread->startSuspensionEvent_.wait (10000))
  12368. {
  12369. if (thread->affinityMask_ != 0)
  12370. setCurrentThreadAffinityMask (thread->affinityMask_);
  12371. thread->run();
  12372. }
  12373. }
  12374. JUCE_CATCH_ALL_ASSERT
  12375. {
  12376. const ScopedLock sl (runningThreadsLock);
  12377. jassert (runningThreads.contains (thread));
  12378. runningThreads.removeValue (thread);
  12379. }
  12380. #if JUCE_WINDOWS
  12381. juce_CloseThreadHandle (thread->threadHandle_);
  12382. #endif
  12383. thread->threadHandle_ = 0;
  12384. thread->threadId_ = 0;
  12385. }
  12386. // used to wrap the incoming call from the platform-specific code
  12387. void JUCE_API juce_threadEntryPoint (void* userData)
  12388. {
  12389. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12390. }
  12391. Thread::Thread (const String& threadName)
  12392. : threadName_ (threadName),
  12393. threadHandle_ (0),
  12394. threadPriority_ (5),
  12395. threadId_ (0),
  12396. affinityMask_ (0),
  12397. threadShouldExit_ (false)
  12398. {
  12399. }
  12400. Thread::~Thread()
  12401. {
  12402. stopThread (100);
  12403. }
  12404. void Thread::startThread()
  12405. {
  12406. const ScopedLock sl (startStopLock);
  12407. threadShouldExit_ = false;
  12408. if (threadHandle_ == 0)
  12409. {
  12410. threadHandle_ = juce_createThread (this);
  12411. juce_setThreadPriority (threadHandle_, threadPriority_);
  12412. startSuspensionEvent_.signal();
  12413. }
  12414. }
  12415. void Thread::startThread (const int priority)
  12416. {
  12417. const ScopedLock sl (startStopLock);
  12418. if (threadHandle_ == 0)
  12419. {
  12420. threadPriority_ = priority;
  12421. startThread();
  12422. }
  12423. else
  12424. {
  12425. setPriority (priority);
  12426. }
  12427. }
  12428. bool Thread::isThreadRunning() const
  12429. {
  12430. return threadHandle_ != 0;
  12431. }
  12432. void Thread::signalThreadShouldExit()
  12433. {
  12434. threadShouldExit_ = true;
  12435. }
  12436. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12437. {
  12438. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12439. jassert (getThreadId() != getCurrentThreadId());
  12440. const int sleepMsPerIteration = 5;
  12441. int count = timeOutMilliseconds / sleepMsPerIteration;
  12442. while (isThreadRunning())
  12443. {
  12444. if (timeOutMilliseconds > 0 && --count < 0)
  12445. return false;
  12446. sleep (sleepMsPerIteration);
  12447. }
  12448. return true;
  12449. }
  12450. void Thread::stopThread (const int timeOutMilliseconds)
  12451. {
  12452. // agh! You can't stop the thread that's calling this method! How on earth
  12453. // would that work??
  12454. jassert (getCurrentThreadId() != getThreadId());
  12455. const ScopedLock sl (startStopLock);
  12456. if (isThreadRunning())
  12457. {
  12458. signalThreadShouldExit();
  12459. notify();
  12460. if (timeOutMilliseconds != 0)
  12461. waitForThreadToExit (timeOutMilliseconds);
  12462. if (isThreadRunning())
  12463. {
  12464. // very bad karma if this point is reached, as
  12465. // there are bound to be locks and events left in
  12466. // silly states when a thread is killed by force..
  12467. jassertfalse;
  12468. Logger::writeToLog ("!! killing thread by force !!");
  12469. juce_killThread (threadHandle_);
  12470. threadHandle_ = 0;
  12471. threadId_ = 0;
  12472. const ScopedLock sl2 (runningThreadsLock);
  12473. runningThreads.removeValue (this);
  12474. }
  12475. }
  12476. }
  12477. bool Thread::setPriority (const int priority)
  12478. {
  12479. const ScopedLock sl (startStopLock);
  12480. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12481. if (worked)
  12482. threadPriority_ = priority;
  12483. return worked;
  12484. }
  12485. bool Thread::setCurrentThreadPriority (const int priority)
  12486. {
  12487. return juce_setThreadPriority (0, priority);
  12488. }
  12489. void Thread::setAffinityMask (const uint32 affinityMask)
  12490. {
  12491. affinityMask_ = affinityMask;
  12492. }
  12493. bool Thread::wait (const int timeOutMilliseconds) const
  12494. {
  12495. return defaultEvent_.wait (timeOutMilliseconds);
  12496. }
  12497. void Thread::notify() const
  12498. {
  12499. defaultEvent_.signal();
  12500. }
  12501. int Thread::getNumRunningThreads()
  12502. {
  12503. return runningThreads.size();
  12504. }
  12505. Thread* Thread::getCurrentThread()
  12506. {
  12507. const ThreadID thisId = getCurrentThreadId();
  12508. const ScopedLock sl (runningThreadsLock);
  12509. for (int i = runningThreads.size(); --i >= 0;)
  12510. {
  12511. Thread* const t = runningThreads.getUnchecked(i);
  12512. if (t->threadId_ == thisId)
  12513. return t;
  12514. }
  12515. return 0;
  12516. }
  12517. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12518. {
  12519. {
  12520. const ScopedLock sl (runningThreadsLock);
  12521. for (int i = runningThreads.size(); --i >= 0;)
  12522. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12523. }
  12524. for (;;)
  12525. {
  12526. Thread* firstThread;
  12527. {
  12528. const ScopedLock sl (runningThreadsLock);
  12529. firstThread = runningThreads.getFirst();
  12530. }
  12531. if (firstThread == 0)
  12532. break;
  12533. firstThread->stopThread (timeOutMilliseconds);
  12534. }
  12535. }
  12536. Array<Thread*> Thread::runningThreads;
  12537. CriticalSection Thread::runningThreadsLock;
  12538. END_JUCE_NAMESPACE
  12539. /*** End of inlined file: juce_Thread.cpp ***/
  12540. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12541. BEGIN_JUCE_NAMESPACE
  12542. ThreadPoolJob::ThreadPoolJob (const String& name)
  12543. : jobName (name),
  12544. pool (0),
  12545. shouldStop (false),
  12546. isActive (false),
  12547. shouldBeDeleted (false)
  12548. {
  12549. }
  12550. ThreadPoolJob::~ThreadPoolJob()
  12551. {
  12552. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12553. // to remove it first!
  12554. jassert (pool == 0 || ! pool->contains (this));
  12555. }
  12556. const String ThreadPoolJob::getJobName() const
  12557. {
  12558. return jobName;
  12559. }
  12560. void ThreadPoolJob::setJobName (const String& newName)
  12561. {
  12562. jobName = newName;
  12563. }
  12564. void ThreadPoolJob::signalJobShouldExit()
  12565. {
  12566. shouldStop = true;
  12567. }
  12568. class ThreadPool::ThreadPoolThread : public Thread
  12569. {
  12570. public:
  12571. ThreadPoolThread (ThreadPool& pool_)
  12572. : Thread ("Pool"),
  12573. pool (pool_),
  12574. busy (false)
  12575. {
  12576. }
  12577. ~ThreadPoolThread()
  12578. {
  12579. }
  12580. void run()
  12581. {
  12582. while (! threadShouldExit())
  12583. {
  12584. if (! pool.runNextJob())
  12585. wait (500);
  12586. }
  12587. }
  12588. private:
  12589. ThreadPool& pool;
  12590. bool volatile busy;
  12591. ThreadPoolThread (const ThreadPoolThread&);
  12592. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12593. };
  12594. ThreadPool::ThreadPool (const int numThreads,
  12595. const bool startThreadsOnlyWhenNeeded,
  12596. const int stopThreadsWhenNotUsedTimeoutMs)
  12597. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12598. priority (5)
  12599. {
  12600. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12601. for (int i = jmax (1, numThreads); --i >= 0;)
  12602. threads.add (new ThreadPoolThread (*this));
  12603. if (! startThreadsOnlyWhenNeeded)
  12604. for (int i = threads.size(); --i >= 0;)
  12605. threads.getUnchecked(i)->startThread (priority);
  12606. }
  12607. ThreadPool::~ThreadPool()
  12608. {
  12609. removeAllJobs (true, 4000);
  12610. int i;
  12611. for (i = threads.size(); --i >= 0;)
  12612. threads.getUnchecked(i)->signalThreadShouldExit();
  12613. for (i = threads.size(); --i >= 0;)
  12614. threads.getUnchecked(i)->stopThread (500);
  12615. }
  12616. void ThreadPool::addJob (ThreadPoolJob* const job)
  12617. {
  12618. jassert (job != 0);
  12619. jassert (job->pool == 0);
  12620. if (job->pool == 0)
  12621. {
  12622. job->pool = this;
  12623. job->shouldStop = false;
  12624. job->isActive = false;
  12625. {
  12626. const ScopedLock sl (lock);
  12627. jobs.add (job);
  12628. int numRunning = 0;
  12629. for (int i = threads.size(); --i >= 0;)
  12630. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12631. ++numRunning;
  12632. if (numRunning < threads.size())
  12633. {
  12634. bool startedOne = false;
  12635. int n = 1000;
  12636. while (--n >= 0 && ! startedOne)
  12637. {
  12638. for (int i = threads.size(); --i >= 0;)
  12639. {
  12640. if (! threads.getUnchecked(i)->isThreadRunning())
  12641. {
  12642. threads.getUnchecked(i)->startThread (priority);
  12643. startedOne = true;
  12644. break;
  12645. }
  12646. }
  12647. if (! startedOne)
  12648. Thread::sleep (2);
  12649. }
  12650. }
  12651. }
  12652. for (int i = threads.size(); --i >= 0;)
  12653. threads.getUnchecked(i)->notify();
  12654. }
  12655. }
  12656. int ThreadPool::getNumJobs() const
  12657. {
  12658. return jobs.size();
  12659. }
  12660. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12661. {
  12662. const ScopedLock sl (lock);
  12663. return jobs [index];
  12664. }
  12665. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12666. {
  12667. const ScopedLock sl (lock);
  12668. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12669. }
  12670. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12671. {
  12672. const ScopedLock sl (lock);
  12673. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12674. }
  12675. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12676. const int timeOutMs) const
  12677. {
  12678. if (job != 0)
  12679. {
  12680. const uint32 start = Time::getMillisecondCounter();
  12681. while (contains (job))
  12682. {
  12683. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12684. return false;
  12685. jobFinishedSignal.wait (2);
  12686. }
  12687. }
  12688. return true;
  12689. }
  12690. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12691. const bool interruptIfRunning,
  12692. const int timeOutMs)
  12693. {
  12694. bool dontWait = true;
  12695. if (job != 0)
  12696. {
  12697. const ScopedLock sl (lock);
  12698. if (jobs.contains (job))
  12699. {
  12700. if (job->isActive)
  12701. {
  12702. if (interruptIfRunning)
  12703. job->signalJobShouldExit();
  12704. dontWait = false;
  12705. }
  12706. else
  12707. {
  12708. jobs.removeValue (job);
  12709. }
  12710. }
  12711. }
  12712. return dontWait || waitForJobToFinish (job, timeOutMs);
  12713. }
  12714. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12715. const int timeOutMs,
  12716. const bool deleteInactiveJobs,
  12717. ThreadPool::JobSelector* selectedJobsToRemove)
  12718. {
  12719. Array <ThreadPoolJob*> jobsToWaitFor;
  12720. {
  12721. const ScopedLock sl (lock);
  12722. for (int i = jobs.size(); --i >= 0;)
  12723. {
  12724. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12725. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12726. {
  12727. if (job->isActive)
  12728. {
  12729. jobsToWaitFor.add (job);
  12730. if (interruptRunningJobs)
  12731. job->signalJobShouldExit();
  12732. }
  12733. else
  12734. {
  12735. jobs.remove (i);
  12736. if (deleteInactiveJobs)
  12737. delete job;
  12738. }
  12739. }
  12740. }
  12741. }
  12742. const uint32 start = Time::getMillisecondCounter();
  12743. for (;;)
  12744. {
  12745. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12746. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12747. jobsToWaitFor.remove (i);
  12748. if (jobsToWaitFor.size() == 0)
  12749. break;
  12750. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12751. return false;
  12752. jobFinishedSignal.wait (20);
  12753. }
  12754. return true;
  12755. }
  12756. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12757. {
  12758. StringArray s;
  12759. const ScopedLock sl (lock);
  12760. for (int i = 0; i < jobs.size(); ++i)
  12761. {
  12762. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12763. if (job->isActive || ! onlyReturnActiveJobs)
  12764. s.add (job->getJobName());
  12765. }
  12766. return s;
  12767. }
  12768. bool ThreadPool::setThreadPriorities (const int newPriority)
  12769. {
  12770. bool ok = true;
  12771. if (priority != newPriority)
  12772. {
  12773. priority = newPriority;
  12774. for (int i = threads.size(); --i >= 0;)
  12775. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12776. ok = false;
  12777. }
  12778. return ok;
  12779. }
  12780. bool ThreadPool::runNextJob()
  12781. {
  12782. ThreadPoolJob* job = 0;
  12783. {
  12784. const ScopedLock sl (lock);
  12785. for (int i = 0; i < jobs.size(); ++i)
  12786. {
  12787. job = jobs[i];
  12788. if (job != 0 && ! (job->isActive || job->shouldStop))
  12789. break;
  12790. job = 0;
  12791. }
  12792. if (job != 0)
  12793. job->isActive = true;
  12794. }
  12795. if (job != 0)
  12796. {
  12797. JUCE_TRY
  12798. {
  12799. ThreadPoolJob::JobStatus result = job->runJob();
  12800. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12801. const ScopedLock sl (lock);
  12802. if (jobs.contains (job))
  12803. {
  12804. job->isActive = false;
  12805. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12806. {
  12807. job->pool = 0;
  12808. job->shouldStop = true;
  12809. jobs.removeValue (job);
  12810. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12811. delete job;
  12812. jobFinishedSignal.signal();
  12813. }
  12814. else
  12815. {
  12816. // move the job to the end of the queue if it wants another go
  12817. jobs.move (jobs.indexOf (job), -1);
  12818. }
  12819. }
  12820. }
  12821. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12822. catch (...)
  12823. {
  12824. const ScopedLock sl (lock);
  12825. jobs.removeValue (job);
  12826. }
  12827. #endif
  12828. }
  12829. else
  12830. {
  12831. if (threadStopTimeout > 0
  12832. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12833. {
  12834. const ScopedLock sl (lock);
  12835. if (jobs.size() == 0)
  12836. for (int i = threads.size(); --i >= 0;)
  12837. threads.getUnchecked(i)->signalThreadShouldExit();
  12838. }
  12839. else
  12840. {
  12841. return false;
  12842. }
  12843. }
  12844. return true;
  12845. }
  12846. END_JUCE_NAMESPACE
  12847. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12848. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12849. BEGIN_JUCE_NAMESPACE
  12850. TimeSliceThread::TimeSliceThread (const String& threadName)
  12851. : Thread (threadName),
  12852. index (0),
  12853. clientBeingCalled (0),
  12854. clientsChanged (false)
  12855. {
  12856. }
  12857. TimeSliceThread::~TimeSliceThread()
  12858. {
  12859. stopThread (2000);
  12860. }
  12861. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12862. {
  12863. const ScopedLock sl (listLock);
  12864. clients.addIfNotAlreadyThere (client);
  12865. clientsChanged = true;
  12866. notify();
  12867. }
  12868. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12869. {
  12870. const ScopedLock sl1 (listLock);
  12871. clientsChanged = true;
  12872. // if there's a chance we're in the middle of calling this client, we need to
  12873. // also lock the outer lock..
  12874. if (clientBeingCalled == client)
  12875. {
  12876. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12877. const ScopedLock sl2 (callbackLock);
  12878. const ScopedLock sl3 (listLock);
  12879. clients.removeValue (client);
  12880. }
  12881. else
  12882. {
  12883. clients.removeValue (client);
  12884. }
  12885. }
  12886. int TimeSliceThread::getNumClients() const
  12887. {
  12888. return clients.size();
  12889. }
  12890. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12891. {
  12892. const ScopedLock sl (listLock);
  12893. return clients [i];
  12894. }
  12895. void TimeSliceThread::run()
  12896. {
  12897. int numCallsSinceBusy = 0;
  12898. while (! threadShouldExit())
  12899. {
  12900. int timeToWait = 500;
  12901. {
  12902. const ScopedLock sl (callbackLock);
  12903. {
  12904. const ScopedLock sl2 (listLock);
  12905. if (clients.size() > 0)
  12906. {
  12907. index = (index + 1) % clients.size();
  12908. clientBeingCalled = clients [index];
  12909. }
  12910. else
  12911. {
  12912. index = 0;
  12913. clientBeingCalled = 0;
  12914. }
  12915. if (clientsChanged)
  12916. {
  12917. clientsChanged = false;
  12918. numCallsSinceBusy = 0;
  12919. }
  12920. }
  12921. if (clientBeingCalled != 0)
  12922. {
  12923. if (clientBeingCalled->useTimeSlice())
  12924. numCallsSinceBusy = 0;
  12925. else
  12926. ++numCallsSinceBusy;
  12927. if (numCallsSinceBusy >= clients.size())
  12928. timeToWait = 500;
  12929. else if (index == 0)
  12930. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12931. else
  12932. timeToWait = 0;
  12933. }
  12934. }
  12935. if (timeToWait > 0)
  12936. wait (timeToWait);
  12937. }
  12938. }
  12939. END_JUCE_NAMESPACE
  12940. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12941. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  12942. BEGIN_JUCE_NAMESPACE
  12943. DeletedAtShutdown::DeletedAtShutdown()
  12944. {
  12945. const ScopedLock sl (getLock());
  12946. getObjects().add (this);
  12947. }
  12948. DeletedAtShutdown::~DeletedAtShutdown()
  12949. {
  12950. const ScopedLock sl (getLock());
  12951. getObjects().removeValue (this);
  12952. }
  12953. void DeletedAtShutdown::deleteAll()
  12954. {
  12955. // make a local copy of the array, so it can't get into a loop if something
  12956. // creates another DeletedAtShutdown object during its destructor.
  12957. Array <DeletedAtShutdown*> localCopy;
  12958. {
  12959. const ScopedLock sl (getLock());
  12960. localCopy = getObjects();
  12961. }
  12962. for (int i = localCopy.size(); --i >= 0;)
  12963. {
  12964. JUCE_TRY
  12965. {
  12966. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  12967. // double-check that it's not already been deleted during another object's destructor.
  12968. {
  12969. const ScopedLock sl (getLock());
  12970. if (! getObjects().contains (deletee))
  12971. deletee = 0;
  12972. }
  12973. delete deletee;
  12974. }
  12975. JUCE_CATCH_EXCEPTION
  12976. }
  12977. // if no objects got re-created during shutdown, this should have been emptied by their
  12978. // destructors
  12979. jassert (getObjects().size() == 0);
  12980. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  12981. }
  12982. CriticalSection& DeletedAtShutdown::getLock()
  12983. {
  12984. static CriticalSection lock;
  12985. return lock;
  12986. }
  12987. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  12988. {
  12989. static Array <DeletedAtShutdown*> objects;
  12990. return objects;
  12991. }
  12992. END_JUCE_NAMESPACE
  12993. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  12994. #endif
  12995. #if JUCE_BUILD_MISC
  12996. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12997. BEGIN_JUCE_NAMESPACE
  12998. class ValueTree::SetPropertyAction : public UndoableAction
  12999. {
  13000. public:
  13001. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13002. const var& newValue_, const var& oldValue_,
  13003. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13004. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13005. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13006. {
  13007. }
  13008. ~SetPropertyAction() {}
  13009. bool perform()
  13010. {
  13011. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13012. if (isDeletingProperty)
  13013. target->removeProperty (name, 0);
  13014. else
  13015. target->setProperty (name, newValue, 0);
  13016. return true;
  13017. }
  13018. bool undo()
  13019. {
  13020. if (isAddingNewProperty)
  13021. target->removeProperty (name, 0);
  13022. else
  13023. target->setProperty (name, oldValue, 0);
  13024. return true;
  13025. }
  13026. int getSizeInUnits()
  13027. {
  13028. return (int) sizeof (*this); //xxx should be more accurate
  13029. }
  13030. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13031. {
  13032. if (! (isAddingNewProperty || isDeletingProperty))
  13033. {
  13034. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13035. if (next != 0 && next->target == target && next->name == name
  13036. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13037. {
  13038. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13039. }
  13040. }
  13041. return 0;
  13042. }
  13043. private:
  13044. const SharedObjectPtr target;
  13045. const Identifier name;
  13046. const var newValue;
  13047. var oldValue;
  13048. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13049. SetPropertyAction (const SetPropertyAction&);
  13050. SetPropertyAction& operator= (const SetPropertyAction&);
  13051. };
  13052. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13053. {
  13054. public:
  13055. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13056. const SharedObjectPtr& newChild_)
  13057. : target (target_),
  13058. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13059. childIndex (childIndex_),
  13060. isDeleting (newChild_ == 0)
  13061. {
  13062. jassert (child != 0);
  13063. }
  13064. ~AddOrRemoveChildAction() {}
  13065. bool perform()
  13066. {
  13067. if (isDeleting)
  13068. target->removeChild (childIndex, 0);
  13069. else
  13070. target->addChild (child, childIndex, 0);
  13071. return true;
  13072. }
  13073. bool undo()
  13074. {
  13075. if (isDeleting)
  13076. {
  13077. target->addChild (child, childIndex, 0);
  13078. }
  13079. else
  13080. {
  13081. // If you hit this, it seems that your object's state is getting confused - probably
  13082. // because you've interleaved some undoable and non-undoable operations?
  13083. jassert (childIndex < target->children.size());
  13084. target->removeChild (childIndex, 0);
  13085. }
  13086. return true;
  13087. }
  13088. int getSizeInUnits()
  13089. {
  13090. return (int) sizeof (*this); //xxx should be more accurate
  13091. }
  13092. private:
  13093. const SharedObjectPtr target, child;
  13094. const int childIndex;
  13095. const bool isDeleting;
  13096. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  13097. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  13098. };
  13099. class ValueTree::MoveChildAction : public UndoableAction
  13100. {
  13101. public:
  13102. MoveChildAction (const SharedObjectPtr& parent_,
  13103. const int startIndex_, const int endIndex_)
  13104. : parent (parent_),
  13105. startIndex (startIndex_),
  13106. endIndex (endIndex_)
  13107. {
  13108. }
  13109. ~MoveChildAction() {}
  13110. bool perform()
  13111. {
  13112. parent->moveChild (startIndex, endIndex, 0);
  13113. return true;
  13114. }
  13115. bool undo()
  13116. {
  13117. parent->moveChild (endIndex, startIndex, 0);
  13118. return true;
  13119. }
  13120. int getSizeInUnits()
  13121. {
  13122. return (int) sizeof (*this); //xxx should be more accurate
  13123. }
  13124. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13125. {
  13126. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13127. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13128. return new MoveChildAction (parent, startIndex, next->endIndex);
  13129. return 0;
  13130. }
  13131. private:
  13132. const SharedObjectPtr parent;
  13133. const int startIndex, endIndex;
  13134. MoveChildAction (const MoveChildAction&);
  13135. MoveChildAction& operator= (const MoveChildAction&);
  13136. };
  13137. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13138. : type (type_), parent (0)
  13139. {
  13140. }
  13141. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13142. : type (other.type), properties (other.properties), parent (0)
  13143. {
  13144. for (int i = 0; i < other.children.size(); ++i)
  13145. {
  13146. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13147. child->parent = this;
  13148. children.add (child);
  13149. }
  13150. }
  13151. ValueTree::SharedObject::~SharedObject()
  13152. {
  13153. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13154. for (int i = children.size(); --i >= 0;)
  13155. {
  13156. const SharedObjectPtr c (children.getUnchecked(i));
  13157. c->parent = 0;
  13158. children.remove (i);
  13159. c->sendParentChangeMessage();
  13160. }
  13161. }
  13162. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13163. {
  13164. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13165. {
  13166. ValueTree* const v = valueTreesWithListeners[i];
  13167. if (v != 0)
  13168. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13169. }
  13170. }
  13171. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13172. {
  13173. ValueTree tree (this);
  13174. ValueTree::SharedObject* t = this;
  13175. while (t != 0)
  13176. {
  13177. t->sendPropertyChangeMessage (tree, property);
  13178. t = t->parent;
  13179. }
  13180. }
  13181. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13182. {
  13183. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13184. {
  13185. ValueTree* const v = valueTreesWithListeners[i];
  13186. if (v != 0)
  13187. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13188. }
  13189. }
  13190. void ValueTree::SharedObject::sendChildChangeMessage()
  13191. {
  13192. ValueTree tree (this);
  13193. ValueTree::SharedObject* t = this;
  13194. while (t != 0)
  13195. {
  13196. t->sendChildChangeMessage (tree);
  13197. t = t->parent;
  13198. }
  13199. }
  13200. void ValueTree::SharedObject::sendParentChangeMessage()
  13201. {
  13202. ValueTree tree (this);
  13203. int i;
  13204. for (i = children.size(); --i >= 0;)
  13205. {
  13206. SharedObject* const t = children[i];
  13207. if (t != 0)
  13208. t->sendParentChangeMessage();
  13209. }
  13210. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13211. {
  13212. ValueTree* const v = valueTreesWithListeners[i];
  13213. if (v != 0)
  13214. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13215. }
  13216. }
  13217. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13218. {
  13219. return properties [name];
  13220. }
  13221. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13222. {
  13223. return properties.getWithDefault (name, defaultReturnValue);
  13224. }
  13225. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13226. {
  13227. if (undoManager == 0)
  13228. {
  13229. if (properties.set (name, newValue))
  13230. sendPropertyChangeMessage (name);
  13231. }
  13232. else
  13233. {
  13234. var* const existingValue = properties.getItem (name);
  13235. if (existingValue != 0)
  13236. {
  13237. if (*existingValue != newValue)
  13238. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13239. }
  13240. else
  13241. {
  13242. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13243. }
  13244. }
  13245. }
  13246. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  13247. {
  13248. return properties.contains (name);
  13249. }
  13250. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13251. {
  13252. if (undoManager == 0)
  13253. {
  13254. if (properties.remove (name))
  13255. sendPropertyChangeMessage (name);
  13256. }
  13257. else
  13258. {
  13259. if (properties.contains (name))
  13260. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  13261. }
  13262. }
  13263. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  13264. {
  13265. if (undoManager == 0)
  13266. {
  13267. while (properties.size() > 0)
  13268. {
  13269. const Identifier name (properties.getName (properties.size() - 1));
  13270. properties.remove (name);
  13271. sendPropertyChangeMessage (name);
  13272. }
  13273. }
  13274. else
  13275. {
  13276. for (int i = properties.size(); --i >= 0;)
  13277. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  13278. }
  13279. }
  13280. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  13281. {
  13282. for (int i = 0; i < children.size(); ++i)
  13283. if (children.getUnchecked(i)->type == typeToMatch)
  13284. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13285. return ValueTree::invalid;
  13286. }
  13287. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  13288. {
  13289. for (int i = 0; i < children.size(); ++i)
  13290. if (children.getUnchecked(i)->type == typeToMatch)
  13291. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13292. SharedObject* const newObject = new SharedObject (typeToMatch);
  13293. addChild (newObject, -1, undoManager);
  13294. return ValueTree (newObject);
  13295. }
  13296. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13297. {
  13298. for (int i = 0; i < children.size(); ++i)
  13299. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  13300. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13301. return ValueTree::invalid;
  13302. }
  13303. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  13304. {
  13305. const SharedObject* p = parent;
  13306. while (p != 0)
  13307. {
  13308. if (p == possibleParent)
  13309. return true;
  13310. p = p->parent;
  13311. }
  13312. return false;
  13313. }
  13314. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  13315. {
  13316. return children.indexOf (child.object);
  13317. }
  13318. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  13319. {
  13320. if (child != 0 && child->parent != this)
  13321. {
  13322. if (child != this && ! isAChildOf (child))
  13323. {
  13324. // You should always make sure that a child is removed from its previous parent before
  13325. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13326. // undomanager should be used when removing it from its current parent..
  13327. jassert (child->parent == 0);
  13328. if (child->parent != 0)
  13329. {
  13330. jassert (child->parent->children.indexOf (child) >= 0);
  13331. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13332. }
  13333. if (undoManager == 0)
  13334. {
  13335. children.insert (index, child);
  13336. child->parent = this;
  13337. sendChildChangeMessage();
  13338. child->sendParentChangeMessage();
  13339. }
  13340. else
  13341. {
  13342. if (index < 0)
  13343. index = children.size();
  13344. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13345. }
  13346. }
  13347. else
  13348. {
  13349. // You're attempting to create a recursive loop! A node
  13350. // can't be a child of one of its own children!
  13351. jassertfalse;
  13352. }
  13353. }
  13354. }
  13355. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13356. {
  13357. const SharedObjectPtr child (children [childIndex]);
  13358. if (child != 0)
  13359. {
  13360. if (undoManager == 0)
  13361. {
  13362. children.remove (childIndex);
  13363. child->parent = 0;
  13364. sendChildChangeMessage();
  13365. child->sendParentChangeMessage();
  13366. }
  13367. else
  13368. {
  13369. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13370. }
  13371. }
  13372. }
  13373. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13374. {
  13375. while (children.size() > 0)
  13376. removeChild (children.size() - 1, undoManager);
  13377. }
  13378. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13379. {
  13380. // The source index must be a valid index!
  13381. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13382. if (currentIndex != newIndex
  13383. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13384. {
  13385. if (undoManager == 0)
  13386. {
  13387. children.move (currentIndex, newIndex);
  13388. sendChildChangeMessage();
  13389. }
  13390. else
  13391. {
  13392. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13393. newIndex = children.size() - 1;
  13394. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13395. }
  13396. }
  13397. }
  13398. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  13399. {
  13400. if (type != other.type
  13401. || properties.size() != other.properties.size()
  13402. || children.size() != other.children.size()
  13403. || properties != other.properties)
  13404. return false;
  13405. for (int i = 0; i < children.size(); ++i)
  13406. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  13407. return false;
  13408. return true;
  13409. }
  13410. ValueTree::ValueTree() throw()
  13411. : object (0)
  13412. {
  13413. }
  13414. const ValueTree ValueTree::invalid;
  13415. ValueTree::ValueTree (const Identifier& type_)
  13416. : object (new ValueTree::SharedObject (type_))
  13417. {
  13418. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  13419. }
  13420. ValueTree::ValueTree (SharedObject* const object_)
  13421. : object (object_)
  13422. {
  13423. }
  13424. ValueTree::ValueTree (const ValueTree& other)
  13425. : object (other.object)
  13426. {
  13427. }
  13428. ValueTree& ValueTree::operator= (const ValueTree& other)
  13429. {
  13430. if (listeners.size() > 0)
  13431. {
  13432. if (object != 0)
  13433. object->valueTreesWithListeners.removeValue (this);
  13434. if (other.object != 0)
  13435. other.object->valueTreesWithListeners.add (this);
  13436. }
  13437. object = other.object;
  13438. return *this;
  13439. }
  13440. ValueTree::~ValueTree()
  13441. {
  13442. if (listeners.size() > 0 && object != 0)
  13443. object->valueTreesWithListeners.removeValue (this);
  13444. }
  13445. bool ValueTree::operator== (const ValueTree& other) const throw()
  13446. {
  13447. return object == other.object;
  13448. }
  13449. bool ValueTree::operator!= (const ValueTree& other) const throw()
  13450. {
  13451. return object != other.object;
  13452. }
  13453. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  13454. {
  13455. return object == other.object
  13456. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  13457. }
  13458. ValueTree ValueTree::createCopy() const
  13459. {
  13460. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13461. }
  13462. bool ValueTree::hasType (const Identifier& typeName) const
  13463. {
  13464. return object != 0 && object->type == typeName;
  13465. }
  13466. const Identifier ValueTree::getType() const
  13467. {
  13468. return object != 0 ? object->type : Identifier();
  13469. }
  13470. ValueTree ValueTree::getParent() const
  13471. {
  13472. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13473. }
  13474. ValueTree ValueTree::getSibling (const int delta) const
  13475. {
  13476. if (object == 0 || object->parent == 0)
  13477. return invalid;
  13478. const int index = object->parent->indexOf (*this) + delta;
  13479. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  13480. }
  13481. const var& ValueTree::operator[] (const Identifier& name) const
  13482. {
  13483. return object == 0 ? var::null : object->getProperty (name);
  13484. }
  13485. const var& ValueTree::getProperty (const Identifier& name) const
  13486. {
  13487. return object == 0 ? var::null : object->getProperty (name);
  13488. }
  13489. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13490. {
  13491. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13492. }
  13493. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13494. {
  13495. jassert (name.toString().isNotEmpty());
  13496. if (object != 0 && name.toString().isNotEmpty())
  13497. object->setProperty (name, newValue, undoManager);
  13498. }
  13499. bool ValueTree::hasProperty (const Identifier& name) const
  13500. {
  13501. return object != 0 && object->hasProperty (name);
  13502. }
  13503. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13504. {
  13505. if (object != 0)
  13506. object->removeProperty (name, undoManager);
  13507. }
  13508. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13509. {
  13510. if (object != 0)
  13511. object->removeAllProperties (undoManager);
  13512. }
  13513. int ValueTree::getNumProperties() const
  13514. {
  13515. return object == 0 ? 0 : object->properties.size();
  13516. }
  13517. const Identifier ValueTree::getPropertyName (const int index) const
  13518. {
  13519. return object == 0 ? Identifier()
  13520. : object->properties.getName (index);
  13521. }
  13522. class ValueTreePropertyValueSource : public Value::ValueSource,
  13523. public ValueTree::Listener
  13524. {
  13525. public:
  13526. ValueTreePropertyValueSource (const ValueTree& tree_,
  13527. const Identifier& property_,
  13528. UndoManager* const undoManager_)
  13529. : tree (tree_),
  13530. property (property_),
  13531. undoManager (undoManager_)
  13532. {
  13533. tree.addListener (this);
  13534. }
  13535. ~ValueTreePropertyValueSource()
  13536. {
  13537. tree.removeListener (this);
  13538. }
  13539. const var getValue() const
  13540. {
  13541. return tree [property];
  13542. }
  13543. void setValue (const var& newValue)
  13544. {
  13545. tree.setProperty (property, newValue, undoManager);
  13546. }
  13547. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  13548. {
  13549. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13550. sendChangeMessage (false);
  13551. }
  13552. void valueTreeChildrenChanged (ValueTree&) {}
  13553. void valueTreeParentChanged (ValueTree&) {}
  13554. private:
  13555. ValueTree tree;
  13556. const Identifier property;
  13557. UndoManager* const undoManager;
  13558. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13559. };
  13560. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  13561. {
  13562. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13563. }
  13564. int ValueTree::getNumChildren() const
  13565. {
  13566. return object == 0 ? 0 : object->children.size();
  13567. }
  13568. ValueTree ValueTree::getChild (int index) const
  13569. {
  13570. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13571. }
  13572. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  13573. {
  13574. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13575. }
  13576. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  13577. {
  13578. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  13579. }
  13580. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13581. {
  13582. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13583. }
  13584. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13585. {
  13586. return object != 0 && object->isAChildOf (possibleParent.object);
  13587. }
  13588. int ValueTree::indexOf (const ValueTree& child) const
  13589. {
  13590. return object != 0 ? object->indexOf (child) : -1;
  13591. }
  13592. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  13593. {
  13594. if (object != 0)
  13595. object->addChild (child.object, index, undoManager);
  13596. }
  13597. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13598. {
  13599. if (object != 0)
  13600. object->removeChild (childIndex, undoManager);
  13601. }
  13602. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13603. {
  13604. if (object != 0)
  13605. object->removeChild (object->children.indexOf (child.object), undoManager);
  13606. }
  13607. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13608. {
  13609. if (object != 0)
  13610. object->removeAllChildren (undoManager);
  13611. }
  13612. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13613. {
  13614. if (object != 0)
  13615. object->moveChild (currentIndex, newIndex, undoManager);
  13616. }
  13617. void ValueTree::addListener (Listener* listener)
  13618. {
  13619. if (listener != 0)
  13620. {
  13621. if (listeners.size() == 0 && object != 0)
  13622. object->valueTreesWithListeners.add (this);
  13623. listeners.add (listener);
  13624. }
  13625. }
  13626. void ValueTree::removeListener (Listener* listener)
  13627. {
  13628. listeners.remove (listener);
  13629. if (listeners.size() == 0 && object != 0)
  13630. object->valueTreesWithListeners.removeValue (this);
  13631. }
  13632. XmlElement* ValueTree::SharedObject::createXml() const
  13633. {
  13634. XmlElement* xml = new XmlElement (type.toString());
  13635. int i;
  13636. for (i = 0; i < properties.size(); ++i)
  13637. {
  13638. Identifier name (properties.getName(i));
  13639. const var& v = properties [name];
  13640. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13641. xml->setAttribute (name.toString(), v.toString());
  13642. }
  13643. for (i = 0; i < children.size(); ++i)
  13644. xml->addChildElement (children.getUnchecked(i)->createXml());
  13645. return xml;
  13646. }
  13647. XmlElement* ValueTree::createXml() const
  13648. {
  13649. return object != 0 ? object->createXml() : 0;
  13650. }
  13651. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13652. {
  13653. ValueTree v (xml.getTagName());
  13654. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13655. for (int i = 0; i < numAtts; ++i)
  13656. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13657. forEachXmlChildElement (xml, e)
  13658. {
  13659. v.addChild (fromXml (*e), -1, 0);
  13660. }
  13661. return v;
  13662. }
  13663. void ValueTree::writeToStream (OutputStream& output)
  13664. {
  13665. output.writeString (getType().toString());
  13666. const int numProps = getNumProperties();
  13667. output.writeCompressedInt (numProps);
  13668. int i;
  13669. for (i = 0; i < numProps; ++i)
  13670. {
  13671. const Identifier name (getPropertyName(i));
  13672. output.writeString (name.toString());
  13673. getProperty(name).writeToStream (output);
  13674. }
  13675. const int numChildren = getNumChildren();
  13676. output.writeCompressedInt (numChildren);
  13677. for (i = 0; i < numChildren; ++i)
  13678. getChild (i).writeToStream (output);
  13679. }
  13680. ValueTree ValueTree::readFromStream (InputStream& input)
  13681. {
  13682. const String type (input.readString());
  13683. if (type.isEmpty())
  13684. return ValueTree::invalid;
  13685. ValueTree v (type);
  13686. const int numProps = input.readCompressedInt();
  13687. if (numProps < 0)
  13688. {
  13689. jassertfalse; // trying to read corrupted data!
  13690. return v;
  13691. }
  13692. int i;
  13693. for (i = 0; i < numProps; ++i)
  13694. {
  13695. const String name (input.readString());
  13696. jassert (name.isNotEmpty());
  13697. const var value (var::readFromStream (input));
  13698. v.setProperty (name, value, 0);
  13699. }
  13700. const int numChildren = input.readCompressedInt();
  13701. for (i = 0; i < numChildren; ++i)
  13702. v.addChild (readFromStream (input), -1, 0);
  13703. return v;
  13704. }
  13705. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  13706. {
  13707. MemoryInputStream in (data, numBytes, false);
  13708. return readFromStream (in);
  13709. }
  13710. END_JUCE_NAMESPACE
  13711. /*** End of inlined file: juce_ValueTree.cpp ***/
  13712. /*** Start of inlined file: juce_Value.cpp ***/
  13713. BEGIN_JUCE_NAMESPACE
  13714. Value::ValueSource::ValueSource()
  13715. {
  13716. }
  13717. Value::ValueSource::~ValueSource()
  13718. {
  13719. }
  13720. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13721. {
  13722. if (synchronous)
  13723. {
  13724. for (int i = valuesWithListeners.size(); --i >= 0;)
  13725. {
  13726. Value* const v = valuesWithListeners[i];
  13727. if (v != 0)
  13728. v->callListeners();
  13729. }
  13730. }
  13731. else
  13732. {
  13733. triggerAsyncUpdate();
  13734. }
  13735. }
  13736. void Value::ValueSource::handleAsyncUpdate()
  13737. {
  13738. sendChangeMessage (true);
  13739. }
  13740. class SimpleValueSource : public Value::ValueSource
  13741. {
  13742. public:
  13743. SimpleValueSource()
  13744. {
  13745. }
  13746. SimpleValueSource (const var& initialValue)
  13747. : value (initialValue)
  13748. {
  13749. }
  13750. ~SimpleValueSource()
  13751. {
  13752. }
  13753. const var getValue() const
  13754. {
  13755. return value;
  13756. }
  13757. void setValue (const var& newValue)
  13758. {
  13759. if (newValue != value)
  13760. {
  13761. value = newValue;
  13762. sendChangeMessage (false);
  13763. }
  13764. }
  13765. private:
  13766. var value;
  13767. SimpleValueSource (const SimpleValueSource&);
  13768. SimpleValueSource& operator= (const SimpleValueSource&);
  13769. };
  13770. Value::Value()
  13771. : value (new SimpleValueSource())
  13772. {
  13773. }
  13774. Value::Value (ValueSource* const value_)
  13775. : value (value_)
  13776. {
  13777. jassert (value_ != 0);
  13778. }
  13779. Value::Value (const var& initialValue)
  13780. : value (new SimpleValueSource (initialValue))
  13781. {
  13782. }
  13783. Value::Value (const Value& other)
  13784. : value (other.value)
  13785. {
  13786. }
  13787. Value& Value::operator= (const Value& other)
  13788. {
  13789. value = other.value;
  13790. return *this;
  13791. }
  13792. Value::~Value()
  13793. {
  13794. if (listeners.size() > 0)
  13795. value->valuesWithListeners.removeValue (this);
  13796. }
  13797. const var Value::getValue() const
  13798. {
  13799. return value->getValue();
  13800. }
  13801. Value::operator const var() const
  13802. {
  13803. return getValue();
  13804. }
  13805. void Value::setValue (const var& newValue)
  13806. {
  13807. value->setValue (newValue);
  13808. }
  13809. const String Value::toString() const
  13810. {
  13811. return value->getValue().toString();
  13812. }
  13813. Value& Value::operator= (const var& newValue)
  13814. {
  13815. value->setValue (newValue);
  13816. return *this;
  13817. }
  13818. void Value::referTo (const Value& valueToReferTo)
  13819. {
  13820. if (valueToReferTo.value != value)
  13821. {
  13822. if (listeners.size() > 0)
  13823. {
  13824. value->valuesWithListeners.removeValue (this);
  13825. valueToReferTo.value->valuesWithListeners.add (this);
  13826. }
  13827. value = valueToReferTo.value;
  13828. callListeners();
  13829. }
  13830. }
  13831. bool Value::refersToSameSourceAs (const Value& other) const
  13832. {
  13833. return value == other.value;
  13834. }
  13835. bool Value::operator== (const Value& other) const
  13836. {
  13837. return value == other.value || value->getValue() == other.getValue();
  13838. }
  13839. bool Value::operator!= (const Value& other) const
  13840. {
  13841. return value != other.value && value->getValue() != other.getValue();
  13842. }
  13843. void Value::addListener (Listener* const listener)
  13844. {
  13845. if (listener != 0)
  13846. {
  13847. if (listeners.size() == 0)
  13848. value->valuesWithListeners.add (this);
  13849. listeners.add (listener);
  13850. }
  13851. }
  13852. void Value::removeListener (Listener* const listener)
  13853. {
  13854. listeners.remove (listener);
  13855. if (listeners.size() == 0)
  13856. value->valuesWithListeners.removeValue (this);
  13857. }
  13858. void Value::callListeners()
  13859. {
  13860. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13861. listeners.call (&Listener::valueChanged, v);
  13862. }
  13863. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13864. {
  13865. return stream << value.toString();
  13866. }
  13867. END_JUCE_NAMESPACE
  13868. /*** End of inlined file: juce_Value.cpp ***/
  13869. /*** Start of inlined file: juce_Application.cpp ***/
  13870. BEGIN_JUCE_NAMESPACE
  13871. JUCEApplication::JUCEApplication()
  13872. : appReturnValue (0),
  13873. stillInitialising (true)
  13874. {
  13875. jassert (appInstance == 0);
  13876. appInstance = this;
  13877. }
  13878. JUCEApplication::~JUCEApplication()
  13879. {
  13880. if (appLock != 0)
  13881. {
  13882. appLock->exit();
  13883. appLock = 0;
  13884. }
  13885. jassert (appInstance == this);
  13886. appInstance = 0;
  13887. }
  13888. JUCEApplication* JUCEApplication::appInstance = 0;
  13889. JUCEApplication* JUCEApplication::getInstance() throw()
  13890. {
  13891. return appInstance;
  13892. }
  13893. bool JUCEApplication::isInitialising() const throw()
  13894. {
  13895. return stillInitialising;
  13896. }
  13897. const String JUCEApplication::getApplicationVersion()
  13898. {
  13899. return String::empty;
  13900. }
  13901. bool JUCEApplication::moreThanOneInstanceAllowed()
  13902. {
  13903. return true;
  13904. }
  13905. void JUCEApplication::anotherInstanceStarted (const String&)
  13906. {
  13907. }
  13908. void JUCEApplication::systemRequestedQuit()
  13909. {
  13910. quit();
  13911. }
  13912. void JUCEApplication::quit()
  13913. {
  13914. MessageManager::getInstance()->stopDispatchLoop();
  13915. }
  13916. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13917. {
  13918. appReturnValue = newReturnValue;
  13919. }
  13920. void JUCEApplication::actionListenerCallback (const String& message)
  13921. {
  13922. if (message.startsWith (getApplicationName() + "/"))
  13923. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13924. }
  13925. void JUCEApplication::unhandledException (const std::exception*,
  13926. const String&,
  13927. const int)
  13928. {
  13929. jassertfalse;
  13930. }
  13931. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13932. const char* const sourceFile,
  13933. const int lineNumber)
  13934. {
  13935. if (appInstance != 0)
  13936. appInstance->unhandledException (e, sourceFile, lineNumber);
  13937. }
  13938. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13939. {
  13940. return 0;
  13941. }
  13942. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13943. {
  13944. commands.add (StandardApplicationCommandIDs::quit);
  13945. }
  13946. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13947. {
  13948. if (commandID == StandardApplicationCommandIDs::quit)
  13949. {
  13950. result.setInfo (TRANS("Quit"),
  13951. TRANS("Quits the application"),
  13952. "Application",
  13953. 0);
  13954. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13955. }
  13956. }
  13957. bool JUCEApplication::perform (const InvocationInfo& info)
  13958. {
  13959. if (info.commandID == StandardApplicationCommandIDs::quit)
  13960. {
  13961. systemRequestedQuit();
  13962. return true;
  13963. }
  13964. return false;
  13965. }
  13966. bool JUCEApplication::initialiseApp (const String& commandLine)
  13967. {
  13968. commandLineParameters = commandLine.trim();
  13969. #if ! JUCE_IOS
  13970. jassert (appLock == 0); // initialiseApp must only be called once!
  13971. if (! moreThanOneInstanceAllowed())
  13972. {
  13973. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13974. if (! appLock->enter(0))
  13975. {
  13976. appLock = 0;
  13977. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13978. DBG ("Another instance is running - quitting...");
  13979. return false;
  13980. }
  13981. }
  13982. #endif
  13983. // let the app do its setting-up..
  13984. initialise (commandLineParameters);
  13985. // register for broadcast new app messages
  13986. MessageManager::getInstance()->registerBroadcastListener (this);
  13987. stillInitialising = false;
  13988. return true;
  13989. }
  13990. int JUCEApplication::shutdownApp()
  13991. {
  13992. jassert (appInstance == this);
  13993. MessageManager::getInstance()->deregisterBroadcastListener (this);
  13994. JUCE_TRY
  13995. {
  13996. // give the app a chance to clean up..
  13997. shutdown();
  13998. }
  13999. JUCE_CATCH_EXCEPTION
  14000. return getApplicationReturnValue();
  14001. }
  14002. int JUCEApplication::main (const String& commandLine, JUCEApplication* const app)
  14003. {
  14004. const ScopedPointer<JUCEApplication> appDeleter (app);
  14005. if (! app->initialiseApp (commandLine))
  14006. return 0;
  14007. JUCE_TRY
  14008. {
  14009. // loop until a quit message is received..
  14010. MessageManager::getInstance()->runDispatchLoop();
  14011. }
  14012. JUCE_CATCH_EXCEPTION
  14013. return app->shutdownApp();
  14014. }
  14015. #if JUCE_IOS
  14016. extern int juce_iOSMain (int argc, const char* argv[]);
  14017. #endif
  14018. #if ! JUCE_WINDOWS
  14019. extern const char* juce_Argv0;
  14020. #endif
  14021. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  14022. {
  14023. JUCE_AUTORELEASEPOOL
  14024. #if ! JUCE_WINDOWS
  14025. juce_Argv0 = argv[0];
  14026. #endif
  14027. #if JUCE_IOS
  14028. const ScopedPointer<JUCEApplication> appDeleter (newApp);
  14029. return juce_iOSMain (argc, argv);
  14030. #else
  14031. String cmd;
  14032. for (int i = 1; i < argc; ++i)
  14033. cmd << argv[i] << ' ';
  14034. return JUCEApplication::main (cmd, newApp);
  14035. #endif
  14036. }
  14037. END_JUCE_NAMESPACE
  14038. /*** End of inlined file: juce_Application.cpp ***/
  14039. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14040. BEGIN_JUCE_NAMESPACE
  14041. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14042. : commandID (commandID_),
  14043. flags (0)
  14044. {
  14045. }
  14046. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14047. const String& description_,
  14048. const String& categoryName_,
  14049. const int flags_) throw()
  14050. {
  14051. shortName = shortName_;
  14052. description = description_;
  14053. categoryName = categoryName_;
  14054. flags = flags_;
  14055. }
  14056. void ApplicationCommandInfo::setActive (const bool b) throw()
  14057. {
  14058. if (b)
  14059. flags &= ~isDisabled;
  14060. else
  14061. flags |= isDisabled;
  14062. }
  14063. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14064. {
  14065. if (b)
  14066. flags |= isTicked;
  14067. else
  14068. flags &= ~isTicked;
  14069. }
  14070. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14071. {
  14072. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14073. }
  14074. END_JUCE_NAMESPACE
  14075. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14076. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14077. BEGIN_JUCE_NAMESPACE
  14078. ApplicationCommandManager::ApplicationCommandManager()
  14079. : firstTarget (0)
  14080. {
  14081. keyMappings = new KeyPressMappingSet (this);
  14082. Desktop::getInstance().addFocusChangeListener (this);
  14083. }
  14084. ApplicationCommandManager::~ApplicationCommandManager()
  14085. {
  14086. Desktop::getInstance().removeFocusChangeListener (this);
  14087. keyMappings = 0;
  14088. }
  14089. void ApplicationCommandManager::clearCommands()
  14090. {
  14091. commands.clear();
  14092. keyMappings->clearAllKeyPresses();
  14093. triggerAsyncUpdate();
  14094. }
  14095. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14096. {
  14097. // zero isn't a valid command ID!
  14098. jassert (newCommand.commandID != 0);
  14099. // the name isn't optional!
  14100. jassert (newCommand.shortName.isNotEmpty());
  14101. if (getCommandForID (newCommand.commandID) == 0)
  14102. {
  14103. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14104. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14105. commands.add (newInfo);
  14106. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14107. triggerAsyncUpdate();
  14108. }
  14109. else
  14110. {
  14111. // trying to re-register the same command with different parameters?
  14112. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14113. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14114. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14115. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14116. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14117. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14118. }
  14119. }
  14120. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14121. {
  14122. if (target != 0)
  14123. {
  14124. Array <CommandID> commandIDs;
  14125. target->getAllCommands (commandIDs);
  14126. for (int i = 0; i < commandIDs.size(); ++i)
  14127. {
  14128. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14129. target->getCommandInfo (info.commandID, info);
  14130. registerCommand (info);
  14131. }
  14132. }
  14133. }
  14134. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14135. {
  14136. for (int i = commands.size(); --i >= 0;)
  14137. {
  14138. if (commands.getUnchecked (i)->commandID == commandID)
  14139. {
  14140. commands.remove (i);
  14141. triggerAsyncUpdate();
  14142. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14143. for (int j = keys.size(); --j >= 0;)
  14144. keyMappings->removeKeyPress (keys.getReference (j));
  14145. }
  14146. }
  14147. }
  14148. void ApplicationCommandManager::commandStatusChanged()
  14149. {
  14150. triggerAsyncUpdate();
  14151. }
  14152. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14153. {
  14154. for (int i = commands.size(); --i >= 0;)
  14155. if (commands.getUnchecked(i)->commandID == commandID)
  14156. return commands.getUnchecked(i);
  14157. return 0;
  14158. }
  14159. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14160. {
  14161. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14162. return (ci != 0) ? ci->shortName : String::empty;
  14163. }
  14164. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14165. {
  14166. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14167. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14168. : String::empty;
  14169. }
  14170. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14171. {
  14172. StringArray s;
  14173. for (int i = 0; i < commands.size(); ++i)
  14174. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14175. return s;
  14176. }
  14177. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14178. {
  14179. Array <CommandID> results;
  14180. for (int i = 0; i < commands.size(); ++i)
  14181. if (commands.getUnchecked(i)->categoryName == categoryName)
  14182. results.add (commands.getUnchecked(i)->commandID);
  14183. return results;
  14184. }
  14185. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14186. {
  14187. ApplicationCommandTarget::InvocationInfo info (commandID);
  14188. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14189. return invoke (info, asynchronously);
  14190. }
  14191. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14192. {
  14193. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14194. // manager first..
  14195. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14196. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14197. if (target == 0)
  14198. return false;
  14199. ApplicationCommandInfo commandInfo (0);
  14200. target->getCommandInfo (info_.commandID, commandInfo);
  14201. ApplicationCommandTarget::InvocationInfo info (info_);
  14202. info.commandFlags = commandInfo.flags;
  14203. sendListenerInvokeCallback (info);
  14204. const bool ok = target->invoke (info, asynchronously);
  14205. commandStatusChanged();
  14206. return ok;
  14207. }
  14208. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14209. {
  14210. return firstTarget != 0 ? firstTarget
  14211. : findDefaultComponentTarget();
  14212. }
  14213. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14214. {
  14215. firstTarget = newTarget;
  14216. }
  14217. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14218. ApplicationCommandInfo& upToDateInfo)
  14219. {
  14220. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14221. if (target == 0)
  14222. target = JUCEApplication::getInstance();
  14223. if (target != 0)
  14224. target = target->getTargetForCommand (commandID);
  14225. if (target != 0)
  14226. target->getCommandInfo (commandID, upToDateInfo);
  14227. return target;
  14228. }
  14229. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14230. {
  14231. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14232. if (target == 0 && c != 0)
  14233. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14234. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14235. return target;
  14236. }
  14237. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14238. {
  14239. Component* c = Component::getCurrentlyFocusedComponent();
  14240. if (c == 0)
  14241. {
  14242. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14243. if (activeWindow != 0)
  14244. {
  14245. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14246. if (c == 0)
  14247. c = activeWindow;
  14248. }
  14249. }
  14250. if (c == 0 && Process::isForegroundProcess())
  14251. {
  14252. // getting a bit desperate now - try all desktop comps..
  14253. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14254. {
  14255. ApplicationCommandTarget* const target
  14256. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14257. ->getPeer()->getLastFocusedSubcomponent());
  14258. if (target != 0)
  14259. return target;
  14260. }
  14261. }
  14262. if (c != 0)
  14263. {
  14264. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14265. // if we're focused on a ResizableWindow, chances are that it's the content
  14266. // component that really should get the event. And if not, the event will
  14267. // still be passed up to the top level window anyway, so let's send it to the
  14268. // content comp.
  14269. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14270. c = resizableWindow->getContentComponent();
  14271. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14272. if (target != 0)
  14273. return target;
  14274. }
  14275. return JUCEApplication::getInstance();
  14276. }
  14277. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14278. {
  14279. listeners.add (listener);
  14280. }
  14281. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14282. {
  14283. listeners.remove (listener);
  14284. }
  14285. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14286. {
  14287. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14288. }
  14289. void ApplicationCommandManager::handleAsyncUpdate()
  14290. {
  14291. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14292. }
  14293. void ApplicationCommandManager::globalFocusChanged (Component*)
  14294. {
  14295. commandStatusChanged();
  14296. }
  14297. END_JUCE_NAMESPACE
  14298. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14299. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14300. BEGIN_JUCE_NAMESPACE
  14301. ApplicationCommandTarget::ApplicationCommandTarget()
  14302. {
  14303. }
  14304. ApplicationCommandTarget::~ApplicationCommandTarget()
  14305. {
  14306. messageInvoker = 0;
  14307. }
  14308. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14309. {
  14310. if (isCommandActive (info.commandID))
  14311. {
  14312. if (async)
  14313. {
  14314. if (messageInvoker == 0)
  14315. messageInvoker = new CommandTargetMessageInvoker (this);
  14316. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14317. return true;
  14318. }
  14319. else
  14320. {
  14321. const bool success = perform (info);
  14322. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14323. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14324. // returns the command's info.
  14325. return success;
  14326. }
  14327. }
  14328. return false;
  14329. }
  14330. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14331. {
  14332. Component* c = dynamic_cast <Component*> (this);
  14333. if (c != 0)
  14334. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14335. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14336. return 0;
  14337. }
  14338. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14339. {
  14340. ApplicationCommandTarget* target = this;
  14341. int depth = 0;
  14342. while (target != 0)
  14343. {
  14344. Array <CommandID> commandIDs;
  14345. target->getAllCommands (commandIDs);
  14346. if (commandIDs.contains (commandID))
  14347. return target;
  14348. target = target->getNextCommandTarget();
  14349. ++depth;
  14350. jassert (depth < 100); // could be a recursive command chain??
  14351. jassert (target != this); // definitely a recursive command chain!
  14352. if (depth > 100 || target == this)
  14353. break;
  14354. }
  14355. if (target == 0)
  14356. {
  14357. target = JUCEApplication::getInstance();
  14358. if (target != 0)
  14359. {
  14360. Array <CommandID> commandIDs;
  14361. target->getAllCommands (commandIDs);
  14362. if (commandIDs.contains (commandID))
  14363. return target;
  14364. }
  14365. }
  14366. return 0;
  14367. }
  14368. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14369. {
  14370. ApplicationCommandInfo info (commandID);
  14371. info.flags = ApplicationCommandInfo::isDisabled;
  14372. getCommandInfo (commandID, info);
  14373. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14374. }
  14375. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14376. {
  14377. ApplicationCommandTarget* target = this;
  14378. int depth = 0;
  14379. while (target != 0)
  14380. {
  14381. if (target->tryToInvoke (info, async))
  14382. return true;
  14383. target = target->getNextCommandTarget();
  14384. ++depth;
  14385. jassert (depth < 100); // could be a recursive command chain??
  14386. jassert (target != this); // definitely a recursive command chain!
  14387. if (depth > 100 || target == this)
  14388. break;
  14389. }
  14390. if (target == 0)
  14391. {
  14392. target = JUCEApplication::getInstance();
  14393. if (target != 0)
  14394. return target->tryToInvoke (info, async);
  14395. }
  14396. return false;
  14397. }
  14398. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14399. {
  14400. ApplicationCommandTarget::InvocationInfo info (commandID);
  14401. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14402. return invoke (info, asynchronously);
  14403. }
  14404. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14405. : commandID (commandID_),
  14406. commandFlags (0),
  14407. invocationMethod (direct),
  14408. originatingComponent (0),
  14409. isKeyDown (false),
  14410. millisecsSinceKeyPressed (0)
  14411. {
  14412. }
  14413. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14414. : owner (owner_)
  14415. {
  14416. }
  14417. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14418. {
  14419. }
  14420. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14421. {
  14422. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14423. owner->tryToInvoke (*info, false);
  14424. }
  14425. END_JUCE_NAMESPACE
  14426. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14427. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14428. BEGIN_JUCE_NAMESPACE
  14429. juce_ImplementSingleton (ApplicationProperties)
  14430. ApplicationProperties::ApplicationProperties() throw()
  14431. : msBeforeSaving (3000),
  14432. options (PropertiesFile::storeAsBinary),
  14433. commonSettingsAreReadOnly (0)
  14434. {
  14435. }
  14436. ApplicationProperties::~ApplicationProperties()
  14437. {
  14438. closeFiles();
  14439. clearSingletonInstance();
  14440. }
  14441. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14442. const String& fileNameSuffix,
  14443. const String& folderName_,
  14444. const int millisecondsBeforeSaving,
  14445. const int propertiesFileOptions) throw()
  14446. {
  14447. appName = applicationName;
  14448. fileSuffix = fileNameSuffix;
  14449. folderName = folderName_;
  14450. msBeforeSaving = millisecondsBeforeSaving;
  14451. options = propertiesFileOptions;
  14452. }
  14453. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14454. const bool testCommonSettings,
  14455. const bool showWarningDialogOnFailure)
  14456. {
  14457. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14458. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14459. if (! (userOk && commonOk))
  14460. {
  14461. if (showWarningDialogOnFailure)
  14462. {
  14463. String filenames;
  14464. if (userProps != 0 && ! userOk)
  14465. filenames << '\n' << userProps->getFile().getFullPathName();
  14466. if (commonProps != 0 && ! commonOk)
  14467. filenames << '\n' << commonProps->getFile().getFullPathName();
  14468. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14469. appName + TRANS(" - Unable to save settings"),
  14470. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14471. + appName + TRANS(" needs to be able to write to the following files:\n")
  14472. + filenames
  14473. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14474. }
  14475. return false;
  14476. }
  14477. return true;
  14478. }
  14479. void ApplicationProperties::openFiles() throw()
  14480. {
  14481. // You need to call setStorageParameters() before trying to get hold of the
  14482. // properties!
  14483. jassert (appName.isNotEmpty());
  14484. if (appName.isNotEmpty())
  14485. {
  14486. if (userProps == 0)
  14487. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14488. false, msBeforeSaving, options);
  14489. if (commonProps == 0)
  14490. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14491. true, msBeforeSaving, options);
  14492. userProps->setFallbackPropertySet (commonProps);
  14493. }
  14494. }
  14495. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14496. {
  14497. if (userProps == 0)
  14498. openFiles();
  14499. return userProps;
  14500. }
  14501. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14502. {
  14503. if (commonProps == 0)
  14504. openFiles();
  14505. if (returnUserPropsIfReadOnly)
  14506. {
  14507. if (commonSettingsAreReadOnly == 0)
  14508. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14509. if (commonSettingsAreReadOnly > 0)
  14510. return userProps;
  14511. }
  14512. return commonProps;
  14513. }
  14514. bool ApplicationProperties::saveIfNeeded()
  14515. {
  14516. return (userProps == 0 || userProps->saveIfNeeded())
  14517. && (commonProps == 0 || commonProps->saveIfNeeded());
  14518. }
  14519. void ApplicationProperties::closeFiles()
  14520. {
  14521. userProps = 0;
  14522. commonProps = 0;
  14523. }
  14524. END_JUCE_NAMESPACE
  14525. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14526. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14527. BEGIN_JUCE_NAMESPACE
  14528. namespace PropertyFileConstants
  14529. {
  14530. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14531. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14532. static const char* const fileTag = "PROPERTIES";
  14533. static const char* const valueTag = "VALUE";
  14534. static const char* const nameAttribute = "name";
  14535. static const char* const valueAttribute = "val";
  14536. }
  14537. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14538. const int options_, InterProcessLock* const processLock_)
  14539. : PropertySet (ignoreCaseOfKeyNames),
  14540. file (f),
  14541. timerInterval (millisecondsBeforeSaving),
  14542. options (options_),
  14543. loadedOk (false),
  14544. needsWriting (false),
  14545. processLock (processLock_)
  14546. {
  14547. // You need to correctly specify just one storage format for the file
  14548. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14549. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14550. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14551. ProcessScopedLock pl (createProcessLock());
  14552. if (pl != 0 && ! pl->isLocked())
  14553. return; // locking failure..
  14554. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14555. if (fileStream != 0)
  14556. {
  14557. int magicNumber = fileStream->readInt();
  14558. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14559. {
  14560. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14561. magicNumber = PropertyFileConstants::magicNumber;
  14562. }
  14563. if (magicNumber == PropertyFileConstants::magicNumber)
  14564. {
  14565. loadedOk = true;
  14566. BufferedInputStream in (fileStream.release(), 2048, true);
  14567. int numValues = in.readInt();
  14568. while (--numValues >= 0 && ! in.isExhausted())
  14569. {
  14570. const String key (in.readString());
  14571. const String value (in.readString());
  14572. jassert (key.isNotEmpty());
  14573. if (key.isNotEmpty())
  14574. getAllProperties().set (key, value);
  14575. }
  14576. }
  14577. else
  14578. {
  14579. // Not a binary props file - let's see if it's XML..
  14580. fileStream = 0;
  14581. XmlDocument parser (f);
  14582. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14583. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14584. {
  14585. doc = parser.getDocumentElement();
  14586. if (doc != 0)
  14587. {
  14588. loadedOk = true;
  14589. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14590. {
  14591. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14592. if (name.isNotEmpty())
  14593. {
  14594. getAllProperties().set (name,
  14595. e->getFirstChildElement() != 0
  14596. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14597. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14598. }
  14599. }
  14600. }
  14601. else
  14602. {
  14603. // must be a pretty broken XML file we're trying to parse here,
  14604. // or a sign that this object needs an InterProcessLock,
  14605. // or just a failure reading the file. This last reason is why
  14606. // we don't jassertfalse here.
  14607. }
  14608. }
  14609. }
  14610. }
  14611. else
  14612. {
  14613. loadedOk = ! f.exists();
  14614. }
  14615. }
  14616. PropertiesFile::~PropertiesFile()
  14617. {
  14618. if (! saveIfNeeded())
  14619. jassertfalse;
  14620. }
  14621. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14622. {
  14623. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14624. }
  14625. bool PropertiesFile::saveIfNeeded()
  14626. {
  14627. const ScopedLock sl (getLock());
  14628. return (! needsWriting) || save();
  14629. }
  14630. bool PropertiesFile::needsToBeSaved() const
  14631. {
  14632. const ScopedLock sl (getLock());
  14633. return needsWriting;
  14634. }
  14635. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14636. {
  14637. const ScopedLock sl (getLock());
  14638. needsWriting = needsToBeSaved_;
  14639. }
  14640. bool PropertiesFile::save()
  14641. {
  14642. const ScopedLock sl (getLock());
  14643. stopTimer();
  14644. if (file == File::nonexistent
  14645. || file.isDirectory()
  14646. || ! file.getParentDirectory().createDirectory())
  14647. return false;
  14648. if ((options & storeAsXML) != 0)
  14649. {
  14650. XmlElement doc (PropertyFileConstants::fileTag);
  14651. for (int i = 0; i < getAllProperties().size(); ++i)
  14652. {
  14653. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14654. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14655. // if the value seems to contain xml, store it as such..
  14656. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14657. XmlElement* const childElement = xmlContent.getDocumentElement();
  14658. if (childElement != 0)
  14659. e->addChildElement (childElement);
  14660. else
  14661. e->setAttribute (PropertyFileConstants::valueAttribute,
  14662. getAllProperties().getAllValues() [i]);
  14663. }
  14664. ProcessScopedLock pl (createProcessLock());
  14665. if (pl != 0 && ! pl->isLocked())
  14666. return false; // locking failure..
  14667. if (doc.writeToFile (file, String::empty))
  14668. {
  14669. needsWriting = false;
  14670. return true;
  14671. }
  14672. }
  14673. else
  14674. {
  14675. ProcessScopedLock pl (createProcessLock());
  14676. if (pl != 0 && ! pl->isLocked())
  14677. return false; // locking failure..
  14678. TemporaryFile tempFile (file);
  14679. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14680. if (out != 0)
  14681. {
  14682. if ((options & storeAsCompressedBinary) != 0)
  14683. {
  14684. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14685. out->flush();
  14686. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14687. }
  14688. else
  14689. {
  14690. // have you set up the storage option flags correctly?
  14691. jassert ((options & storeAsBinary) != 0);
  14692. out->writeInt (PropertyFileConstants::magicNumber);
  14693. }
  14694. const int numProperties = getAllProperties().size();
  14695. out->writeInt (numProperties);
  14696. for (int i = 0; i < numProperties; ++i)
  14697. {
  14698. out->writeString (getAllProperties().getAllKeys() [i]);
  14699. out->writeString (getAllProperties().getAllValues() [i]);
  14700. }
  14701. out = 0;
  14702. if (tempFile.overwriteTargetFileWithTemporary())
  14703. {
  14704. needsWriting = false;
  14705. return true;
  14706. }
  14707. }
  14708. }
  14709. return false;
  14710. }
  14711. void PropertiesFile::timerCallback()
  14712. {
  14713. saveIfNeeded();
  14714. }
  14715. void PropertiesFile::propertyChanged()
  14716. {
  14717. sendChangeMessage (this);
  14718. needsWriting = true;
  14719. if (timerInterval > 0)
  14720. startTimer (timerInterval);
  14721. else if (timerInterval == 0)
  14722. saveIfNeeded();
  14723. }
  14724. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14725. const String& fileNameSuffix,
  14726. const String& folderName,
  14727. const bool commonToAllUsers)
  14728. {
  14729. // mustn't have illegal characters in this name..
  14730. jassert (applicationName == File::createLegalFileName (applicationName));
  14731. #if JUCE_MAC || JUCE_IOS
  14732. File dir (commonToAllUsers ? "/Library/Preferences"
  14733. : "~/Library/Preferences");
  14734. if (folderName.isNotEmpty())
  14735. dir = dir.getChildFile (folderName);
  14736. #endif
  14737. #ifdef JUCE_LINUX
  14738. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14739. + (folderName.isNotEmpty() ? folderName
  14740. : ("." + applicationName)));
  14741. #endif
  14742. #if JUCE_WINDOWS
  14743. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14744. : File::userApplicationDataDirectory));
  14745. if (dir == File::nonexistent)
  14746. return File::nonexistent;
  14747. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14748. : applicationName);
  14749. #endif
  14750. return dir.getChildFile (applicationName)
  14751. .withFileExtension (fileNameSuffix);
  14752. }
  14753. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14754. const String& fileNameSuffix,
  14755. const String& folderName,
  14756. const bool commonToAllUsers,
  14757. const int millisecondsBeforeSaving,
  14758. const int propertiesFileOptions,
  14759. InterProcessLock* processLock_)
  14760. {
  14761. const File file (getDefaultAppSettingsFile (applicationName,
  14762. fileNameSuffix,
  14763. folderName,
  14764. commonToAllUsers));
  14765. jassert (file != File::nonexistent);
  14766. if (file == File::nonexistent)
  14767. return 0;
  14768. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14769. }
  14770. END_JUCE_NAMESPACE
  14771. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14772. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14773. BEGIN_JUCE_NAMESPACE
  14774. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14775. const String& fileWildcard_,
  14776. const String& openFileDialogTitle_,
  14777. const String& saveFileDialogTitle_)
  14778. : changedSinceSave (false),
  14779. fileExtension (fileExtension_),
  14780. fileWildcard (fileWildcard_),
  14781. openFileDialogTitle (openFileDialogTitle_),
  14782. saveFileDialogTitle (saveFileDialogTitle_)
  14783. {
  14784. }
  14785. FileBasedDocument::~FileBasedDocument()
  14786. {
  14787. }
  14788. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14789. {
  14790. if (changedSinceSave != hasChanged)
  14791. {
  14792. changedSinceSave = hasChanged;
  14793. sendChangeMessage (this);
  14794. }
  14795. }
  14796. void FileBasedDocument::changed()
  14797. {
  14798. changedSinceSave = true;
  14799. sendChangeMessage (this);
  14800. }
  14801. void FileBasedDocument::setFile (const File& newFile)
  14802. {
  14803. if (documentFile != newFile)
  14804. {
  14805. documentFile = newFile;
  14806. changed();
  14807. }
  14808. }
  14809. bool FileBasedDocument::loadFrom (const File& newFile,
  14810. const bool showMessageOnFailure)
  14811. {
  14812. MouseCursor::showWaitCursor();
  14813. const File oldFile (documentFile);
  14814. documentFile = newFile;
  14815. String error;
  14816. if (newFile.existsAsFile())
  14817. {
  14818. error = loadDocument (newFile);
  14819. if (error.isEmpty())
  14820. {
  14821. setChangedFlag (false);
  14822. MouseCursor::hideWaitCursor();
  14823. setLastDocumentOpened (newFile);
  14824. return true;
  14825. }
  14826. }
  14827. else
  14828. {
  14829. error = "The file doesn't exist";
  14830. }
  14831. documentFile = oldFile;
  14832. MouseCursor::hideWaitCursor();
  14833. if (showMessageOnFailure)
  14834. {
  14835. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14836. TRANS("Failed to open file..."),
  14837. TRANS("There was an error while trying to load the file:\n\n")
  14838. + newFile.getFullPathName()
  14839. + "\n\n"
  14840. + error);
  14841. }
  14842. return false;
  14843. }
  14844. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14845. {
  14846. FileChooser fc (openFileDialogTitle,
  14847. getLastDocumentOpened(),
  14848. fileWildcard);
  14849. if (fc.browseForFileToOpen())
  14850. return loadFrom (fc.getResult(), showMessageOnFailure);
  14851. return false;
  14852. }
  14853. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14854. const bool showMessageOnFailure)
  14855. {
  14856. return saveAs (documentFile,
  14857. false,
  14858. askUserForFileIfNotSpecified,
  14859. showMessageOnFailure);
  14860. }
  14861. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14862. const bool warnAboutOverwritingExistingFiles,
  14863. const bool askUserForFileIfNotSpecified,
  14864. const bool showMessageOnFailure)
  14865. {
  14866. if (newFile == File::nonexistent)
  14867. {
  14868. if (askUserForFileIfNotSpecified)
  14869. {
  14870. return saveAsInteractive (true);
  14871. }
  14872. else
  14873. {
  14874. // can't save to an unspecified file
  14875. jassertfalse;
  14876. return failedToWriteToFile;
  14877. }
  14878. }
  14879. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14880. {
  14881. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14882. TRANS("File already exists"),
  14883. TRANS("There's already a file called:\n\n")
  14884. + newFile.getFullPathName()
  14885. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14886. TRANS("overwrite"),
  14887. TRANS("cancel")))
  14888. {
  14889. return userCancelledSave;
  14890. }
  14891. }
  14892. MouseCursor::showWaitCursor();
  14893. const File oldFile (documentFile);
  14894. documentFile = newFile;
  14895. String error (saveDocument (newFile));
  14896. if (error.isEmpty())
  14897. {
  14898. setChangedFlag (false);
  14899. MouseCursor::hideWaitCursor();
  14900. return savedOk;
  14901. }
  14902. documentFile = oldFile;
  14903. MouseCursor::hideWaitCursor();
  14904. if (showMessageOnFailure)
  14905. {
  14906. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14907. TRANS("Error writing to file..."),
  14908. TRANS("An error occurred while trying to save \"")
  14909. + getDocumentTitle()
  14910. + TRANS("\" to the file:\n\n")
  14911. + newFile.getFullPathName()
  14912. + "\n\n"
  14913. + error);
  14914. }
  14915. return failedToWriteToFile;
  14916. }
  14917. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14918. {
  14919. if (! hasChangedSinceSaved())
  14920. return savedOk;
  14921. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14922. TRANS("Closing document..."),
  14923. TRANS("Do you want to save the changes to \"")
  14924. + getDocumentTitle() + "\"?",
  14925. TRANS("save"),
  14926. TRANS("discard changes"),
  14927. TRANS("cancel"));
  14928. if (r == 1)
  14929. {
  14930. // save changes
  14931. return save (true, true);
  14932. }
  14933. else if (r == 2)
  14934. {
  14935. // discard changes
  14936. return savedOk;
  14937. }
  14938. return userCancelledSave;
  14939. }
  14940. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14941. {
  14942. File f;
  14943. if (documentFile.existsAsFile())
  14944. f = documentFile;
  14945. else
  14946. f = getLastDocumentOpened();
  14947. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14948. if (legalFilename.isEmpty())
  14949. legalFilename = "unnamed";
  14950. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14951. f = f.getSiblingFile (legalFilename);
  14952. else
  14953. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14954. f = f.withFileExtension (fileExtension)
  14955. .getNonexistentSibling (true);
  14956. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14957. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14958. {
  14959. setLastDocumentOpened (fc.getResult());
  14960. File chosen (fc.getResult());
  14961. if (chosen.getFileExtension().isEmpty())
  14962. {
  14963. chosen = chosen.withFileExtension (fileExtension);
  14964. if (chosen.exists())
  14965. {
  14966. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14967. TRANS("File already exists"),
  14968. TRANS("There's already a file called:")
  14969. + "\n\n" + chosen.getFullPathName()
  14970. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14971. TRANS("overwrite"),
  14972. TRANS("cancel")))
  14973. {
  14974. return userCancelledSave;
  14975. }
  14976. }
  14977. }
  14978. return saveAs (chosen, false, false, true);
  14979. }
  14980. return userCancelledSave;
  14981. }
  14982. END_JUCE_NAMESPACE
  14983. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14984. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14985. BEGIN_JUCE_NAMESPACE
  14986. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14987. : maxNumberOfItems (10)
  14988. {
  14989. }
  14990. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14991. {
  14992. }
  14993. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14994. {
  14995. maxNumberOfItems = jmax (1, newMaxNumber);
  14996. while (getNumFiles() > maxNumberOfItems)
  14997. files.remove (getNumFiles() - 1);
  14998. }
  14999. int RecentlyOpenedFilesList::getNumFiles() const
  15000. {
  15001. return files.size();
  15002. }
  15003. const File RecentlyOpenedFilesList::getFile (const int index) const
  15004. {
  15005. return File (files [index]);
  15006. }
  15007. void RecentlyOpenedFilesList::clear()
  15008. {
  15009. files.clear();
  15010. }
  15011. void RecentlyOpenedFilesList::addFile (const File& file)
  15012. {
  15013. const String path (file.getFullPathName());
  15014. files.removeString (path, true);
  15015. files.insert (0, path);
  15016. setMaxNumberOfItems (maxNumberOfItems);
  15017. }
  15018. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15019. {
  15020. for (int i = getNumFiles(); --i >= 0;)
  15021. if (! getFile(i).exists())
  15022. files.remove (i);
  15023. }
  15024. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15025. const int baseItemId,
  15026. const bool showFullPaths,
  15027. const bool dontAddNonExistentFiles,
  15028. const File** filesToAvoid)
  15029. {
  15030. int num = 0;
  15031. for (int i = 0; i < getNumFiles(); ++i)
  15032. {
  15033. const File f (getFile(i));
  15034. if ((! dontAddNonExistentFiles) || f.exists())
  15035. {
  15036. bool needsAvoiding = false;
  15037. if (filesToAvoid != 0)
  15038. {
  15039. const File** avoid = filesToAvoid;
  15040. while (*avoid != 0)
  15041. {
  15042. if (f == **avoid)
  15043. {
  15044. needsAvoiding = true;
  15045. break;
  15046. }
  15047. ++avoid;
  15048. }
  15049. }
  15050. if (! needsAvoiding)
  15051. {
  15052. menuToAddTo.addItem (baseItemId + i,
  15053. showFullPaths ? f.getFullPathName()
  15054. : f.getFileName());
  15055. ++num;
  15056. }
  15057. }
  15058. }
  15059. return num;
  15060. }
  15061. const String RecentlyOpenedFilesList::toString() const
  15062. {
  15063. return files.joinIntoString ("\n");
  15064. }
  15065. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15066. {
  15067. clear();
  15068. files.addLines (stringifiedVersion);
  15069. setMaxNumberOfItems (maxNumberOfItems);
  15070. }
  15071. END_JUCE_NAMESPACE
  15072. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15073. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15074. BEGIN_JUCE_NAMESPACE
  15075. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15076. const int minimumTransactions)
  15077. : totalUnitsStored (0),
  15078. nextIndex (0),
  15079. newTransaction (true),
  15080. reentrancyCheck (false)
  15081. {
  15082. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15083. minimumTransactions);
  15084. }
  15085. UndoManager::~UndoManager()
  15086. {
  15087. clearUndoHistory();
  15088. }
  15089. void UndoManager::clearUndoHistory()
  15090. {
  15091. transactions.clear();
  15092. transactionNames.clear();
  15093. totalUnitsStored = 0;
  15094. nextIndex = 0;
  15095. sendChangeMessage (this);
  15096. }
  15097. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15098. {
  15099. return totalUnitsStored;
  15100. }
  15101. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15102. const int minimumTransactions)
  15103. {
  15104. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15105. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15106. }
  15107. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15108. {
  15109. if (command_ != 0)
  15110. {
  15111. ScopedPointer<UndoableAction> command (command_);
  15112. if (actionName.isNotEmpty())
  15113. currentTransactionName = actionName;
  15114. if (reentrancyCheck)
  15115. {
  15116. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15117. // undo() methods, or else these actions won't actually get done.
  15118. return false;
  15119. }
  15120. else if (command->perform())
  15121. {
  15122. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15123. if (commandSet != 0 && ! newTransaction)
  15124. {
  15125. UndoableAction* lastAction = commandSet->getLast();
  15126. if (lastAction != 0)
  15127. {
  15128. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15129. if (coalescedAction != 0)
  15130. {
  15131. command = coalescedAction;
  15132. totalUnitsStored -= lastAction->getSizeInUnits();
  15133. commandSet->removeLast();
  15134. }
  15135. }
  15136. }
  15137. else
  15138. {
  15139. commandSet = new OwnedArray<UndoableAction>();
  15140. transactions.insert (nextIndex, commandSet);
  15141. transactionNames.insert (nextIndex, currentTransactionName);
  15142. ++nextIndex;
  15143. }
  15144. totalUnitsStored += command->getSizeInUnits();
  15145. commandSet->add (command.release());
  15146. newTransaction = false;
  15147. while (nextIndex < transactions.size())
  15148. {
  15149. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15150. for (int i = lastSet->size(); --i >= 0;)
  15151. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15152. transactions.removeLast();
  15153. transactionNames.remove (transactionNames.size() - 1);
  15154. }
  15155. while (nextIndex > 0
  15156. && totalUnitsStored > maxNumUnitsToKeep
  15157. && transactions.size() > minimumTransactionsToKeep)
  15158. {
  15159. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15160. for (int i = firstSet->size(); --i >= 0;)
  15161. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15162. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15163. transactions.remove (0);
  15164. transactionNames.remove (0);
  15165. --nextIndex;
  15166. }
  15167. sendChangeMessage (this);
  15168. return true;
  15169. }
  15170. }
  15171. return false;
  15172. }
  15173. void UndoManager::beginNewTransaction (const String& actionName)
  15174. {
  15175. newTransaction = true;
  15176. currentTransactionName = actionName;
  15177. }
  15178. void UndoManager::setCurrentTransactionName (const String& newName)
  15179. {
  15180. currentTransactionName = newName;
  15181. }
  15182. bool UndoManager::canUndo() const
  15183. {
  15184. return nextIndex > 0;
  15185. }
  15186. bool UndoManager::canRedo() const
  15187. {
  15188. return nextIndex < transactions.size();
  15189. }
  15190. const String UndoManager::getUndoDescription() const
  15191. {
  15192. return transactionNames [nextIndex - 1];
  15193. }
  15194. const String UndoManager::getRedoDescription() const
  15195. {
  15196. return transactionNames [nextIndex];
  15197. }
  15198. bool UndoManager::undo()
  15199. {
  15200. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15201. if (commandSet == 0)
  15202. return false;
  15203. reentrancyCheck = true;
  15204. bool failed = false;
  15205. for (int i = commandSet->size(); --i >= 0;)
  15206. {
  15207. if (! commandSet->getUnchecked(i)->undo())
  15208. {
  15209. jassertfalse;
  15210. failed = true;
  15211. break;
  15212. }
  15213. }
  15214. reentrancyCheck = false;
  15215. if (failed)
  15216. clearUndoHistory();
  15217. else
  15218. --nextIndex;
  15219. beginNewTransaction();
  15220. sendChangeMessage (this);
  15221. return true;
  15222. }
  15223. bool UndoManager::redo()
  15224. {
  15225. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15226. if (commandSet == 0)
  15227. return false;
  15228. reentrancyCheck = true;
  15229. bool failed = false;
  15230. for (int i = 0; i < commandSet->size(); ++i)
  15231. {
  15232. if (! commandSet->getUnchecked(i)->perform())
  15233. {
  15234. jassertfalse;
  15235. failed = true;
  15236. break;
  15237. }
  15238. }
  15239. reentrancyCheck = false;
  15240. if (failed)
  15241. clearUndoHistory();
  15242. else
  15243. ++nextIndex;
  15244. beginNewTransaction();
  15245. sendChangeMessage (this);
  15246. return true;
  15247. }
  15248. bool UndoManager::undoCurrentTransactionOnly()
  15249. {
  15250. return newTransaction ? false : undo();
  15251. }
  15252. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15253. {
  15254. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15255. if (commandSet != 0 && ! newTransaction)
  15256. {
  15257. for (int i = 0; i < commandSet->size(); ++i)
  15258. actionsFound.add (commandSet->getUnchecked(i));
  15259. }
  15260. }
  15261. int UndoManager::getNumActionsInCurrentTransaction() const
  15262. {
  15263. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15264. if (commandSet != 0 && ! newTransaction)
  15265. return commandSet->size();
  15266. return 0;
  15267. }
  15268. END_JUCE_NAMESPACE
  15269. /*** End of inlined file: juce_UndoManager.cpp ***/
  15270. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15271. BEGIN_JUCE_NAMESPACE
  15272. static const char* const aiffFormatName = "AIFF file";
  15273. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15274. class AiffAudioFormatReader : public AudioFormatReader
  15275. {
  15276. public:
  15277. int bytesPerFrame;
  15278. int64 dataChunkStart;
  15279. bool littleEndian;
  15280. AiffAudioFormatReader (InputStream* in)
  15281. : AudioFormatReader (in, TRANS (aiffFormatName))
  15282. {
  15283. if (input->readInt() == chunkName ("FORM"))
  15284. {
  15285. const int len = input->readIntBigEndian();
  15286. const int64 end = input->getPosition() + len;
  15287. const int nextType = input->readInt();
  15288. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15289. {
  15290. bool hasGotVer = false;
  15291. bool hasGotData = false;
  15292. bool hasGotType = false;
  15293. while (input->getPosition() < end)
  15294. {
  15295. const int type = input->readInt();
  15296. const uint32 length = (uint32) input->readIntBigEndian();
  15297. const int64 chunkEnd = input->getPosition() + length;
  15298. if (type == chunkName ("FVER"))
  15299. {
  15300. hasGotVer = true;
  15301. const int ver = input->readIntBigEndian();
  15302. if (ver != 0 && ver != (int)0xa2805140)
  15303. break;
  15304. }
  15305. else if (type == chunkName ("COMM"))
  15306. {
  15307. hasGotType = true;
  15308. numChannels = (unsigned int)input->readShortBigEndian();
  15309. lengthInSamples = input->readIntBigEndian();
  15310. bitsPerSample = input->readShortBigEndian();
  15311. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15312. unsigned char sampleRateBytes[10];
  15313. input->read (sampleRateBytes, 10);
  15314. const int byte0 = sampleRateBytes[0];
  15315. if ((byte0 & 0x80) != 0
  15316. || byte0 <= 0x3F || byte0 > 0x40
  15317. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15318. break;
  15319. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15320. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15321. sampleRate = (int) sampRate;
  15322. if (length <= 18)
  15323. {
  15324. // some types don't have a chunk large enough to include a compression
  15325. // type, so assume it's just big-endian pcm
  15326. littleEndian = false;
  15327. }
  15328. else
  15329. {
  15330. const int compType = input->readInt();
  15331. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15332. {
  15333. littleEndian = false;
  15334. }
  15335. else if (compType == chunkName ("sowt"))
  15336. {
  15337. littleEndian = true;
  15338. }
  15339. else
  15340. {
  15341. sampleRate = 0;
  15342. break;
  15343. }
  15344. }
  15345. }
  15346. else if (type == chunkName ("SSND"))
  15347. {
  15348. hasGotData = true;
  15349. const int offset = input->readIntBigEndian();
  15350. dataChunkStart = input->getPosition() + 4 + offset;
  15351. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15352. }
  15353. else if ((hasGotVer && hasGotData && hasGotType)
  15354. || chunkEnd < input->getPosition()
  15355. || input->isExhausted())
  15356. {
  15357. break;
  15358. }
  15359. input->setPosition (chunkEnd);
  15360. }
  15361. }
  15362. }
  15363. }
  15364. ~AiffAudioFormatReader()
  15365. {
  15366. }
  15367. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15368. int64 startSampleInFile, int numSamples)
  15369. {
  15370. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15371. if (samplesAvailable < numSamples)
  15372. {
  15373. for (int i = numDestChannels; --i >= 0;)
  15374. if (destSamples[i] != 0)
  15375. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15376. numSamples = (int) samplesAvailable;
  15377. }
  15378. if (numSamples <= 0)
  15379. return true;
  15380. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15381. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15382. char tempBuffer [tempBufSize];
  15383. while (numSamples > 0)
  15384. {
  15385. int* left = destSamples[0];
  15386. if (left != 0)
  15387. left += startOffsetInDestBuffer;
  15388. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15389. if (right != 0)
  15390. right += startOffsetInDestBuffer;
  15391. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15392. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15393. if (bytesRead < numThisTime * bytesPerFrame)
  15394. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15395. if (bitsPerSample == 16)
  15396. {
  15397. if (littleEndian)
  15398. {
  15399. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15400. if (numChannels > 1)
  15401. {
  15402. if (left == 0)
  15403. {
  15404. for (int i = numThisTime; --i >= 0;)
  15405. {
  15406. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15407. ++src;
  15408. }
  15409. }
  15410. else if (right == 0)
  15411. {
  15412. for (int i = numThisTime; --i >= 0;)
  15413. {
  15414. ++src;
  15415. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15416. }
  15417. }
  15418. else
  15419. {
  15420. for (int i = numThisTime; --i >= 0;)
  15421. {
  15422. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15423. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15424. }
  15425. }
  15426. }
  15427. else
  15428. {
  15429. for (int i = numThisTime; --i >= 0;)
  15430. {
  15431. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15432. }
  15433. }
  15434. }
  15435. else
  15436. {
  15437. const char* src = tempBuffer;
  15438. if (numChannels > 1)
  15439. {
  15440. if (left == 0)
  15441. {
  15442. for (int i = numThisTime; --i >= 0;)
  15443. {
  15444. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15445. src += 4;
  15446. }
  15447. }
  15448. else if (right == 0)
  15449. {
  15450. for (int i = numThisTime; --i >= 0;)
  15451. {
  15452. src += 2;
  15453. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15454. src += 2;
  15455. }
  15456. }
  15457. else
  15458. {
  15459. for (int i = numThisTime; --i >= 0;)
  15460. {
  15461. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15462. src += 2;
  15463. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15464. src += 2;
  15465. }
  15466. }
  15467. }
  15468. else
  15469. {
  15470. for (int i = numThisTime; --i >= 0;)
  15471. {
  15472. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15473. src += 2;
  15474. }
  15475. }
  15476. }
  15477. }
  15478. else if (bitsPerSample == 24)
  15479. {
  15480. const char* src = (const char*)tempBuffer;
  15481. if (littleEndian)
  15482. {
  15483. if (numChannels > 1)
  15484. {
  15485. if (left == 0)
  15486. {
  15487. for (int i = numThisTime; --i >= 0;)
  15488. {
  15489. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15490. src += 6;
  15491. }
  15492. }
  15493. else if (right == 0)
  15494. {
  15495. for (int i = numThisTime; --i >= 0;)
  15496. {
  15497. src += 3;
  15498. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15499. src += 3;
  15500. }
  15501. }
  15502. else
  15503. {
  15504. for (int i = numThisTime; --i >= 0;)
  15505. {
  15506. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15507. src += 3;
  15508. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15509. src += 3;
  15510. }
  15511. }
  15512. }
  15513. else
  15514. {
  15515. for (int i = numThisTime; --i >= 0;)
  15516. {
  15517. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15518. src += 3;
  15519. }
  15520. }
  15521. }
  15522. else
  15523. {
  15524. if (numChannels > 1)
  15525. {
  15526. if (left == 0)
  15527. {
  15528. for (int i = numThisTime; --i >= 0;)
  15529. {
  15530. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15531. src += 6;
  15532. }
  15533. }
  15534. else if (right == 0)
  15535. {
  15536. for (int i = numThisTime; --i >= 0;)
  15537. {
  15538. src += 3;
  15539. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15540. src += 3;
  15541. }
  15542. }
  15543. else
  15544. {
  15545. for (int i = numThisTime; --i >= 0;)
  15546. {
  15547. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15548. src += 3;
  15549. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15550. src += 3;
  15551. }
  15552. }
  15553. }
  15554. else
  15555. {
  15556. for (int i = numThisTime; --i >= 0;)
  15557. {
  15558. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15559. src += 3;
  15560. }
  15561. }
  15562. }
  15563. }
  15564. else if (bitsPerSample == 32)
  15565. {
  15566. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15567. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15568. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15569. if (littleEndian)
  15570. {
  15571. if (numChannels > 1)
  15572. {
  15573. if (l == 0)
  15574. {
  15575. for (int i = numThisTime; --i >= 0;)
  15576. {
  15577. ++src;
  15578. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15579. }
  15580. }
  15581. else if (r == 0)
  15582. {
  15583. for (int i = numThisTime; --i >= 0;)
  15584. {
  15585. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15586. ++src;
  15587. }
  15588. }
  15589. else
  15590. {
  15591. for (int i = numThisTime; --i >= 0;)
  15592. {
  15593. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15594. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15595. }
  15596. }
  15597. }
  15598. else
  15599. {
  15600. for (int i = numThisTime; --i >= 0;)
  15601. {
  15602. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15603. }
  15604. }
  15605. }
  15606. else
  15607. {
  15608. if (numChannels > 1)
  15609. {
  15610. if (l == 0)
  15611. {
  15612. for (int i = numThisTime; --i >= 0;)
  15613. {
  15614. ++src;
  15615. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15616. }
  15617. }
  15618. else if (r == 0)
  15619. {
  15620. for (int i = numThisTime; --i >= 0;)
  15621. {
  15622. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15623. ++src;
  15624. }
  15625. }
  15626. else
  15627. {
  15628. for (int i = numThisTime; --i >= 0;)
  15629. {
  15630. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15631. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15632. }
  15633. }
  15634. }
  15635. else
  15636. {
  15637. for (int i = numThisTime; --i >= 0;)
  15638. {
  15639. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15640. }
  15641. }
  15642. }
  15643. left = reinterpret_cast <int*> (l);
  15644. right = reinterpret_cast <int*> (r);
  15645. }
  15646. else if (bitsPerSample == 8)
  15647. {
  15648. const char* src = tempBuffer;
  15649. if (numChannels > 1)
  15650. {
  15651. if (left == 0)
  15652. {
  15653. for (int i = numThisTime; --i >= 0;)
  15654. {
  15655. *right++ = ((int) *src++) << 24;
  15656. ++src;
  15657. }
  15658. }
  15659. else if (right == 0)
  15660. {
  15661. for (int i = numThisTime; --i >= 0;)
  15662. {
  15663. ++src;
  15664. *left++ = ((int) *src++) << 24;
  15665. }
  15666. }
  15667. else
  15668. {
  15669. for (int i = numThisTime; --i >= 0;)
  15670. {
  15671. *left++ = ((int) *src++) << 24;
  15672. *right++ = ((int) *src++) << 24;
  15673. }
  15674. }
  15675. }
  15676. else
  15677. {
  15678. for (int i = numThisTime; --i >= 0;)
  15679. {
  15680. *left++ = ((int) *src++) << 24;
  15681. }
  15682. }
  15683. }
  15684. startOffsetInDestBuffer += numThisTime;
  15685. numSamples -= numThisTime;
  15686. }
  15687. if (numSamples > 0)
  15688. {
  15689. for (int i = numDestChannels; --i >= 0;)
  15690. if (destSamples[i] != 0)
  15691. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15692. sizeof (int) * numSamples);
  15693. }
  15694. return true;
  15695. }
  15696. juce_UseDebuggingNewOperator
  15697. private:
  15698. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15699. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15700. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15701. };
  15702. class AiffAudioFormatWriter : public AudioFormatWriter
  15703. {
  15704. MemoryBlock tempBlock;
  15705. uint32 lengthInSamples, bytesWritten;
  15706. int64 headerPosition;
  15707. bool writeFailed;
  15708. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15709. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15710. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15711. void writeHeader()
  15712. {
  15713. const bool couldSeekOk = output->setPosition (headerPosition);
  15714. (void) couldSeekOk;
  15715. // if this fails, you've given it an output stream that can't seek! It needs
  15716. // to be able to seek back to write the header
  15717. jassert (couldSeekOk);
  15718. const int headerLen = 54;
  15719. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15720. audioBytes += (audioBytes & 1);
  15721. output->writeInt (chunkName ("FORM"));
  15722. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15723. output->writeInt (chunkName ("AIFF"));
  15724. output->writeInt (chunkName ("COMM"));
  15725. output->writeIntBigEndian (18);
  15726. output->writeShortBigEndian ((short) numChannels);
  15727. output->writeIntBigEndian (lengthInSamples);
  15728. output->writeShortBigEndian ((short) bitsPerSample);
  15729. uint8 sampleRateBytes[10];
  15730. zeromem (sampleRateBytes, 10);
  15731. if (sampleRate <= 1)
  15732. {
  15733. sampleRateBytes[0] = 0x3f;
  15734. sampleRateBytes[1] = 0xff;
  15735. sampleRateBytes[2] = 0x80;
  15736. }
  15737. else
  15738. {
  15739. int mask = 0x40000000;
  15740. sampleRateBytes[0] = 0x40;
  15741. if (sampleRate >= mask)
  15742. {
  15743. jassertfalse;
  15744. sampleRateBytes[1] = 0x1d;
  15745. }
  15746. else
  15747. {
  15748. int n = (int) sampleRate;
  15749. int i;
  15750. for (i = 0; i <= 32 ; ++i)
  15751. {
  15752. if ((n & mask) != 0)
  15753. break;
  15754. mask >>= 1;
  15755. }
  15756. n = n << (i + 1);
  15757. sampleRateBytes[1] = (uint8) (29 - i);
  15758. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15759. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15760. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15761. sampleRateBytes[5] = (uint8) (n & 0xff);
  15762. }
  15763. }
  15764. output->write (sampleRateBytes, 10);
  15765. output->writeInt (chunkName ("SSND"));
  15766. output->writeIntBigEndian (audioBytes + 8);
  15767. output->writeInt (0);
  15768. output->writeInt (0);
  15769. jassert (output->getPosition() == headerLen);
  15770. }
  15771. public:
  15772. AiffAudioFormatWriter (OutputStream* out,
  15773. const double sampleRate_,
  15774. const unsigned int chans,
  15775. const int bits)
  15776. : AudioFormatWriter (out,
  15777. TRANS (aiffFormatName),
  15778. sampleRate_,
  15779. chans,
  15780. bits),
  15781. lengthInSamples (0),
  15782. bytesWritten (0),
  15783. writeFailed (false)
  15784. {
  15785. headerPosition = out->getPosition();
  15786. writeHeader();
  15787. }
  15788. ~AiffAudioFormatWriter()
  15789. {
  15790. if ((bytesWritten & 1) != 0)
  15791. output->writeByte (0);
  15792. writeHeader();
  15793. }
  15794. bool write (const int** data, int numSamples)
  15795. {
  15796. if (writeFailed)
  15797. return false;
  15798. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15799. tempBlock.ensureSize (bytes, false);
  15800. char* buffer = static_cast <char*> (tempBlock.getData());
  15801. const int* left = data[0];
  15802. const int* right = data[1];
  15803. if (right == 0)
  15804. right = left;
  15805. if (bitsPerSample == 16)
  15806. {
  15807. short* b = reinterpret_cast <short*> (buffer);
  15808. if (numChannels > 1)
  15809. {
  15810. for (int i = numSamples; --i >= 0;)
  15811. {
  15812. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15813. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15814. }
  15815. }
  15816. else
  15817. {
  15818. for (int i = numSamples; --i >= 0;)
  15819. {
  15820. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15821. }
  15822. }
  15823. }
  15824. else if (bitsPerSample == 24)
  15825. {
  15826. char* b = buffer;
  15827. if (numChannels > 1)
  15828. {
  15829. for (int i = numSamples; --i >= 0;)
  15830. {
  15831. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15832. b += 3;
  15833. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15834. b += 3;
  15835. }
  15836. }
  15837. else
  15838. {
  15839. for (int i = numSamples; --i >= 0;)
  15840. {
  15841. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15842. b += 3;
  15843. }
  15844. }
  15845. }
  15846. else if (bitsPerSample == 32)
  15847. {
  15848. uint32* b = reinterpret_cast <uint32*> (buffer);
  15849. if (numChannels > 1)
  15850. {
  15851. for (int i = numSamples; --i >= 0;)
  15852. {
  15853. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15854. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15855. }
  15856. }
  15857. else
  15858. {
  15859. for (int i = numSamples; --i >= 0;)
  15860. {
  15861. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15862. }
  15863. }
  15864. }
  15865. else if (bitsPerSample == 8)
  15866. {
  15867. char* b = buffer;
  15868. if (numChannels > 1)
  15869. {
  15870. for (int i = numSamples; --i >= 0;)
  15871. {
  15872. *b++ = (char) (*left++ >> 24);
  15873. *b++ = (char) (*right++ >> 24);
  15874. }
  15875. }
  15876. else
  15877. {
  15878. for (int i = numSamples; --i >= 0;)
  15879. {
  15880. *b++ = (char) (*left++ >> 24);
  15881. }
  15882. }
  15883. }
  15884. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15885. || ! output->write (buffer, bytes))
  15886. {
  15887. // failed to write to disk, so let's try writing the header.
  15888. // If it's just run out of disk space, then if it does manage
  15889. // to write the header, we'll still have a useable file..
  15890. writeHeader();
  15891. writeFailed = true;
  15892. return false;
  15893. }
  15894. else
  15895. {
  15896. bytesWritten += bytes;
  15897. lengthInSamples += numSamples;
  15898. return true;
  15899. }
  15900. }
  15901. juce_UseDebuggingNewOperator
  15902. };
  15903. AiffAudioFormat::AiffAudioFormat()
  15904. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15905. {
  15906. }
  15907. AiffAudioFormat::~AiffAudioFormat()
  15908. {
  15909. }
  15910. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15911. {
  15912. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15913. return Array <int> (rates);
  15914. }
  15915. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15916. {
  15917. const int depths[] = { 8, 16, 24, 0 };
  15918. return Array <int> (depths);
  15919. }
  15920. bool AiffAudioFormat::canDoStereo()
  15921. {
  15922. return true;
  15923. }
  15924. bool AiffAudioFormat::canDoMono()
  15925. {
  15926. return true;
  15927. }
  15928. #if JUCE_MAC
  15929. bool AiffAudioFormat::canHandleFile (const File& f)
  15930. {
  15931. if (AudioFormat::canHandleFile (f))
  15932. return true;
  15933. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15934. return type == 'AIFF' || type == 'AIFC'
  15935. || type == 'aiff' || type == 'aifc';
  15936. }
  15937. #endif
  15938. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15939. const bool deleteStreamIfOpeningFails)
  15940. {
  15941. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15942. if (w->sampleRate != 0)
  15943. return w.release();
  15944. if (! deleteStreamIfOpeningFails)
  15945. w->input = 0;
  15946. return 0;
  15947. }
  15948. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15949. double sampleRate,
  15950. unsigned int chans,
  15951. int bitsPerSample,
  15952. const StringPairArray& /*metadataValues*/,
  15953. int /*qualityOptionIndex*/)
  15954. {
  15955. if (getPossibleBitDepths().contains (bitsPerSample))
  15956. {
  15957. return new AiffAudioFormatWriter (out,
  15958. sampleRate,
  15959. chans,
  15960. bitsPerSample);
  15961. }
  15962. return 0;
  15963. }
  15964. END_JUCE_NAMESPACE
  15965. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15966. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15967. BEGIN_JUCE_NAMESPACE
  15968. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15969. const String& formatName_)
  15970. : sampleRate (0),
  15971. bitsPerSample (0),
  15972. lengthInSamples (0),
  15973. numChannels (0),
  15974. usesFloatingPointData (false),
  15975. input (in),
  15976. formatName (formatName_)
  15977. {
  15978. }
  15979. AudioFormatReader::~AudioFormatReader()
  15980. {
  15981. delete input;
  15982. }
  15983. bool AudioFormatReader::read (int** destSamples,
  15984. int numDestChannels,
  15985. int64 startSampleInSource,
  15986. int numSamplesToRead,
  15987. const bool fillLeftoverChannelsWithCopies)
  15988. {
  15989. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15990. int startOffsetInDestBuffer = 0;
  15991. if (startSampleInSource < 0)
  15992. {
  15993. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15994. for (int i = numDestChannels; --i >= 0;)
  15995. if (destSamples[i] != 0)
  15996. zeromem (destSamples[i], sizeof (int) * silence);
  15997. startOffsetInDestBuffer += silence;
  15998. numSamplesToRead -= silence;
  15999. startSampleInSource = 0;
  16000. }
  16001. if (numSamplesToRead <= 0)
  16002. return true;
  16003. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16004. startSampleInSource, numSamplesToRead))
  16005. return false;
  16006. if (numDestChannels > (int) numChannels)
  16007. {
  16008. if (fillLeftoverChannelsWithCopies)
  16009. {
  16010. int* lastFullChannel = destSamples[0];
  16011. for (int i = (int) numChannels; --i > 0;)
  16012. {
  16013. if (destSamples[i] != 0)
  16014. {
  16015. lastFullChannel = destSamples[i];
  16016. break;
  16017. }
  16018. }
  16019. if (lastFullChannel != 0)
  16020. for (int i = numChannels; i < numDestChannels; ++i)
  16021. if (destSamples[i] != 0)
  16022. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16023. }
  16024. else
  16025. {
  16026. for (int i = numChannels; i < numDestChannels; ++i)
  16027. if (destSamples[i] != 0)
  16028. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16029. }
  16030. }
  16031. return true;
  16032. }
  16033. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16034. {
  16035. float mn = buffer[0];
  16036. float mx = mn;
  16037. for (int i = 1; i < num; ++i)
  16038. {
  16039. const float s = buffer[i];
  16040. if (s > mx) mx = s;
  16041. if (s < mn) mn = s;
  16042. }
  16043. maxVal = mx;
  16044. minVal = mn;
  16045. }
  16046. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16047. int64 numSamples,
  16048. float& lowestLeft, float& highestLeft,
  16049. float& lowestRight, float& highestRight)
  16050. {
  16051. if (numSamples <= 0)
  16052. {
  16053. lowestLeft = 0;
  16054. lowestRight = 0;
  16055. highestLeft = 0;
  16056. highestRight = 0;
  16057. return;
  16058. }
  16059. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16060. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16061. int* tempBuffer[3];
  16062. tempBuffer[0] = (int*) tempSpace.getData();
  16063. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16064. tempBuffer[2] = 0;
  16065. if (usesFloatingPointData)
  16066. {
  16067. float lmin = 1.0e6f;
  16068. float lmax = -lmin;
  16069. float rmin = lmin;
  16070. float rmax = lmax;
  16071. while (numSamples > 0)
  16072. {
  16073. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16074. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16075. numSamples -= numToDo;
  16076. startSampleInFile += numToDo;
  16077. float bufmin, bufmax;
  16078. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16079. lmin = jmin (lmin, bufmin);
  16080. lmax = jmax (lmax, bufmax);
  16081. if (numChannels > 1)
  16082. {
  16083. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16084. rmin = jmin (rmin, bufmin);
  16085. rmax = jmax (rmax, bufmax);
  16086. }
  16087. }
  16088. if (numChannels <= 1)
  16089. {
  16090. rmax = lmax;
  16091. rmin = lmin;
  16092. }
  16093. lowestLeft = lmin;
  16094. highestLeft = lmax;
  16095. lowestRight = rmin;
  16096. highestRight = rmax;
  16097. }
  16098. else
  16099. {
  16100. int lmax = std::numeric_limits<int>::min();
  16101. int lmin = std::numeric_limits<int>::max();
  16102. int rmax = std::numeric_limits<int>::min();
  16103. int rmin = std::numeric_limits<int>::max();
  16104. while (numSamples > 0)
  16105. {
  16106. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16107. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16108. numSamples -= numToDo;
  16109. startSampleInFile += numToDo;
  16110. for (int j = numChannels; --j >= 0;)
  16111. {
  16112. int bufMax = std::numeric_limits<int>::min();
  16113. int bufMin = std::numeric_limits<int>::max();
  16114. const int* const b = tempBuffer[j];
  16115. for (int i = 0; i < numToDo; ++i)
  16116. {
  16117. const int samp = b[i];
  16118. if (samp < bufMin)
  16119. bufMin = samp;
  16120. if (samp > bufMax)
  16121. bufMax = samp;
  16122. }
  16123. if (j == 0)
  16124. {
  16125. lmax = jmax (lmax, bufMax);
  16126. lmin = jmin (lmin, bufMin);
  16127. }
  16128. else
  16129. {
  16130. rmax = jmax (rmax, bufMax);
  16131. rmin = jmin (rmin, bufMin);
  16132. }
  16133. }
  16134. }
  16135. if (numChannels <= 1)
  16136. {
  16137. rmax = lmax;
  16138. rmin = lmin;
  16139. }
  16140. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16141. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16142. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16143. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16144. }
  16145. }
  16146. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16147. int64 numSamplesToSearch,
  16148. const double magnitudeRangeMinimum,
  16149. const double magnitudeRangeMaximum,
  16150. const int minimumConsecutiveSamples)
  16151. {
  16152. if (numSamplesToSearch == 0)
  16153. return -1;
  16154. const int bufferSize = 4096;
  16155. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16156. int* tempBuffer[3];
  16157. tempBuffer[0] = (int*) tempSpace.getData();
  16158. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16159. tempBuffer[2] = 0;
  16160. int consecutive = 0;
  16161. int64 firstMatchPos = -1;
  16162. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16163. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16164. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16165. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16166. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16167. while (numSamplesToSearch != 0)
  16168. {
  16169. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16170. int64 bufferStart = startSample;
  16171. if (numSamplesToSearch < 0)
  16172. bufferStart -= numThisTime;
  16173. if (bufferStart >= (int) lengthInSamples)
  16174. break;
  16175. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16176. int num = numThisTime;
  16177. while (--num >= 0)
  16178. {
  16179. if (numSamplesToSearch < 0)
  16180. --startSample;
  16181. bool matches = false;
  16182. const int index = (int) (startSample - bufferStart);
  16183. if (usesFloatingPointData)
  16184. {
  16185. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16186. if (sample1 >= magnitudeRangeMinimum
  16187. && sample1 <= magnitudeRangeMaximum)
  16188. {
  16189. matches = true;
  16190. }
  16191. else if (numChannels > 1)
  16192. {
  16193. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16194. matches = (sample2 >= magnitudeRangeMinimum
  16195. && sample2 <= magnitudeRangeMaximum);
  16196. }
  16197. }
  16198. else
  16199. {
  16200. const int sample1 = abs (tempBuffer[0] [index]);
  16201. if (sample1 >= intMagnitudeRangeMinimum
  16202. && sample1 <= intMagnitudeRangeMaximum)
  16203. {
  16204. matches = true;
  16205. }
  16206. else if (numChannels > 1)
  16207. {
  16208. const int sample2 = abs (tempBuffer[1][index]);
  16209. matches = (sample2 >= intMagnitudeRangeMinimum
  16210. && sample2 <= intMagnitudeRangeMaximum);
  16211. }
  16212. }
  16213. if (matches)
  16214. {
  16215. if (firstMatchPos < 0)
  16216. firstMatchPos = startSample;
  16217. if (++consecutive >= minimumConsecutiveSamples)
  16218. {
  16219. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16220. return -1;
  16221. return firstMatchPos;
  16222. }
  16223. }
  16224. else
  16225. {
  16226. consecutive = 0;
  16227. firstMatchPos = -1;
  16228. }
  16229. if (numSamplesToSearch > 0)
  16230. ++startSample;
  16231. }
  16232. if (numSamplesToSearch > 0)
  16233. numSamplesToSearch -= numThisTime;
  16234. else
  16235. numSamplesToSearch += numThisTime;
  16236. }
  16237. return -1;
  16238. }
  16239. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16240. const String& formatName_,
  16241. const double rate,
  16242. const unsigned int numChannels_,
  16243. const unsigned int bitsPerSample_)
  16244. : sampleRate (rate),
  16245. numChannels (numChannels_),
  16246. bitsPerSample (bitsPerSample_),
  16247. usesFloatingPointData (false),
  16248. output (out),
  16249. formatName (formatName_)
  16250. {
  16251. }
  16252. AudioFormatWriter::~AudioFormatWriter()
  16253. {
  16254. delete output;
  16255. }
  16256. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16257. int64 startSample,
  16258. int64 numSamplesToRead)
  16259. {
  16260. const int bufferSize = 16384;
  16261. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16262. int* buffers [128];
  16263. zerostruct (buffers);
  16264. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16265. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16266. if (numSamplesToRead < 0)
  16267. numSamplesToRead = reader.lengthInSamples;
  16268. while (numSamplesToRead > 0)
  16269. {
  16270. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16271. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16272. return false;
  16273. if (reader.usesFloatingPointData != isFloatingPoint())
  16274. {
  16275. int** bufferChan = buffers;
  16276. while (*bufferChan != 0)
  16277. {
  16278. int* b = *bufferChan++;
  16279. if (isFloatingPoint())
  16280. {
  16281. // int -> float
  16282. const double factor = 1.0 / std::numeric_limits<int>::max();
  16283. for (int i = 0; i < numToDo; ++i)
  16284. ((float*) b)[i] = (float) (factor * b[i]);
  16285. }
  16286. else
  16287. {
  16288. // float -> int
  16289. for (int i = 0; i < numToDo; ++i)
  16290. {
  16291. const double samp = *(const float*) b;
  16292. if (samp <= -1.0)
  16293. *b++ = std::numeric_limits<int>::min();
  16294. else if (samp >= 1.0)
  16295. *b++ = std::numeric_limits<int>::max();
  16296. else
  16297. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16298. }
  16299. }
  16300. }
  16301. }
  16302. if (! write ((const int**) buffers, numToDo))
  16303. return false;
  16304. numSamplesToRead -= numToDo;
  16305. startSample += numToDo;
  16306. }
  16307. return true;
  16308. }
  16309. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16310. int numSamplesToRead,
  16311. const int samplesPerBlock)
  16312. {
  16313. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16314. int* buffers [128];
  16315. zerostruct (buffers);
  16316. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16317. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16318. while (numSamplesToRead > 0)
  16319. {
  16320. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16321. AudioSourceChannelInfo info;
  16322. info.buffer = &tempBuffer;
  16323. info.startSample = 0;
  16324. info.numSamples = numToDo;
  16325. info.clearActiveBufferRegion();
  16326. source.getNextAudioBlock (info);
  16327. if (! isFloatingPoint())
  16328. {
  16329. int** bufferChan = buffers;
  16330. while (*bufferChan != 0)
  16331. {
  16332. int* b = *bufferChan++;
  16333. // float -> int
  16334. for (int j = numToDo; --j >= 0;)
  16335. {
  16336. const double samp = *(const float*) b;
  16337. if (samp <= -1.0)
  16338. *b++ = std::numeric_limits<int>::min();
  16339. else if (samp >= 1.0)
  16340. *b++ = std::numeric_limits<int>::max();
  16341. else
  16342. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16343. }
  16344. }
  16345. }
  16346. if (! write ((const int**) buffers, numToDo))
  16347. return false;
  16348. numSamplesToRead -= numToDo;
  16349. }
  16350. return true;
  16351. }
  16352. AudioFormat::AudioFormat (const String& name,
  16353. const StringArray& extensions)
  16354. : formatName (name),
  16355. fileExtensions (extensions)
  16356. {
  16357. }
  16358. AudioFormat::~AudioFormat()
  16359. {
  16360. }
  16361. const String& AudioFormat::getFormatName() const
  16362. {
  16363. return formatName;
  16364. }
  16365. const StringArray& AudioFormat::getFileExtensions() const
  16366. {
  16367. return fileExtensions;
  16368. }
  16369. bool AudioFormat::canHandleFile (const File& f)
  16370. {
  16371. for (int i = 0; i < fileExtensions.size(); ++i)
  16372. if (f.hasFileExtension (fileExtensions[i]))
  16373. return true;
  16374. return false;
  16375. }
  16376. bool AudioFormat::isCompressed()
  16377. {
  16378. return false;
  16379. }
  16380. const StringArray AudioFormat::getQualityOptions()
  16381. {
  16382. return StringArray();
  16383. }
  16384. END_JUCE_NAMESPACE
  16385. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16386. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16387. BEGIN_JUCE_NAMESPACE
  16388. AudioFormatManager::AudioFormatManager()
  16389. : defaultFormatIndex (0)
  16390. {
  16391. }
  16392. AudioFormatManager::~AudioFormatManager()
  16393. {
  16394. clearFormats();
  16395. clearSingletonInstance();
  16396. }
  16397. juce_ImplementSingleton (AudioFormatManager);
  16398. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16399. const bool makeThisTheDefaultFormat)
  16400. {
  16401. jassert (newFormat != 0);
  16402. if (newFormat != 0)
  16403. {
  16404. #if JUCE_DEBUG
  16405. for (int i = getNumKnownFormats(); --i >= 0;)
  16406. {
  16407. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16408. {
  16409. jassertfalse; // trying to add the same format twice!
  16410. }
  16411. }
  16412. #endif
  16413. if (makeThisTheDefaultFormat)
  16414. defaultFormatIndex = getNumKnownFormats();
  16415. knownFormats.add (newFormat);
  16416. }
  16417. }
  16418. void AudioFormatManager::registerBasicFormats()
  16419. {
  16420. #if JUCE_MAC
  16421. registerFormat (new AiffAudioFormat(), true);
  16422. registerFormat (new WavAudioFormat(), false);
  16423. #else
  16424. registerFormat (new WavAudioFormat(), true);
  16425. registerFormat (new AiffAudioFormat(), false);
  16426. #endif
  16427. #if JUCE_USE_FLAC
  16428. registerFormat (new FlacAudioFormat(), false);
  16429. #endif
  16430. #if JUCE_USE_OGGVORBIS
  16431. registerFormat (new OggVorbisAudioFormat(), false);
  16432. #endif
  16433. }
  16434. void AudioFormatManager::clearFormats()
  16435. {
  16436. knownFormats.clear();
  16437. defaultFormatIndex = 0;
  16438. }
  16439. int AudioFormatManager::getNumKnownFormats() const
  16440. {
  16441. return knownFormats.size();
  16442. }
  16443. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16444. {
  16445. return knownFormats [index];
  16446. }
  16447. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16448. {
  16449. return getKnownFormat (defaultFormatIndex);
  16450. }
  16451. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16452. {
  16453. String e (fileExtension);
  16454. if (! e.startsWithChar ('.'))
  16455. e = "." + e;
  16456. for (int i = 0; i < getNumKnownFormats(); ++i)
  16457. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16458. return getKnownFormat(i);
  16459. return 0;
  16460. }
  16461. const String AudioFormatManager::getWildcardForAllFormats() const
  16462. {
  16463. StringArray allExtensions;
  16464. int i;
  16465. for (i = 0; i < getNumKnownFormats(); ++i)
  16466. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16467. allExtensions.trim();
  16468. allExtensions.removeEmptyStrings();
  16469. String s;
  16470. for (i = 0; i < allExtensions.size(); ++i)
  16471. {
  16472. s << '*';
  16473. if (! allExtensions[i].startsWithChar ('.'))
  16474. s << '.';
  16475. s << allExtensions[i];
  16476. if (i < allExtensions.size() - 1)
  16477. s << ';';
  16478. }
  16479. return s;
  16480. }
  16481. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16482. {
  16483. // you need to actually register some formats before the manager can
  16484. // use them to open a file!
  16485. jassert (getNumKnownFormats() > 0);
  16486. for (int i = 0; i < getNumKnownFormats(); ++i)
  16487. {
  16488. AudioFormat* const af = getKnownFormat(i);
  16489. if (af->canHandleFile (file))
  16490. {
  16491. InputStream* const in = file.createInputStream();
  16492. if (in != 0)
  16493. {
  16494. AudioFormatReader* const r = af->createReaderFor (in, true);
  16495. if (r != 0)
  16496. return r;
  16497. }
  16498. }
  16499. }
  16500. return 0;
  16501. }
  16502. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16503. {
  16504. // you need to actually register some formats before the manager can
  16505. // use them to open a file!
  16506. jassert (getNumKnownFormats() > 0);
  16507. ScopedPointer <InputStream> in (audioFileStream);
  16508. if (in != 0)
  16509. {
  16510. const int64 originalStreamPos = in->getPosition();
  16511. for (int i = 0; i < getNumKnownFormats(); ++i)
  16512. {
  16513. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16514. if (r != 0)
  16515. {
  16516. in.release();
  16517. return r;
  16518. }
  16519. in->setPosition (originalStreamPos);
  16520. // the stream that is passed-in must be capable of being repositioned so
  16521. // that all the formats can have a go at opening it.
  16522. jassert (in->getPosition() == originalStreamPos);
  16523. }
  16524. }
  16525. return 0;
  16526. }
  16527. END_JUCE_NAMESPACE
  16528. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16529. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16530. BEGIN_JUCE_NAMESPACE
  16531. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16532. const int64 startSample_,
  16533. const int64 length_,
  16534. const bool deleteSourceWhenDeleted_)
  16535. : AudioFormatReader (0, source_->getFormatName()),
  16536. source (source_),
  16537. startSample (startSample_),
  16538. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16539. {
  16540. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16541. sampleRate = source->sampleRate;
  16542. bitsPerSample = source->bitsPerSample;
  16543. lengthInSamples = length;
  16544. numChannels = source->numChannels;
  16545. usesFloatingPointData = source->usesFloatingPointData;
  16546. }
  16547. AudioSubsectionReader::~AudioSubsectionReader()
  16548. {
  16549. if (deleteSourceWhenDeleted)
  16550. delete source;
  16551. }
  16552. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16553. int64 startSampleInFile, int numSamples)
  16554. {
  16555. if (startSampleInFile + numSamples > length)
  16556. {
  16557. for (int i = numDestChannels; --i >= 0;)
  16558. if (destSamples[i] != 0)
  16559. zeromem (destSamples[i], sizeof (int) * numSamples);
  16560. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16561. if (numSamples <= 0)
  16562. return true;
  16563. }
  16564. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16565. startSampleInFile + startSample, numSamples);
  16566. }
  16567. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16568. int64 numSamples,
  16569. float& lowestLeft,
  16570. float& highestLeft,
  16571. float& lowestRight,
  16572. float& highestRight)
  16573. {
  16574. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16575. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16576. source->readMaxLevels (startSampleInFile + startSample,
  16577. numSamples,
  16578. lowestLeft,
  16579. highestLeft,
  16580. lowestRight,
  16581. highestRight);
  16582. }
  16583. END_JUCE_NAMESPACE
  16584. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16585. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16586. BEGIN_JUCE_NAMESPACE
  16587. const int timeBeforeDeletingReader = 2000;
  16588. struct AudioThumbnailDataFormat
  16589. {
  16590. char thumbnailMagic[4];
  16591. int samplesPerThumbSample;
  16592. int64 totalSamples; // source samples
  16593. int64 numFinishedSamples; // source samples
  16594. int numThumbnailSamples;
  16595. int numChannels;
  16596. int sampleRate;
  16597. char future[16];
  16598. char data[1];
  16599. void swapEndiannessIfNeeded() throw()
  16600. {
  16601. #if JUCE_BIG_ENDIAN
  16602. flip (samplesPerThumbSample);
  16603. flip (totalSamples);
  16604. flip (numFinishedSamples);
  16605. flip (numThumbnailSamples);
  16606. flip (numChannels);
  16607. flip (sampleRate);
  16608. #endif
  16609. }
  16610. private:
  16611. #if JUCE_BIG_ENDIAN
  16612. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16613. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16614. #endif
  16615. };
  16616. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16617. AudioFormatManager& formatManagerToUse_,
  16618. AudioThumbnailCache& cacheToUse)
  16619. : formatManagerToUse (formatManagerToUse_),
  16620. cache (cacheToUse),
  16621. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16622. {
  16623. clear();
  16624. }
  16625. AudioThumbnail::~AudioThumbnail()
  16626. {
  16627. cache.removeThumbnail (this);
  16628. const ScopedLock sl (readerLock);
  16629. reader = 0;
  16630. }
  16631. void AudioThumbnail::setSource (InputSource* const newSource)
  16632. {
  16633. cache.removeThumbnail (this);
  16634. timerCallback(); // stops the timer and deletes the reader
  16635. source = newSource;
  16636. clear();
  16637. if (newSource != 0
  16638. && ! (cache.loadThumb (*this, newSource->hashCode())
  16639. && isFullyLoaded()))
  16640. {
  16641. {
  16642. const ScopedLock sl (readerLock);
  16643. reader = createReader();
  16644. }
  16645. if (reader != 0)
  16646. {
  16647. initialiseFromAudioFile (*reader);
  16648. cache.addThumbnail (this);
  16649. }
  16650. }
  16651. sendChangeMessage (this);
  16652. }
  16653. bool AudioThumbnail::useTimeSlice()
  16654. {
  16655. const ScopedLock sl (readerLock);
  16656. if (isFullyLoaded())
  16657. {
  16658. if (reader != 0)
  16659. startTimer (timeBeforeDeletingReader);
  16660. cache.removeThumbnail (this);
  16661. return false;
  16662. }
  16663. if (reader == 0)
  16664. reader = createReader();
  16665. if (reader != 0)
  16666. {
  16667. readNextBlockFromAudioFile (*reader);
  16668. stopTimer();
  16669. sendChangeMessage (this);
  16670. const bool justFinished = isFullyLoaded();
  16671. if (justFinished)
  16672. cache.storeThumb (*this, source->hashCode());
  16673. return ! justFinished;
  16674. }
  16675. return false;
  16676. }
  16677. AudioFormatReader* AudioThumbnail::createReader() const
  16678. {
  16679. if (source != 0)
  16680. {
  16681. InputStream* const audioFileStream = source->createInputStream();
  16682. if (audioFileStream != 0)
  16683. return formatManagerToUse.createReaderFor (audioFileStream);
  16684. }
  16685. return 0;
  16686. }
  16687. void AudioThumbnail::timerCallback()
  16688. {
  16689. stopTimer();
  16690. const ScopedLock sl (readerLock);
  16691. reader = 0;
  16692. }
  16693. void AudioThumbnail::clear()
  16694. {
  16695. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16696. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16697. d->thumbnailMagic[0] = 'j';
  16698. d->thumbnailMagic[1] = 'a';
  16699. d->thumbnailMagic[2] = 't';
  16700. d->thumbnailMagic[3] = 'm';
  16701. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16702. d->totalSamples = 0;
  16703. d->numFinishedSamples = 0;
  16704. d->numThumbnailSamples = 0;
  16705. d->numChannels = 0;
  16706. d->sampleRate = 0;
  16707. numSamplesCached = 0;
  16708. cacheNeedsRefilling = true;
  16709. }
  16710. void AudioThumbnail::loadFrom (InputStream& input)
  16711. {
  16712. const ScopedLock sl (readerLock);
  16713. data.setSize (0);
  16714. input.readIntoMemoryBlock (data);
  16715. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16716. d->swapEndiannessIfNeeded();
  16717. if (! (d->thumbnailMagic[0] == 'j'
  16718. && d->thumbnailMagic[1] == 'a'
  16719. && d->thumbnailMagic[2] == 't'
  16720. && d->thumbnailMagic[3] == 'm'))
  16721. {
  16722. clear();
  16723. }
  16724. numSamplesCached = 0;
  16725. cacheNeedsRefilling = true;
  16726. }
  16727. void AudioThumbnail::saveTo (OutputStream& output) const
  16728. {
  16729. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16730. d->swapEndiannessIfNeeded();
  16731. output.write (data.getData(), (int) data.getSize());
  16732. d->swapEndiannessIfNeeded();
  16733. }
  16734. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16735. {
  16736. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16737. d->totalSamples = fileReader.lengthInSamples;
  16738. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16739. d->numFinishedSamples = 0;
  16740. d->sampleRate = roundToInt (fileReader.sampleRate);
  16741. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16742. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16743. d = (AudioThumbnailDataFormat*) data.getData();
  16744. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16745. return d->totalSamples > 0;
  16746. }
  16747. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16748. {
  16749. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16750. if (d->numFinishedSamples < d->totalSamples)
  16751. {
  16752. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16753. generateSection (fileReader,
  16754. d->numFinishedSamples,
  16755. numToDo);
  16756. d->numFinishedSamples += numToDo;
  16757. }
  16758. cacheNeedsRefilling = true;
  16759. return (d->numFinishedSamples < d->totalSamples);
  16760. }
  16761. int AudioThumbnail::getNumChannels() const throw()
  16762. {
  16763. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16764. jassert (d != 0);
  16765. return d->numChannels;
  16766. }
  16767. double AudioThumbnail::getTotalLength() const throw()
  16768. {
  16769. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16770. jassert (d != 0);
  16771. if (d->sampleRate > 0)
  16772. return d->totalSamples / (double)d->sampleRate;
  16773. else
  16774. return 0.0;
  16775. }
  16776. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16777. int64 startSample,
  16778. int numSamples)
  16779. {
  16780. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16781. jassert (d != 0);
  16782. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16783. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16784. char* l = getChannelData (0);
  16785. char* r = getChannelData (1);
  16786. for (int i = firstDataPos; i < lastDataPos; ++i)
  16787. {
  16788. const int sourceStart = i * d->samplesPerThumbSample;
  16789. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16790. float lowestLeft, highestLeft, lowestRight, highestRight;
  16791. fileReader.readMaxLevels (sourceStart,
  16792. sourceEnd - sourceStart,
  16793. lowestLeft,
  16794. highestLeft,
  16795. lowestRight,
  16796. highestRight);
  16797. int n = i * 2;
  16798. if (r != 0)
  16799. {
  16800. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16801. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16802. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16803. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16804. }
  16805. else
  16806. {
  16807. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16808. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16809. }
  16810. }
  16811. }
  16812. char* AudioThumbnail::getChannelData (int channel) const
  16813. {
  16814. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16815. jassert (d != 0);
  16816. if (channel >= 0 && channel < d->numChannels)
  16817. return d->data + (channel * 2 * d->numThumbnailSamples);
  16818. return 0;
  16819. }
  16820. bool AudioThumbnail::isFullyLoaded() const throw()
  16821. {
  16822. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16823. jassert (d != 0);
  16824. return d->numFinishedSamples >= d->totalSamples;
  16825. }
  16826. void AudioThumbnail::refillCache (const int numSamples,
  16827. double startTime,
  16828. const double timePerPixel)
  16829. {
  16830. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16831. jassert (d != 0);
  16832. if (numSamples <= 0
  16833. || timePerPixel <= 0.0
  16834. || d->sampleRate <= 0)
  16835. {
  16836. numSamplesCached = 0;
  16837. cacheNeedsRefilling = true;
  16838. return;
  16839. }
  16840. if (numSamples == numSamplesCached
  16841. && numChannelsCached == d->numChannels
  16842. && startTime == cachedStart
  16843. && timePerPixel == cachedTimePerPixel
  16844. && ! cacheNeedsRefilling)
  16845. {
  16846. return;
  16847. }
  16848. numSamplesCached = numSamples;
  16849. numChannelsCached = d->numChannels;
  16850. cachedStart = startTime;
  16851. cachedTimePerPixel = timePerPixel;
  16852. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16853. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16854. const ScopedLock sl (readerLock);
  16855. cacheNeedsRefilling = false;
  16856. if (needExtraDetail && reader == 0)
  16857. reader = createReader();
  16858. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16859. {
  16860. startTimer (timeBeforeDeletingReader);
  16861. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16862. int sample = roundToInt (startTime * d->sampleRate);
  16863. for (int i = numSamples; --i >= 0;)
  16864. {
  16865. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16866. if (sample >= 0)
  16867. {
  16868. if (sample >= reader->lengthInSamples)
  16869. break;
  16870. float lmin, lmax, rmin, rmax;
  16871. reader->readMaxLevels (sample,
  16872. jmax (1, nextSample - sample),
  16873. lmin, lmax, rmin, rmax);
  16874. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16875. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16876. if (numChannelsCached > 1)
  16877. {
  16878. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16879. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16880. }
  16881. cacheData += 2 * numChannelsCached;
  16882. }
  16883. startTime += timePerPixel;
  16884. sample = nextSample;
  16885. }
  16886. }
  16887. else
  16888. {
  16889. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16890. {
  16891. char* const channelData = getChannelData (channelNum);
  16892. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16893. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16894. startTime = cachedStart;
  16895. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16896. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16897. for (int i = numSamples; --i >= 0;)
  16898. {
  16899. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16900. if (sample >= 0 && channelData != 0)
  16901. {
  16902. char mx = -128;
  16903. char mn = 127;
  16904. while (sample <= nextSample)
  16905. {
  16906. if (sample >= numFinished)
  16907. break;
  16908. const int n = sample << 1;
  16909. const char sampMin = channelData [n];
  16910. const char sampMax = channelData [n + 1];
  16911. if (sampMin < mn)
  16912. mn = sampMin;
  16913. if (sampMax > mx)
  16914. mx = sampMax;
  16915. ++sample;
  16916. }
  16917. if (mn <= mx)
  16918. {
  16919. cacheData[0] = mn;
  16920. cacheData[1] = mx;
  16921. }
  16922. else
  16923. {
  16924. cacheData[0] = 1;
  16925. cacheData[1] = 0;
  16926. }
  16927. }
  16928. else
  16929. {
  16930. cacheData[0] = 1;
  16931. cacheData[1] = 0;
  16932. }
  16933. cacheData += numChannelsCached * 2;
  16934. startTime += timePerPixel;
  16935. sample = nextSample;
  16936. }
  16937. }
  16938. }
  16939. }
  16940. void AudioThumbnail::drawChannel (Graphics& g,
  16941. int x, int y, int w, int h,
  16942. double startTime,
  16943. double endTime,
  16944. int channelNum,
  16945. const float verticalZoomFactor)
  16946. {
  16947. refillCache (w, startTime, (endTime - startTime) / w);
  16948. if (numSamplesCached >= w
  16949. && channelNum >= 0
  16950. && channelNum < numChannelsCached)
  16951. {
  16952. const float topY = (float) y;
  16953. const float bottomY = topY + h;
  16954. const float midY = topY + h * 0.5f;
  16955. const float vscale = verticalZoomFactor * h / 256.0f;
  16956. const Rectangle<int> clip (g.getClipBounds());
  16957. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16958. w -= skipLeft;
  16959. x += skipLeft;
  16960. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16961. + (channelNum << 1)
  16962. + skipLeft * (numChannelsCached << 1);
  16963. while (--w >= 0)
  16964. {
  16965. const char mn = cacheData[0];
  16966. const char mx = cacheData[1];
  16967. cacheData += numChannelsCached << 1;
  16968. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16969. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16970. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16971. ++x;
  16972. if (x >= clip.getRight())
  16973. break;
  16974. }
  16975. }
  16976. }
  16977. END_JUCE_NAMESPACE
  16978. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16979. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16980. BEGIN_JUCE_NAMESPACE
  16981. struct ThumbnailCacheEntry
  16982. {
  16983. int64 hash;
  16984. uint32 lastUsed;
  16985. MemoryBlock data;
  16986. juce_UseDebuggingNewOperator
  16987. };
  16988. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16989. : TimeSliceThread ("thumb cache"),
  16990. maxNumThumbsToStore (maxNumThumbsToStore_)
  16991. {
  16992. startThread (2);
  16993. }
  16994. AudioThumbnailCache::~AudioThumbnailCache()
  16995. {
  16996. }
  16997. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16998. {
  16999. for (int i = thumbs.size(); --i >= 0;)
  17000. {
  17001. if (thumbs[i]->hash == hashCode)
  17002. {
  17003. MemoryInputStream in (thumbs[i]->data, false);
  17004. thumb.loadFrom (in);
  17005. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  17006. return true;
  17007. }
  17008. }
  17009. return false;
  17010. }
  17011. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17012. const int64 hashCode)
  17013. {
  17014. MemoryOutputStream out;
  17015. thumb.saveTo (out);
  17016. ThumbnailCacheEntry* te = 0;
  17017. for (int i = thumbs.size(); --i >= 0;)
  17018. {
  17019. if (thumbs[i]->hash == hashCode)
  17020. {
  17021. te = thumbs[i];
  17022. break;
  17023. }
  17024. }
  17025. if (te == 0)
  17026. {
  17027. te = new ThumbnailCacheEntry();
  17028. te->hash = hashCode;
  17029. if (thumbs.size() < maxNumThumbsToStore)
  17030. {
  17031. thumbs.add (te);
  17032. }
  17033. else
  17034. {
  17035. int oldest = 0;
  17036. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17037. int i;
  17038. for (i = thumbs.size(); --i >= 0;)
  17039. if (thumbs[i]->lastUsed < oldestTime)
  17040. oldest = i;
  17041. thumbs.set (i, te);
  17042. }
  17043. }
  17044. te->lastUsed = Time::getMillisecondCounter();
  17045. te->data.setSize (0);
  17046. te->data.append (out.getData(), out.getDataSize());
  17047. }
  17048. void AudioThumbnailCache::clear()
  17049. {
  17050. thumbs.clear();
  17051. }
  17052. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17053. {
  17054. addTimeSliceClient (thumb);
  17055. }
  17056. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17057. {
  17058. removeTimeSliceClient (thumb);
  17059. }
  17060. END_JUCE_NAMESPACE
  17061. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17062. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17063. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17064. #if ! JUCE_WINDOWS
  17065. #include <QuickTime/Movies.h>
  17066. #include <QuickTime/QTML.h>
  17067. #include <QuickTime/QuickTimeComponents.h>
  17068. #include <QuickTime/MediaHandlers.h>
  17069. #include <QuickTime/ImageCodec.h>
  17070. #else
  17071. #if JUCE_MSVC
  17072. #pragma warning (push)
  17073. #pragma warning (disable : 4100)
  17074. #endif
  17075. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17076. add its header directory to your include path.
  17077. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17078. flag in juce_Config.h
  17079. */
  17080. #include <Movies.h>
  17081. #include <QTML.h>
  17082. #include <QuickTimeComponents.h>
  17083. #include <MediaHandlers.h>
  17084. #include <ImageCodec.h>
  17085. #if JUCE_MSVC
  17086. #pragma warning (pop)
  17087. #endif
  17088. #endif
  17089. BEGIN_JUCE_NAMESPACE
  17090. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17091. static const char* const quickTimeFormatName = "QuickTime file";
  17092. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17093. class QTAudioReader : public AudioFormatReader
  17094. {
  17095. public:
  17096. QTAudioReader (InputStream* const input_, const int trackNum_)
  17097. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17098. ok (false),
  17099. movie (0),
  17100. trackNum (trackNum_),
  17101. lastSampleRead (0),
  17102. lastThreadId (0),
  17103. extractor (0),
  17104. dataHandle (0)
  17105. {
  17106. bufferList.calloc (256, 1);
  17107. #if JUCE_WINDOWS
  17108. if (InitializeQTML (0) != noErr)
  17109. return;
  17110. #endif
  17111. if (EnterMovies() != noErr)
  17112. return;
  17113. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17114. if (! opened)
  17115. return;
  17116. {
  17117. const int numTracks = GetMovieTrackCount (movie);
  17118. int trackCount = 0;
  17119. for (int i = 1; i <= numTracks; ++i)
  17120. {
  17121. track = GetMovieIndTrack (movie, i);
  17122. media = GetTrackMedia (track);
  17123. OSType mediaType;
  17124. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17125. if (mediaType == SoundMediaType
  17126. && trackCount++ == trackNum_)
  17127. {
  17128. ok = true;
  17129. break;
  17130. }
  17131. }
  17132. }
  17133. if (! ok)
  17134. return;
  17135. ok = false;
  17136. lengthInSamples = GetMediaDecodeDuration (media);
  17137. usesFloatingPointData = false;
  17138. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17139. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17140. / GetMediaTimeScale (media);
  17141. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17142. unsigned long output_layout_size;
  17143. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17144. kQTPropertyClass_MovieAudioExtraction_Audio,
  17145. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17146. 0, &output_layout_size, 0);
  17147. if (err != noErr)
  17148. return;
  17149. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17150. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17151. err = MovieAudioExtractionGetProperty (extractor,
  17152. kQTPropertyClass_MovieAudioExtraction_Audio,
  17153. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17154. output_layout_size, qt_audio_channel_layout, 0);
  17155. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17156. err = MovieAudioExtractionSetProperty (extractor,
  17157. kQTPropertyClass_MovieAudioExtraction_Audio,
  17158. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17159. output_layout_size,
  17160. qt_audio_channel_layout);
  17161. err = MovieAudioExtractionGetProperty (extractor,
  17162. kQTPropertyClass_MovieAudioExtraction_Audio,
  17163. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17164. sizeof (inputStreamDesc),
  17165. &inputStreamDesc, 0);
  17166. if (err != noErr)
  17167. return;
  17168. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17169. | kAudioFormatFlagIsPacked
  17170. | kAudioFormatFlagsNativeEndian;
  17171. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17172. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17173. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17174. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17175. err = MovieAudioExtractionSetProperty (extractor,
  17176. kQTPropertyClass_MovieAudioExtraction_Audio,
  17177. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17178. sizeof (inputStreamDesc),
  17179. &inputStreamDesc);
  17180. if (err != noErr)
  17181. return;
  17182. Boolean allChannelsDiscrete = false;
  17183. err = MovieAudioExtractionSetProperty (extractor,
  17184. kQTPropertyClass_MovieAudioExtraction_Movie,
  17185. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17186. sizeof (allChannelsDiscrete),
  17187. &allChannelsDiscrete);
  17188. if (err != noErr)
  17189. return;
  17190. bufferList->mNumberBuffers = 1;
  17191. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17192. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17193. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17194. bufferList->mBuffers[0].mData = dataBuffer;
  17195. sampleRate = inputStreamDesc.mSampleRate;
  17196. bitsPerSample = 16;
  17197. numChannels = inputStreamDesc.mChannelsPerFrame;
  17198. detachThread();
  17199. ok = true;
  17200. }
  17201. ~QTAudioReader()
  17202. {
  17203. if (dataHandle != 0)
  17204. DisposeHandle (dataHandle);
  17205. if (extractor != 0)
  17206. {
  17207. MovieAudioExtractionEnd (extractor);
  17208. extractor = 0;
  17209. }
  17210. checkThreadIsAttached();
  17211. DisposeMovie (movie);
  17212. #if JUCE_MAC
  17213. ExitMoviesOnThread ();
  17214. #endif
  17215. }
  17216. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17217. int64 startSampleInFile, int numSamples)
  17218. {
  17219. checkThreadIsAttached();
  17220. while (numSamples > 0)
  17221. {
  17222. if (! loadFrame ((int) startSampleInFile))
  17223. return false;
  17224. const int numToDo = jmin (numSamples, samplesPerFrame);
  17225. for (int j = numDestChannels; --j >= 0;)
  17226. {
  17227. if (destSamples[j] != 0)
  17228. {
  17229. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17230. for (int i = 0; i < numToDo; ++i)
  17231. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17232. }
  17233. }
  17234. startOffsetInDestBuffer += numToDo;
  17235. startSampleInFile += numToDo;
  17236. numSamples -= numToDo;
  17237. }
  17238. detachThread();
  17239. return true;
  17240. }
  17241. bool loadFrame (const int sampleNum)
  17242. {
  17243. if (lastSampleRead != sampleNum)
  17244. {
  17245. TimeRecord time;
  17246. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17247. time.base = 0;
  17248. time.value.hi = 0;
  17249. time.value.lo = (UInt32) sampleNum;
  17250. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17251. kQTPropertyClass_MovieAudioExtraction_Movie,
  17252. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17253. sizeof (time), &time);
  17254. if (err != noErr)
  17255. return false;
  17256. }
  17257. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17258. UInt32 outFlags = 0;
  17259. UInt32 actualNumSamples = samplesPerFrame;
  17260. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17261. bufferList, &outFlags);
  17262. lastSampleRead = sampleNum + samplesPerFrame;
  17263. return err == noErr;
  17264. }
  17265. juce_UseDebuggingNewOperator
  17266. bool ok;
  17267. private:
  17268. Movie movie;
  17269. Media media;
  17270. Track track;
  17271. const int trackNum;
  17272. double trackUnitsPerFrame;
  17273. int samplesPerFrame;
  17274. int lastSampleRead;
  17275. Thread::ThreadID lastThreadId;
  17276. MovieAudioExtractionRef extractor;
  17277. AudioStreamBasicDescription inputStreamDesc;
  17278. HeapBlock <AudioBufferList> bufferList;
  17279. HeapBlock <char> dataBuffer;
  17280. Handle dataHandle;
  17281. void checkThreadIsAttached()
  17282. {
  17283. #if JUCE_MAC
  17284. if (Thread::getCurrentThreadId() != lastThreadId)
  17285. EnterMoviesOnThread (0);
  17286. AttachMovieToCurrentThread (movie);
  17287. #endif
  17288. }
  17289. void detachThread()
  17290. {
  17291. #if JUCE_MAC
  17292. DetachMovieFromCurrentThread (movie);
  17293. #endif
  17294. }
  17295. QTAudioReader (const QTAudioReader&);
  17296. QTAudioReader& operator= (const QTAudioReader&);
  17297. };
  17298. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17299. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17300. {
  17301. }
  17302. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17303. {
  17304. }
  17305. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17306. {
  17307. return Array<int>();
  17308. }
  17309. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17310. {
  17311. return Array<int>();
  17312. }
  17313. bool QuickTimeAudioFormat::canDoStereo()
  17314. {
  17315. return true;
  17316. }
  17317. bool QuickTimeAudioFormat::canDoMono()
  17318. {
  17319. return true;
  17320. }
  17321. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17322. const bool deleteStreamIfOpeningFails)
  17323. {
  17324. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17325. if (r->ok)
  17326. return r.release();
  17327. if (! deleteStreamIfOpeningFails)
  17328. r->input = 0;
  17329. return 0;
  17330. }
  17331. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17332. double /*sampleRateToUse*/,
  17333. unsigned int /*numberOfChannels*/,
  17334. int /*bitsPerSample*/,
  17335. const StringPairArray& /*metadataValues*/,
  17336. int /*qualityOptionIndex*/)
  17337. {
  17338. jassertfalse; // not yet implemented!
  17339. return 0;
  17340. }
  17341. END_JUCE_NAMESPACE
  17342. #endif
  17343. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17344. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17345. BEGIN_JUCE_NAMESPACE
  17346. static const char* const wavFormatName = "WAV file";
  17347. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17348. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17349. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17350. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17351. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17352. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17353. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17354. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17355. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17356. const String& originator,
  17357. const String& originatorRef,
  17358. const Time& date,
  17359. const int64 timeReferenceSamples,
  17360. const String& codingHistory)
  17361. {
  17362. StringPairArray m;
  17363. m.set (bwavDescription, description);
  17364. m.set (bwavOriginator, originator);
  17365. m.set (bwavOriginatorRef, originatorRef);
  17366. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17367. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17368. m.set (bwavTimeReference, String (timeReferenceSamples));
  17369. m.set (bwavCodingHistory, codingHistory);
  17370. return m;
  17371. }
  17372. #if JUCE_MSVC
  17373. #pragma pack (push, 1)
  17374. #define PACKED
  17375. #elif JUCE_GCC
  17376. #define PACKED __attribute__((packed))
  17377. #else
  17378. #define PACKED
  17379. #endif
  17380. struct BWAVChunk
  17381. {
  17382. char description [256];
  17383. char originator [32];
  17384. char originatorRef [32];
  17385. char originationDate [10];
  17386. char originationTime [8];
  17387. uint32 timeRefLow;
  17388. uint32 timeRefHigh;
  17389. uint16 version;
  17390. uint8 umid[64];
  17391. uint8 reserved[190];
  17392. char codingHistory[1];
  17393. void copyTo (StringPairArray& values) const
  17394. {
  17395. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17396. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17397. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17398. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17399. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17400. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17401. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17402. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17403. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17404. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17405. }
  17406. static MemoryBlock createFrom (const StringPairArray& values)
  17407. {
  17408. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17409. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17410. data.fillWith (0);
  17411. BWAVChunk* b = (BWAVChunk*) data.getData();
  17412. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17413. // as they get called in the right order..
  17414. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17415. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17416. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17417. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17418. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17419. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17420. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17421. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17422. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17423. if (b->description[0] != 0
  17424. || b->originator[0] != 0
  17425. || b->originationDate[0] != 0
  17426. || b->originationTime[0] != 0
  17427. || b->codingHistory[0] != 0
  17428. || time != 0)
  17429. {
  17430. return data;
  17431. }
  17432. return MemoryBlock();
  17433. }
  17434. } PACKED;
  17435. struct SMPLChunk
  17436. {
  17437. struct SampleLoop
  17438. {
  17439. uint32 identifier;
  17440. uint32 type;
  17441. uint32 start;
  17442. uint32 end;
  17443. uint32 fraction;
  17444. uint32 playCount;
  17445. } PACKED;
  17446. uint32 manufacturer;
  17447. uint32 product;
  17448. uint32 samplePeriod;
  17449. uint32 midiUnityNote;
  17450. uint32 midiPitchFraction;
  17451. uint32 smpteFormat;
  17452. uint32 smpteOffset;
  17453. uint32 numSampleLoops;
  17454. uint32 samplerData;
  17455. SampleLoop loops[1];
  17456. void copyTo (StringPairArray& values, const int totalSize) const
  17457. {
  17458. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17459. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17460. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17461. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17462. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17463. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17464. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17465. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17466. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17467. for (uint32 i = 0; i < numSampleLoops; ++i)
  17468. {
  17469. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17470. break;
  17471. const String prefix ("Loop" + String(i));
  17472. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17473. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17474. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17475. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17476. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17477. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17478. }
  17479. }
  17480. static MemoryBlock createFrom (const StringPairArray& values)
  17481. {
  17482. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17483. if (numLoops <= 0)
  17484. return MemoryBlock();
  17485. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17486. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17487. data.fillWith (0);
  17488. SMPLChunk* s = (SMPLChunk*) data.getData();
  17489. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17490. // as they get called in the right order..
  17491. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17492. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17493. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17494. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17495. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17496. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17497. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17498. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17499. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17500. for (int i = 0; i < numLoops; ++i)
  17501. {
  17502. const String prefix ("Loop" + String(i));
  17503. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17504. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17505. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17506. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17507. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17508. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17509. }
  17510. return data;
  17511. }
  17512. } PACKED;
  17513. struct ExtensibleWavSubFormat
  17514. {
  17515. uint32 data1;
  17516. uint16 data2;
  17517. uint16 data3;
  17518. uint8 data4[8];
  17519. } PACKED;
  17520. #if JUCE_MSVC
  17521. #pragma pack (pop)
  17522. #endif
  17523. #undef PACKED
  17524. class WavAudioFormatReader : public AudioFormatReader
  17525. {
  17526. int bytesPerFrame;
  17527. int64 dataChunkStart, dataLength;
  17528. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17529. WavAudioFormatReader (const WavAudioFormatReader&);
  17530. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17531. public:
  17532. int64 bwavChunkStart, bwavSize;
  17533. WavAudioFormatReader (InputStream* const in)
  17534. : AudioFormatReader (in, TRANS (wavFormatName)),
  17535. dataLength (0),
  17536. bwavChunkStart (0),
  17537. bwavSize (0)
  17538. {
  17539. if (input->readInt() == chunkName ("RIFF"))
  17540. {
  17541. const uint32 len = (uint32) input->readInt();
  17542. const int64 end = input->getPosition() + len;
  17543. bool hasGotType = false;
  17544. bool hasGotData = false;
  17545. if (input->readInt() == chunkName ("WAVE"))
  17546. {
  17547. while (input->getPosition() < end
  17548. && ! input->isExhausted())
  17549. {
  17550. const int chunkType = input->readInt();
  17551. uint32 length = (uint32) input->readInt();
  17552. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17553. if (chunkType == chunkName ("fmt "))
  17554. {
  17555. // read the format chunk
  17556. const unsigned short format = input->readShort();
  17557. const short numChans = input->readShort();
  17558. sampleRate = input->readInt();
  17559. const int bytesPerSec = input->readInt();
  17560. numChannels = numChans;
  17561. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17562. bitsPerSample = 8 * bytesPerFrame / numChans;
  17563. if (format == 3)
  17564. {
  17565. usesFloatingPointData = true;
  17566. }
  17567. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17568. {
  17569. if (length < 40) // too short
  17570. {
  17571. bytesPerFrame = 0;
  17572. }
  17573. else
  17574. {
  17575. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17576. ExtensibleWavSubFormat subFormat;
  17577. subFormat.data1 = input->readInt();
  17578. subFormat.data2 = input->readShort();
  17579. subFormat.data3 = input->readShort();
  17580. input->read (subFormat.data4, sizeof (subFormat.data4));
  17581. const ExtensibleWavSubFormat pcmFormat
  17582. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17583. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17584. {
  17585. const ExtensibleWavSubFormat ambisonicFormat
  17586. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17587. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17588. bytesPerFrame = 0;
  17589. }
  17590. }
  17591. }
  17592. else if (format != 1)
  17593. {
  17594. bytesPerFrame = 0;
  17595. }
  17596. hasGotType = true;
  17597. }
  17598. else if (chunkType == chunkName ("data"))
  17599. {
  17600. // get the data chunk's position
  17601. dataLength = length;
  17602. dataChunkStart = input->getPosition();
  17603. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17604. hasGotData = true;
  17605. }
  17606. else if (chunkType == chunkName ("bext"))
  17607. {
  17608. bwavChunkStart = input->getPosition();
  17609. bwavSize = length;
  17610. // Broadcast-wav extension chunk..
  17611. HeapBlock <BWAVChunk> bwav;
  17612. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17613. input->read (bwav, length);
  17614. bwav->copyTo (metadataValues);
  17615. }
  17616. else if (chunkType == chunkName ("smpl"))
  17617. {
  17618. HeapBlock <SMPLChunk> smpl;
  17619. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17620. input->read (smpl, length);
  17621. smpl->copyTo (metadataValues, length);
  17622. }
  17623. else if (chunkEnd <= input->getPosition())
  17624. {
  17625. break;
  17626. }
  17627. input->setPosition (chunkEnd);
  17628. }
  17629. }
  17630. }
  17631. }
  17632. ~WavAudioFormatReader()
  17633. {
  17634. }
  17635. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17636. int64 startSampleInFile, int numSamples)
  17637. {
  17638. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17639. if (samplesAvailable < numSamples)
  17640. {
  17641. for (int i = numDestChannels; --i >= 0;)
  17642. if (destSamples[i] != 0)
  17643. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17644. numSamples = (int) samplesAvailable;
  17645. }
  17646. if (numSamples <= 0)
  17647. return true;
  17648. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17649. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17650. char tempBuffer [tempBufSize];
  17651. while (numSamples > 0)
  17652. {
  17653. int* left = destSamples[0];
  17654. if (left != 0)
  17655. left += startOffsetInDestBuffer;
  17656. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17657. if (right != 0)
  17658. right += startOffsetInDestBuffer;
  17659. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17660. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17661. if (bytesRead < numThisTime * bytesPerFrame)
  17662. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17663. if (bitsPerSample == 16)
  17664. {
  17665. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17666. if (numChannels > 1)
  17667. {
  17668. if (left == 0)
  17669. {
  17670. for (int i = numThisTime; --i >= 0;)
  17671. {
  17672. ++src;
  17673. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17674. }
  17675. }
  17676. else if (right == 0)
  17677. {
  17678. for (int i = numThisTime; --i >= 0;)
  17679. {
  17680. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17681. ++src;
  17682. }
  17683. }
  17684. else
  17685. {
  17686. for (int i = numThisTime; --i >= 0;)
  17687. {
  17688. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17689. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17690. }
  17691. }
  17692. }
  17693. else
  17694. {
  17695. for (int i = numThisTime; --i >= 0;)
  17696. {
  17697. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17698. }
  17699. }
  17700. }
  17701. else if (bitsPerSample == 24)
  17702. {
  17703. const char* src = tempBuffer;
  17704. if (numChannels > 1)
  17705. {
  17706. if (left == 0)
  17707. {
  17708. for (int i = numThisTime; --i >= 0;)
  17709. {
  17710. src += 3;
  17711. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17712. src += 3;
  17713. }
  17714. }
  17715. else if (right == 0)
  17716. {
  17717. for (int i = numThisTime; --i >= 0;)
  17718. {
  17719. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17720. src += 6;
  17721. }
  17722. }
  17723. else
  17724. {
  17725. for (int i = 0; i < numThisTime; ++i)
  17726. {
  17727. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17728. src += 3;
  17729. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17730. src += 3;
  17731. }
  17732. }
  17733. }
  17734. else
  17735. {
  17736. for (int i = 0; i < numThisTime; ++i)
  17737. {
  17738. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17739. src += 3;
  17740. }
  17741. }
  17742. }
  17743. else if (bitsPerSample == 32)
  17744. {
  17745. const unsigned int* src = (const unsigned int*) tempBuffer;
  17746. unsigned int* l = (unsigned int*) left;
  17747. unsigned int* r = (unsigned int*) right;
  17748. if (numChannels > 1)
  17749. {
  17750. if (l == 0)
  17751. {
  17752. for (int i = numThisTime; --i >= 0;)
  17753. {
  17754. ++src;
  17755. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17756. }
  17757. }
  17758. else if (r == 0)
  17759. {
  17760. for (int i = numThisTime; --i >= 0;)
  17761. {
  17762. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17763. ++src;
  17764. }
  17765. }
  17766. else
  17767. {
  17768. for (int i = numThisTime; --i >= 0;)
  17769. {
  17770. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17771. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17772. }
  17773. }
  17774. }
  17775. else
  17776. {
  17777. for (int i = numThisTime; --i >= 0;)
  17778. {
  17779. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17780. }
  17781. }
  17782. left = (int*)l;
  17783. right = (int*)r;
  17784. }
  17785. else if (bitsPerSample == 8)
  17786. {
  17787. const unsigned char* src = (const unsigned char*) tempBuffer;
  17788. if (numChannels > 1)
  17789. {
  17790. if (left == 0)
  17791. {
  17792. for (int i = numThisTime; --i >= 0;)
  17793. {
  17794. ++src;
  17795. *right++ = ((int) *src++ - 128) << 24;
  17796. }
  17797. }
  17798. else if (right == 0)
  17799. {
  17800. for (int i = numThisTime; --i >= 0;)
  17801. {
  17802. *left++ = ((int) *src++ - 128) << 24;
  17803. ++src;
  17804. }
  17805. }
  17806. else
  17807. {
  17808. for (int i = numThisTime; --i >= 0;)
  17809. {
  17810. *left++ = ((int) *src++ - 128) << 24;
  17811. *right++ = ((int) *src++ - 128) << 24;
  17812. }
  17813. }
  17814. }
  17815. else
  17816. {
  17817. for (int i = numThisTime; --i >= 0;)
  17818. {
  17819. *left++ = ((int)*src++ - 128) << 24;
  17820. }
  17821. }
  17822. }
  17823. startOffsetInDestBuffer += numThisTime;
  17824. numSamples -= numThisTime;
  17825. }
  17826. if (numSamples > 0)
  17827. {
  17828. for (int i = numDestChannels; --i >= 0;)
  17829. if (destSamples[i] != 0)
  17830. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17831. sizeof (int) * numSamples);
  17832. }
  17833. return true;
  17834. }
  17835. juce_UseDebuggingNewOperator
  17836. };
  17837. class WavAudioFormatWriter : public AudioFormatWriter
  17838. {
  17839. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17840. uint32 lengthInSamples, bytesWritten;
  17841. int64 headerPosition;
  17842. bool writeFailed;
  17843. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17844. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17845. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17846. void writeHeader()
  17847. {
  17848. const bool seekedOk = output->setPosition (headerPosition);
  17849. (void) seekedOk;
  17850. // if this fails, you've given it an output stream that can't seek! It needs
  17851. // to be able to seek back to write the header
  17852. jassert (seekedOk);
  17853. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17854. output->writeInt (chunkName ("RIFF"));
  17855. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17856. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17857. output->writeInt (chunkName ("WAVE"));
  17858. output->writeInt (chunkName ("fmt "));
  17859. output->writeInt (16);
  17860. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17861. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17862. output->writeShort ((short) numChannels);
  17863. output->writeInt ((int) sampleRate);
  17864. output->writeInt (bytesPerFrame * (int) sampleRate);
  17865. output->writeShort ((short) bytesPerFrame);
  17866. output->writeShort ((short) bitsPerSample);
  17867. if (bwavChunk.getSize() > 0)
  17868. {
  17869. output->writeInt (chunkName ("bext"));
  17870. output->writeInt ((int) bwavChunk.getSize());
  17871. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17872. }
  17873. if (smplChunk.getSize() > 0)
  17874. {
  17875. output->writeInt (chunkName ("smpl"));
  17876. output->writeInt ((int) smplChunk.getSize());
  17877. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17878. }
  17879. output->writeInt (chunkName ("data"));
  17880. output->writeInt (lengthInSamples * bytesPerFrame);
  17881. usesFloatingPointData = (bitsPerSample == 32);
  17882. }
  17883. public:
  17884. WavAudioFormatWriter (OutputStream* const out,
  17885. const double sampleRate_,
  17886. const unsigned int numChannels_,
  17887. const int bits,
  17888. const StringPairArray& metadataValues)
  17889. : AudioFormatWriter (out,
  17890. TRANS (wavFormatName),
  17891. sampleRate_,
  17892. numChannels_,
  17893. bits),
  17894. lengthInSamples (0),
  17895. bytesWritten (0),
  17896. writeFailed (false)
  17897. {
  17898. if (metadataValues.size() > 0)
  17899. {
  17900. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17901. smplChunk = SMPLChunk::createFrom (metadataValues);
  17902. }
  17903. headerPosition = out->getPosition();
  17904. writeHeader();
  17905. }
  17906. ~WavAudioFormatWriter()
  17907. {
  17908. writeHeader();
  17909. }
  17910. bool write (const int** data, int numSamples)
  17911. {
  17912. if (writeFailed)
  17913. return false;
  17914. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17915. tempBlock.ensureSize (bytes, false);
  17916. char* buffer = static_cast <char*> (tempBlock.getData());
  17917. const int* left = data[0];
  17918. const int* right = data[1];
  17919. if (right == 0)
  17920. right = left;
  17921. if (bitsPerSample == 16)
  17922. {
  17923. short* b = (short*) buffer;
  17924. if (numChannels > 1)
  17925. {
  17926. for (int i = numSamples; --i >= 0;)
  17927. {
  17928. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17929. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17930. }
  17931. }
  17932. else
  17933. {
  17934. for (int i = numSamples; --i >= 0;)
  17935. {
  17936. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17937. }
  17938. }
  17939. }
  17940. else if (bitsPerSample == 24)
  17941. {
  17942. char* b = buffer;
  17943. if (numChannels > 1)
  17944. {
  17945. for (int i = numSamples; --i >= 0;)
  17946. {
  17947. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17948. b += 3;
  17949. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17950. b += 3;
  17951. }
  17952. }
  17953. else
  17954. {
  17955. for (int i = numSamples; --i >= 0;)
  17956. {
  17957. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17958. b += 3;
  17959. }
  17960. }
  17961. }
  17962. else if (bitsPerSample == 32)
  17963. {
  17964. unsigned int* b = (unsigned int*) buffer;
  17965. if (numChannels > 1)
  17966. {
  17967. for (int i = numSamples; --i >= 0;)
  17968. {
  17969. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17970. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17971. }
  17972. }
  17973. else
  17974. {
  17975. for (int i = numSamples; --i >= 0;)
  17976. {
  17977. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17978. }
  17979. }
  17980. }
  17981. else if (bitsPerSample == 8)
  17982. {
  17983. unsigned char* b = (unsigned char*) buffer;
  17984. if (numChannels > 1)
  17985. {
  17986. for (int i = numSamples; --i >= 0;)
  17987. {
  17988. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17989. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17990. }
  17991. }
  17992. else
  17993. {
  17994. for (int i = numSamples; --i >= 0;)
  17995. {
  17996. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17997. }
  17998. }
  17999. }
  18000. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18001. || ! output->write (buffer, bytes))
  18002. {
  18003. // failed to write to disk, so let's try writing the header.
  18004. // If it's just run out of disk space, then if it does manage
  18005. // to write the header, we'll still have a useable file..
  18006. writeHeader();
  18007. writeFailed = true;
  18008. return false;
  18009. }
  18010. else
  18011. {
  18012. bytesWritten += bytes;
  18013. lengthInSamples += numSamples;
  18014. return true;
  18015. }
  18016. }
  18017. juce_UseDebuggingNewOperator
  18018. };
  18019. WavAudioFormat::WavAudioFormat()
  18020. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18021. {
  18022. }
  18023. WavAudioFormat::~WavAudioFormat()
  18024. {
  18025. }
  18026. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18027. {
  18028. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18029. return Array <int> (rates);
  18030. }
  18031. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18032. {
  18033. const int depths[] = { 8, 16, 24, 32, 0 };
  18034. return Array <int> (depths);
  18035. }
  18036. bool WavAudioFormat::canDoStereo()
  18037. {
  18038. return true;
  18039. }
  18040. bool WavAudioFormat::canDoMono()
  18041. {
  18042. return true;
  18043. }
  18044. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18045. const bool deleteStreamIfOpeningFails)
  18046. {
  18047. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18048. if (r->sampleRate != 0)
  18049. return r.release();
  18050. if (! deleteStreamIfOpeningFails)
  18051. r->input = 0;
  18052. return 0;
  18053. }
  18054. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18055. double sampleRate,
  18056. unsigned int numChannels,
  18057. int bitsPerSample,
  18058. const StringPairArray& metadataValues,
  18059. int /*qualityOptionIndex*/)
  18060. {
  18061. if (getPossibleBitDepths().contains (bitsPerSample))
  18062. {
  18063. return new WavAudioFormatWriter (out,
  18064. sampleRate,
  18065. numChannels,
  18066. bitsPerSample,
  18067. metadataValues);
  18068. }
  18069. return 0;
  18070. }
  18071. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18072. {
  18073. TemporaryFile tempFile (file);
  18074. WavAudioFormat wav;
  18075. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18076. if (reader != 0)
  18077. {
  18078. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18079. if (outStream != 0)
  18080. {
  18081. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18082. reader->numChannels, reader->bitsPerSample,
  18083. metadata, 0));
  18084. if (writer != 0)
  18085. {
  18086. outStream.release();
  18087. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18088. writer = 0;
  18089. reader = 0;
  18090. return ok && tempFile.overwriteTargetFileWithTemporary();
  18091. }
  18092. }
  18093. }
  18094. return false;
  18095. }
  18096. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18097. {
  18098. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18099. if (reader != 0)
  18100. {
  18101. const int64 bwavPos = reader->bwavChunkStart;
  18102. const int64 bwavSize = reader->bwavSize;
  18103. reader = 0;
  18104. if (bwavSize > 0)
  18105. {
  18106. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18107. if (chunk.getSize() <= (size_t) bwavSize)
  18108. {
  18109. // the new one will fit in the space available, so write it directly..
  18110. const int64 oldSize = wavFile.getSize();
  18111. {
  18112. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18113. out->setPosition (bwavPos);
  18114. out->write (chunk.getData(), (int) chunk.getSize());
  18115. out->setPosition (oldSize);
  18116. }
  18117. jassert (wavFile.getSize() == oldSize);
  18118. return true;
  18119. }
  18120. }
  18121. }
  18122. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18123. }
  18124. END_JUCE_NAMESPACE
  18125. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18126. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18127. BEGIN_JUCE_NAMESPACE
  18128. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18129. const bool deleteReaderWhenThisIsDeleted)
  18130. : reader (reader_),
  18131. deleteReader (deleteReaderWhenThisIsDeleted),
  18132. nextPlayPos (0),
  18133. looping (false)
  18134. {
  18135. jassert (reader != 0);
  18136. }
  18137. AudioFormatReaderSource::~AudioFormatReaderSource()
  18138. {
  18139. releaseResources();
  18140. if (deleteReader)
  18141. delete reader;
  18142. }
  18143. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18144. {
  18145. nextPlayPos = newPosition;
  18146. }
  18147. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18148. {
  18149. looping = shouldLoop;
  18150. }
  18151. int AudioFormatReaderSource::getNextReadPosition() const
  18152. {
  18153. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18154. : nextPlayPos;
  18155. }
  18156. int AudioFormatReaderSource::getTotalLength() const
  18157. {
  18158. return (int) reader->lengthInSamples;
  18159. }
  18160. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18161. double /*sampleRate*/)
  18162. {
  18163. }
  18164. void AudioFormatReaderSource::releaseResources()
  18165. {
  18166. }
  18167. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18168. {
  18169. if (info.numSamples > 0)
  18170. {
  18171. const int start = nextPlayPos;
  18172. if (looping)
  18173. {
  18174. const int newStart = start % (int) reader->lengthInSamples;
  18175. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18176. if (newEnd > newStart)
  18177. {
  18178. info.buffer->readFromAudioReader (reader,
  18179. info.startSample,
  18180. newEnd - newStart,
  18181. newStart,
  18182. true, true);
  18183. }
  18184. else
  18185. {
  18186. const int endSamps = (int) reader->lengthInSamples - newStart;
  18187. info.buffer->readFromAudioReader (reader,
  18188. info.startSample,
  18189. endSamps,
  18190. newStart,
  18191. true, true);
  18192. info.buffer->readFromAudioReader (reader,
  18193. info.startSample + endSamps,
  18194. newEnd,
  18195. 0,
  18196. true, true);
  18197. }
  18198. nextPlayPos = newEnd;
  18199. }
  18200. else
  18201. {
  18202. info.buffer->readFromAudioReader (reader,
  18203. info.startSample,
  18204. info.numSamples,
  18205. start,
  18206. true, true);
  18207. nextPlayPos += info.numSamples;
  18208. }
  18209. }
  18210. }
  18211. END_JUCE_NAMESPACE
  18212. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18213. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18214. BEGIN_JUCE_NAMESPACE
  18215. AudioSourcePlayer::AudioSourcePlayer()
  18216. : source (0),
  18217. sampleRate (0),
  18218. bufferSize (0),
  18219. tempBuffer (2, 8),
  18220. lastGain (1.0f),
  18221. gain (1.0f)
  18222. {
  18223. }
  18224. AudioSourcePlayer::~AudioSourcePlayer()
  18225. {
  18226. setSource (0);
  18227. }
  18228. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18229. {
  18230. if (source != newSource)
  18231. {
  18232. AudioSource* const oldSource = source;
  18233. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18234. newSource->prepareToPlay (bufferSize, sampleRate);
  18235. {
  18236. const ScopedLock sl (readLock);
  18237. source = newSource;
  18238. }
  18239. if (oldSource != 0)
  18240. oldSource->releaseResources();
  18241. }
  18242. }
  18243. void AudioSourcePlayer::setGain (const float newGain) throw()
  18244. {
  18245. gain = newGain;
  18246. }
  18247. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18248. int totalNumInputChannels,
  18249. float** outputChannelData,
  18250. int totalNumOutputChannels,
  18251. int numSamples)
  18252. {
  18253. // these should have been prepared by audioDeviceAboutToStart()...
  18254. jassert (sampleRate > 0 && bufferSize > 0);
  18255. const ScopedLock sl (readLock);
  18256. if (source != 0)
  18257. {
  18258. AudioSourceChannelInfo info;
  18259. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18260. // messy stuff needed to compact the channels down into an array
  18261. // of non-zero pointers..
  18262. for (i = 0; i < totalNumInputChannels; ++i)
  18263. {
  18264. if (inputChannelData[i] != 0)
  18265. {
  18266. inputChans [numInputs++] = inputChannelData[i];
  18267. if (numInputs >= numElementsInArray (inputChans))
  18268. break;
  18269. }
  18270. }
  18271. for (i = 0; i < totalNumOutputChannels; ++i)
  18272. {
  18273. if (outputChannelData[i] != 0)
  18274. {
  18275. outputChans [numOutputs++] = outputChannelData[i];
  18276. if (numOutputs >= numElementsInArray (outputChans))
  18277. break;
  18278. }
  18279. }
  18280. if (numInputs > numOutputs)
  18281. {
  18282. // if there aren't enough output channels for the number of
  18283. // inputs, we need to create some temporary extra ones (can't
  18284. // use the input data in case it gets written to)
  18285. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18286. false, false, true);
  18287. for (i = 0; i < numOutputs; ++i)
  18288. {
  18289. channels[numActiveChans] = outputChans[i];
  18290. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18291. ++numActiveChans;
  18292. }
  18293. for (i = numOutputs; i < numInputs; ++i)
  18294. {
  18295. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18296. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18297. ++numActiveChans;
  18298. }
  18299. }
  18300. else
  18301. {
  18302. for (i = 0; i < numInputs; ++i)
  18303. {
  18304. channels[numActiveChans] = outputChans[i];
  18305. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18306. ++numActiveChans;
  18307. }
  18308. for (i = numInputs; i < numOutputs; ++i)
  18309. {
  18310. channels[numActiveChans] = outputChans[i];
  18311. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18312. ++numActiveChans;
  18313. }
  18314. }
  18315. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18316. info.buffer = &buffer;
  18317. info.startSample = 0;
  18318. info.numSamples = numSamples;
  18319. source->getNextAudioBlock (info);
  18320. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18321. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18322. lastGain = gain;
  18323. }
  18324. else
  18325. {
  18326. for (int i = 0; i < totalNumOutputChannels; ++i)
  18327. if (outputChannelData[i] != 0)
  18328. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18329. }
  18330. }
  18331. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18332. {
  18333. sampleRate = device->getCurrentSampleRate();
  18334. bufferSize = device->getCurrentBufferSizeSamples();
  18335. zeromem (channels, sizeof (channels));
  18336. if (source != 0)
  18337. source->prepareToPlay (bufferSize, sampleRate);
  18338. }
  18339. void AudioSourcePlayer::audioDeviceStopped()
  18340. {
  18341. if (source != 0)
  18342. source->releaseResources();
  18343. sampleRate = 0.0;
  18344. bufferSize = 0;
  18345. tempBuffer.setSize (2, 8);
  18346. }
  18347. END_JUCE_NAMESPACE
  18348. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18349. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18350. BEGIN_JUCE_NAMESPACE
  18351. AudioTransportSource::AudioTransportSource()
  18352. : source (0),
  18353. resamplerSource (0),
  18354. bufferingSource (0),
  18355. positionableSource (0),
  18356. masterSource (0),
  18357. gain (1.0f),
  18358. lastGain (1.0f),
  18359. playing (false),
  18360. stopped (true),
  18361. sampleRate (44100.0),
  18362. sourceSampleRate (0.0),
  18363. blockSize (128),
  18364. readAheadBufferSize (0),
  18365. isPrepared (false),
  18366. inputStreamEOF (false)
  18367. {
  18368. }
  18369. AudioTransportSource::~AudioTransportSource()
  18370. {
  18371. setSource (0);
  18372. releaseResources();
  18373. }
  18374. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18375. int readAheadBufferSize_,
  18376. double sourceSampleRateToCorrectFor)
  18377. {
  18378. if (source == newSource)
  18379. {
  18380. if (source == 0)
  18381. return;
  18382. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18383. }
  18384. readAheadBufferSize = readAheadBufferSize_;
  18385. sourceSampleRate = sourceSampleRateToCorrectFor;
  18386. ResamplingAudioSource* newResamplerSource = 0;
  18387. BufferingAudioSource* newBufferingSource = 0;
  18388. PositionableAudioSource* newPositionableSource = 0;
  18389. AudioSource* newMasterSource = 0;
  18390. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18391. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18392. AudioSource* oldMasterSource = masterSource;
  18393. if (newSource != 0)
  18394. {
  18395. newPositionableSource = newSource;
  18396. if (readAheadBufferSize_ > 0)
  18397. newPositionableSource = newBufferingSource
  18398. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18399. newPositionableSource->setNextReadPosition (0);
  18400. if (sourceSampleRateToCorrectFor != 0)
  18401. newMasterSource = newResamplerSource
  18402. = new ResamplingAudioSource (newPositionableSource, false);
  18403. else
  18404. newMasterSource = newPositionableSource;
  18405. if (isPrepared)
  18406. {
  18407. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18408. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18409. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18410. }
  18411. }
  18412. {
  18413. const ScopedLock sl (callbackLock);
  18414. source = newSource;
  18415. resamplerSource = newResamplerSource;
  18416. bufferingSource = newBufferingSource;
  18417. masterSource = newMasterSource;
  18418. positionableSource = newPositionableSource;
  18419. playing = false;
  18420. }
  18421. if (oldMasterSource != 0)
  18422. oldMasterSource->releaseResources();
  18423. }
  18424. void AudioTransportSource::start()
  18425. {
  18426. if ((! playing) && masterSource != 0)
  18427. {
  18428. {
  18429. const ScopedLock sl (callbackLock);
  18430. playing = true;
  18431. stopped = false;
  18432. inputStreamEOF = false;
  18433. }
  18434. sendChangeMessage (this);
  18435. }
  18436. }
  18437. void AudioTransportSource::stop()
  18438. {
  18439. if (playing)
  18440. {
  18441. {
  18442. const ScopedLock sl (callbackLock);
  18443. playing = false;
  18444. }
  18445. int n = 500;
  18446. while (--n >= 0 && ! stopped)
  18447. Thread::sleep (2);
  18448. sendChangeMessage (this);
  18449. }
  18450. }
  18451. void AudioTransportSource::setPosition (double newPosition)
  18452. {
  18453. if (sampleRate > 0.0)
  18454. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18455. }
  18456. double AudioTransportSource::getCurrentPosition() const
  18457. {
  18458. if (sampleRate > 0.0)
  18459. return getNextReadPosition() / sampleRate;
  18460. else
  18461. return 0.0;
  18462. }
  18463. void AudioTransportSource::setNextReadPosition (int newPosition)
  18464. {
  18465. if (positionableSource != 0)
  18466. {
  18467. if (sampleRate > 0 && sourceSampleRate > 0)
  18468. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18469. positionableSource->setNextReadPosition (newPosition);
  18470. }
  18471. }
  18472. int AudioTransportSource::getNextReadPosition() const
  18473. {
  18474. if (positionableSource != 0)
  18475. {
  18476. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18477. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18478. }
  18479. return 0;
  18480. }
  18481. int AudioTransportSource::getTotalLength() const
  18482. {
  18483. const ScopedLock sl (callbackLock);
  18484. if (positionableSource != 0)
  18485. {
  18486. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18487. return roundToInt (positionableSource->getTotalLength() * ratio);
  18488. }
  18489. return 0;
  18490. }
  18491. bool AudioTransportSource::isLooping() const
  18492. {
  18493. const ScopedLock sl (callbackLock);
  18494. return positionableSource != 0
  18495. && positionableSource->isLooping();
  18496. }
  18497. void AudioTransportSource::setGain (const float newGain) throw()
  18498. {
  18499. gain = newGain;
  18500. }
  18501. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18502. double sampleRate_)
  18503. {
  18504. const ScopedLock sl (callbackLock);
  18505. sampleRate = sampleRate_;
  18506. blockSize = samplesPerBlockExpected;
  18507. if (masterSource != 0)
  18508. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18509. if (resamplerSource != 0 && sourceSampleRate != 0)
  18510. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18511. isPrepared = true;
  18512. }
  18513. void AudioTransportSource::releaseResources()
  18514. {
  18515. const ScopedLock sl (callbackLock);
  18516. if (masterSource != 0)
  18517. masterSource->releaseResources();
  18518. isPrepared = false;
  18519. }
  18520. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18521. {
  18522. const ScopedLock sl (callbackLock);
  18523. inputStreamEOF = false;
  18524. if (masterSource != 0 && ! stopped)
  18525. {
  18526. masterSource->getNextAudioBlock (info);
  18527. if (! playing)
  18528. {
  18529. // just stopped playing, so fade out the last block..
  18530. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18531. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18532. if (info.numSamples > 256)
  18533. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18534. }
  18535. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18536. && ! positionableSource->isLooping())
  18537. {
  18538. playing = false;
  18539. inputStreamEOF = true;
  18540. sendChangeMessage (this);
  18541. }
  18542. stopped = ! playing;
  18543. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18544. {
  18545. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18546. lastGain, gain);
  18547. }
  18548. }
  18549. else
  18550. {
  18551. info.clearActiveBufferRegion();
  18552. stopped = true;
  18553. }
  18554. lastGain = gain;
  18555. }
  18556. END_JUCE_NAMESPACE
  18557. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18558. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18559. BEGIN_JUCE_NAMESPACE
  18560. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18561. public Thread,
  18562. private Timer
  18563. {
  18564. public:
  18565. SharedBufferingAudioSourceThread()
  18566. : Thread ("Audio Buffer")
  18567. {
  18568. }
  18569. ~SharedBufferingAudioSourceThread()
  18570. {
  18571. stopThread (10000);
  18572. clearSingletonInstance();
  18573. }
  18574. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18575. void addSource (BufferingAudioSource* source)
  18576. {
  18577. const ScopedLock sl (lock);
  18578. if (! sources.contains (source))
  18579. {
  18580. sources.add (source);
  18581. startThread();
  18582. stopTimer();
  18583. }
  18584. notify();
  18585. }
  18586. void removeSource (BufferingAudioSource* source)
  18587. {
  18588. const ScopedLock sl (lock);
  18589. sources.removeValue (source);
  18590. if (sources.size() == 0)
  18591. startTimer (5000);
  18592. }
  18593. private:
  18594. Array <BufferingAudioSource*> sources;
  18595. CriticalSection lock;
  18596. void run()
  18597. {
  18598. while (! threadShouldExit())
  18599. {
  18600. bool busy = false;
  18601. for (int i = sources.size(); --i >= 0;)
  18602. {
  18603. if (threadShouldExit())
  18604. return;
  18605. const ScopedLock sl (lock);
  18606. BufferingAudioSource* const b = sources[i];
  18607. if (b != 0 && b->readNextBufferChunk())
  18608. busy = true;
  18609. }
  18610. if (! busy)
  18611. wait (500);
  18612. }
  18613. }
  18614. void timerCallback()
  18615. {
  18616. stopTimer();
  18617. if (sources.size() == 0)
  18618. deleteInstance();
  18619. }
  18620. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18621. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18622. };
  18623. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18624. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18625. const bool deleteSourceWhenDeleted_,
  18626. int numberOfSamplesToBuffer_)
  18627. : source (source_),
  18628. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18629. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18630. buffer (2, 0),
  18631. bufferValidStart (0),
  18632. bufferValidEnd (0),
  18633. nextPlayPos (0),
  18634. wasSourceLooping (false)
  18635. {
  18636. jassert (source_ != 0);
  18637. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18638. // not using a larger buffer..
  18639. }
  18640. BufferingAudioSource::~BufferingAudioSource()
  18641. {
  18642. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18643. if (thread != 0)
  18644. thread->removeSource (this);
  18645. if (deleteSourceWhenDeleted)
  18646. delete source;
  18647. }
  18648. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18649. {
  18650. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18651. sampleRate = sampleRate_;
  18652. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18653. buffer.clear();
  18654. bufferValidStart = 0;
  18655. bufferValidEnd = 0;
  18656. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18657. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18658. buffer.getNumSamples() / 2))
  18659. {
  18660. SharedBufferingAudioSourceThread::getInstance()->notify();
  18661. Thread::sleep (5);
  18662. }
  18663. }
  18664. void BufferingAudioSource::releaseResources()
  18665. {
  18666. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18667. if (thread != 0)
  18668. thread->removeSource (this);
  18669. buffer.setSize (2, 0);
  18670. source->releaseResources();
  18671. }
  18672. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18673. {
  18674. const ScopedLock sl (bufferStartPosLock);
  18675. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18676. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18677. if (validStart == validEnd)
  18678. {
  18679. // total cache miss
  18680. info.clearActiveBufferRegion();
  18681. }
  18682. else
  18683. {
  18684. if (validStart > 0)
  18685. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18686. if (validEnd < info.numSamples)
  18687. info.buffer->clear (info.startSample + validEnd,
  18688. info.numSamples - validEnd); // partial cache miss at end
  18689. if (validStart < validEnd)
  18690. {
  18691. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18692. {
  18693. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18694. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18695. if (startBufferIndex < endBufferIndex)
  18696. {
  18697. info.buffer->copyFrom (chan, info.startSample + validStart,
  18698. buffer,
  18699. chan, startBufferIndex,
  18700. validEnd - validStart);
  18701. }
  18702. else
  18703. {
  18704. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18705. info.buffer->copyFrom (chan, info.startSample + validStart,
  18706. buffer,
  18707. chan, startBufferIndex,
  18708. initialSize);
  18709. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18710. buffer,
  18711. chan, 0,
  18712. (validEnd - validStart) - initialSize);
  18713. }
  18714. }
  18715. }
  18716. nextPlayPos += info.numSamples;
  18717. if (source->isLooping() && nextPlayPos > 0)
  18718. nextPlayPos %= source->getTotalLength();
  18719. }
  18720. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18721. if (thread != 0)
  18722. thread->notify();
  18723. }
  18724. int BufferingAudioSource::getNextReadPosition() const
  18725. {
  18726. return (source->isLooping() && nextPlayPos > 0)
  18727. ? nextPlayPos % source->getTotalLength()
  18728. : nextPlayPos;
  18729. }
  18730. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18731. {
  18732. const ScopedLock sl (bufferStartPosLock);
  18733. nextPlayPos = newPosition;
  18734. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18735. if (thread != 0)
  18736. thread->notify();
  18737. }
  18738. bool BufferingAudioSource::readNextBufferChunk()
  18739. {
  18740. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18741. {
  18742. const ScopedLock sl (bufferStartPosLock);
  18743. if (wasSourceLooping != isLooping())
  18744. {
  18745. wasSourceLooping = isLooping();
  18746. bufferValidStart = 0;
  18747. bufferValidEnd = 0;
  18748. }
  18749. newBVS = jmax (0, nextPlayPos);
  18750. newBVE = newBVS + buffer.getNumSamples() - 4;
  18751. sectionToReadStart = 0;
  18752. sectionToReadEnd = 0;
  18753. const int maxChunkSize = 2048;
  18754. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18755. {
  18756. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18757. sectionToReadStart = newBVS;
  18758. sectionToReadEnd = newBVE;
  18759. bufferValidStart = 0;
  18760. bufferValidEnd = 0;
  18761. }
  18762. else if (abs (newBVS - bufferValidStart) > 512
  18763. || abs (newBVE - bufferValidEnd) > 512)
  18764. {
  18765. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18766. sectionToReadStart = bufferValidEnd;
  18767. sectionToReadEnd = newBVE;
  18768. bufferValidStart = newBVS;
  18769. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18770. }
  18771. }
  18772. if (sectionToReadStart != sectionToReadEnd)
  18773. {
  18774. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18775. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18776. if (bufferIndexStart < bufferIndexEnd)
  18777. {
  18778. readBufferSection (sectionToReadStart,
  18779. sectionToReadEnd - sectionToReadStart,
  18780. bufferIndexStart);
  18781. }
  18782. else
  18783. {
  18784. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18785. readBufferSection (sectionToReadStart,
  18786. initialSize,
  18787. bufferIndexStart);
  18788. readBufferSection (sectionToReadStart + initialSize,
  18789. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18790. 0);
  18791. }
  18792. const ScopedLock sl2 (bufferStartPosLock);
  18793. bufferValidStart = newBVS;
  18794. bufferValidEnd = newBVE;
  18795. return true;
  18796. }
  18797. else
  18798. {
  18799. return false;
  18800. }
  18801. }
  18802. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18803. {
  18804. if (source->getNextReadPosition() != start)
  18805. source->setNextReadPosition (start);
  18806. AudioSourceChannelInfo info;
  18807. info.buffer = &buffer;
  18808. info.startSample = bufferOffset;
  18809. info.numSamples = length;
  18810. source->getNextAudioBlock (info);
  18811. }
  18812. END_JUCE_NAMESPACE
  18813. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18814. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18815. BEGIN_JUCE_NAMESPACE
  18816. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18817. const bool deleteSourceWhenDeleted_)
  18818. : requiredNumberOfChannels (2),
  18819. source (source_),
  18820. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18821. buffer (2, 16)
  18822. {
  18823. remappedInfo.buffer = &buffer;
  18824. remappedInfo.startSample = 0;
  18825. }
  18826. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18827. {
  18828. if (deleteSourceWhenDeleted)
  18829. delete source;
  18830. }
  18831. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18832. {
  18833. const ScopedLock sl (lock);
  18834. requiredNumberOfChannels = requiredNumberOfChannels_;
  18835. }
  18836. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18837. {
  18838. const ScopedLock sl (lock);
  18839. remappedInputs.clear();
  18840. remappedOutputs.clear();
  18841. }
  18842. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18843. {
  18844. const ScopedLock sl (lock);
  18845. while (remappedInputs.size() < destIndex)
  18846. remappedInputs.add (-1);
  18847. remappedInputs.set (destIndex, sourceIndex);
  18848. }
  18849. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18850. {
  18851. const ScopedLock sl (lock);
  18852. while (remappedOutputs.size() < sourceIndex)
  18853. remappedOutputs.add (-1);
  18854. remappedOutputs.set (sourceIndex, destIndex);
  18855. }
  18856. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18857. {
  18858. const ScopedLock sl (lock);
  18859. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18860. return remappedInputs.getUnchecked (inputChannelIndex);
  18861. return -1;
  18862. }
  18863. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18864. {
  18865. const ScopedLock sl (lock);
  18866. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18867. return remappedOutputs .getUnchecked (outputChannelIndex);
  18868. return -1;
  18869. }
  18870. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18871. {
  18872. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18873. }
  18874. void ChannelRemappingAudioSource::releaseResources()
  18875. {
  18876. source->releaseResources();
  18877. }
  18878. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18879. {
  18880. const ScopedLock sl (lock);
  18881. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18882. const int numChans = bufferToFill.buffer->getNumChannels();
  18883. int i;
  18884. for (i = 0; i < buffer.getNumChannels(); ++i)
  18885. {
  18886. const int remappedChan = getRemappedInputChannel (i);
  18887. if (remappedChan >= 0 && remappedChan < numChans)
  18888. {
  18889. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18890. remappedChan,
  18891. bufferToFill.startSample,
  18892. bufferToFill.numSamples);
  18893. }
  18894. else
  18895. {
  18896. buffer.clear (i, 0, bufferToFill.numSamples);
  18897. }
  18898. }
  18899. remappedInfo.numSamples = bufferToFill.numSamples;
  18900. source->getNextAudioBlock (remappedInfo);
  18901. bufferToFill.clearActiveBufferRegion();
  18902. for (i = 0; i < requiredNumberOfChannels; ++i)
  18903. {
  18904. const int remappedChan = getRemappedOutputChannel (i);
  18905. if (remappedChan >= 0 && remappedChan < numChans)
  18906. {
  18907. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18908. buffer, i, 0, bufferToFill.numSamples);
  18909. }
  18910. }
  18911. }
  18912. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18913. {
  18914. XmlElement* e = new XmlElement ("MAPPINGS");
  18915. String ins, outs;
  18916. int i;
  18917. const ScopedLock sl (lock);
  18918. for (i = 0; i < remappedInputs.size(); ++i)
  18919. ins << remappedInputs.getUnchecked(i) << ' ';
  18920. for (i = 0; i < remappedOutputs.size(); ++i)
  18921. outs << remappedOutputs.getUnchecked(i) << ' ';
  18922. e->setAttribute ("inputs", ins.trimEnd());
  18923. e->setAttribute ("outputs", outs.trimEnd());
  18924. return e;
  18925. }
  18926. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18927. {
  18928. if (e.hasTagName ("MAPPINGS"))
  18929. {
  18930. const ScopedLock sl (lock);
  18931. clearAllMappings();
  18932. StringArray ins, outs;
  18933. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18934. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18935. int i;
  18936. for (i = 0; i < ins.size(); ++i)
  18937. remappedInputs.add (ins[i].getIntValue());
  18938. for (i = 0; i < outs.size(); ++i)
  18939. remappedOutputs.add (outs[i].getIntValue());
  18940. }
  18941. }
  18942. END_JUCE_NAMESPACE
  18943. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18944. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18945. BEGIN_JUCE_NAMESPACE
  18946. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18947. const bool deleteInputWhenDeleted_)
  18948. : input (inputSource),
  18949. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18950. {
  18951. jassert (inputSource != 0);
  18952. for (int i = 2; --i >= 0;)
  18953. iirFilters.add (new IIRFilter());
  18954. }
  18955. IIRFilterAudioSource::~IIRFilterAudioSource()
  18956. {
  18957. if (deleteInputWhenDeleted)
  18958. delete input;
  18959. }
  18960. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18961. {
  18962. for (int i = iirFilters.size(); --i >= 0;)
  18963. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18964. }
  18965. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18966. {
  18967. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18968. for (int i = iirFilters.size(); --i >= 0;)
  18969. iirFilters.getUnchecked(i)->reset();
  18970. }
  18971. void IIRFilterAudioSource::releaseResources()
  18972. {
  18973. input->releaseResources();
  18974. }
  18975. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18976. {
  18977. input->getNextAudioBlock (bufferToFill);
  18978. const int numChannels = bufferToFill.buffer->getNumChannels();
  18979. while (numChannels > iirFilters.size())
  18980. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18981. for (int i = 0; i < numChannels; ++i)
  18982. iirFilters.getUnchecked(i)
  18983. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18984. bufferToFill.numSamples);
  18985. }
  18986. END_JUCE_NAMESPACE
  18987. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18988. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18989. BEGIN_JUCE_NAMESPACE
  18990. MixerAudioSource::MixerAudioSource()
  18991. : tempBuffer (2, 0),
  18992. currentSampleRate (0.0),
  18993. bufferSizeExpected (0)
  18994. {
  18995. }
  18996. MixerAudioSource::~MixerAudioSource()
  18997. {
  18998. removeAllInputs();
  18999. }
  19000. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19001. {
  19002. if (input != 0 && ! inputs.contains (input))
  19003. {
  19004. double localRate;
  19005. int localBufferSize;
  19006. {
  19007. const ScopedLock sl (lock);
  19008. localRate = currentSampleRate;
  19009. localBufferSize = bufferSizeExpected;
  19010. }
  19011. if (localRate != 0.0)
  19012. input->prepareToPlay (localBufferSize, localRate);
  19013. const ScopedLock sl (lock);
  19014. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19015. inputs.add (input);
  19016. }
  19017. }
  19018. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19019. {
  19020. if (input != 0)
  19021. {
  19022. int index;
  19023. {
  19024. const ScopedLock sl (lock);
  19025. index = inputs.indexOf (input);
  19026. if (index >= 0)
  19027. {
  19028. inputsToDelete.shiftBits (index, 1);
  19029. inputs.remove (index);
  19030. }
  19031. }
  19032. if (index >= 0)
  19033. {
  19034. input->releaseResources();
  19035. if (deleteInput)
  19036. delete input;
  19037. }
  19038. }
  19039. }
  19040. void MixerAudioSource::removeAllInputs()
  19041. {
  19042. OwnedArray<AudioSource> toDelete;
  19043. {
  19044. const ScopedLock sl (lock);
  19045. for (int i = inputs.size(); --i >= 0;)
  19046. if (inputsToDelete[i])
  19047. toDelete.add (inputs.getUnchecked(i));
  19048. }
  19049. }
  19050. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19051. {
  19052. tempBuffer.setSize (2, samplesPerBlockExpected);
  19053. const ScopedLock sl (lock);
  19054. currentSampleRate = sampleRate;
  19055. bufferSizeExpected = samplesPerBlockExpected;
  19056. for (int i = inputs.size(); --i >= 0;)
  19057. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19058. }
  19059. void MixerAudioSource::releaseResources()
  19060. {
  19061. const ScopedLock sl (lock);
  19062. for (int i = inputs.size(); --i >= 0;)
  19063. inputs.getUnchecked(i)->releaseResources();
  19064. tempBuffer.setSize (2, 0);
  19065. currentSampleRate = 0;
  19066. bufferSizeExpected = 0;
  19067. }
  19068. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19069. {
  19070. const ScopedLock sl (lock);
  19071. if (inputs.size() > 0)
  19072. {
  19073. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19074. if (inputs.size() > 1)
  19075. {
  19076. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19077. info.buffer->getNumSamples());
  19078. AudioSourceChannelInfo info2;
  19079. info2.buffer = &tempBuffer;
  19080. info2.numSamples = info.numSamples;
  19081. info2.startSample = 0;
  19082. for (int i = 1; i < inputs.size(); ++i)
  19083. {
  19084. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19085. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19086. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19087. }
  19088. }
  19089. }
  19090. else
  19091. {
  19092. info.clearActiveBufferRegion();
  19093. }
  19094. }
  19095. END_JUCE_NAMESPACE
  19096. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19097. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19098. BEGIN_JUCE_NAMESPACE
  19099. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19100. const bool deleteInputWhenDeleted_,
  19101. const int numChannels_)
  19102. : input (inputSource),
  19103. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19104. ratio (1.0),
  19105. lastRatio (1.0),
  19106. buffer (numChannels_, 0),
  19107. sampsInBuffer (0),
  19108. numChannels (numChannels_)
  19109. {
  19110. jassert (input != 0);
  19111. }
  19112. ResamplingAudioSource::~ResamplingAudioSource()
  19113. {
  19114. if (deleteInputWhenDeleted)
  19115. delete input;
  19116. }
  19117. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19118. {
  19119. jassert (samplesInPerOutputSample > 0);
  19120. const ScopedLock sl (ratioLock);
  19121. ratio = jmax (0.0, samplesInPerOutputSample);
  19122. }
  19123. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19124. double sampleRate)
  19125. {
  19126. const ScopedLock sl (ratioLock);
  19127. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19128. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19129. buffer.clear();
  19130. sampsInBuffer = 0;
  19131. bufferPos = 0;
  19132. subSampleOffset = 0.0;
  19133. filterStates.calloc (numChannels);
  19134. srcBuffers.calloc (numChannels);
  19135. destBuffers.calloc (numChannels);
  19136. createLowPass (ratio);
  19137. resetFilters();
  19138. }
  19139. void ResamplingAudioSource::releaseResources()
  19140. {
  19141. input->releaseResources();
  19142. buffer.setSize (numChannels, 0);
  19143. }
  19144. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19145. {
  19146. const ScopedLock sl (ratioLock);
  19147. if (lastRatio != ratio)
  19148. {
  19149. createLowPass (ratio);
  19150. lastRatio = ratio;
  19151. }
  19152. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19153. int bufferSize = buffer.getNumSamples();
  19154. if (bufferSize < sampsNeeded + 8)
  19155. {
  19156. bufferPos %= bufferSize;
  19157. bufferSize = sampsNeeded + 32;
  19158. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19159. }
  19160. bufferPos %= bufferSize;
  19161. int endOfBufferPos = bufferPos + sampsInBuffer;
  19162. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19163. while (sampsNeeded > sampsInBuffer)
  19164. {
  19165. endOfBufferPos %= bufferSize;
  19166. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19167. bufferSize - endOfBufferPos);
  19168. AudioSourceChannelInfo readInfo;
  19169. readInfo.buffer = &buffer;
  19170. readInfo.numSamples = numToDo;
  19171. readInfo.startSample = endOfBufferPos;
  19172. input->getNextAudioBlock (readInfo);
  19173. if (ratio > 1.0001)
  19174. {
  19175. // for down-sampling, pre-apply the filter..
  19176. for (int i = channelsToProcess; --i >= 0;)
  19177. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19178. }
  19179. sampsInBuffer += numToDo;
  19180. endOfBufferPos += numToDo;
  19181. }
  19182. for (int channel = 0; channel < channelsToProcess; ++channel)
  19183. {
  19184. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19185. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19186. }
  19187. int nextPos = (bufferPos + 1) % bufferSize;
  19188. for (int m = info.numSamples; --m >= 0;)
  19189. {
  19190. const float alpha = (float) subSampleOffset;
  19191. const float invAlpha = 1.0f - alpha;
  19192. for (int channel = 0; channel < channelsToProcess; ++channel)
  19193. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19194. subSampleOffset += ratio;
  19195. jassert (sampsInBuffer > 0);
  19196. while (subSampleOffset >= 1.0)
  19197. {
  19198. if (++bufferPos >= bufferSize)
  19199. bufferPos = 0;
  19200. --sampsInBuffer;
  19201. nextPos = (bufferPos + 1) % bufferSize;
  19202. subSampleOffset -= 1.0;
  19203. }
  19204. }
  19205. if (ratio < 0.9999)
  19206. {
  19207. // for up-sampling, apply the filter after transposing..
  19208. for (int i = channelsToProcess; --i >= 0;)
  19209. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19210. }
  19211. else if (ratio <= 1.0001)
  19212. {
  19213. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19214. for (int i = channelsToProcess; --i >= 0;)
  19215. {
  19216. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19217. FilterState& fs = filterStates[i];
  19218. if (info.numSamples > 1)
  19219. {
  19220. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19221. }
  19222. else
  19223. {
  19224. fs.y2 = fs.y1;
  19225. fs.x2 = fs.x1;
  19226. }
  19227. fs.y1 = fs.x1 = *endOfBuffer;
  19228. }
  19229. }
  19230. jassert (sampsInBuffer >= 0);
  19231. }
  19232. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19233. {
  19234. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19235. : 0.5 * frequencyRatio;
  19236. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19237. const double nSquared = n * n;
  19238. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19239. setFilterCoefficients (c1,
  19240. c1 * 2.0f,
  19241. c1,
  19242. 1.0,
  19243. c1 * 2.0 * (1.0 - nSquared),
  19244. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19245. }
  19246. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19247. {
  19248. const double a = 1.0 / c4;
  19249. c1 *= a;
  19250. c2 *= a;
  19251. c3 *= a;
  19252. c5 *= a;
  19253. c6 *= a;
  19254. coefficients[0] = c1;
  19255. coefficients[1] = c2;
  19256. coefficients[2] = c3;
  19257. coefficients[3] = c4;
  19258. coefficients[4] = c5;
  19259. coefficients[5] = c6;
  19260. }
  19261. void ResamplingAudioSource::resetFilters()
  19262. {
  19263. zeromem (filterStates, sizeof (FilterState) * numChannels);
  19264. }
  19265. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19266. {
  19267. while (--num >= 0)
  19268. {
  19269. const double in = *samples;
  19270. double out = coefficients[0] * in
  19271. + coefficients[1] * fs.x1
  19272. + coefficients[2] * fs.x2
  19273. - coefficients[4] * fs.y1
  19274. - coefficients[5] * fs.y2;
  19275. #if JUCE_INTEL
  19276. if (! (out < -1.0e-8 || out > 1.0e-8))
  19277. out = 0;
  19278. #endif
  19279. fs.x2 = fs.x1;
  19280. fs.x1 = in;
  19281. fs.y2 = fs.y1;
  19282. fs.y1 = out;
  19283. *samples++ = (float) out;
  19284. }
  19285. }
  19286. END_JUCE_NAMESPACE
  19287. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19288. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19289. BEGIN_JUCE_NAMESPACE
  19290. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19291. : frequency (1000.0),
  19292. sampleRate (44100.0),
  19293. currentPhase (0.0),
  19294. phasePerSample (0.0),
  19295. amplitude (0.5f)
  19296. {
  19297. }
  19298. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19299. {
  19300. }
  19301. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19302. {
  19303. amplitude = newAmplitude;
  19304. }
  19305. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19306. {
  19307. frequency = newFrequencyHz;
  19308. phasePerSample = 0.0;
  19309. }
  19310. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19311. double sampleRate_)
  19312. {
  19313. currentPhase = 0.0;
  19314. phasePerSample = 0.0;
  19315. sampleRate = sampleRate_;
  19316. }
  19317. void ToneGeneratorAudioSource::releaseResources()
  19318. {
  19319. }
  19320. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19321. {
  19322. if (phasePerSample == 0.0)
  19323. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19324. for (int i = 0; i < info.numSamples; ++i)
  19325. {
  19326. const float sample = amplitude * (float) std::sin (currentPhase);
  19327. currentPhase += phasePerSample;
  19328. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19329. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19330. }
  19331. }
  19332. END_JUCE_NAMESPACE
  19333. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19334. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19335. BEGIN_JUCE_NAMESPACE
  19336. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19337. : sampleRate (0),
  19338. bufferSize (0),
  19339. useDefaultInputChannels (true),
  19340. useDefaultOutputChannels (true)
  19341. {
  19342. }
  19343. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19344. {
  19345. return outputDeviceName == other.outputDeviceName
  19346. && inputDeviceName == other.inputDeviceName
  19347. && sampleRate == other.sampleRate
  19348. && bufferSize == other.bufferSize
  19349. && inputChannels == other.inputChannels
  19350. && useDefaultInputChannels == other.useDefaultInputChannels
  19351. && outputChannels == other.outputChannels
  19352. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19353. }
  19354. AudioDeviceManager::AudioDeviceManager()
  19355. : currentAudioDevice (0),
  19356. numInputChansNeeded (0),
  19357. numOutputChansNeeded (2),
  19358. listNeedsScanning (true),
  19359. useInputNames (false),
  19360. inputLevelMeasurementEnabledCount (0),
  19361. inputLevel (0),
  19362. tempBuffer (2, 2),
  19363. defaultMidiOutput (0),
  19364. cpuUsageMs (0),
  19365. timeToCpuScale (0)
  19366. {
  19367. callbackHandler.owner = this;
  19368. }
  19369. AudioDeviceManager::~AudioDeviceManager()
  19370. {
  19371. currentAudioDevice = 0;
  19372. defaultMidiOutput = 0;
  19373. }
  19374. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19375. {
  19376. if (availableDeviceTypes.size() == 0)
  19377. {
  19378. createAudioDeviceTypes (availableDeviceTypes);
  19379. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19380. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19381. if (availableDeviceTypes.size() > 0)
  19382. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19383. }
  19384. }
  19385. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19386. {
  19387. scanDevicesIfNeeded();
  19388. return availableDeviceTypes;
  19389. }
  19390. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19391. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19392. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19393. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19394. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19395. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19396. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19397. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19398. {
  19399. (void) list; // (to avoid 'unused param' warnings)
  19400. #if JUCE_WINDOWS
  19401. #if JUCE_WASAPI
  19402. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19403. list.add (juce_createAudioIODeviceType_WASAPI());
  19404. #endif
  19405. #if JUCE_DIRECTSOUND
  19406. list.add (juce_createAudioIODeviceType_DirectSound());
  19407. #endif
  19408. #if JUCE_ASIO
  19409. list.add (juce_createAudioIODeviceType_ASIO());
  19410. #endif
  19411. #endif
  19412. #if JUCE_MAC
  19413. list.add (juce_createAudioIODeviceType_CoreAudio());
  19414. #endif
  19415. #if JUCE_IOS
  19416. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19417. #endif
  19418. #if JUCE_LINUX && JUCE_ALSA
  19419. list.add (juce_createAudioIODeviceType_ALSA());
  19420. #endif
  19421. #if JUCE_LINUX && JUCE_JACK
  19422. list.add (juce_createAudioIODeviceType_JACK());
  19423. #endif
  19424. }
  19425. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19426. const int numOutputChannelsNeeded,
  19427. const XmlElement* const e,
  19428. const bool selectDefaultDeviceOnFailure,
  19429. const String& preferredDefaultDeviceName,
  19430. const AudioDeviceSetup* preferredSetupOptions)
  19431. {
  19432. scanDevicesIfNeeded();
  19433. numInputChansNeeded = numInputChannelsNeeded;
  19434. numOutputChansNeeded = numOutputChannelsNeeded;
  19435. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19436. {
  19437. lastExplicitSettings = new XmlElement (*e);
  19438. String error;
  19439. AudioDeviceSetup setup;
  19440. if (preferredSetupOptions != 0)
  19441. setup = *preferredSetupOptions;
  19442. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19443. {
  19444. setup.inputDeviceName = setup.outputDeviceName
  19445. = e->getStringAttribute ("audioDeviceName");
  19446. }
  19447. else
  19448. {
  19449. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19450. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19451. }
  19452. currentDeviceType = e->getStringAttribute ("deviceType");
  19453. if (currentDeviceType.isEmpty())
  19454. {
  19455. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19456. if (type != 0)
  19457. currentDeviceType = type->getTypeName();
  19458. else if (availableDeviceTypes.size() > 0)
  19459. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19460. }
  19461. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19462. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19463. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19464. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19465. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19466. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19467. error = setAudioDeviceSetup (setup, true);
  19468. midiInsFromXml.clear();
  19469. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19470. midiInsFromXml.add (c->getStringAttribute ("name"));
  19471. const StringArray allMidiIns (MidiInput::getDevices());
  19472. for (int i = allMidiIns.size(); --i >= 0;)
  19473. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19474. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19475. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19476. false, preferredDefaultDeviceName);
  19477. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19478. return error;
  19479. }
  19480. else
  19481. {
  19482. AudioDeviceSetup setup;
  19483. if (preferredSetupOptions != 0)
  19484. {
  19485. setup = *preferredSetupOptions;
  19486. }
  19487. else if (preferredDefaultDeviceName.isNotEmpty())
  19488. {
  19489. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19490. {
  19491. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19492. StringArray outs (type->getDeviceNames (false));
  19493. int i;
  19494. for (i = 0; i < outs.size(); ++i)
  19495. {
  19496. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19497. {
  19498. setup.outputDeviceName = outs[i];
  19499. break;
  19500. }
  19501. }
  19502. StringArray ins (type->getDeviceNames (true));
  19503. for (i = 0; i < ins.size(); ++i)
  19504. {
  19505. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19506. {
  19507. setup.inputDeviceName = ins[i];
  19508. break;
  19509. }
  19510. }
  19511. }
  19512. }
  19513. insertDefaultDeviceNames (setup);
  19514. return setAudioDeviceSetup (setup, false);
  19515. }
  19516. }
  19517. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19518. {
  19519. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19520. if (type != 0)
  19521. {
  19522. if (setup.outputDeviceName.isEmpty())
  19523. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19524. if (setup.inputDeviceName.isEmpty())
  19525. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19526. }
  19527. }
  19528. XmlElement* AudioDeviceManager::createStateXml() const
  19529. {
  19530. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19531. }
  19532. void AudioDeviceManager::scanDevicesIfNeeded()
  19533. {
  19534. if (listNeedsScanning)
  19535. {
  19536. listNeedsScanning = false;
  19537. createDeviceTypesIfNeeded();
  19538. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19539. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19540. }
  19541. }
  19542. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19543. {
  19544. scanDevicesIfNeeded();
  19545. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19546. {
  19547. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19548. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19549. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19550. {
  19551. return type;
  19552. }
  19553. }
  19554. return 0;
  19555. }
  19556. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19557. {
  19558. setup = currentSetup;
  19559. }
  19560. void AudioDeviceManager::deleteCurrentDevice()
  19561. {
  19562. currentAudioDevice = 0;
  19563. currentSetup.inputDeviceName = String::empty;
  19564. currentSetup.outputDeviceName = String::empty;
  19565. }
  19566. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19567. const bool treatAsChosenDevice)
  19568. {
  19569. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19570. {
  19571. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19572. && currentDeviceType != type)
  19573. {
  19574. currentDeviceType = type;
  19575. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19576. insertDefaultDeviceNames (s);
  19577. setAudioDeviceSetup (s, treatAsChosenDevice);
  19578. sendChangeMessage (this);
  19579. break;
  19580. }
  19581. }
  19582. }
  19583. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19584. {
  19585. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19586. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19587. return availableDeviceTypes[i];
  19588. return availableDeviceTypes[0];
  19589. }
  19590. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19591. const bool treatAsChosenDevice)
  19592. {
  19593. jassert (&newSetup != &currentSetup); // this will have no effect
  19594. if (newSetup == currentSetup && currentAudioDevice != 0)
  19595. return String::empty;
  19596. if (! (newSetup == currentSetup))
  19597. sendChangeMessage (this);
  19598. stopDevice();
  19599. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19600. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19601. String error;
  19602. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19603. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19604. {
  19605. deleteCurrentDevice();
  19606. if (treatAsChosenDevice)
  19607. updateXml();
  19608. return String::empty;
  19609. }
  19610. if (currentSetup.inputDeviceName != newInputDeviceName
  19611. || currentSetup.outputDeviceName != newOutputDeviceName
  19612. || currentAudioDevice == 0)
  19613. {
  19614. deleteCurrentDevice();
  19615. scanDevicesIfNeeded();
  19616. if (newOutputDeviceName.isNotEmpty()
  19617. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19618. {
  19619. return "No such device: " + newOutputDeviceName;
  19620. }
  19621. if (newInputDeviceName.isNotEmpty()
  19622. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19623. {
  19624. return "No such device: " + newInputDeviceName;
  19625. }
  19626. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19627. if (currentAudioDevice == 0)
  19628. 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!";
  19629. else
  19630. error = currentAudioDevice->getLastError();
  19631. if (error.isNotEmpty())
  19632. {
  19633. deleteCurrentDevice();
  19634. return error;
  19635. }
  19636. if (newSetup.useDefaultInputChannels)
  19637. {
  19638. inputChannels.clear();
  19639. inputChannels.setRange (0, numInputChansNeeded, true);
  19640. }
  19641. if (newSetup.useDefaultOutputChannels)
  19642. {
  19643. outputChannels.clear();
  19644. outputChannels.setRange (0, numOutputChansNeeded, true);
  19645. }
  19646. if (newInputDeviceName.isEmpty())
  19647. inputChannels.clear();
  19648. if (newOutputDeviceName.isEmpty())
  19649. outputChannels.clear();
  19650. }
  19651. if (! newSetup.useDefaultInputChannels)
  19652. inputChannels = newSetup.inputChannels;
  19653. if (! newSetup.useDefaultOutputChannels)
  19654. outputChannels = newSetup.outputChannels;
  19655. currentSetup = newSetup;
  19656. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19657. error = currentAudioDevice->open (inputChannels,
  19658. outputChannels,
  19659. currentSetup.sampleRate,
  19660. currentSetup.bufferSize);
  19661. if (error.isEmpty())
  19662. {
  19663. currentDeviceType = currentAudioDevice->getTypeName();
  19664. currentAudioDevice->start (&callbackHandler);
  19665. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19666. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19667. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19668. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19669. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19670. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19671. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19672. if (treatAsChosenDevice)
  19673. updateXml();
  19674. }
  19675. else
  19676. {
  19677. deleteCurrentDevice();
  19678. }
  19679. return error;
  19680. }
  19681. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19682. {
  19683. jassert (currentAudioDevice != 0);
  19684. if (rate > 0)
  19685. {
  19686. bool ok = false;
  19687. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19688. {
  19689. const double sr = currentAudioDevice->getSampleRate (i);
  19690. if (sr == rate)
  19691. ok = true;
  19692. }
  19693. if (! ok)
  19694. rate = 0;
  19695. }
  19696. if (rate == 0)
  19697. {
  19698. double lowestAbove44 = 0.0;
  19699. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19700. {
  19701. const double sr = currentAudioDevice->getSampleRate (i);
  19702. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19703. lowestAbove44 = sr;
  19704. }
  19705. if (lowestAbove44 == 0.0)
  19706. rate = currentAudioDevice->getSampleRate (0);
  19707. else
  19708. rate = lowestAbove44;
  19709. }
  19710. return rate;
  19711. }
  19712. void AudioDeviceManager::stopDevice()
  19713. {
  19714. if (currentAudioDevice != 0)
  19715. currentAudioDevice->stop();
  19716. testSound = 0;
  19717. }
  19718. void AudioDeviceManager::closeAudioDevice()
  19719. {
  19720. stopDevice();
  19721. currentAudioDevice = 0;
  19722. }
  19723. void AudioDeviceManager::restartLastAudioDevice()
  19724. {
  19725. if (currentAudioDevice == 0)
  19726. {
  19727. if (currentSetup.inputDeviceName.isEmpty()
  19728. && currentSetup.outputDeviceName.isEmpty())
  19729. {
  19730. // This method will only reload the last device that was running
  19731. // before closeAudioDevice() was called - you need to actually open
  19732. // one first, with setAudioDevice().
  19733. jassertfalse;
  19734. return;
  19735. }
  19736. AudioDeviceSetup s (currentSetup);
  19737. setAudioDeviceSetup (s, false);
  19738. }
  19739. }
  19740. void AudioDeviceManager::updateXml()
  19741. {
  19742. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19743. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19744. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19745. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19746. if (currentAudioDevice != 0)
  19747. {
  19748. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19749. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19750. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19751. if (! currentSetup.useDefaultInputChannels)
  19752. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19753. if (! currentSetup.useDefaultOutputChannels)
  19754. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19755. }
  19756. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19757. {
  19758. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19759. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19760. }
  19761. if (midiInsFromXml.size() > 0)
  19762. {
  19763. // Add any midi devices that have been enabled before, but which aren't currently
  19764. // open because the device has been disconnected.
  19765. const StringArray availableMidiDevices (MidiInput::getDevices());
  19766. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19767. {
  19768. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19769. {
  19770. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19771. m->setAttribute ("name", midiInsFromXml[i]);
  19772. }
  19773. }
  19774. }
  19775. if (defaultMidiOutputName.isNotEmpty())
  19776. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19777. }
  19778. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19779. {
  19780. {
  19781. const ScopedLock sl (audioCallbackLock);
  19782. if (callbacks.contains (newCallback))
  19783. return;
  19784. }
  19785. if (currentAudioDevice != 0 && newCallback != 0)
  19786. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19787. const ScopedLock sl (audioCallbackLock);
  19788. callbacks.add (newCallback);
  19789. }
  19790. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19791. {
  19792. if (callback != 0)
  19793. {
  19794. bool needsDeinitialising = currentAudioDevice != 0;
  19795. {
  19796. const ScopedLock sl (audioCallbackLock);
  19797. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19798. callbacks.removeValue (callback);
  19799. }
  19800. if (needsDeinitialising)
  19801. callback->audioDeviceStopped();
  19802. }
  19803. }
  19804. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19805. int numInputChannels,
  19806. float** outputChannelData,
  19807. int numOutputChannels,
  19808. int numSamples)
  19809. {
  19810. const ScopedLock sl (audioCallbackLock);
  19811. if (inputLevelMeasurementEnabledCount > 0)
  19812. {
  19813. for (int j = 0; j < numSamples; ++j)
  19814. {
  19815. float s = 0;
  19816. for (int i = 0; i < numInputChannels; ++i)
  19817. s += std::abs (inputChannelData[i][j]);
  19818. s /= numInputChannels;
  19819. const double decayFactor = 0.99992;
  19820. if (s > inputLevel)
  19821. inputLevel = s;
  19822. else if (inputLevel > 0.001f)
  19823. inputLevel *= decayFactor;
  19824. else
  19825. inputLevel = 0;
  19826. }
  19827. }
  19828. if (callbacks.size() > 0)
  19829. {
  19830. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19831. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19832. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19833. outputChannelData, numOutputChannels, numSamples);
  19834. float** const tempChans = tempBuffer.getArrayOfChannels();
  19835. for (int i = callbacks.size(); --i > 0;)
  19836. {
  19837. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19838. tempChans, numOutputChannels, numSamples);
  19839. for (int chan = 0; chan < numOutputChannels; ++chan)
  19840. {
  19841. const float* const src = tempChans [chan];
  19842. float* const dst = outputChannelData [chan];
  19843. if (src != 0 && dst != 0)
  19844. for (int j = 0; j < numSamples; ++j)
  19845. dst[j] += src[j];
  19846. }
  19847. }
  19848. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19849. const double filterAmount = 0.2;
  19850. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19851. }
  19852. else
  19853. {
  19854. for (int i = 0; i < numOutputChannels; ++i)
  19855. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19856. }
  19857. if (testSound != 0)
  19858. {
  19859. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19860. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19861. for (int i = 0; i < numOutputChannels; ++i)
  19862. for (int j = 0; j < numSamps; ++j)
  19863. outputChannelData [i][j] += src[j];
  19864. testSoundPosition += numSamps;
  19865. if (testSoundPosition >= testSound->getNumSamples())
  19866. testSound = 0;
  19867. }
  19868. }
  19869. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19870. {
  19871. cpuUsageMs = 0;
  19872. const double sampleRate = device->getCurrentSampleRate();
  19873. const int blockSize = device->getCurrentBufferSizeSamples();
  19874. if (sampleRate > 0.0 && blockSize > 0)
  19875. {
  19876. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19877. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19878. }
  19879. {
  19880. const ScopedLock sl (audioCallbackLock);
  19881. for (int i = callbacks.size(); --i >= 0;)
  19882. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19883. }
  19884. sendChangeMessage (this);
  19885. }
  19886. void AudioDeviceManager::audioDeviceStoppedInt()
  19887. {
  19888. cpuUsageMs = 0;
  19889. timeToCpuScale = 0;
  19890. sendChangeMessage (this);
  19891. const ScopedLock sl (audioCallbackLock);
  19892. for (int i = callbacks.size(); --i >= 0;)
  19893. callbacks.getUnchecked(i)->audioDeviceStopped();
  19894. }
  19895. double AudioDeviceManager::getCpuUsage() const
  19896. {
  19897. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19898. }
  19899. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19900. const bool enabled)
  19901. {
  19902. if (enabled != isMidiInputEnabled (name))
  19903. {
  19904. if (enabled)
  19905. {
  19906. const int index = MidiInput::getDevices().indexOf (name);
  19907. if (index >= 0)
  19908. {
  19909. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19910. if (min != 0)
  19911. {
  19912. enabledMidiInputs.add (min);
  19913. min->start();
  19914. }
  19915. }
  19916. }
  19917. else
  19918. {
  19919. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19920. if (enabledMidiInputs[i]->getName() == name)
  19921. enabledMidiInputs.remove (i);
  19922. }
  19923. updateXml();
  19924. sendChangeMessage (this);
  19925. }
  19926. }
  19927. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19928. {
  19929. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19930. if (enabledMidiInputs[i]->getName() == name)
  19931. return true;
  19932. return false;
  19933. }
  19934. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19935. MidiInputCallback* callback)
  19936. {
  19937. removeMidiInputCallback (name, callback);
  19938. if (name.isEmpty())
  19939. {
  19940. midiCallbacks.add (callback);
  19941. midiCallbackDevices.add (0);
  19942. }
  19943. else
  19944. {
  19945. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19946. {
  19947. if (enabledMidiInputs[i]->getName() == name)
  19948. {
  19949. const ScopedLock sl (midiCallbackLock);
  19950. midiCallbacks.add (callback);
  19951. midiCallbackDevices.add (enabledMidiInputs[i]);
  19952. break;
  19953. }
  19954. }
  19955. }
  19956. }
  19957. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19958. MidiInputCallback* /*callback*/)
  19959. {
  19960. const ScopedLock sl (midiCallbackLock);
  19961. for (int i = midiCallbacks.size(); --i >= 0;)
  19962. {
  19963. String devName;
  19964. if (midiCallbackDevices.getUnchecked(i) != 0)
  19965. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19966. if (devName == name)
  19967. {
  19968. midiCallbacks.remove (i);
  19969. midiCallbackDevices.remove (i);
  19970. }
  19971. }
  19972. }
  19973. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19974. const MidiMessage& message)
  19975. {
  19976. if (! message.isActiveSense())
  19977. {
  19978. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19979. const ScopedLock sl (midiCallbackLock);
  19980. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19981. {
  19982. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19983. if (md == source || (md == 0 && isDefaultSource))
  19984. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19985. }
  19986. }
  19987. }
  19988. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19989. {
  19990. if (defaultMidiOutputName != deviceName)
  19991. {
  19992. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19993. {
  19994. const ScopedLock sl (audioCallbackLock);
  19995. oldCallbacks = callbacks;
  19996. callbacks.clear();
  19997. }
  19998. if (currentAudioDevice != 0)
  19999. for (int i = oldCallbacks.size(); --i >= 0;)
  20000. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20001. defaultMidiOutput = 0;
  20002. defaultMidiOutputName = deviceName;
  20003. if (deviceName.isNotEmpty())
  20004. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20005. if (currentAudioDevice != 0)
  20006. for (int i = oldCallbacks.size(); --i >= 0;)
  20007. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20008. {
  20009. const ScopedLock sl (audioCallbackLock);
  20010. callbacks = oldCallbacks;
  20011. }
  20012. updateXml();
  20013. sendChangeMessage (this);
  20014. }
  20015. }
  20016. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20017. int numInputChannels,
  20018. float** outputChannelData,
  20019. int numOutputChannels,
  20020. int numSamples)
  20021. {
  20022. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20023. }
  20024. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20025. {
  20026. owner->audioDeviceAboutToStartInt (device);
  20027. }
  20028. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20029. {
  20030. owner->audioDeviceStoppedInt();
  20031. }
  20032. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20033. {
  20034. owner->handleIncomingMidiMessageInt (source, message);
  20035. }
  20036. void AudioDeviceManager::playTestSound()
  20037. {
  20038. { // cunningly nested to swap, unlock and delete in that order.
  20039. ScopedPointer <AudioSampleBuffer> oldSound;
  20040. {
  20041. const ScopedLock sl (audioCallbackLock);
  20042. oldSound = testSound;
  20043. }
  20044. }
  20045. testSoundPosition = 0;
  20046. if (currentAudioDevice != 0)
  20047. {
  20048. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20049. const int soundLength = (int) sampleRate;
  20050. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20051. float* samples = newSound->getSampleData (0);
  20052. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20053. const float amplitude = 0.5f;
  20054. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20055. for (int i = 0; i < soundLength; ++i)
  20056. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20057. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20058. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20059. const ScopedLock sl (audioCallbackLock);
  20060. testSound = newSound;
  20061. }
  20062. }
  20063. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20064. {
  20065. const ScopedLock sl (audioCallbackLock);
  20066. if (enableMeasurement)
  20067. ++inputLevelMeasurementEnabledCount;
  20068. else
  20069. --inputLevelMeasurementEnabledCount;
  20070. inputLevel = 0;
  20071. }
  20072. double AudioDeviceManager::getCurrentInputLevel() const
  20073. {
  20074. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20075. return inputLevel;
  20076. }
  20077. END_JUCE_NAMESPACE
  20078. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20079. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20080. BEGIN_JUCE_NAMESPACE
  20081. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20082. : name (deviceName),
  20083. typeName (typeName_)
  20084. {
  20085. }
  20086. AudioIODevice::~AudioIODevice()
  20087. {
  20088. }
  20089. bool AudioIODevice::hasControlPanel() const
  20090. {
  20091. return false;
  20092. }
  20093. bool AudioIODevice::showControlPanel()
  20094. {
  20095. jassertfalse; // this should only be called for devices which return true from
  20096. // their hasControlPanel() method.
  20097. return false;
  20098. }
  20099. END_JUCE_NAMESPACE
  20100. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20101. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20102. BEGIN_JUCE_NAMESPACE
  20103. AudioIODeviceType::AudioIODeviceType (const String& name)
  20104. : typeName (name)
  20105. {
  20106. }
  20107. AudioIODeviceType::~AudioIODeviceType()
  20108. {
  20109. }
  20110. END_JUCE_NAMESPACE
  20111. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20112. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20113. BEGIN_JUCE_NAMESPACE
  20114. MidiOutput::MidiOutput()
  20115. : Thread ("midi out"),
  20116. internal (0),
  20117. firstMessage (0)
  20118. {
  20119. }
  20120. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20121. const double sampleNumber)
  20122. : message (data, len, sampleNumber)
  20123. {
  20124. }
  20125. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20126. const double millisecondCounterToStartAt,
  20127. double samplesPerSecondForBuffer)
  20128. {
  20129. // You've got to call startBackgroundThread() for this to actually work..
  20130. jassert (isThreadRunning());
  20131. // this needs to be a value in the future - RTFM for this method!
  20132. jassert (millisecondCounterToStartAt > 0);
  20133. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20134. MidiBuffer::Iterator i (buffer);
  20135. const uint8* data;
  20136. int len, time;
  20137. while (i.getNextEvent (data, len, time))
  20138. {
  20139. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20140. PendingMessage* const m
  20141. = new PendingMessage (data, len, eventTime);
  20142. const ScopedLock sl (lock);
  20143. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20144. {
  20145. m->next = firstMessage;
  20146. firstMessage = m;
  20147. }
  20148. else
  20149. {
  20150. PendingMessage* mm = firstMessage;
  20151. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20152. mm = mm->next;
  20153. m->next = mm->next;
  20154. mm->next = m;
  20155. }
  20156. }
  20157. notify();
  20158. }
  20159. void MidiOutput::clearAllPendingMessages()
  20160. {
  20161. const ScopedLock sl (lock);
  20162. while (firstMessage != 0)
  20163. {
  20164. PendingMessage* const m = firstMessage;
  20165. firstMessage = firstMessage->next;
  20166. delete m;
  20167. }
  20168. }
  20169. void MidiOutput::startBackgroundThread()
  20170. {
  20171. startThread (9);
  20172. }
  20173. void MidiOutput::stopBackgroundThread()
  20174. {
  20175. stopThread (5000);
  20176. }
  20177. void MidiOutput::run()
  20178. {
  20179. while (! threadShouldExit())
  20180. {
  20181. uint32 now = Time::getMillisecondCounter();
  20182. uint32 eventTime = 0;
  20183. uint32 timeToWait = 500;
  20184. PendingMessage* message;
  20185. {
  20186. const ScopedLock sl (lock);
  20187. message = firstMessage;
  20188. if (message != 0)
  20189. {
  20190. eventTime = roundToInt (message->message.getTimeStamp());
  20191. if (eventTime > now + 20)
  20192. {
  20193. timeToWait = eventTime - (now + 20);
  20194. message = 0;
  20195. }
  20196. else
  20197. {
  20198. firstMessage = message->next;
  20199. }
  20200. }
  20201. }
  20202. if (message != 0)
  20203. {
  20204. if (eventTime > now)
  20205. {
  20206. Time::waitForMillisecondCounter (eventTime);
  20207. if (threadShouldExit())
  20208. break;
  20209. }
  20210. if (eventTime > now - 200)
  20211. sendMessageNow (message->message);
  20212. delete message;
  20213. }
  20214. else
  20215. {
  20216. jassert (timeToWait < 1000 * 30);
  20217. wait (timeToWait);
  20218. }
  20219. }
  20220. clearAllPendingMessages();
  20221. }
  20222. END_JUCE_NAMESPACE
  20223. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20224. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20225. BEGIN_JUCE_NAMESPACE
  20226. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20227. {
  20228. const double maxVal = (double) 0x7fff;
  20229. char* intData = static_cast <char*> (dest);
  20230. if (dest != (void*) source || destBytesPerSample <= 4)
  20231. {
  20232. for (int i = 0; i < numSamples; ++i)
  20233. {
  20234. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20235. intData += destBytesPerSample;
  20236. }
  20237. }
  20238. else
  20239. {
  20240. intData += destBytesPerSample * numSamples;
  20241. for (int i = numSamples; --i >= 0;)
  20242. {
  20243. intData -= destBytesPerSample;
  20244. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20245. }
  20246. }
  20247. }
  20248. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20249. {
  20250. const double maxVal = (double) 0x7fff;
  20251. char* intData = static_cast <char*> (dest);
  20252. if (dest != (void*) source || destBytesPerSample <= 4)
  20253. {
  20254. for (int i = 0; i < numSamples; ++i)
  20255. {
  20256. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20257. intData += destBytesPerSample;
  20258. }
  20259. }
  20260. else
  20261. {
  20262. intData += destBytesPerSample * numSamples;
  20263. for (int i = numSamples; --i >= 0;)
  20264. {
  20265. intData -= destBytesPerSample;
  20266. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20267. }
  20268. }
  20269. }
  20270. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20271. {
  20272. const double maxVal = (double) 0x7fffff;
  20273. char* intData = static_cast <char*> (dest);
  20274. if (dest != (void*) source || destBytesPerSample <= 4)
  20275. {
  20276. for (int i = 0; i < numSamples; ++i)
  20277. {
  20278. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20279. intData += destBytesPerSample;
  20280. }
  20281. }
  20282. else
  20283. {
  20284. intData += destBytesPerSample * numSamples;
  20285. for (int i = numSamples; --i >= 0;)
  20286. {
  20287. intData -= destBytesPerSample;
  20288. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20289. }
  20290. }
  20291. }
  20292. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20293. {
  20294. const double maxVal = (double) 0x7fffff;
  20295. char* intData = static_cast <char*> (dest);
  20296. if (dest != (void*) source || destBytesPerSample <= 4)
  20297. {
  20298. for (int i = 0; i < numSamples; ++i)
  20299. {
  20300. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20301. intData += destBytesPerSample;
  20302. }
  20303. }
  20304. else
  20305. {
  20306. intData += destBytesPerSample * numSamples;
  20307. for (int i = numSamples; --i >= 0;)
  20308. {
  20309. intData -= destBytesPerSample;
  20310. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20311. }
  20312. }
  20313. }
  20314. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20315. {
  20316. const double maxVal = (double) 0x7fffffff;
  20317. char* intData = static_cast <char*> (dest);
  20318. if (dest != (void*) source || destBytesPerSample <= 4)
  20319. {
  20320. for (int i = 0; i < numSamples; ++i)
  20321. {
  20322. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20323. intData += destBytesPerSample;
  20324. }
  20325. }
  20326. else
  20327. {
  20328. intData += destBytesPerSample * numSamples;
  20329. for (int i = numSamples; --i >= 0;)
  20330. {
  20331. intData -= destBytesPerSample;
  20332. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20333. }
  20334. }
  20335. }
  20336. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20337. {
  20338. const double maxVal = (double) 0x7fffffff;
  20339. char* intData = static_cast <char*> (dest);
  20340. if (dest != (void*) source || destBytesPerSample <= 4)
  20341. {
  20342. for (int i = 0; i < numSamples; ++i)
  20343. {
  20344. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20345. intData += destBytesPerSample;
  20346. }
  20347. }
  20348. else
  20349. {
  20350. intData += destBytesPerSample * numSamples;
  20351. for (int i = numSamples; --i >= 0;)
  20352. {
  20353. intData -= destBytesPerSample;
  20354. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20355. }
  20356. }
  20357. }
  20358. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20359. {
  20360. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20361. char* d = static_cast <char*> (dest);
  20362. for (int i = 0; i < numSamples; ++i)
  20363. {
  20364. *(float*) d = source[i];
  20365. #if JUCE_BIG_ENDIAN
  20366. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20367. #endif
  20368. d += destBytesPerSample;
  20369. }
  20370. }
  20371. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20372. {
  20373. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20374. char* d = static_cast <char*> (dest);
  20375. for (int i = 0; i < numSamples; ++i)
  20376. {
  20377. *(float*) d = source[i];
  20378. #if JUCE_LITTLE_ENDIAN
  20379. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20380. #endif
  20381. d += destBytesPerSample;
  20382. }
  20383. }
  20384. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20385. {
  20386. const float scale = 1.0f / 0x7fff;
  20387. const char* intData = static_cast <const char*> (source);
  20388. if (source != (void*) dest || srcBytesPerSample >= 4)
  20389. {
  20390. for (int i = 0; i < numSamples; ++i)
  20391. {
  20392. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20393. intData += srcBytesPerSample;
  20394. }
  20395. }
  20396. else
  20397. {
  20398. intData += srcBytesPerSample * numSamples;
  20399. for (int i = numSamples; --i >= 0;)
  20400. {
  20401. intData -= srcBytesPerSample;
  20402. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20403. }
  20404. }
  20405. }
  20406. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20407. {
  20408. const float scale = 1.0f / 0x7fff;
  20409. const char* intData = static_cast <const char*> (source);
  20410. if (source != (void*) dest || srcBytesPerSample >= 4)
  20411. {
  20412. for (int i = 0; i < numSamples; ++i)
  20413. {
  20414. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20415. intData += srcBytesPerSample;
  20416. }
  20417. }
  20418. else
  20419. {
  20420. intData += srcBytesPerSample * numSamples;
  20421. for (int i = numSamples; --i >= 0;)
  20422. {
  20423. intData -= srcBytesPerSample;
  20424. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20425. }
  20426. }
  20427. }
  20428. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20429. {
  20430. const float scale = 1.0f / 0x7fffff;
  20431. const char* intData = static_cast <const char*> (source);
  20432. if (source != (void*) dest || srcBytesPerSample >= 4)
  20433. {
  20434. for (int i = 0; i < numSamples; ++i)
  20435. {
  20436. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20437. intData += srcBytesPerSample;
  20438. }
  20439. }
  20440. else
  20441. {
  20442. intData += srcBytesPerSample * numSamples;
  20443. for (int i = numSamples; --i >= 0;)
  20444. {
  20445. intData -= srcBytesPerSample;
  20446. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20447. }
  20448. }
  20449. }
  20450. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20451. {
  20452. const float scale = 1.0f / 0x7fffff;
  20453. const char* intData = static_cast <const char*> (source);
  20454. if (source != (void*) dest || srcBytesPerSample >= 4)
  20455. {
  20456. for (int i = 0; i < numSamples; ++i)
  20457. {
  20458. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20459. intData += srcBytesPerSample;
  20460. }
  20461. }
  20462. else
  20463. {
  20464. intData += srcBytesPerSample * numSamples;
  20465. for (int i = numSamples; --i >= 0;)
  20466. {
  20467. intData -= srcBytesPerSample;
  20468. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20469. }
  20470. }
  20471. }
  20472. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20473. {
  20474. const float scale = 1.0f / 0x7fffffff;
  20475. const char* intData = static_cast <const char*> (source);
  20476. if (source != (void*) dest || srcBytesPerSample >= 4)
  20477. {
  20478. for (int i = 0; i < numSamples; ++i)
  20479. {
  20480. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20481. intData += srcBytesPerSample;
  20482. }
  20483. }
  20484. else
  20485. {
  20486. intData += srcBytesPerSample * numSamples;
  20487. for (int i = numSamples; --i >= 0;)
  20488. {
  20489. intData -= srcBytesPerSample;
  20490. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20491. }
  20492. }
  20493. }
  20494. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20495. {
  20496. const float scale = 1.0f / 0x7fffffff;
  20497. const char* intData = static_cast <const char*> (source);
  20498. if (source != (void*) dest || srcBytesPerSample >= 4)
  20499. {
  20500. for (int i = 0; i < numSamples; ++i)
  20501. {
  20502. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20503. intData += srcBytesPerSample;
  20504. }
  20505. }
  20506. else
  20507. {
  20508. intData += srcBytesPerSample * numSamples;
  20509. for (int i = numSamples; --i >= 0;)
  20510. {
  20511. intData -= srcBytesPerSample;
  20512. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20513. }
  20514. }
  20515. }
  20516. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20517. {
  20518. const char* s = static_cast <const char*> (source);
  20519. for (int i = 0; i < numSamples; ++i)
  20520. {
  20521. dest[i] = *(float*)s;
  20522. #if JUCE_BIG_ENDIAN
  20523. uint32* const d = (uint32*) (dest + i);
  20524. *d = ByteOrder::swap (*d);
  20525. #endif
  20526. s += srcBytesPerSample;
  20527. }
  20528. }
  20529. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20530. {
  20531. const char* s = static_cast <const char*> (source);
  20532. for (int i = 0; i < numSamples; ++i)
  20533. {
  20534. dest[i] = *(float*)s;
  20535. #if JUCE_LITTLE_ENDIAN
  20536. uint32* const d = (uint32*) (dest + i);
  20537. *d = ByteOrder::swap (*d);
  20538. #endif
  20539. s += srcBytesPerSample;
  20540. }
  20541. }
  20542. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20543. const float* const source,
  20544. void* const dest,
  20545. const int numSamples)
  20546. {
  20547. switch (destFormat)
  20548. {
  20549. case int16LE:
  20550. convertFloatToInt16LE (source, dest, numSamples);
  20551. break;
  20552. case int16BE:
  20553. convertFloatToInt16BE (source, dest, numSamples);
  20554. break;
  20555. case int24LE:
  20556. convertFloatToInt24LE (source, dest, numSamples);
  20557. break;
  20558. case int24BE:
  20559. convertFloatToInt24BE (source, dest, numSamples);
  20560. break;
  20561. case int32LE:
  20562. convertFloatToInt32LE (source, dest, numSamples);
  20563. break;
  20564. case int32BE:
  20565. convertFloatToInt32BE (source, dest, numSamples);
  20566. break;
  20567. case float32LE:
  20568. convertFloatToFloat32LE (source, dest, numSamples);
  20569. break;
  20570. case float32BE:
  20571. convertFloatToFloat32BE (source, dest, numSamples);
  20572. break;
  20573. default:
  20574. jassertfalse;
  20575. break;
  20576. }
  20577. }
  20578. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20579. const void* const source,
  20580. float* const dest,
  20581. const int numSamples)
  20582. {
  20583. switch (sourceFormat)
  20584. {
  20585. case int16LE:
  20586. convertInt16LEToFloat (source, dest, numSamples);
  20587. break;
  20588. case int16BE:
  20589. convertInt16BEToFloat (source, dest, numSamples);
  20590. break;
  20591. case int24LE:
  20592. convertInt24LEToFloat (source, dest, numSamples);
  20593. break;
  20594. case int24BE:
  20595. convertInt24BEToFloat (source, dest, numSamples);
  20596. break;
  20597. case int32LE:
  20598. convertInt32LEToFloat (source, dest, numSamples);
  20599. break;
  20600. case int32BE:
  20601. convertInt32BEToFloat (source, dest, numSamples);
  20602. break;
  20603. case float32LE:
  20604. convertFloat32LEToFloat (source, dest, numSamples);
  20605. break;
  20606. case float32BE:
  20607. convertFloat32BEToFloat (source, dest, numSamples);
  20608. break;
  20609. default:
  20610. jassertfalse;
  20611. break;
  20612. }
  20613. }
  20614. void AudioDataConverters::interleaveSamples (const float** const source,
  20615. float* const dest,
  20616. const int numSamples,
  20617. const int numChannels)
  20618. {
  20619. for (int chan = 0; chan < numChannels; ++chan)
  20620. {
  20621. int i = chan;
  20622. const float* src = source [chan];
  20623. for (int j = 0; j < numSamples; ++j)
  20624. {
  20625. dest [i] = src [j];
  20626. i += numChannels;
  20627. }
  20628. }
  20629. }
  20630. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20631. float** const dest,
  20632. const int numSamples,
  20633. const int numChannels)
  20634. {
  20635. for (int chan = 0; chan < numChannels; ++chan)
  20636. {
  20637. int i = chan;
  20638. float* dst = dest [chan];
  20639. for (int j = 0; j < numSamples; ++j)
  20640. {
  20641. dst [j] = source [i];
  20642. i += numChannels;
  20643. }
  20644. }
  20645. }
  20646. END_JUCE_NAMESPACE
  20647. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20648. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20649. BEGIN_JUCE_NAMESPACE
  20650. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20651. const int numSamples) throw()
  20652. : numChannels (numChannels_),
  20653. size (numSamples)
  20654. {
  20655. jassert (numSamples >= 0);
  20656. jassert (numChannels_ > 0);
  20657. allocateData();
  20658. }
  20659. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20660. : numChannels (other.numChannels),
  20661. size (other.size)
  20662. {
  20663. allocateData();
  20664. const size_t numBytes = size * sizeof (float);
  20665. for (int i = 0; i < numChannels; ++i)
  20666. memcpy (channels[i], other.channels[i], numBytes);
  20667. }
  20668. void AudioSampleBuffer::allocateData()
  20669. {
  20670. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20671. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20672. allocatedData.malloc (allocatedBytes);
  20673. channels = reinterpret_cast <float**> (allocatedData.getData());
  20674. float* chan = (float*) (allocatedData + channelListSize);
  20675. for (int i = 0; i < numChannels; ++i)
  20676. {
  20677. channels[i] = chan;
  20678. chan += size;
  20679. }
  20680. channels [numChannels] = 0;
  20681. }
  20682. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20683. const int numChannels_,
  20684. const int numSamples) throw()
  20685. : numChannels (numChannels_),
  20686. size (numSamples),
  20687. allocatedBytes (0)
  20688. {
  20689. jassert (numChannels_ > 0);
  20690. allocateChannels (dataToReferTo);
  20691. }
  20692. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20693. const int newNumChannels,
  20694. const int newNumSamples) throw()
  20695. {
  20696. jassert (newNumChannels > 0);
  20697. allocatedBytes = 0;
  20698. allocatedData.free();
  20699. numChannels = newNumChannels;
  20700. size = newNumSamples;
  20701. allocateChannels (dataToReferTo);
  20702. }
  20703. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20704. {
  20705. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20706. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20707. {
  20708. channels = static_cast <float**> (preallocatedChannelSpace);
  20709. }
  20710. else
  20711. {
  20712. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20713. channels = reinterpret_cast <float**> (allocatedData.getData());
  20714. }
  20715. for (int i = 0; i < numChannels; ++i)
  20716. {
  20717. // you have to pass in the same number of valid pointers as numChannels
  20718. jassert (dataToReferTo[i] != 0);
  20719. channels[i] = dataToReferTo[i];
  20720. }
  20721. channels [numChannels] = 0;
  20722. }
  20723. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20724. {
  20725. if (this != &other)
  20726. {
  20727. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20728. const size_t numBytes = size * sizeof (float);
  20729. for (int i = 0; i < numChannels; ++i)
  20730. memcpy (channels[i], other.channels[i], numBytes);
  20731. }
  20732. return *this;
  20733. }
  20734. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20735. {
  20736. }
  20737. void AudioSampleBuffer::setSize (const int newNumChannels,
  20738. const int newNumSamples,
  20739. const bool keepExistingContent,
  20740. const bool clearExtraSpace,
  20741. const bool avoidReallocating) throw()
  20742. {
  20743. jassert (newNumChannels > 0);
  20744. if (newNumSamples != size || newNumChannels != numChannels)
  20745. {
  20746. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20747. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20748. if (keepExistingContent)
  20749. {
  20750. HeapBlock <char> newData;
  20751. newData.allocate (newTotalBytes, clearExtraSpace);
  20752. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20753. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20754. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20755. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20756. for (int i = 0; i < numChansToCopy; ++i)
  20757. {
  20758. memcpy (newChan, channels[i], numBytesToCopy);
  20759. newChannels[i] = newChan;
  20760. newChan += newNumSamples;
  20761. }
  20762. allocatedData.swapWith (newData);
  20763. allocatedBytes = (int) newTotalBytes;
  20764. channels = newChannels;
  20765. }
  20766. else
  20767. {
  20768. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20769. {
  20770. if (clearExtraSpace)
  20771. zeromem (allocatedData, newTotalBytes);
  20772. }
  20773. else
  20774. {
  20775. allocatedBytes = newTotalBytes;
  20776. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20777. channels = reinterpret_cast <float**> (allocatedData.getData());
  20778. }
  20779. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20780. for (int i = 0; i < newNumChannels; ++i)
  20781. {
  20782. channels[i] = chan;
  20783. chan += newNumSamples;
  20784. }
  20785. }
  20786. channels [newNumChannels] = 0;
  20787. size = newNumSamples;
  20788. numChannels = newNumChannels;
  20789. }
  20790. }
  20791. void AudioSampleBuffer::clear() throw()
  20792. {
  20793. for (int i = 0; i < numChannels; ++i)
  20794. zeromem (channels[i], size * sizeof (float));
  20795. }
  20796. void AudioSampleBuffer::clear (const int startSample,
  20797. const int numSamples) throw()
  20798. {
  20799. jassert (startSample >= 0 && startSample + numSamples <= size);
  20800. for (int i = 0; i < numChannels; ++i)
  20801. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20802. }
  20803. void AudioSampleBuffer::clear (const int channel,
  20804. const int startSample,
  20805. const int numSamples) throw()
  20806. {
  20807. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20808. jassert (startSample >= 0 && startSample + numSamples <= size);
  20809. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20810. }
  20811. void AudioSampleBuffer::applyGain (const int channel,
  20812. const int startSample,
  20813. int numSamples,
  20814. const float gain) throw()
  20815. {
  20816. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20817. jassert (startSample >= 0 && startSample + numSamples <= size);
  20818. if (gain != 1.0f)
  20819. {
  20820. float* d = channels [channel] + startSample;
  20821. if (gain == 0.0f)
  20822. {
  20823. zeromem (d, sizeof (float) * numSamples);
  20824. }
  20825. else
  20826. {
  20827. while (--numSamples >= 0)
  20828. *d++ *= gain;
  20829. }
  20830. }
  20831. }
  20832. void AudioSampleBuffer::applyGainRamp (const int channel,
  20833. const int startSample,
  20834. int numSamples,
  20835. float startGain,
  20836. float endGain) throw()
  20837. {
  20838. if (startGain == endGain)
  20839. {
  20840. applyGain (channel, startSample, numSamples, startGain);
  20841. }
  20842. else
  20843. {
  20844. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20845. jassert (startSample >= 0 && startSample + numSamples <= size);
  20846. const float increment = (endGain - startGain) / numSamples;
  20847. float* d = channels [channel] + startSample;
  20848. while (--numSamples >= 0)
  20849. {
  20850. *d++ *= startGain;
  20851. startGain += increment;
  20852. }
  20853. }
  20854. }
  20855. void AudioSampleBuffer::applyGain (const int startSample,
  20856. const int numSamples,
  20857. const float gain) throw()
  20858. {
  20859. for (int i = 0; i < numChannels; ++i)
  20860. applyGain (i, startSample, numSamples, gain);
  20861. }
  20862. void AudioSampleBuffer::addFrom (const int destChannel,
  20863. const int destStartSample,
  20864. const AudioSampleBuffer& source,
  20865. const int sourceChannel,
  20866. const int sourceStartSample,
  20867. int numSamples,
  20868. const float gain) throw()
  20869. {
  20870. jassert (&source != this || sourceChannel != destChannel);
  20871. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20872. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20873. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20874. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20875. if (gain != 0.0f && numSamples > 0)
  20876. {
  20877. float* d = channels [destChannel] + destStartSample;
  20878. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20879. if (gain != 1.0f)
  20880. {
  20881. while (--numSamples >= 0)
  20882. *d++ += gain * *s++;
  20883. }
  20884. else
  20885. {
  20886. while (--numSamples >= 0)
  20887. *d++ += *s++;
  20888. }
  20889. }
  20890. }
  20891. void AudioSampleBuffer::addFrom (const int destChannel,
  20892. const int destStartSample,
  20893. const float* source,
  20894. int numSamples,
  20895. const float gain) throw()
  20896. {
  20897. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20898. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20899. jassert (source != 0);
  20900. if (gain != 0.0f && numSamples > 0)
  20901. {
  20902. float* d = channels [destChannel] + destStartSample;
  20903. if (gain != 1.0f)
  20904. {
  20905. while (--numSamples >= 0)
  20906. *d++ += gain * *source++;
  20907. }
  20908. else
  20909. {
  20910. while (--numSamples >= 0)
  20911. *d++ += *source++;
  20912. }
  20913. }
  20914. }
  20915. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20916. const int destStartSample,
  20917. const float* source,
  20918. int numSamples,
  20919. float startGain,
  20920. const float endGain) throw()
  20921. {
  20922. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20923. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20924. jassert (source != 0);
  20925. if (startGain == endGain)
  20926. {
  20927. addFrom (destChannel,
  20928. destStartSample,
  20929. source,
  20930. numSamples,
  20931. startGain);
  20932. }
  20933. else
  20934. {
  20935. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20936. {
  20937. const float increment = (endGain - startGain) / numSamples;
  20938. float* d = channels [destChannel] + destStartSample;
  20939. while (--numSamples >= 0)
  20940. {
  20941. *d++ += startGain * *source++;
  20942. startGain += increment;
  20943. }
  20944. }
  20945. }
  20946. }
  20947. void AudioSampleBuffer::copyFrom (const int destChannel,
  20948. const int destStartSample,
  20949. const AudioSampleBuffer& source,
  20950. const int sourceChannel,
  20951. const int sourceStartSample,
  20952. int numSamples) throw()
  20953. {
  20954. jassert (&source != this || sourceChannel != destChannel);
  20955. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20956. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20957. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20958. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20959. if (numSamples > 0)
  20960. {
  20961. memcpy (channels [destChannel] + destStartSample,
  20962. source.channels [sourceChannel] + sourceStartSample,
  20963. sizeof (float) * numSamples);
  20964. }
  20965. }
  20966. void AudioSampleBuffer::copyFrom (const int destChannel,
  20967. const int destStartSample,
  20968. const float* source,
  20969. int numSamples) throw()
  20970. {
  20971. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20972. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20973. jassert (source != 0);
  20974. if (numSamples > 0)
  20975. {
  20976. memcpy (channels [destChannel] + destStartSample,
  20977. source,
  20978. sizeof (float) * numSamples);
  20979. }
  20980. }
  20981. void AudioSampleBuffer::copyFrom (const int destChannel,
  20982. const int destStartSample,
  20983. const float* source,
  20984. int numSamples,
  20985. const float gain) throw()
  20986. {
  20987. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20988. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20989. jassert (source != 0);
  20990. if (numSamples > 0)
  20991. {
  20992. float* d = channels [destChannel] + destStartSample;
  20993. if (gain != 1.0f)
  20994. {
  20995. if (gain == 0)
  20996. {
  20997. zeromem (d, sizeof (float) * numSamples);
  20998. }
  20999. else
  21000. {
  21001. while (--numSamples >= 0)
  21002. *d++ = gain * *source++;
  21003. }
  21004. }
  21005. else
  21006. {
  21007. memcpy (d, source, sizeof (float) * numSamples);
  21008. }
  21009. }
  21010. }
  21011. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21012. const int destStartSample,
  21013. const float* source,
  21014. int numSamples,
  21015. float startGain,
  21016. float endGain) throw()
  21017. {
  21018. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21019. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21020. jassert (source != 0);
  21021. if (startGain == endGain)
  21022. {
  21023. copyFrom (destChannel,
  21024. destStartSample,
  21025. source,
  21026. numSamples,
  21027. startGain);
  21028. }
  21029. else
  21030. {
  21031. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21032. {
  21033. const float increment = (endGain - startGain) / numSamples;
  21034. float* d = channels [destChannel] + destStartSample;
  21035. while (--numSamples >= 0)
  21036. {
  21037. *d++ = startGain * *source++;
  21038. startGain += increment;
  21039. }
  21040. }
  21041. }
  21042. }
  21043. void AudioSampleBuffer::findMinMax (const int channel,
  21044. const int startSample,
  21045. int numSamples,
  21046. float& minVal,
  21047. float& maxVal) const throw()
  21048. {
  21049. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21050. jassert (startSample >= 0 && startSample + numSamples <= size);
  21051. if (numSamples <= 0)
  21052. {
  21053. minVal = 0.0f;
  21054. maxVal = 0.0f;
  21055. }
  21056. else
  21057. {
  21058. const float* d = channels [channel] + startSample;
  21059. float mn = *d++;
  21060. float mx = mn;
  21061. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21062. {
  21063. const float samp = *d++;
  21064. if (samp > mx)
  21065. mx = samp;
  21066. if (samp < mn)
  21067. mn = samp;
  21068. }
  21069. maxVal = mx;
  21070. minVal = mn;
  21071. }
  21072. }
  21073. float AudioSampleBuffer::getMagnitude (const int channel,
  21074. const int startSample,
  21075. const int numSamples) const throw()
  21076. {
  21077. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21078. jassert (startSample >= 0 && startSample + numSamples <= size);
  21079. float mn, mx;
  21080. findMinMax (channel, startSample, numSamples, mn, mx);
  21081. return jmax (mn, -mn, mx, -mx);
  21082. }
  21083. float AudioSampleBuffer::getMagnitude (const int startSample,
  21084. const int numSamples) const throw()
  21085. {
  21086. float mag = 0.0f;
  21087. for (int i = 0; i < numChannels; ++i)
  21088. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21089. return mag;
  21090. }
  21091. float AudioSampleBuffer::getRMSLevel (const int channel,
  21092. const int startSample,
  21093. const int numSamples) const throw()
  21094. {
  21095. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21096. jassert (startSample >= 0 && startSample + numSamples <= size);
  21097. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21098. return 0.0f;
  21099. const float* const data = channels [channel] + startSample;
  21100. double sum = 0.0;
  21101. for (int i = 0; i < numSamples; ++i)
  21102. {
  21103. const float sample = data [i];
  21104. sum += sample * sample;
  21105. }
  21106. return (float) std::sqrt (sum / numSamples);
  21107. }
  21108. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21109. const int startSample,
  21110. const int numSamples,
  21111. const int readerStartSample,
  21112. const bool useLeftChan,
  21113. const bool useRightChan)
  21114. {
  21115. jassert (reader != 0);
  21116. jassert (startSample >= 0 && startSample + numSamples <= size);
  21117. if (numSamples > 0)
  21118. {
  21119. int* chans[3];
  21120. if (useLeftChan == useRightChan)
  21121. {
  21122. chans[0] = (int*) getSampleData (0, startSample);
  21123. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21124. }
  21125. else if (useLeftChan || (reader->numChannels == 1))
  21126. {
  21127. chans[0] = (int*) getSampleData (0, startSample);
  21128. chans[1] = 0;
  21129. }
  21130. else if (useRightChan)
  21131. {
  21132. chans[0] = 0;
  21133. chans[1] = (int*) getSampleData (0, startSample);
  21134. }
  21135. chans[2] = 0;
  21136. reader->read (chans, 2, readerStartSample, numSamples, true);
  21137. if (! reader->usesFloatingPointData)
  21138. {
  21139. for (int j = 0; j < 2; ++j)
  21140. {
  21141. float* const d = reinterpret_cast <float*> (chans[j]);
  21142. if (d != 0)
  21143. {
  21144. const float multiplier = 1.0f / 0x7fffffff;
  21145. for (int i = 0; i < numSamples; ++i)
  21146. d[i] = *(int*)(d + i) * multiplier;
  21147. }
  21148. }
  21149. }
  21150. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21151. {
  21152. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21153. memcpy (getSampleData (1, startSample),
  21154. getSampleData (0, startSample),
  21155. sizeof (float) * numSamples);
  21156. }
  21157. }
  21158. }
  21159. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21160. const int startSample,
  21161. const int numSamples) const
  21162. {
  21163. jassert (startSample >= 0 && startSample + numSamples <= size && numChannels > 0);
  21164. if (numSamples > 0)
  21165. {
  21166. HeapBlock<int> tempBuffer;
  21167. HeapBlock<int*> chans (numChannels + 1);
  21168. chans [numChannels] = 0;
  21169. if (writer->isFloatingPoint())
  21170. {
  21171. for (int i = numChannels; --i >= 0;)
  21172. chans[i] = (int*) channels[i] + startSample;
  21173. }
  21174. else
  21175. {
  21176. tempBuffer.malloc (numSamples * numChannels);
  21177. for (int j = 0; j < numChannels; ++j)
  21178. {
  21179. int* const dest = tempBuffer + j * numSamples;
  21180. const float* const src = channels[j] + startSample;
  21181. chans[j] = dest;
  21182. for (int i = 0; i < numSamples; ++i)
  21183. {
  21184. const double samp = src[i];
  21185. if (samp <= -1.0)
  21186. dest[i] = std::numeric_limits<int>::min();
  21187. else if (samp >= 1.0)
  21188. dest[i] = std::numeric_limits<int>::max();
  21189. else
  21190. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21191. }
  21192. }
  21193. }
  21194. writer->write ((const int**) chans.getData(), numSamples);
  21195. }
  21196. }
  21197. END_JUCE_NAMESPACE
  21198. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21199. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21200. BEGIN_JUCE_NAMESPACE
  21201. IIRFilter::IIRFilter()
  21202. : active (false)
  21203. {
  21204. reset();
  21205. }
  21206. IIRFilter::IIRFilter (const IIRFilter& other)
  21207. : active (other.active)
  21208. {
  21209. const ScopedLock sl (other.processLock);
  21210. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21211. reset();
  21212. }
  21213. IIRFilter::~IIRFilter()
  21214. {
  21215. }
  21216. void IIRFilter::reset() throw()
  21217. {
  21218. const ScopedLock sl (processLock);
  21219. x1 = 0;
  21220. x2 = 0;
  21221. y1 = 0;
  21222. y2 = 0;
  21223. }
  21224. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21225. {
  21226. float out = coefficients[0] * in
  21227. + coefficients[1] * x1
  21228. + coefficients[2] * x2
  21229. - coefficients[4] * y1
  21230. - coefficients[5] * y2;
  21231. #if JUCE_INTEL
  21232. if (! (out < -1.0e-8 || out > 1.0e-8))
  21233. out = 0;
  21234. #endif
  21235. x2 = x1;
  21236. x1 = in;
  21237. y2 = y1;
  21238. y1 = out;
  21239. return out;
  21240. }
  21241. void IIRFilter::processSamples (float* const samples,
  21242. const int numSamples) throw()
  21243. {
  21244. const ScopedLock sl (processLock);
  21245. if (active)
  21246. {
  21247. for (int i = 0; i < numSamples; ++i)
  21248. {
  21249. const float in = samples[i];
  21250. float out = coefficients[0] * in
  21251. + coefficients[1] * x1
  21252. + coefficients[2] * x2
  21253. - coefficients[4] * y1
  21254. - coefficients[5] * y2;
  21255. #if JUCE_INTEL
  21256. if (! (out < -1.0e-8 || out > 1.0e-8))
  21257. out = 0;
  21258. #endif
  21259. x2 = x1;
  21260. x1 = in;
  21261. y2 = y1;
  21262. y1 = out;
  21263. samples[i] = out;
  21264. }
  21265. }
  21266. }
  21267. void IIRFilter::makeLowPass (const double sampleRate,
  21268. const double frequency) throw()
  21269. {
  21270. jassert (sampleRate > 0);
  21271. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21272. const double nSquared = n * n;
  21273. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21274. setCoefficients (c1,
  21275. c1 * 2.0f,
  21276. c1,
  21277. 1.0,
  21278. c1 * 2.0 * (1.0 - nSquared),
  21279. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21280. }
  21281. void IIRFilter::makeHighPass (const double sampleRate,
  21282. const double frequency) throw()
  21283. {
  21284. const double n = tan (double_Pi * frequency / sampleRate);
  21285. const double nSquared = n * n;
  21286. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21287. setCoefficients (c1,
  21288. c1 * -2.0f,
  21289. c1,
  21290. 1.0,
  21291. c1 * 2.0 * (nSquared - 1.0),
  21292. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21293. }
  21294. void IIRFilter::makeLowShelf (const double sampleRate,
  21295. const double cutOffFrequency,
  21296. const double Q,
  21297. const float gainFactor) throw()
  21298. {
  21299. jassert (sampleRate > 0);
  21300. jassert (Q > 0);
  21301. const double A = jmax (0.0f, gainFactor);
  21302. const double aminus1 = A - 1.0;
  21303. const double aplus1 = A + 1.0;
  21304. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21305. const double coso = std::cos (omega);
  21306. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21307. const double aminus1TimesCoso = aminus1 * coso;
  21308. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21309. A * 2.0 * (aminus1 - aplus1 * coso),
  21310. A * (aplus1 - aminus1TimesCoso - beta),
  21311. aplus1 + aminus1TimesCoso + beta,
  21312. -2.0 * (aminus1 + aplus1 * coso),
  21313. aplus1 + aminus1TimesCoso - beta);
  21314. }
  21315. void IIRFilter::makeHighShelf (const double sampleRate,
  21316. const double cutOffFrequency,
  21317. const double Q,
  21318. const float gainFactor) throw()
  21319. {
  21320. jassert (sampleRate > 0);
  21321. jassert (Q > 0);
  21322. const double A = jmax (0.0f, gainFactor);
  21323. const double aminus1 = A - 1.0;
  21324. const double aplus1 = A + 1.0;
  21325. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21326. const double coso = std::cos (omega);
  21327. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21328. const double aminus1TimesCoso = aminus1 * coso;
  21329. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21330. A * -2.0 * (aminus1 + aplus1 * coso),
  21331. A * (aplus1 + aminus1TimesCoso - beta),
  21332. aplus1 - aminus1TimesCoso + beta,
  21333. 2.0 * (aminus1 - aplus1 * coso),
  21334. aplus1 - aminus1TimesCoso - beta);
  21335. }
  21336. void IIRFilter::makeBandPass (const double sampleRate,
  21337. const double centreFrequency,
  21338. const double Q,
  21339. const float gainFactor) throw()
  21340. {
  21341. jassert (sampleRate > 0);
  21342. jassert (Q > 0);
  21343. const double A = jmax (0.0f, gainFactor);
  21344. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21345. const double alpha = 0.5 * std::sin (omega) / Q;
  21346. const double c2 = -2.0 * std::cos (omega);
  21347. const double alphaTimesA = alpha * A;
  21348. const double alphaOverA = alpha / A;
  21349. setCoefficients (1.0 + alphaTimesA,
  21350. c2,
  21351. 1.0 - alphaTimesA,
  21352. 1.0 + alphaOverA,
  21353. c2,
  21354. 1.0 - alphaOverA);
  21355. }
  21356. void IIRFilter::makeInactive() throw()
  21357. {
  21358. const ScopedLock sl (processLock);
  21359. active = false;
  21360. }
  21361. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21362. {
  21363. const ScopedLock sl (processLock);
  21364. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21365. active = other.active;
  21366. }
  21367. void IIRFilter::setCoefficients (double c1,
  21368. double c2,
  21369. double c3,
  21370. double c4,
  21371. double c5,
  21372. double c6) throw()
  21373. {
  21374. const double a = 1.0 / c4;
  21375. c1 *= a;
  21376. c2 *= a;
  21377. c3 *= a;
  21378. c5 *= a;
  21379. c6 *= a;
  21380. const ScopedLock sl (processLock);
  21381. coefficients[0] = (float) c1;
  21382. coefficients[1] = (float) c2;
  21383. coefficients[2] = (float) c3;
  21384. coefficients[3] = (float) c4;
  21385. coefficients[4] = (float) c5;
  21386. coefficients[5] = (float) c6;
  21387. active = true;
  21388. }
  21389. END_JUCE_NAMESPACE
  21390. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21391. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21392. BEGIN_JUCE_NAMESPACE
  21393. MidiBuffer::MidiBuffer() throw()
  21394. : bytesUsed (0)
  21395. {
  21396. }
  21397. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21398. : bytesUsed (0)
  21399. {
  21400. addEvent (message, 0);
  21401. }
  21402. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21403. : data (other.data),
  21404. bytesUsed (other.bytesUsed)
  21405. {
  21406. }
  21407. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21408. {
  21409. bytesUsed = other.bytesUsed;
  21410. data = other.data;
  21411. return *this;
  21412. }
  21413. void MidiBuffer::swapWith (MidiBuffer& other)
  21414. {
  21415. data.swapWith (other.data);
  21416. swapVariables <int> (bytesUsed, other.bytesUsed);
  21417. }
  21418. MidiBuffer::~MidiBuffer() throw()
  21419. {
  21420. }
  21421. inline uint8* MidiBuffer::getData() const throw()
  21422. {
  21423. return static_cast <uint8*> (data.getData());
  21424. }
  21425. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21426. {
  21427. return *static_cast <const int*> (d);
  21428. }
  21429. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21430. {
  21431. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21432. }
  21433. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21434. {
  21435. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21436. }
  21437. void MidiBuffer::clear() throw()
  21438. {
  21439. bytesUsed = 0;
  21440. }
  21441. void MidiBuffer::clear (const int startSample,
  21442. const int numSamples) throw()
  21443. {
  21444. uint8* const start = findEventAfter (getData(), startSample - 1);
  21445. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21446. if (end > start)
  21447. {
  21448. const int bytesToMove = bytesUsed - (int) (end - getData());
  21449. if (bytesToMove > 0)
  21450. memmove (start, end, bytesToMove);
  21451. bytesUsed -= (int) (end - start);
  21452. }
  21453. }
  21454. void MidiBuffer::addEvent (const MidiMessage& m,
  21455. const int sampleNumber) throw()
  21456. {
  21457. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21458. }
  21459. static int findActualEventLength (const uint8* const data,
  21460. const int maxBytes) throw()
  21461. {
  21462. unsigned int byte = (unsigned int) *data;
  21463. int size = 0;
  21464. if (byte == 0xf0 || byte == 0xf7)
  21465. {
  21466. const uint8* d = data + 1;
  21467. while (d < data + maxBytes)
  21468. if (*d++ == 0xf7)
  21469. break;
  21470. size = (int) (d - data);
  21471. }
  21472. else if (byte == 0xff)
  21473. {
  21474. int n;
  21475. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21476. size = jmin (maxBytes, n + 2 + bytesLeft);
  21477. }
  21478. else if (byte >= 0x80)
  21479. {
  21480. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21481. }
  21482. return size;
  21483. }
  21484. void MidiBuffer::addEvent (const uint8* const newData,
  21485. const int maxBytes,
  21486. const int sampleNumber) throw()
  21487. {
  21488. const int numBytes = findActualEventLength (newData, maxBytes);
  21489. if (numBytes > 0)
  21490. {
  21491. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21492. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21493. uint8* d = findEventAfter (getData(), sampleNumber);
  21494. const int bytesToMove = bytesUsed - (int) (d - getData());
  21495. if (bytesToMove > 0)
  21496. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21497. *reinterpret_cast <int*> (d) = sampleNumber;
  21498. d += sizeof (int);
  21499. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21500. d += sizeof (uint16);
  21501. memcpy (d, newData, numBytes);
  21502. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21503. }
  21504. }
  21505. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21506. const int startSample,
  21507. const int numSamples,
  21508. const int sampleDeltaToAdd) throw()
  21509. {
  21510. Iterator i (otherBuffer);
  21511. i.setNextSamplePosition (startSample);
  21512. const uint8* eventData;
  21513. int eventSize, position;
  21514. while (i.getNextEvent (eventData, eventSize, position)
  21515. && (position < startSample + numSamples || numSamples < 0))
  21516. {
  21517. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21518. }
  21519. }
  21520. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21521. {
  21522. data.ensureSize (minimumNumBytes);
  21523. }
  21524. bool MidiBuffer::isEmpty() const throw()
  21525. {
  21526. return bytesUsed == 0;
  21527. }
  21528. int MidiBuffer::getNumEvents() const throw()
  21529. {
  21530. int n = 0;
  21531. const uint8* d = getData();
  21532. const uint8* const end = d + bytesUsed;
  21533. while (d < end)
  21534. {
  21535. d += getEventTotalSize (d);
  21536. ++n;
  21537. }
  21538. return n;
  21539. }
  21540. int MidiBuffer::getFirstEventTime() const throw()
  21541. {
  21542. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21543. }
  21544. int MidiBuffer::getLastEventTime() const throw()
  21545. {
  21546. if (bytesUsed == 0)
  21547. return 0;
  21548. const uint8* d = getData();
  21549. const uint8* const endData = d + bytesUsed;
  21550. for (;;)
  21551. {
  21552. const uint8* const nextOne = d + getEventTotalSize (d);
  21553. if (nextOne >= endData)
  21554. return getEventTime (d);
  21555. d = nextOne;
  21556. }
  21557. }
  21558. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21559. {
  21560. const uint8* const endData = getData() + bytesUsed;
  21561. while (d < endData && getEventTime (d) <= samplePosition)
  21562. d += getEventTotalSize (d);
  21563. return d;
  21564. }
  21565. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21566. : buffer (buffer_),
  21567. data (buffer_.getData())
  21568. {
  21569. }
  21570. MidiBuffer::Iterator::~Iterator() throw()
  21571. {
  21572. }
  21573. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21574. {
  21575. data = buffer.getData();
  21576. const uint8* dataEnd = data + buffer.bytesUsed;
  21577. while (data < dataEnd && getEventTime (data) < samplePosition)
  21578. data += getEventTotalSize (data);
  21579. }
  21580. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21581. {
  21582. if (data >= buffer.getData() + buffer.bytesUsed)
  21583. return false;
  21584. samplePosition = getEventTime (data);
  21585. numBytes = getEventDataSize (data);
  21586. data += sizeof (int) + sizeof (uint16);
  21587. midiData = data;
  21588. data += numBytes;
  21589. return true;
  21590. }
  21591. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21592. {
  21593. if (data >= buffer.getData() + buffer.bytesUsed)
  21594. return false;
  21595. samplePosition = getEventTime (data);
  21596. const int numBytes = getEventDataSize (data);
  21597. data += sizeof (int) + sizeof (uint16);
  21598. result = MidiMessage (data, numBytes, samplePosition);
  21599. data += numBytes;
  21600. return true;
  21601. }
  21602. END_JUCE_NAMESPACE
  21603. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21604. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21605. BEGIN_JUCE_NAMESPACE
  21606. namespace MidiFileHelpers
  21607. {
  21608. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21609. {
  21610. unsigned int buffer = v & 0x7F;
  21611. while ((v >>= 7) != 0)
  21612. {
  21613. buffer <<= 8;
  21614. buffer |= ((v & 0x7F) | 0x80);
  21615. }
  21616. for (;;)
  21617. {
  21618. out.writeByte ((char) buffer);
  21619. if (buffer & 0x80)
  21620. buffer >>= 8;
  21621. else
  21622. break;
  21623. }
  21624. }
  21625. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21626. {
  21627. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21628. data += 4;
  21629. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21630. {
  21631. bool ok = false;
  21632. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21633. {
  21634. for (int i = 0; i < 8; ++i)
  21635. {
  21636. ch = ByteOrder::bigEndianInt (data);
  21637. data += 4;
  21638. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21639. {
  21640. ok = true;
  21641. break;
  21642. }
  21643. }
  21644. }
  21645. if (! ok)
  21646. return false;
  21647. }
  21648. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21649. data += 4;
  21650. fileType = (short) ByteOrder::bigEndianShort (data);
  21651. data += 2;
  21652. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21653. data += 2;
  21654. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21655. data += 2;
  21656. bytesRemaining -= 6;
  21657. data += bytesRemaining;
  21658. return true;
  21659. }
  21660. static double convertTicksToSeconds (const double time,
  21661. const MidiMessageSequence& tempoEvents,
  21662. const int timeFormat)
  21663. {
  21664. if (timeFormat > 0)
  21665. {
  21666. int numer = 4, denom = 4;
  21667. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21668. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21669. double secsPerTick = 0.5 * tickLen;
  21670. const int numEvents = tempoEvents.getNumEvents();
  21671. for (int i = 0; i < numEvents; ++i)
  21672. {
  21673. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21674. if (time <= m.getTimeStamp())
  21675. break;
  21676. if (timeFormat > 0)
  21677. {
  21678. correctedTempoTime = correctedTempoTime
  21679. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21680. }
  21681. else
  21682. {
  21683. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21684. }
  21685. tempoTime = m.getTimeStamp();
  21686. if (m.isTempoMetaEvent())
  21687. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21688. else if (m.isTimeSignatureMetaEvent())
  21689. m.getTimeSignatureInfo (numer, denom);
  21690. while (i + 1 < numEvents)
  21691. {
  21692. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21693. if (m2.getTimeStamp() == tempoTime)
  21694. {
  21695. ++i;
  21696. if (m2.isTempoMetaEvent())
  21697. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21698. else if (m2.isTimeSignatureMetaEvent())
  21699. m2.getTimeSignatureInfo (numer, denom);
  21700. }
  21701. else
  21702. {
  21703. break;
  21704. }
  21705. }
  21706. }
  21707. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21708. }
  21709. else
  21710. {
  21711. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21712. }
  21713. }
  21714. }
  21715. MidiFile::MidiFile()
  21716. : timeFormat ((short) (unsigned short) 0xe728)
  21717. {
  21718. }
  21719. MidiFile::~MidiFile()
  21720. {
  21721. clear();
  21722. }
  21723. void MidiFile::clear()
  21724. {
  21725. tracks.clear();
  21726. }
  21727. int MidiFile::getNumTracks() const throw()
  21728. {
  21729. return tracks.size();
  21730. }
  21731. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21732. {
  21733. return tracks [index];
  21734. }
  21735. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21736. {
  21737. tracks.add (new MidiMessageSequence (trackSequence));
  21738. }
  21739. short MidiFile::getTimeFormat() const throw()
  21740. {
  21741. return timeFormat;
  21742. }
  21743. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21744. {
  21745. timeFormat = (short) ticks;
  21746. }
  21747. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21748. const int subframeResolution) throw()
  21749. {
  21750. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21751. }
  21752. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21753. {
  21754. for (int i = tracks.size(); --i >= 0;)
  21755. {
  21756. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21757. for (int j = 0; j < numEvents; ++j)
  21758. {
  21759. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21760. if (m.isTempoMetaEvent())
  21761. tempoChangeEvents.addEvent (m);
  21762. }
  21763. }
  21764. }
  21765. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21766. {
  21767. for (int i = tracks.size(); --i >= 0;)
  21768. {
  21769. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21770. for (int j = 0; j < numEvents; ++j)
  21771. {
  21772. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21773. if (m.isTimeSignatureMetaEvent())
  21774. timeSigEvents.addEvent (m);
  21775. }
  21776. }
  21777. }
  21778. double MidiFile::getLastTimestamp() const
  21779. {
  21780. double t = 0.0;
  21781. for (int i = tracks.size(); --i >= 0;)
  21782. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21783. return t;
  21784. }
  21785. bool MidiFile::readFrom (InputStream& sourceStream)
  21786. {
  21787. clear();
  21788. MemoryBlock data;
  21789. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21790. // (put a sanity-check on the file size, as midi files are generally small)
  21791. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21792. {
  21793. size_t size = data.getSize();
  21794. const uint8* d = static_cast <const uint8*> (data.getData());
  21795. short fileType, expectedTracks;
  21796. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21797. {
  21798. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21799. int track = 0;
  21800. while (size > 0 && track < expectedTracks)
  21801. {
  21802. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21803. d += 4;
  21804. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21805. d += 4;
  21806. if (chunkSize <= 0)
  21807. break;
  21808. if (size < 0)
  21809. return false;
  21810. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21811. {
  21812. readNextTrack (d, chunkSize);
  21813. }
  21814. size -= chunkSize + 8;
  21815. d += chunkSize;
  21816. ++track;
  21817. }
  21818. return true;
  21819. }
  21820. }
  21821. return false;
  21822. }
  21823. // a comparator that puts all the note-offs before note-ons that have the same time
  21824. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21825. const MidiMessageSequence::MidiEventHolder* const second)
  21826. {
  21827. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21828. if (diff == 0)
  21829. {
  21830. if (first->message.isNoteOff() && second->message.isNoteOn())
  21831. return -1;
  21832. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21833. return 1;
  21834. else
  21835. return 0;
  21836. }
  21837. else
  21838. {
  21839. return (diff > 0) ? 1 : -1;
  21840. }
  21841. }
  21842. void MidiFile::readNextTrack (const uint8* data, int size)
  21843. {
  21844. double time = 0;
  21845. char lastStatusByte = 0;
  21846. MidiMessageSequence result;
  21847. while (size > 0)
  21848. {
  21849. int bytesUsed;
  21850. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21851. data += bytesUsed;
  21852. size -= bytesUsed;
  21853. time += delay;
  21854. int messSize = 0;
  21855. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21856. if (messSize <= 0)
  21857. break;
  21858. size -= messSize;
  21859. data += messSize;
  21860. result.addEvent (mm);
  21861. const char firstByte = *(mm.getRawData());
  21862. if ((firstByte & 0xf0) != 0xf0)
  21863. lastStatusByte = firstByte;
  21864. }
  21865. // use a sort that puts all the note-offs before note-ons that have the same time
  21866. result.list.sort (*this, true);
  21867. result.updateMatchedPairs();
  21868. addTrack (result);
  21869. }
  21870. void MidiFile::convertTimestampTicksToSeconds()
  21871. {
  21872. MidiMessageSequence tempoEvents;
  21873. findAllTempoEvents (tempoEvents);
  21874. findAllTimeSigEvents (tempoEvents);
  21875. for (int i = 0; i < tracks.size(); ++i)
  21876. {
  21877. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21878. for (int j = ms.getNumEvents(); --j >= 0;)
  21879. {
  21880. MidiMessage& m = ms.getEventPointer(j)->message;
  21881. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21882. tempoEvents,
  21883. timeFormat));
  21884. }
  21885. }
  21886. }
  21887. bool MidiFile::writeTo (OutputStream& out)
  21888. {
  21889. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21890. out.writeIntBigEndian (6);
  21891. out.writeShortBigEndian (1); // type
  21892. out.writeShortBigEndian ((short) tracks.size());
  21893. out.writeShortBigEndian (timeFormat);
  21894. for (int i = 0; i < tracks.size(); ++i)
  21895. writeTrack (out, i);
  21896. out.flush();
  21897. return true;
  21898. }
  21899. void MidiFile::writeTrack (OutputStream& mainOut,
  21900. const int trackNum)
  21901. {
  21902. MemoryOutputStream out;
  21903. const MidiMessageSequence& ms = *tracks[trackNum];
  21904. int lastTick = 0;
  21905. char lastStatusByte = 0;
  21906. for (int i = 0; i < ms.getNumEvents(); ++i)
  21907. {
  21908. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21909. const int tick = roundToInt (mm.getTimeStamp());
  21910. const int delta = jmax (0, tick - lastTick);
  21911. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21912. lastTick = tick;
  21913. const char statusByte = *(mm.getRawData());
  21914. if ((statusByte == lastStatusByte)
  21915. && ((statusByte & 0xf0) != 0xf0)
  21916. && i > 0
  21917. && mm.getRawDataSize() > 1)
  21918. {
  21919. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21920. }
  21921. else
  21922. {
  21923. out.write (mm.getRawData(), mm.getRawDataSize());
  21924. }
  21925. lastStatusByte = statusByte;
  21926. }
  21927. out.writeByte (0);
  21928. const MidiMessage m (MidiMessage::endOfTrack());
  21929. out.write (m.getRawData(),
  21930. m.getRawDataSize());
  21931. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21932. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21933. mainOut.write (out.getData(), (int) out.getDataSize());
  21934. }
  21935. END_JUCE_NAMESPACE
  21936. /*** End of inlined file: juce_MidiFile.cpp ***/
  21937. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21938. BEGIN_JUCE_NAMESPACE
  21939. MidiKeyboardState::MidiKeyboardState()
  21940. {
  21941. zerostruct (noteStates);
  21942. }
  21943. MidiKeyboardState::~MidiKeyboardState()
  21944. {
  21945. }
  21946. void MidiKeyboardState::reset()
  21947. {
  21948. const ScopedLock sl (lock);
  21949. zerostruct (noteStates);
  21950. eventsToAdd.clear();
  21951. }
  21952. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21953. {
  21954. jassert (midiChannel >= 0 && midiChannel <= 16);
  21955. return ((unsigned int) n) < 128
  21956. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21957. }
  21958. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21959. {
  21960. return ((unsigned int) n) < 128
  21961. && (noteStates[n] & midiChannelMask) != 0;
  21962. }
  21963. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21964. {
  21965. jassert (midiChannel >= 0 && midiChannel <= 16);
  21966. jassert (((unsigned int) midiNoteNumber) < 128);
  21967. const ScopedLock sl (lock);
  21968. if (((unsigned int) midiNoteNumber) < 128)
  21969. {
  21970. const int timeNow = (int) Time::getMillisecondCounter();
  21971. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21972. eventsToAdd.clear (0, timeNow - 500);
  21973. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21974. }
  21975. }
  21976. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21977. {
  21978. if (((unsigned int) midiNoteNumber) < 128)
  21979. {
  21980. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21981. for (int i = listeners.size(); --i >= 0;)
  21982. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21983. }
  21984. }
  21985. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21986. {
  21987. const ScopedLock sl (lock);
  21988. if (isNoteOn (midiChannel, midiNoteNumber))
  21989. {
  21990. const int timeNow = (int) Time::getMillisecondCounter();
  21991. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21992. eventsToAdd.clear (0, timeNow - 500);
  21993. noteOffInternal (midiChannel, midiNoteNumber);
  21994. }
  21995. }
  21996. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21997. {
  21998. if (isNoteOn (midiChannel, midiNoteNumber))
  21999. {
  22000. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22001. for (int i = listeners.size(); --i >= 0;)
  22002. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22003. }
  22004. }
  22005. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22006. {
  22007. const ScopedLock sl (lock);
  22008. if (midiChannel <= 0)
  22009. {
  22010. for (int i = 1; i <= 16; ++i)
  22011. allNotesOff (i);
  22012. }
  22013. else
  22014. {
  22015. for (int i = 0; i < 128; ++i)
  22016. noteOff (midiChannel, i);
  22017. }
  22018. }
  22019. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22020. {
  22021. if (message.isNoteOn())
  22022. {
  22023. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22024. }
  22025. else if (message.isNoteOff())
  22026. {
  22027. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22028. }
  22029. else if (message.isAllNotesOff())
  22030. {
  22031. for (int i = 0; i < 128; ++i)
  22032. noteOffInternal (message.getChannel(), i);
  22033. }
  22034. }
  22035. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22036. const int startSample,
  22037. const int numSamples,
  22038. const bool injectIndirectEvents)
  22039. {
  22040. MidiBuffer::Iterator i (buffer);
  22041. MidiMessage message (0xf4, 0.0);
  22042. int time;
  22043. const ScopedLock sl (lock);
  22044. while (i.getNextEvent (message, time))
  22045. processNextMidiEvent (message);
  22046. if (injectIndirectEvents)
  22047. {
  22048. MidiBuffer::Iterator i2 (eventsToAdd);
  22049. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22050. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22051. while (i2.getNextEvent (message, time))
  22052. {
  22053. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22054. buffer.addEvent (message, startSample + pos);
  22055. }
  22056. }
  22057. eventsToAdd.clear();
  22058. }
  22059. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22060. {
  22061. const ScopedLock sl (lock);
  22062. listeners.addIfNotAlreadyThere (listener);
  22063. }
  22064. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22065. {
  22066. const ScopedLock sl (lock);
  22067. listeners.removeValue (listener);
  22068. }
  22069. END_JUCE_NAMESPACE
  22070. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22071. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22072. BEGIN_JUCE_NAMESPACE
  22073. int MidiMessage::readVariableLengthVal (const uint8* data,
  22074. int& numBytesUsed) throw()
  22075. {
  22076. numBytesUsed = 0;
  22077. int v = 0;
  22078. int i;
  22079. do
  22080. {
  22081. i = (int) *data++;
  22082. if (++numBytesUsed > 6)
  22083. break;
  22084. v = (v << 7) + (i & 0x7f);
  22085. } while (i & 0x80);
  22086. return v;
  22087. }
  22088. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22089. {
  22090. // this method only works for valid starting bytes of a short midi message
  22091. jassert (firstByte >= 0x80
  22092. && firstByte != 0xf0
  22093. && firstByte != 0xf7);
  22094. static const char messageLengths[] =
  22095. {
  22096. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22097. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22098. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22099. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22100. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22101. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22102. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22103. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22104. };
  22105. return messageLengths [firstByte & 0x7f];
  22106. }
  22107. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22108. : timeStamp (t),
  22109. size (dataSize)
  22110. {
  22111. jassert (dataSize > 0);
  22112. if (dataSize <= 4)
  22113. data = static_cast<uint8*> (preallocatedData.asBytes);
  22114. else
  22115. data = new uint8 [dataSize];
  22116. memcpy (data, d, dataSize);
  22117. // check that the length matches the data..
  22118. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22119. }
  22120. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22121. : timeStamp (t),
  22122. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22123. size (1)
  22124. {
  22125. data[0] = (uint8) byte1;
  22126. // check that the length matches the data..
  22127. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22128. }
  22129. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22130. : timeStamp (t),
  22131. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22132. size (2)
  22133. {
  22134. data[0] = (uint8) byte1;
  22135. data[1] = (uint8) byte2;
  22136. // check that the length matches the data..
  22137. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22138. }
  22139. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22140. : timeStamp (t),
  22141. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22142. size (3)
  22143. {
  22144. data[0] = (uint8) byte1;
  22145. data[1] = (uint8) byte2;
  22146. data[2] = (uint8) byte3;
  22147. // check that the length matches the data..
  22148. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22149. }
  22150. MidiMessage::MidiMessage (const MidiMessage& other)
  22151. : timeStamp (other.timeStamp),
  22152. size (other.size)
  22153. {
  22154. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22155. {
  22156. data = new uint8 [size];
  22157. memcpy (data, other.data, size);
  22158. }
  22159. else
  22160. {
  22161. data = static_cast<uint8*> (preallocatedData.asBytes);
  22162. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22163. }
  22164. }
  22165. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22166. : timeStamp (newTimeStamp),
  22167. size (other.size)
  22168. {
  22169. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22170. {
  22171. data = new uint8 [size];
  22172. memcpy (data, other.data, size);
  22173. }
  22174. else
  22175. {
  22176. data = static_cast<uint8*> (preallocatedData.asBytes);
  22177. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22178. }
  22179. }
  22180. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22181. : timeStamp (t),
  22182. data (static_cast<uint8*> (preallocatedData.asBytes))
  22183. {
  22184. const uint8* src = static_cast <const uint8*> (src_);
  22185. unsigned int byte = (unsigned int) *src;
  22186. if (byte < 0x80)
  22187. {
  22188. byte = (unsigned int) (uint8) lastStatusByte;
  22189. numBytesUsed = -1;
  22190. }
  22191. else
  22192. {
  22193. numBytesUsed = 0;
  22194. --sz;
  22195. ++src;
  22196. }
  22197. if (byte >= 0x80)
  22198. {
  22199. if (byte == 0xf0)
  22200. {
  22201. const uint8* d = src;
  22202. while (d < src + sz)
  22203. {
  22204. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22205. {
  22206. if (*d == 0xf7) // include an 0xf7 if we hit one
  22207. ++d;
  22208. break;
  22209. }
  22210. ++d;
  22211. }
  22212. size = 1 + (int) (d - src);
  22213. data = new uint8 [size];
  22214. *data = (uint8) byte;
  22215. memcpy (data + 1, src, size - 1);
  22216. }
  22217. else if (byte == 0xff)
  22218. {
  22219. int n;
  22220. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22221. size = jmin (sz + 1, n + 2 + bytesLeft);
  22222. data = new uint8 [size];
  22223. *data = (uint8) byte;
  22224. memcpy (data + 1, src, size - 1);
  22225. }
  22226. else
  22227. {
  22228. preallocatedData.asInt32 = 0;
  22229. size = getMessageLengthFromFirstByte ((uint8) byte);
  22230. data[0] = (uint8) byte;
  22231. if (size > 1)
  22232. {
  22233. data[1] = src[0];
  22234. if (size > 2)
  22235. data[2] = src[1];
  22236. }
  22237. }
  22238. numBytesUsed += size;
  22239. }
  22240. else
  22241. {
  22242. preallocatedData.asInt32 = 0;
  22243. size = 0;
  22244. }
  22245. }
  22246. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22247. {
  22248. if (this != &other)
  22249. {
  22250. timeStamp = other.timeStamp;
  22251. size = other.size;
  22252. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22253. delete[] data;
  22254. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22255. {
  22256. data = new uint8 [size];
  22257. memcpy (data, other.data, size);
  22258. }
  22259. else
  22260. {
  22261. data = static_cast<uint8*> (preallocatedData.asBytes);
  22262. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22263. }
  22264. }
  22265. return *this;
  22266. }
  22267. MidiMessage::~MidiMessage()
  22268. {
  22269. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22270. delete[] data;
  22271. }
  22272. int MidiMessage::getChannel() const throw()
  22273. {
  22274. if ((data[0] & 0xf0) != 0xf0)
  22275. return (data[0] & 0xf) + 1;
  22276. else
  22277. return 0;
  22278. }
  22279. bool MidiMessage::isForChannel (const int channel) const throw()
  22280. {
  22281. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22282. return ((data[0] & 0xf) == channel - 1)
  22283. && ((data[0] & 0xf0) != 0xf0);
  22284. }
  22285. void MidiMessage::setChannel (const int channel) throw()
  22286. {
  22287. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22288. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22289. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22290. | (uint8)(channel - 1));
  22291. }
  22292. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22293. {
  22294. return ((data[0] & 0xf0) == 0x90)
  22295. && (returnTrueForVelocity0 || data[2] != 0);
  22296. }
  22297. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22298. {
  22299. return ((data[0] & 0xf0) == 0x80)
  22300. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22301. }
  22302. bool MidiMessage::isNoteOnOrOff() const throw()
  22303. {
  22304. const int d = data[0] & 0xf0;
  22305. return (d == 0x90) || (d == 0x80);
  22306. }
  22307. int MidiMessage::getNoteNumber() const throw()
  22308. {
  22309. return data[1];
  22310. }
  22311. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22312. {
  22313. if (isNoteOnOrOff())
  22314. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22315. }
  22316. uint8 MidiMessage::getVelocity() const throw()
  22317. {
  22318. if (isNoteOnOrOff())
  22319. return data[2];
  22320. else
  22321. return 0;
  22322. }
  22323. float MidiMessage::getFloatVelocity() const throw()
  22324. {
  22325. return getVelocity() * (1.0f / 127.0f);
  22326. }
  22327. void MidiMessage::setVelocity (const float newVelocity) throw()
  22328. {
  22329. if (isNoteOnOrOff())
  22330. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22331. }
  22332. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22333. {
  22334. if (isNoteOnOrOff())
  22335. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22336. }
  22337. bool MidiMessage::isAftertouch() const throw()
  22338. {
  22339. return (data[0] & 0xf0) == 0xa0;
  22340. }
  22341. int MidiMessage::getAfterTouchValue() const throw()
  22342. {
  22343. return data[2];
  22344. }
  22345. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22346. const int noteNum,
  22347. const int aftertouchValue) throw()
  22348. {
  22349. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22350. jassert (((unsigned int) noteNum) <= 127);
  22351. jassert (((unsigned int) aftertouchValue) <= 127);
  22352. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22353. noteNum & 0x7f,
  22354. aftertouchValue & 0x7f);
  22355. }
  22356. bool MidiMessage::isChannelPressure() const throw()
  22357. {
  22358. return (data[0] & 0xf0) == 0xd0;
  22359. }
  22360. int MidiMessage::getChannelPressureValue() const throw()
  22361. {
  22362. jassert (isChannelPressure());
  22363. return data[1];
  22364. }
  22365. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22366. const int pressure) throw()
  22367. {
  22368. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22369. jassert (((unsigned int) pressure) <= 127);
  22370. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22371. pressure & 0x7f);
  22372. }
  22373. bool MidiMessage::isProgramChange() const throw()
  22374. {
  22375. return (data[0] & 0xf0) == 0xc0;
  22376. }
  22377. int MidiMessage::getProgramChangeNumber() const throw()
  22378. {
  22379. return data[1];
  22380. }
  22381. const MidiMessage MidiMessage::programChange (const int channel,
  22382. const int programNumber) throw()
  22383. {
  22384. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22385. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22386. programNumber & 0x7f);
  22387. }
  22388. bool MidiMessage::isPitchWheel() const throw()
  22389. {
  22390. return (data[0] & 0xf0) == 0xe0;
  22391. }
  22392. int MidiMessage::getPitchWheelValue() const throw()
  22393. {
  22394. return data[1] | (data[2] << 7);
  22395. }
  22396. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22397. const int position) throw()
  22398. {
  22399. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22400. jassert (((unsigned int) position) <= 0x3fff);
  22401. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22402. position & 127,
  22403. (position >> 7) & 127);
  22404. }
  22405. bool MidiMessage::isController() const throw()
  22406. {
  22407. return (data[0] & 0xf0) == 0xb0;
  22408. }
  22409. int MidiMessage::getControllerNumber() const throw()
  22410. {
  22411. jassert (isController());
  22412. return data[1];
  22413. }
  22414. int MidiMessage::getControllerValue() const throw()
  22415. {
  22416. jassert (isController());
  22417. return data[2];
  22418. }
  22419. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22420. const int controllerType,
  22421. const int value) throw()
  22422. {
  22423. // the channel must be between 1 and 16 inclusive
  22424. jassert (channel > 0 && channel <= 16);
  22425. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22426. controllerType & 127,
  22427. value & 127);
  22428. }
  22429. const MidiMessage MidiMessage::noteOn (const int channel,
  22430. const int noteNumber,
  22431. const float velocity) throw()
  22432. {
  22433. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22434. }
  22435. const MidiMessage MidiMessage::noteOn (const int channel,
  22436. const int noteNumber,
  22437. const uint8 velocity) throw()
  22438. {
  22439. jassert (channel > 0 && channel <= 16);
  22440. jassert (((unsigned int) noteNumber) <= 127);
  22441. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22442. noteNumber & 127,
  22443. jlimit (0, 127, roundToInt (velocity)));
  22444. }
  22445. const MidiMessage MidiMessage::noteOff (const int channel,
  22446. const int noteNumber) throw()
  22447. {
  22448. jassert (channel > 0 && channel <= 16);
  22449. jassert (((unsigned int) noteNumber) <= 127);
  22450. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22451. }
  22452. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22453. {
  22454. jassert (channel > 0 && channel <= 16);
  22455. return controllerEvent (channel, 123, 0);
  22456. }
  22457. bool MidiMessage::isAllNotesOff() const throw()
  22458. {
  22459. return (data[0] & 0xf0) == 0xb0
  22460. && data[1] == 123;
  22461. }
  22462. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22463. {
  22464. return controllerEvent (channel, 120, 0);
  22465. }
  22466. bool MidiMessage::isAllSoundOff() const throw()
  22467. {
  22468. return (data[0] & 0xf0) == 0xb0
  22469. && data[1] == 120;
  22470. }
  22471. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22472. {
  22473. return controllerEvent (channel, 121, 0);
  22474. }
  22475. const MidiMessage MidiMessage::masterVolume (const float volume)
  22476. {
  22477. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22478. uint8 buf[8];
  22479. buf[0] = 0xf0;
  22480. buf[1] = 0x7f;
  22481. buf[2] = 0x7f;
  22482. buf[3] = 0x04;
  22483. buf[4] = 0x01;
  22484. buf[5] = (uint8) (vol & 0x7f);
  22485. buf[6] = (uint8) (vol >> 7);
  22486. buf[7] = 0xf7;
  22487. return MidiMessage (buf, 8);
  22488. }
  22489. bool MidiMessage::isSysEx() const throw()
  22490. {
  22491. return *data == 0xf0;
  22492. }
  22493. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22494. {
  22495. MemoryBlock mm (dataSize + 2);
  22496. uint8* const m = static_cast <uint8*> (mm.getData());
  22497. m[0] = 0xf0;
  22498. memcpy (m + 1, sysexData, dataSize);
  22499. m[dataSize + 1] = 0xf7;
  22500. return MidiMessage (m, dataSize + 2);
  22501. }
  22502. const uint8* MidiMessage::getSysExData() const throw()
  22503. {
  22504. return (isSysEx()) ? getRawData() + 1 : 0;
  22505. }
  22506. int MidiMessage::getSysExDataSize() const throw()
  22507. {
  22508. return (isSysEx()) ? size - 2 : 0;
  22509. }
  22510. bool MidiMessage::isMetaEvent() const throw()
  22511. {
  22512. return *data == 0xff;
  22513. }
  22514. bool MidiMessage::isActiveSense() const throw()
  22515. {
  22516. return *data == 0xfe;
  22517. }
  22518. int MidiMessage::getMetaEventType() const throw()
  22519. {
  22520. if (*data != 0xff)
  22521. return -1;
  22522. else
  22523. return data[1];
  22524. }
  22525. int MidiMessage::getMetaEventLength() const throw()
  22526. {
  22527. if (*data == 0xff)
  22528. {
  22529. int n;
  22530. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22531. }
  22532. return 0;
  22533. }
  22534. const uint8* MidiMessage::getMetaEventData() const throw()
  22535. {
  22536. int n;
  22537. const uint8* d = data + 2;
  22538. readVariableLengthVal (d, n);
  22539. return d + n;
  22540. }
  22541. bool MidiMessage::isTrackMetaEvent() const throw()
  22542. {
  22543. return getMetaEventType() == 0;
  22544. }
  22545. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22546. {
  22547. return getMetaEventType() == 47;
  22548. }
  22549. bool MidiMessage::isTextMetaEvent() const throw()
  22550. {
  22551. const int t = getMetaEventType();
  22552. return t > 0 && t < 16;
  22553. }
  22554. const String MidiMessage::getTextFromTextMetaEvent() const
  22555. {
  22556. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22557. }
  22558. bool MidiMessage::isTrackNameEvent() const throw()
  22559. {
  22560. return (data[1] == 3)
  22561. && (*data == 0xff);
  22562. }
  22563. bool MidiMessage::isTempoMetaEvent() const throw()
  22564. {
  22565. return (data[1] == 81)
  22566. && (*data == 0xff);
  22567. }
  22568. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22569. {
  22570. return (data[1] == 0x20)
  22571. && (*data == 0xff)
  22572. && (data[2] == 1);
  22573. }
  22574. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22575. {
  22576. return data[3] + 1;
  22577. }
  22578. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22579. {
  22580. if (! isTempoMetaEvent())
  22581. return 0.0;
  22582. const uint8* const d = getMetaEventData();
  22583. return (((unsigned int) d[0] << 16)
  22584. | ((unsigned int) d[1] << 8)
  22585. | d[2])
  22586. / 1000000.0;
  22587. }
  22588. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22589. {
  22590. if (timeFormat > 0)
  22591. {
  22592. if (! isTempoMetaEvent())
  22593. return 0.5 / timeFormat;
  22594. return getTempoSecondsPerQuarterNote() / timeFormat;
  22595. }
  22596. else
  22597. {
  22598. const int frameCode = (-timeFormat) >> 8;
  22599. double framesPerSecond;
  22600. switch (frameCode)
  22601. {
  22602. case 24: framesPerSecond = 24.0; break;
  22603. case 25: framesPerSecond = 25.0; break;
  22604. case 29: framesPerSecond = 29.97; break;
  22605. case 30: framesPerSecond = 30.0; break;
  22606. default: framesPerSecond = 30.0; break;
  22607. }
  22608. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22609. }
  22610. }
  22611. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22612. {
  22613. uint8 d[8];
  22614. d[0] = 0xff;
  22615. d[1] = 81;
  22616. d[2] = 3;
  22617. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22618. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22619. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22620. return MidiMessage (d, 6, 0.0);
  22621. }
  22622. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22623. {
  22624. return (data[1] == 0x58)
  22625. && (*data == (uint8) 0xff);
  22626. }
  22627. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22628. {
  22629. if (isTimeSignatureMetaEvent())
  22630. {
  22631. const uint8* const d = getMetaEventData();
  22632. numerator = d[0];
  22633. denominator = 1 << d[1];
  22634. }
  22635. else
  22636. {
  22637. numerator = 4;
  22638. denominator = 4;
  22639. }
  22640. }
  22641. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22642. {
  22643. uint8 d[8];
  22644. d[0] = 0xff;
  22645. d[1] = 0x58;
  22646. d[2] = 0x04;
  22647. d[3] = (uint8) numerator;
  22648. int n = 1;
  22649. int powerOfTwo = 0;
  22650. while (n < denominator)
  22651. {
  22652. n <<= 1;
  22653. ++powerOfTwo;
  22654. }
  22655. d[4] = (uint8) powerOfTwo;
  22656. d[5] = 0x01;
  22657. d[6] = 96;
  22658. return MidiMessage (d, 7, 0.0);
  22659. }
  22660. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22661. {
  22662. uint8 d[8];
  22663. d[0] = 0xff;
  22664. d[1] = 0x20;
  22665. d[2] = 0x01;
  22666. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22667. return MidiMessage (d, 4, 0.0);
  22668. }
  22669. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22670. {
  22671. return getMetaEventType() == 89;
  22672. }
  22673. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22674. {
  22675. return (int) *getMetaEventData();
  22676. }
  22677. const MidiMessage MidiMessage::endOfTrack() throw()
  22678. {
  22679. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22680. }
  22681. bool MidiMessage::isSongPositionPointer() const throw()
  22682. {
  22683. return *data == 0xf2;
  22684. }
  22685. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22686. {
  22687. return data[1] | (data[2] << 7);
  22688. }
  22689. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22690. {
  22691. return MidiMessage (0xf2,
  22692. positionInMidiBeats & 127,
  22693. (positionInMidiBeats >> 7) & 127);
  22694. }
  22695. bool MidiMessage::isMidiStart() const throw()
  22696. {
  22697. return *data == 0xfa;
  22698. }
  22699. const MidiMessage MidiMessage::midiStart() throw()
  22700. {
  22701. return MidiMessage (0xfa);
  22702. }
  22703. bool MidiMessage::isMidiContinue() const throw()
  22704. {
  22705. return *data == 0xfb;
  22706. }
  22707. const MidiMessage MidiMessage::midiContinue() throw()
  22708. {
  22709. return MidiMessage (0xfb);
  22710. }
  22711. bool MidiMessage::isMidiStop() const throw()
  22712. {
  22713. return *data == 0xfc;
  22714. }
  22715. const MidiMessage MidiMessage::midiStop() throw()
  22716. {
  22717. return MidiMessage (0xfc);
  22718. }
  22719. bool MidiMessage::isMidiClock() const throw()
  22720. {
  22721. return *data == 0xf8;
  22722. }
  22723. const MidiMessage MidiMessage::midiClock() throw()
  22724. {
  22725. return MidiMessage (0xf8);
  22726. }
  22727. bool MidiMessage::isQuarterFrame() const throw()
  22728. {
  22729. return *data == 0xf1;
  22730. }
  22731. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22732. {
  22733. return ((int) data[1]) >> 4;
  22734. }
  22735. int MidiMessage::getQuarterFrameValue() const throw()
  22736. {
  22737. return ((int) data[1]) & 0x0f;
  22738. }
  22739. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22740. const int value) throw()
  22741. {
  22742. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22743. }
  22744. bool MidiMessage::isFullFrame() const throw()
  22745. {
  22746. return data[0] == 0xf0
  22747. && data[1] == 0x7f
  22748. && size >= 10
  22749. && data[3] == 0x01
  22750. && data[4] == 0x01;
  22751. }
  22752. void MidiMessage::getFullFrameParameters (int& hours,
  22753. int& minutes,
  22754. int& seconds,
  22755. int& frames,
  22756. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22757. {
  22758. jassert (isFullFrame());
  22759. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22760. hours = data[5] & 0x1f;
  22761. minutes = data[6];
  22762. seconds = data[7];
  22763. frames = data[8];
  22764. }
  22765. const MidiMessage MidiMessage::fullFrame (const int hours,
  22766. const int minutes,
  22767. const int seconds,
  22768. const int frames,
  22769. MidiMessage::SmpteTimecodeType timecodeType)
  22770. {
  22771. uint8 d[10];
  22772. d[0] = 0xf0;
  22773. d[1] = 0x7f;
  22774. d[2] = 0x7f;
  22775. d[3] = 0x01;
  22776. d[4] = 0x01;
  22777. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22778. d[6] = (uint8) minutes;
  22779. d[7] = (uint8) seconds;
  22780. d[8] = (uint8) frames;
  22781. d[9] = 0xf7;
  22782. return MidiMessage (d, 10, 0.0);
  22783. }
  22784. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22785. {
  22786. return data[0] == 0xf0
  22787. && data[1] == 0x7f
  22788. && data[3] == 0x06
  22789. && size > 5;
  22790. }
  22791. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22792. {
  22793. jassert (isMidiMachineControlMessage());
  22794. return (MidiMachineControlCommand) data[4];
  22795. }
  22796. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22797. {
  22798. uint8 d[6];
  22799. d[0] = 0xf0;
  22800. d[1] = 0x7f;
  22801. d[2] = 0x00;
  22802. d[3] = 0x06;
  22803. d[4] = (uint8) command;
  22804. d[5] = 0xf7;
  22805. return MidiMessage (d, 6, 0.0);
  22806. }
  22807. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22808. int& minutes,
  22809. int& seconds,
  22810. int& frames) const throw()
  22811. {
  22812. if (size >= 12
  22813. && data[0] == 0xf0
  22814. && data[1] == 0x7f
  22815. && data[3] == 0x06
  22816. && data[4] == 0x44
  22817. && data[5] == 0x06
  22818. && data[6] == 0x01)
  22819. {
  22820. hours = data[7] % 24; // (that some machines send out hours > 24)
  22821. minutes = data[8];
  22822. seconds = data[9];
  22823. frames = data[10];
  22824. return true;
  22825. }
  22826. return false;
  22827. }
  22828. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22829. int minutes,
  22830. int seconds,
  22831. int frames)
  22832. {
  22833. uint8 d[12];
  22834. d[0] = 0xf0;
  22835. d[1] = 0x7f;
  22836. d[2] = 0x00;
  22837. d[3] = 0x06;
  22838. d[4] = 0x44;
  22839. d[5] = 0x06;
  22840. d[6] = 0x01;
  22841. d[7] = (uint8) hours;
  22842. d[8] = (uint8) minutes;
  22843. d[9] = (uint8) seconds;
  22844. d[10] = (uint8) frames;
  22845. d[11] = 0xf7;
  22846. return MidiMessage (d, 12, 0.0);
  22847. }
  22848. const String MidiMessage::getMidiNoteName (int note,
  22849. bool useSharps,
  22850. bool includeOctaveNumber,
  22851. int octaveNumForMiddleC) throw()
  22852. {
  22853. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22854. "F", "F#", "G", "G#", "A",
  22855. "A#", "B" };
  22856. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22857. "F", "Gb", "G", "Ab", "A",
  22858. "Bb", "B" };
  22859. if (((unsigned int) note) < 128)
  22860. {
  22861. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22862. : flatNoteNames [note % 12]);
  22863. if (includeOctaveNumber)
  22864. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22865. else
  22866. return s;
  22867. }
  22868. return String::empty;
  22869. }
  22870. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22871. {
  22872. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22873. return 440.0 * pow (2.0, noteNumber / 12.0);
  22874. }
  22875. const String MidiMessage::getGMInstrumentName (int n) throw()
  22876. {
  22877. const char *names[] =
  22878. {
  22879. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22880. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22881. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22882. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22883. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22884. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22885. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22886. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22887. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22888. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22889. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22890. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22891. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22892. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22893. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22894. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22895. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22896. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22897. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22898. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22899. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22900. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22901. "Applause", "Gunshot"
  22902. };
  22903. return (((unsigned int) n) < 128) ? names[n]
  22904. : (const char*)0;
  22905. }
  22906. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22907. {
  22908. const char* names[] =
  22909. {
  22910. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22911. "Bass", "Strings", "Ensemble", "Brass",
  22912. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22913. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22914. };
  22915. return (((unsigned int) n) <= 15) ? names[n]
  22916. : (const char*)0;
  22917. }
  22918. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22919. {
  22920. const char* names[] =
  22921. {
  22922. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22923. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22924. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22925. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22926. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22927. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22928. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22929. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22930. "Mute Triangle", "Open Triangle"
  22931. };
  22932. return (n >= 35 && n <= 81) ? names [n - 35]
  22933. : (const char*)0;
  22934. }
  22935. const String MidiMessage::getControllerName (int n) throw()
  22936. {
  22937. const char* names[] =
  22938. {
  22939. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22940. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22941. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22942. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22943. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22944. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22945. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22946. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22947. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22948. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22949. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22950. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22951. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22952. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22953. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22954. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22955. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22956. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22957. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22959. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22960. "Poly Operation"
  22961. };
  22962. return (((unsigned int) n) < 128) ? names[n]
  22963. : (const char*)0;
  22964. }
  22965. END_JUCE_NAMESPACE
  22966. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22967. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22968. BEGIN_JUCE_NAMESPACE
  22969. MidiMessageCollector::MidiMessageCollector()
  22970. : lastCallbackTime (0),
  22971. sampleRate (44100.0001)
  22972. {
  22973. }
  22974. MidiMessageCollector::~MidiMessageCollector()
  22975. {
  22976. }
  22977. void MidiMessageCollector::reset (const double sampleRate_)
  22978. {
  22979. jassert (sampleRate_ > 0);
  22980. const ScopedLock sl (midiCallbackLock);
  22981. sampleRate = sampleRate_;
  22982. incomingMessages.clear();
  22983. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22984. }
  22985. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22986. {
  22987. // you need to call reset() to set the correct sample rate before using this object
  22988. jassert (sampleRate != 44100.0001);
  22989. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22990. // for details of what the number should be.
  22991. jassert (message.getTimeStamp() != 0);
  22992. const ScopedLock sl (midiCallbackLock);
  22993. const int sampleNumber
  22994. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22995. incomingMessages.addEvent (message, sampleNumber);
  22996. // if the messages don't get used for over a second, we'd better
  22997. // get rid of any old ones to avoid the queue getting too big
  22998. if (sampleNumber > sampleRate)
  22999. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23000. }
  23001. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23002. const int numSamples)
  23003. {
  23004. // you need to call reset() to set the correct sample rate before using this object
  23005. jassert (sampleRate != 44100.0001);
  23006. const double timeNow = Time::getMillisecondCounterHiRes();
  23007. const double msElapsed = timeNow - lastCallbackTime;
  23008. const ScopedLock sl (midiCallbackLock);
  23009. lastCallbackTime = timeNow;
  23010. if (! incomingMessages.isEmpty())
  23011. {
  23012. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23013. int startSample = 0;
  23014. int scale = 1 << 16;
  23015. const uint8* midiData;
  23016. int numBytes, samplePosition;
  23017. MidiBuffer::Iterator iter (incomingMessages);
  23018. if (numSourceSamples > numSamples)
  23019. {
  23020. // if our list of events is longer than the buffer we're being
  23021. // asked for, scale them down to squeeze them all in..
  23022. const int maxBlockLengthToUse = numSamples << 5;
  23023. if (numSourceSamples > maxBlockLengthToUse)
  23024. {
  23025. startSample = numSourceSamples - maxBlockLengthToUse;
  23026. numSourceSamples = maxBlockLengthToUse;
  23027. iter.setNextSamplePosition (startSample);
  23028. }
  23029. scale = (numSamples << 10) / numSourceSamples;
  23030. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23031. {
  23032. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23033. destBuffer.addEvent (midiData, numBytes,
  23034. jlimit (0, numSamples - 1, samplePosition));
  23035. }
  23036. }
  23037. else
  23038. {
  23039. // if our event list is shorter than the number we need, put them
  23040. // towards the end of the buffer
  23041. startSample = numSamples - numSourceSamples;
  23042. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23043. {
  23044. destBuffer.addEvent (midiData, numBytes,
  23045. jlimit (0, numSamples - 1, samplePosition + startSample));
  23046. }
  23047. }
  23048. incomingMessages.clear();
  23049. }
  23050. }
  23051. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23052. {
  23053. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23054. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23055. addMessageToQueue (m);
  23056. }
  23057. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23058. {
  23059. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23060. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23061. addMessageToQueue (m);
  23062. }
  23063. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23064. {
  23065. addMessageToQueue (message);
  23066. }
  23067. END_JUCE_NAMESPACE
  23068. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23069. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23070. BEGIN_JUCE_NAMESPACE
  23071. MidiMessageSequence::MidiMessageSequence()
  23072. {
  23073. }
  23074. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23075. {
  23076. list.ensureStorageAllocated (other.list.size());
  23077. for (int i = 0; i < other.list.size(); ++i)
  23078. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23079. }
  23080. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23081. {
  23082. MidiMessageSequence otherCopy (other);
  23083. swapWith (otherCopy);
  23084. return *this;
  23085. }
  23086. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23087. {
  23088. list.swapWithArray (other.list);
  23089. }
  23090. MidiMessageSequence::~MidiMessageSequence()
  23091. {
  23092. }
  23093. void MidiMessageSequence::clear()
  23094. {
  23095. list.clear();
  23096. }
  23097. int MidiMessageSequence::getNumEvents() const
  23098. {
  23099. return list.size();
  23100. }
  23101. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23102. {
  23103. return list [index];
  23104. }
  23105. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23106. {
  23107. const MidiEventHolder* const meh = list [index];
  23108. if (meh != 0 && meh->noteOffObject != 0)
  23109. return meh->noteOffObject->message.getTimeStamp();
  23110. else
  23111. return 0.0;
  23112. }
  23113. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23114. {
  23115. const MidiEventHolder* const meh = list [index];
  23116. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23117. }
  23118. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23119. {
  23120. return list.indexOf (event);
  23121. }
  23122. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23123. {
  23124. const int numEvents = list.size();
  23125. int i;
  23126. for (i = 0; i < numEvents; ++i)
  23127. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23128. break;
  23129. return i;
  23130. }
  23131. double MidiMessageSequence::getStartTime() const
  23132. {
  23133. if (list.size() > 0)
  23134. return list.getUnchecked(0)->message.getTimeStamp();
  23135. else
  23136. return 0;
  23137. }
  23138. double MidiMessageSequence::getEndTime() const
  23139. {
  23140. if (list.size() > 0)
  23141. return list.getLast()->message.getTimeStamp();
  23142. else
  23143. return 0;
  23144. }
  23145. double MidiMessageSequence::getEventTime (const int index) const
  23146. {
  23147. if (((unsigned int) index) < (unsigned int) list.size())
  23148. return list.getUnchecked (index)->message.getTimeStamp();
  23149. return 0.0;
  23150. }
  23151. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23152. double timeAdjustment)
  23153. {
  23154. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23155. timeAdjustment += newMessage.getTimeStamp();
  23156. newOne->message.setTimeStamp (timeAdjustment);
  23157. int i;
  23158. for (i = list.size(); --i >= 0;)
  23159. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23160. break;
  23161. list.insert (i + 1, newOne);
  23162. }
  23163. void MidiMessageSequence::deleteEvent (const int index,
  23164. const bool deleteMatchingNoteUp)
  23165. {
  23166. if (((unsigned int) index) < (unsigned int) list.size())
  23167. {
  23168. if (deleteMatchingNoteUp)
  23169. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23170. list.remove (index);
  23171. }
  23172. }
  23173. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23174. double timeAdjustment,
  23175. double firstAllowableTime,
  23176. double endOfAllowableDestTimes)
  23177. {
  23178. firstAllowableTime -= timeAdjustment;
  23179. endOfAllowableDestTimes -= timeAdjustment;
  23180. for (int i = 0; i < other.list.size(); ++i)
  23181. {
  23182. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23183. const double t = m.getTimeStamp();
  23184. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23185. {
  23186. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23187. newOne->message.setTimeStamp (timeAdjustment + t);
  23188. list.add (newOne);
  23189. }
  23190. }
  23191. sort();
  23192. }
  23193. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23194. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23195. {
  23196. const double diff = first->message.getTimeStamp()
  23197. - second->message.getTimeStamp();
  23198. return (diff > 0) - (diff < 0);
  23199. }
  23200. void MidiMessageSequence::sort()
  23201. {
  23202. list.sort (*this, true);
  23203. }
  23204. void MidiMessageSequence::updateMatchedPairs()
  23205. {
  23206. for (int i = 0; i < list.size(); ++i)
  23207. {
  23208. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23209. if (m1.isNoteOn())
  23210. {
  23211. list.getUnchecked(i)->noteOffObject = 0;
  23212. const int note = m1.getNoteNumber();
  23213. const int chan = m1.getChannel();
  23214. const int len = list.size();
  23215. for (int j = i + 1; j < len; ++j)
  23216. {
  23217. const MidiMessage& m = list.getUnchecked(j)->message;
  23218. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23219. {
  23220. if (m.isNoteOff())
  23221. {
  23222. list.getUnchecked(i)->noteOffObject = list[j];
  23223. break;
  23224. }
  23225. else if (m.isNoteOn())
  23226. {
  23227. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23228. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23229. list.getUnchecked(i)->noteOffObject = list[j];
  23230. break;
  23231. }
  23232. }
  23233. }
  23234. }
  23235. }
  23236. }
  23237. void MidiMessageSequence::addTimeToMessages (const double delta)
  23238. {
  23239. for (int i = list.size(); --i >= 0;)
  23240. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23241. + delta);
  23242. }
  23243. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23244. MidiMessageSequence& destSequence,
  23245. const bool alsoIncludeMetaEvents) const
  23246. {
  23247. for (int i = 0; i < list.size(); ++i)
  23248. {
  23249. const MidiMessage& mm = list.getUnchecked(i)->message;
  23250. if (mm.isForChannel (channelNumberToExtract)
  23251. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23252. {
  23253. destSequence.addEvent (mm);
  23254. }
  23255. }
  23256. }
  23257. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23258. {
  23259. for (int i = 0; i < list.size(); ++i)
  23260. {
  23261. const MidiMessage& mm = list.getUnchecked(i)->message;
  23262. if (mm.isSysEx())
  23263. destSequence.addEvent (mm);
  23264. }
  23265. }
  23266. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23267. {
  23268. for (int i = list.size(); --i >= 0;)
  23269. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23270. list.remove(i);
  23271. }
  23272. void MidiMessageSequence::deleteSysExMessages()
  23273. {
  23274. for (int i = list.size(); --i >= 0;)
  23275. if (list.getUnchecked(i)->message.isSysEx())
  23276. list.remove(i);
  23277. }
  23278. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23279. const double time,
  23280. OwnedArray<MidiMessage>& dest)
  23281. {
  23282. bool doneProg = false;
  23283. bool donePitchWheel = false;
  23284. Array <int> doneControllers;
  23285. doneControllers.ensureStorageAllocated (32);
  23286. for (int i = list.size(); --i >= 0;)
  23287. {
  23288. const MidiMessage& mm = list.getUnchecked(i)->message;
  23289. if (mm.isForChannel (channelNumber)
  23290. && mm.getTimeStamp() <= time)
  23291. {
  23292. if (mm.isProgramChange())
  23293. {
  23294. if (! doneProg)
  23295. {
  23296. dest.add (new MidiMessage (mm, 0.0));
  23297. doneProg = true;
  23298. }
  23299. }
  23300. else if (mm.isController())
  23301. {
  23302. if (! doneControllers.contains (mm.getControllerNumber()))
  23303. {
  23304. dest.add (new MidiMessage (mm, 0.0));
  23305. doneControllers.add (mm.getControllerNumber());
  23306. }
  23307. }
  23308. else if (mm.isPitchWheel())
  23309. {
  23310. if (! donePitchWheel)
  23311. {
  23312. dest.add (new MidiMessage (mm, 0.0));
  23313. donePitchWheel = true;
  23314. }
  23315. }
  23316. }
  23317. }
  23318. }
  23319. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23320. : message (message_),
  23321. noteOffObject (0)
  23322. {
  23323. }
  23324. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23325. {
  23326. }
  23327. END_JUCE_NAMESPACE
  23328. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23329. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23330. BEGIN_JUCE_NAMESPACE
  23331. AudioPluginFormat::AudioPluginFormat() throw()
  23332. {
  23333. }
  23334. AudioPluginFormat::~AudioPluginFormat()
  23335. {
  23336. }
  23337. END_JUCE_NAMESPACE
  23338. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23339. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23340. BEGIN_JUCE_NAMESPACE
  23341. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23342. {
  23343. }
  23344. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23345. {
  23346. clearSingletonInstance();
  23347. }
  23348. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23349. void AudioPluginFormatManager::addDefaultFormats()
  23350. {
  23351. #if JUCE_DEBUG
  23352. // you should only call this method once!
  23353. for (int i = formats.size(); --i >= 0;)
  23354. {
  23355. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23356. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23357. #endif
  23358. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23359. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23360. #endif
  23361. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23362. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23363. #endif
  23364. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23365. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23366. #endif
  23367. }
  23368. #endif
  23369. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23370. formats.add (new AudioUnitPluginFormat());
  23371. #endif
  23372. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23373. formats.add (new VSTPluginFormat());
  23374. #endif
  23375. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23376. formats.add (new DirectXPluginFormat());
  23377. #endif
  23378. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23379. formats.add (new LADSPAPluginFormat());
  23380. #endif
  23381. }
  23382. int AudioPluginFormatManager::getNumFormats() throw()
  23383. {
  23384. return formats.size();
  23385. }
  23386. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23387. {
  23388. return formats [index];
  23389. }
  23390. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23391. {
  23392. formats.add (format);
  23393. }
  23394. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23395. String& errorMessage) const
  23396. {
  23397. AudioPluginInstance* result = 0;
  23398. for (int i = 0; i < formats.size(); ++i)
  23399. {
  23400. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23401. if (result != 0)
  23402. break;
  23403. }
  23404. if (result == 0)
  23405. {
  23406. if (! doesPluginStillExist (description))
  23407. errorMessage = TRANS ("This plug-in file no longer exists");
  23408. else
  23409. errorMessage = TRANS ("This plug-in failed to load correctly");
  23410. }
  23411. return result;
  23412. }
  23413. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23414. {
  23415. for (int i = 0; i < formats.size(); ++i)
  23416. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23417. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23418. return false;
  23419. }
  23420. END_JUCE_NAMESPACE
  23421. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23422. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23423. #define JUCE_PLUGIN_HOST 1
  23424. BEGIN_JUCE_NAMESPACE
  23425. AudioPluginInstance::AudioPluginInstance()
  23426. {
  23427. }
  23428. AudioPluginInstance::~AudioPluginInstance()
  23429. {
  23430. }
  23431. END_JUCE_NAMESPACE
  23432. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23433. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23434. BEGIN_JUCE_NAMESPACE
  23435. KnownPluginList::KnownPluginList()
  23436. {
  23437. }
  23438. KnownPluginList::~KnownPluginList()
  23439. {
  23440. }
  23441. void KnownPluginList::clear()
  23442. {
  23443. if (types.size() > 0)
  23444. {
  23445. types.clear();
  23446. sendChangeMessage (this);
  23447. }
  23448. }
  23449. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23450. {
  23451. for (int i = 0; i < types.size(); ++i)
  23452. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23453. return types.getUnchecked(i);
  23454. return 0;
  23455. }
  23456. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23457. {
  23458. for (int i = 0; i < types.size(); ++i)
  23459. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23460. return types.getUnchecked(i);
  23461. return 0;
  23462. }
  23463. bool KnownPluginList::addType (const PluginDescription& type)
  23464. {
  23465. for (int i = types.size(); --i >= 0;)
  23466. {
  23467. if (types.getUnchecked(i)->isDuplicateOf (type))
  23468. {
  23469. // strange - found a duplicate plugin with different info..
  23470. jassert (types.getUnchecked(i)->name == type.name);
  23471. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23472. *types.getUnchecked(i) = type;
  23473. return false;
  23474. }
  23475. }
  23476. types.add (new PluginDescription (type));
  23477. sendChangeMessage (this);
  23478. return true;
  23479. }
  23480. void KnownPluginList::removeType (const int index) throw()
  23481. {
  23482. types.remove (index);
  23483. sendChangeMessage (this);
  23484. }
  23485. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23486. {
  23487. if (fileOrIdentifier.startsWithChar ('/')
  23488. || fileOrIdentifier[1] == ':')
  23489. {
  23490. return File (fileOrIdentifier).getLastModificationTime();
  23491. }
  23492. return Time (0);
  23493. }
  23494. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23495. {
  23496. return t1 != t2 || t1 == Time (0);
  23497. }
  23498. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23499. {
  23500. if (getTypeForFile (fileOrIdentifier) == 0)
  23501. return false;
  23502. for (int i = types.size(); --i >= 0;)
  23503. {
  23504. const PluginDescription* const d = types.getUnchecked(i);
  23505. if (d->fileOrIdentifier == fileOrIdentifier
  23506. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23507. {
  23508. return false;
  23509. }
  23510. }
  23511. return true;
  23512. }
  23513. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23514. const bool dontRescanIfAlreadyInList,
  23515. OwnedArray <PluginDescription>& typesFound,
  23516. AudioPluginFormat& format)
  23517. {
  23518. bool addedOne = false;
  23519. if (dontRescanIfAlreadyInList
  23520. && getTypeForFile (fileOrIdentifier) != 0)
  23521. {
  23522. bool needsRescanning = false;
  23523. for (int i = types.size(); --i >= 0;)
  23524. {
  23525. const PluginDescription* const d = types.getUnchecked(i);
  23526. if (d->fileOrIdentifier == fileOrIdentifier)
  23527. {
  23528. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23529. needsRescanning = true;
  23530. else
  23531. typesFound.add (new PluginDescription (*d));
  23532. }
  23533. }
  23534. if (! needsRescanning)
  23535. return false;
  23536. }
  23537. OwnedArray <PluginDescription> found;
  23538. format.findAllTypesForFile (found, fileOrIdentifier);
  23539. for (int i = 0; i < found.size(); ++i)
  23540. {
  23541. PluginDescription* const desc = found.getUnchecked(i);
  23542. jassert (desc != 0);
  23543. if (addType (*desc))
  23544. addedOne = true;
  23545. typesFound.add (new PluginDescription (*desc));
  23546. }
  23547. return addedOne;
  23548. }
  23549. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23550. OwnedArray <PluginDescription>& typesFound)
  23551. {
  23552. for (int i = 0; i < files.size(); ++i)
  23553. {
  23554. bool loaded = false;
  23555. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23556. {
  23557. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23558. if (scanAndAddFile (files[i], true, typesFound, *format))
  23559. loaded = true;
  23560. }
  23561. if (! loaded)
  23562. {
  23563. const File f (files[i]);
  23564. if (f.isDirectory())
  23565. {
  23566. StringArray s;
  23567. {
  23568. Array<File> subFiles;
  23569. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23570. for (int j = 0; j < subFiles.size(); ++j)
  23571. s.add (subFiles.getReference(j).getFullPathName());
  23572. }
  23573. scanAndAddDragAndDroppedFiles (s, typesFound);
  23574. }
  23575. }
  23576. }
  23577. }
  23578. class PluginSorter
  23579. {
  23580. public:
  23581. KnownPluginList::SortMethod method;
  23582. PluginSorter() throw() {}
  23583. int compareElements (const PluginDescription* const first,
  23584. const PluginDescription* const second) const throw()
  23585. {
  23586. int diff = 0;
  23587. if (method == KnownPluginList::sortByCategory)
  23588. diff = first->category.compareLexicographically (second->category);
  23589. else if (method == KnownPluginList::sortByManufacturer)
  23590. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23591. else if (method == KnownPluginList::sortByFileSystemLocation)
  23592. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23593. .upToLastOccurrenceOf ("/", false, false)
  23594. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23595. .upToLastOccurrenceOf ("/", false, false));
  23596. if (diff == 0)
  23597. diff = first->name.compareLexicographically (second->name);
  23598. return diff;
  23599. }
  23600. };
  23601. void KnownPluginList::sort (const SortMethod method)
  23602. {
  23603. if (method != defaultOrder)
  23604. {
  23605. PluginSorter sorter;
  23606. sorter.method = method;
  23607. types.sort (sorter, true);
  23608. sendChangeMessage (this);
  23609. }
  23610. }
  23611. XmlElement* KnownPluginList::createXml() const
  23612. {
  23613. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23614. for (int i = 0; i < types.size(); ++i)
  23615. e->addChildElement (types.getUnchecked(i)->createXml());
  23616. return e;
  23617. }
  23618. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23619. {
  23620. clear();
  23621. if (xml.hasTagName ("KNOWNPLUGINS"))
  23622. {
  23623. forEachXmlChildElement (xml, e)
  23624. {
  23625. PluginDescription info;
  23626. if (info.loadFromXml (*e))
  23627. addType (info);
  23628. }
  23629. }
  23630. }
  23631. const int menuIdBase = 0x324503f4;
  23632. // This is used to turn a bunch of paths into a nested menu structure.
  23633. struct PluginFilesystemTree
  23634. {
  23635. private:
  23636. String folder;
  23637. OwnedArray <PluginFilesystemTree> subFolders;
  23638. Array <PluginDescription*> plugins;
  23639. void addPlugin (PluginDescription* const pd, const String& path)
  23640. {
  23641. if (path.isEmpty())
  23642. {
  23643. plugins.add (pd);
  23644. }
  23645. else
  23646. {
  23647. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23648. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23649. for (int i = subFolders.size(); --i >= 0;)
  23650. {
  23651. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23652. {
  23653. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23654. return;
  23655. }
  23656. }
  23657. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23658. newFolder->folder = firstSubFolder;
  23659. subFolders.add (newFolder);
  23660. newFolder->addPlugin (pd, remainingPath);
  23661. }
  23662. }
  23663. // removes any deeply nested folders that don't contain any actual plugins
  23664. void optimise()
  23665. {
  23666. for (int i = subFolders.size(); --i >= 0;)
  23667. {
  23668. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23669. sub->optimise();
  23670. if (sub->plugins.size() == 0)
  23671. {
  23672. for (int j = 0; j < sub->subFolders.size(); ++j)
  23673. subFolders.add (sub->subFolders.getUnchecked(j));
  23674. sub->subFolders.clear (false);
  23675. subFolders.remove (i);
  23676. }
  23677. }
  23678. }
  23679. public:
  23680. void buildTree (const Array <PluginDescription*>& allPlugins)
  23681. {
  23682. for (int i = 0; i < allPlugins.size(); ++i)
  23683. {
  23684. String path (allPlugins.getUnchecked(i)
  23685. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23686. .upToLastOccurrenceOf ("/", false, false));
  23687. if (path.substring (1, 2) == ":")
  23688. path = path.substring (2);
  23689. addPlugin (allPlugins.getUnchecked(i), path);
  23690. }
  23691. optimise();
  23692. }
  23693. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23694. {
  23695. int i;
  23696. for (i = 0; i < subFolders.size(); ++i)
  23697. {
  23698. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23699. PopupMenu subMenu;
  23700. sub->addToMenu (subMenu, allPlugins);
  23701. #if JUCE_MAC
  23702. // avoid the special AU formatting nonsense on Mac..
  23703. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23704. #else
  23705. m.addSubMenu (sub->folder, subMenu);
  23706. #endif
  23707. }
  23708. for (i = 0; i < plugins.size(); ++i)
  23709. {
  23710. PluginDescription* const plugin = plugins.getUnchecked(i);
  23711. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23712. plugin->name, true, false);
  23713. }
  23714. }
  23715. };
  23716. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23717. {
  23718. Array <PluginDescription*> sorted;
  23719. {
  23720. PluginSorter sorter;
  23721. sorter.method = sortMethod;
  23722. for (int i = 0; i < types.size(); ++i)
  23723. sorted.addSorted (sorter, types.getUnchecked(i));
  23724. }
  23725. if (sortMethod == sortByCategory
  23726. || sortMethod == sortByManufacturer)
  23727. {
  23728. String lastSubMenuName;
  23729. PopupMenu sub;
  23730. for (int i = 0; i < sorted.size(); ++i)
  23731. {
  23732. const PluginDescription* const pd = sorted.getUnchecked(i);
  23733. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23734. : pd->manufacturerName);
  23735. if (! thisSubMenuName.containsNonWhitespaceChars())
  23736. thisSubMenuName = "Other";
  23737. if (thisSubMenuName != lastSubMenuName)
  23738. {
  23739. if (sub.getNumItems() > 0)
  23740. {
  23741. menu.addSubMenu (lastSubMenuName, sub);
  23742. sub.clear();
  23743. }
  23744. lastSubMenuName = thisSubMenuName;
  23745. }
  23746. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23747. }
  23748. if (sub.getNumItems() > 0)
  23749. menu.addSubMenu (lastSubMenuName, sub);
  23750. }
  23751. else if (sortMethod == sortByFileSystemLocation)
  23752. {
  23753. PluginFilesystemTree root;
  23754. root.buildTree (sorted);
  23755. root.addToMenu (menu, types);
  23756. }
  23757. else
  23758. {
  23759. for (int i = 0; i < sorted.size(); ++i)
  23760. {
  23761. const PluginDescription* const pd = sorted.getUnchecked(i);
  23762. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23763. }
  23764. }
  23765. }
  23766. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23767. {
  23768. const int i = menuResultCode - menuIdBase;
  23769. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23770. }
  23771. END_JUCE_NAMESPACE
  23772. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23773. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23774. BEGIN_JUCE_NAMESPACE
  23775. PluginDescription::PluginDescription() throw()
  23776. : uid (0),
  23777. isInstrument (false),
  23778. numInputChannels (0),
  23779. numOutputChannels (0)
  23780. {
  23781. }
  23782. PluginDescription::~PluginDescription() throw()
  23783. {
  23784. }
  23785. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23786. : name (other.name),
  23787. pluginFormatName (other.pluginFormatName),
  23788. category (other.category),
  23789. manufacturerName (other.manufacturerName),
  23790. version (other.version),
  23791. fileOrIdentifier (other.fileOrIdentifier),
  23792. lastFileModTime (other.lastFileModTime),
  23793. uid (other.uid),
  23794. isInstrument (other.isInstrument),
  23795. numInputChannels (other.numInputChannels),
  23796. numOutputChannels (other.numOutputChannels)
  23797. {
  23798. }
  23799. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23800. {
  23801. name = other.name;
  23802. pluginFormatName = other.pluginFormatName;
  23803. category = other.category;
  23804. manufacturerName = other.manufacturerName;
  23805. version = other.version;
  23806. fileOrIdentifier = other.fileOrIdentifier;
  23807. uid = other.uid;
  23808. isInstrument = other.isInstrument;
  23809. lastFileModTime = other.lastFileModTime;
  23810. numInputChannels = other.numInputChannels;
  23811. numOutputChannels = other.numOutputChannels;
  23812. return *this;
  23813. }
  23814. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23815. {
  23816. return fileOrIdentifier == other.fileOrIdentifier
  23817. && uid == other.uid;
  23818. }
  23819. const String PluginDescription::createIdentifierString() const throw()
  23820. {
  23821. return pluginFormatName
  23822. + "-" + name
  23823. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23824. + "-" + String::toHexString (uid);
  23825. }
  23826. XmlElement* PluginDescription::createXml() const
  23827. {
  23828. XmlElement* const e = new XmlElement ("PLUGIN");
  23829. e->setAttribute ("name", name);
  23830. e->setAttribute ("format", pluginFormatName);
  23831. e->setAttribute ("category", category);
  23832. e->setAttribute ("manufacturer", manufacturerName);
  23833. e->setAttribute ("version", version);
  23834. e->setAttribute ("file", fileOrIdentifier);
  23835. e->setAttribute ("uid", String::toHexString (uid));
  23836. e->setAttribute ("isInstrument", isInstrument);
  23837. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23838. e->setAttribute ("numInputs", numInputChannels);
  23839. e->setAttribute ("numOutputs", numOutputChannels);
  23840. return e;
  23841. }
  23842. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23843. {
  23844. if (xml.hasTagName ("PLUGIN"))
  23845. {
  23846. name = xml.getStringAttribute ("name");
  23847. pluginFormatName = xml.getStringAttribute ("format");
  23848. category = xml.getStringAttribute ("category");
  23849. manufacturerName = xml.getStringAttribute ("manufacturer");
  23850. version = xml.getStringAttribute ("version");
  23851. fileOrIdentifier = xml.getStringAttribute ("file");
  23852. uid = xml.getStringAttribute ("uid").getHexValue32();
  23853. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23854. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23855. numInputChannels = xml.getIntAttribute ("numInputs");
  23856. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23857. return true;
  23858. }
  23859. return false;
  23860. }
  23861. END_JUCE_NAMESPACE
  23862. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23863. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23864. BEGIN_JUCE_NAMESPACE
  23865. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23866. AudioPluginFormat& formatToLookFor,
  23867. FileSearchPath directoriesToSearch,
  23868. const bool recursive,
  23869. const File& deadMansPedalFile_)
  23870. : list (listToAddTo),
  23871. format (formatToLookFor),
  23872. deadMansPedalFile (deadMansPedalFile_),
  23873. nextIndex (0),
  23874. progress (0)
  23875. {
  23876. directoriesToSearch.removeRedundantPaths();
  23877. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23878. // If any plugins have crashed recently when being loaded, move them to the
  23879. // end of the list to give the others a chance to load correctly..
  23880. const StringArray crashedPlugins (getDeadMansPedalFile());
  23881. for (int i = 0; i < crashedPlugins.size(); ++i)
  23882. {
  23883. const String f = crashedPlugins[i];
  23884. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23885. if (f == filesOrIdentifiersToScan[j])
  23886. filesOrIdentifiersToScan.move (j, -1);
  23887. }
  23888. }
  23889. PluginDirectoryScanner::~PluginDirectoryScanner()
  23890. {
  23891. }
  23892. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23893. {
  23894. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23895. }
  23896. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23897. {
  23898. String file (filesOrIdentifiersToScan [nextIndex]);
  23899. if (file.isNotEmpty())
  23900. {
  23901. if (! list.isListingUpToDate (file))
  23902. {
  23903. OwnedArray <PluginDescription> typesFound;
  23904. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23905. StringArray crashedPlugins (getDeadMansPedalFile());
  23906. crashedPlugins.removeString (file);
  23907. crashedPlugins.add (file);
  23908. setDeadMansPedalFile (crashedPlugins);
  23909. list.scanAndAddFile (file,
  23910. dontRescanIfAlreadyInList,
  23911. typesFound,
  23912. format);
  23913. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23914. crashedPlugins.removeString (file);
  23915. setDeadMansPedalFile (crashedPlugins);
  23916. if (typesFound.size() == 0)
  23917. failedFiles.add (file);
  23918. }
  23919. ++nextIndex;
  23920. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23921. }
  23922. return nextIndex < filesOrIdentifiersToScan.size();
  23923. }
  23924. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23925. {
  23926. StringArray lines;
  23927. if (deadMansPedalFile != File::nonexistent)
  23928. {
  23929. lines.addLines (deadMansPedalFile.loadFileAsString());
  23930. lines.removeEmptyStrings();
  23931. }
  23932. return lines;
  23933. }
  23934. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23935. {
  23936. if (deadMansPedalFile != File::nonexistent)
  23937. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23938. }
  23939. END_JUCE_NAMESPACE
  23940. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23941. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23942. BEGIN_JUCE_NAMESPACE
  23943. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23944. const File& deadMansPedalFile_,
  23945. PropertiesFile* const propertiesToUse_)
  23946. : list (listToEdit),
  23947. deadMansPedalFile (deadMansPedalFile_),
  23948. propertiesToUse (propertiesToUse_)
  23949. {
  23950. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23951. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23952. optionsButton->addButtonListener (this);
  23953. optionsButton->setTriggeredOnMouseDown (true);
  23954. setSize (400, 600);
  23955. list.addChangeListener (this);
  23956. changeListenerCallback (0);
  23957. }
  23958. PluginListComponent::~PluginListComponent()
  23959. {
  23960. list.removeChangeListener (this);
  23961. deleteAllChildren();
  23962. }
  23963. void PluginListComponent::resized()
  23964. {
  23965. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23966. optionsButton->changeWidthToFitText (24);
  23967. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23968. }
  23969. void PluginListComponent::changeListenerCallback (void*)
  23970. {
  23971. listBox->updateContent();
  23972. listBox->repaint();
  23973. }
  23974. int PluginListComponent::getNumRows()
  23975. {
  23976. return list.getNumTypes();
  23977. }
  23978. void PluginListComponent::paintListBoxItem (int row,
  23979. Graphics& g,
  23980. int width, int height,
  23981. bool rowIsSelected)
  23982. {
  23983. if (rowIsSelected)
  23984. g.fillAll (findColour (TextEditor::highlightColourId));
  23985. const PluginDescription* const pd = list.getType (row);
  23986. if (pd != 0)
  23987. {
  23988. GlyphArrangement ga;
  23989. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23990. g.setColour (Colours::black);
  23991. ga.draw (g);
  23992. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23993. String desc;
  23994. desc << pd->pluginFormatName
  23995. << (pd->isInstrument ? " instrument" : " effect")
  23996. << " - "
  23997. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23998. << " / "
  23999. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24000. if (pd->manufacturerName.isNotEmpty())
  24001. desc << " - " << pd->manufacturerName;
  24002. if (pd->version.isNotEmpty())
  24003. desc << " - " << pd->version;
  24004. if (pd->category.isNotEmpty())
  24005. desc << " - category: '" << pd->category << '\'';
  24006. g.setColour (Colours::grey);
  24007. ga.clear();
  24008. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24009. ga.draw (g);
  24010. }
  24011. }
  24012. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24013. {
  24014. list.removeType (lastRowSelected);
  24015. }
  24016. void PluginListComponent::buttonClicked (Button* b)
  24017. {
  24018. if (optionsButton == b)
  24019. {
  24020. PopupMenu menu;
  24021. menu.addItem (1, TRANS("Clear list"));
  24022. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24023. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24024. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24025. menu.addSeparator();
  24026. menu.addItem (2, TRANS("Sort alphabetically"));
  24027. menu.addItem (3, TRANS("Sort by category"));
  24028. menu.addItem (4, TRANS("Sort by manufacturer"));
  24029. menu.addSeparator();
  24030. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24031. {
  24032. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24033. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24034. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24035. }
  24036. const int r = menu.showAt (optionsButton);
  24037. if (r == 1)
  24038. {
  24039. list.clear();
  24040. }
  24041. else if (r == 2)
  24042. {
  24043. list.sort (KnownPluginList::sortAlphabetically);
  24044. }
  24045. else if (r == 3)
  24046. {
  24047. list.sort (KnownPluginList::sortByCategory);
  24048. }
  24049. else if (r == 4)
  24050. {
  24051. list.sort (KnownPluginList::sortByManufacturer);
  24052. }
  24053. else if (r == 5)
  24054. {
  24055. const SparseSet <int> selected (listBox->getSelectedRows());
  24056. for (int i = list.getNumTypes(); --i >= 0;)
  24057. if (selected.contains (i))
  24058. list.removeType (i);
  24059. }
  24060. else if (r == 6)
  24061. {
  24062. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24063. if (desc != 0)
  24064. {
  24065. if (File (desc->fileOrIdentifier).existsAsFile())
  24066. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24067. }
  24068. }
  24069. else if (r == 7)
  24070. {
  24071. for (int i = list.getNumTypes(); --i >= 0;)
  24072. {
  24073. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24074. {
  24075. list.removeType (i);
  24076. }
  24077. }
  24078. }
  24079. else if (r != 0)
  24080. {
  24081. typeToScan = r - 10;
  24082. startTimer (1);
  24083. }
  24084. }
  24085. }
  24086. void PluginListComponent::timerCallback()
  24087. {
  24088. stopTimer();
  24089. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24090. }
  24091. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24092. {
  24093. return true;
  24094. }
  24095. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24096. {
  24097. OwnedArray <PluginDescription> typesFound;
  24098. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24099. }
  24100. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24101. {
  24102. if (format == 0)
  24103. return;
  24104. FileSearchPath path (format->getDefaultLocationsToSearch());
  24105. if (propertiesToUse != 0)
  24106. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24107. {
  24108. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24109. FileSearchPathListComponent pathList;
  24110. pathList.setSize (500, 300);
  24111. pathList.setPath (path);
  24112. aw.addCustomComponent (&pathList);
  24113. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24114. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24115. if (aw.runModalLoop() == 0)
  24116. return;
  24117. path = pathList.getPath();
  24118. }
  24119. if (propertiesToUse != 0)
  24120. {
  24121. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24122. propertiesToUse->saveIfNeeded();
  24123. }
  24124. double progress = 0.0;
  24125. AlertWindow aw (TRANS("Scanning for plugins..."),
  24126. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24127. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24128. aw.addProgressBarComponent (progress);
  24129. aw.enterModalState();
  24130. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24131. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24132. for (;;)
  24133. {
  24134. aw.setMessage (TRANS("Testing:\n\n")
  24135. + scanner.getNextPluginFileThatWillBeScanned());
  24136. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24137. if (! scanner.scanNextFile (true))
  24138. break;
  24139. if (! aw.isCurrentlyModal())
  24140. break;
  24141. progress = scanner.getProgress();
  24142. }
  24143. if (scanner.getFailedFiles().size() > 0)
  24144. {
  24145. StringArray shortNames;
  24146. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24147. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24148. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24149. TRANS("Scan complete"),
  24150. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24151. + shortNames.joinIntoString (", "));
  24152. }
  24153. }
  24154. END_JUCE_NAMESPACE
  24155. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24156. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24157. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24158. #include <AudioUnit/AudioUnit.h>
  24159. #include <AudioUnit/AUCocoaUIView.h>
  24160. #include <CoreAudioKit/AUGenericView.h>
  24161. #if JUCE_SUPPORT_CARBON
  24162. #include <AudioToolbox/AudioUnitUtilities.h>
  24163. #include <AudioUnit/AudioUnitCarbonView.h>
  24164. #endif
  24165. BEGIN_JUCE_NAMESPACE
  24166. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24167. #endif
  24168. #if JUCE_MAC
  24169. // Change this to disable logging of various activities
  24170. #ifndef AU_LOGGING
  24171. #define AU_LOGGING 1
  24172. #endif
  24173. #if AU_LOGGING
  24174. #define log(a) Logger::writeToLog(a);
  24175. #else
  24176. #define log(a)
  24177. #endif
  24178. namespace AudioUnitFormatHelpers
  24179. {
  24180. static int insideCallback = 0;
  24181. static const String osTypeToString (OSType type)
  24182. {
  24183. char s[4];
  24184. s[0] = (char) (((uint32) type) >> 24);
  24185. s[1] = (char) (((uint32) type) >> 16);
  24186. s[2] = (char) (((uint32) type) >> 8);
  24187. s[3] = (char) ((uint32) type);
  24188. return String (s, 4);
  24189. }
  24190. static OSType stringToOSType (const String& s1)
  24191. {
  24192. const String s (s1 + " ");
  24193. return (((OSType) (unsigned char) s[0]) << 24)
  24194. | (((OSType) (unsigned char) s[1]) << 16)
  24195. | (((OSType) (unsigned char) s[2]) << 8)
  24196. | ((OSType) (unsigned char) s[3]);
  24197. }
  24198. static const char* auIdentifierPrefix = "AudioUnit:";
  24199. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24200. {
  24201. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24202. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24203. String s (auIdentifierPrefix);
  24204. if (desc.componentType == kAudioUnitType_MusicDevice)
  24205. s << "Synths/";
  24206. else if (desc.componentType == kAudioUnitType_MusicEffect
  24207. || desc.componentType == kAudioUnitType_Effect)
  24208. s << "Effects/";
  24209. else if (desc.componentType == kAudioUnitType_Generator)
  24210. s << "Generators/";
  24211. else if (desc.componentType == kAudioUnitType_Panner)
  24212. s << "Panners/";
  24213. s << osTypeToString (desc.componentType) << ","
  24214. << osTypeToString (desc.componentSubType) << ","
  24215. << osTypeToString (desc.componentManufacturer);
  24216. return s;
  24217. }
  24218. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24219. {
  24220. Handle componentNameHandle = NewHandle (sizeof (void*));
  24221. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24222. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24223. {
  24224. ComponentDescription desc;
  24225. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24226. {
  24227. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24228. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24229. if (nameString != 0 && nameString[0] != 0)
  24230. {
  24231. const String all ((const char*) nameString + 1, nameString[0]);
  24232. DBG ("name: "+ all);
  24233. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24234. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24235. }
  24236. if (infoString != 0 && infoString[0] != 0)
  24237. {
  24238. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24239. }
  24240. if (name.isEmpty())
  24241. name = "<Unknown>";
  24242. }
  24243. DisposeHandle (componentNameHandle);
  24244. DisposeHandle (componentInfoHandle);
  24245. }
  24246. }
  24247. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24248. String& name, String& version, String& manufacturer)
  24249. {
  24250. zerostruct (desc);
  24251. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24252. {
  24253. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24254. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24255. StringArray tokens;
  24256. tokens.addTokens (s, ",", String::empty);
  24257. tokens.trim();
  24258. tokens.removeEmptyStrings();
  24259. if (tokens.size() == 3)
  24260. {
  24261. desc.componentType = stringToOSType (tokens[0]);
  24262. desc.componentSubType = stringToOSType (tokens[1]);
  24263. desc.componentManufacturer = stringToOSType (tokens[2]);
  24264. ComponentRecord* comp = FindNextComponent (0, &desc);
  24265. if (comp != 0)
  24266. {
  24267. getAUDetails (comp, name, manufacturer);
  24268. return true;
  24269. }
  24270. }
  24271. }
  24272. return false;
  24273. }
  24274. }
  24275. class AudioUnitPluginWindowCarbon;
  24276. class AudioUnitPluginWindowCocoa;
  24277. class AudioUnitPluginInstance : public AudioPluginInstance
  24278. {
  24279. public:
  24280. ~AudioUnitPluginInstance();
  24281. // AudioPluginInstance methods:
  24282. void fillInPluginDescription (PluginDescription& desc) const
  24283. {
  24284. desc.name = pluginName;
  24285. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24286. desc.uid = ((int) componentDesc.componentType)
  24287. ^ ((int) componentDesc.componentSubType)
  24288. ^ ((int) componentDesc.componentManufacturer);
  24289. desc.lastFileModTime = 0;
  24290. desc.pluginFormatName = "AudioUnit";
  24291. desc.category = getCategory();
  24292. desc.manufacturerName = manufacturer;
  24293. desc.version = version;
  24294. desc.numInputChannels = getNumInputChannels();
  24295. desc.numOutputChannels = getNumOutputChannels();
  24296. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24297. }
  24298. const String getName() const { return pluginName; }
  24299. bool acceptsMidi() const { return wantsMidiMessages; }
  24300. bool producesMidi() const { return false; }
  24301. // AudioProcessor methods:
  24302. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24303. void releaseResources();
  24304. void processBlock (AudioSampleBuffer& buffer,
  24305. MidiBuffer& midiMessages);
  24306. AudioProcessorEditor* createEditor();
  24307. const String getInputChannelName (const int index) const;
  24308. bool isInputChannelStereoPair (int index) const;
  24309. const String getOutputChannelName (const int index) const;
  24310. bool isOutputChannelStereoPair (int index) const;
  24311. int getNumParameters();
  24312. float getParameter (int index);
  24313. void setParameter (int index, float newValue);
  24314. const String getParameterName (int index);
  24315. const String getParameterText (int index);
  24316. bool isParameterAutomatable (int index) const;
  24317. int getNumPrograms();
  24318. int getCurrentProgram();
  24319. void setCurrentProgram (int index);
  24320. const String getProgramName (int index);
  24321. void changeProgramName (int index, const String& newName);
  24322. void getStateInformation (MemoryBlock& destData);
  24323. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24324. void setStateInformation (const void* data, int sizeInBytes);
  24325. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24326. juce_UseDebuggingNewOperator
  24327. private:
  24328. friend class AudioUnitPluginWindowCarbon;
  24329. friend class AudioUnitPluginWindowCocoa;
  24330. friend class AudioUnitPluginFormat;
  24331. ComponentDescription componentDesc;
  24332. String pluginName, manufacturer, version;
  24333. String fileOrIdentifier;
  24334. CriticalSection lock;
  24335. bool initialised, wantsMidiMessages, wasPlaying;
  24336. HeapBlock <AudioBufferList> outputBufferList;
  24337. AudioTimeStamp timeStamp;
  24338. AudioSampleBuffer* currentBuffer;
  24339. AudioUnit audioUnit;
  24340. Array <int> parameterIds;
  24341. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24342. void initialise();
  24343. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24344. const AudioTimeStamp* inTimeStamp,
  24345. UInt32 inBusNumber,
  24346. UInt32 inNumberFrames,
  24347. AudioBufferList* ioData) const;
  24348. static OSStatus renderGetInputCallback (void* inRefCon,
  24349. AudioUnitRenderActionFlags* ioActionFlags,
  24350. const AudioTimeStamp* inTimeStamp,
  24351. UInt32 inBusNumber,
  24352. UInt32 inNumberFrames,
  24353. AudioBufferList* ioData)
  24354. {
  24355. return ((AudioUnitPluginInstance*) inRefCon)
  24356. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24357. }
  24358. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24359. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24360. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24361. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24362. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24363. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24364. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24365. {
  24366. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24367. }
  24368. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24369. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24370. Float64* outCurrentMeasureDownBeat)
  24371. {
  24372. return ((AudioUnitPluginInstance*) inHostUserData)
  24373. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24374. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24375. }
  24376. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24377. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24378. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24379. {
  24380. return ((AudioUnitPluginInstance*) inHostUserData)
  24381. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24382. outCurrentSampleInTimeLine, outIsCycling,
  24383. outCycleStartBeat, outCycleEndBeat);
  24384. }
  24385. void getNumChannels (int& numIns, int& numOuts)
  24386. {
  24387. numIns = 0;
  24388. numOuts = 0;
  24389. AUChannelInfo supportedChannels [128];
  24390. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24391. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24392. 0, supportedChannels, &supportedChannelsSize) == noErr
  24393. && supportedChannelsSize > 0)
  24394. {
  24395. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24396. {
  24397. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24398. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24399. }
  24400. }
  24401. else
  24402. {
  24403. // (this really means the plugin will take any number of ins/outs as long
  24404. // as they are the same)
  24405. numIns = numOuts = 2;
  24406. }
  24407. }
  24408. const String getCategory() const;
  24409. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24410. };
  24411. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24412. : fileOrIdentifier (fileOrIdentifier),
  24413. initialised (false),
  24414. wantsMidiMessages (false),
  24415. audioUnit (0),
  24416. currentBuffer (0)
  24417. {
  24418. using namespace AudioUnitFormatHelpers;
  24419. try
  24420. {
  24421. ++insideCallback;
  24422. log ("Opening AU: " + fileOrIdentifier);
  24423. if (getComponentDescFromFile (fileOrIdentifier))
  24424. {
  24425. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24426. if (comp != 0)
  24427. {
  24428. audioUnit = (AudioUnit) OpenComponent (comp);
  24429. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24430. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24431. }
  24432. }
  24433. --insideCallback;
  24434. }
  24435. catch (...)
  24436. {
  24437. --insideCallback;
  24438. }
  24439. }
  24440. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24441. {
  24442. const ScopedLock sl (lock);
  24443. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  24444. if (audioUnit != 0)
  24445. {
  24446. AudioUnitUninitialize (audioUnit);
  24447. CloseComponent (audioUnit);
  24448. audioUnit = 0;
  24449. }
  24450. }
  24451. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24452. {
  24453. zerostruct (componentDesc);
  24454. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24455. return true;
  24456. const File file (fileOrIdentifier);
  24457. if (! file.hasFileExtension (".component"))
  24458. return false;
  24459. const char* const utf8 = fileOrIdentifier.toUTF8();
  24460. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24461. strlen (utf8), file.isDirectory());
  24462. if (url != 0)
  24463. {
  24464. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24465. CFRelease (url);
  24466. if (bundleRef != 0)
  24467. {
  24468. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24469. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24470. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24471. if (pluginName.isEmpty())
  24472. pluginName = file.getFileNameWithoutExtension();
  24473. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24474. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24475. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24476. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24477. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24478. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24479. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24480. UseResFile (resFileId);
  24481. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24482. {
  24483. Handle h = Get1IndResource ('thng', i);
  24484. if (h != 0)
  24485. {
  24486. HLock (h);
  24487. const uint32* const types = (const uint32*) *h;
  24488. if (types[0] == kAudioUnitType_MusicDevice
  24489. || types[0] == kAudioUnitType_MusicEffect
  24490. || types[0] == kAudioUnitType_Effect
  24491. || types[0] == kAudioUnitType_Generator
  24492. || types[0] == kAudioUnitType_Panner)
  24493. {
  24494. componentDesc.componentType = types[0];
  24495. componentDesc.componentSubType = types[1];
  24496. componentDesc.componentManufacturer = types[2];
  24497. break;
  24498. }
  24499. HUnlock (h);
  24500. ReleaseResource (h);
  24501. }
  24502. }
  24503. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24504. CFRelease (bundleRef);
  24505. }
  24506. }
  24507. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24508. }
  24509. void AudioUnitPluginInstance::initialise()
  24510. {
  24511. if (initialised || audioUnit == 0)
  24512. return;
  24513. log ("Initialising AU: " + pluginName);
  24514. parameterIds.clear();
  24515. {
  24516. UInt32 paramListSize = 0;
  24517. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24518. 0, 0, &paramListSize);
  24519. if (paramListSize > 0)
  24520. {
  24521. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24522. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24523. 0, &parameterIds.getReference(0), &paramListSize);
  24524. }
  24525. }
  24526. {
  24527. AURenderCallbackStruct info;
  24528. zerostruct (info);
  24529. info.inputProcRefCon = this;
  24530. info.inputProc = renderGetInputCallback;
  24531. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24532. 0, &info, sizeof (info));
  24533. }
  24534. {
  24535. HostCallbackInfo info;
  24536. zerostruct (info);
  24537. info.hostUserData = this;
  24538. info.beatAndTempoProc = getBeatAndTempoCallback;
  24539. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24540. info.transportStateProc = getTransportStateCallback;
  24541. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24542. 0, &info, sizeof (info));
  24543. }
  24544. int numIns, numOuts;
  24545. getNumChannels (numIns, numOuts);
  24546. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24547. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24548. setLatencySamples (0);
  24549. }
  24550. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24551. int samplesPerBlockExpected)
  24552. {
  24553. if (audioUnit != 0)
  24554. {
  24555. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24556. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24557. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24558. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24559. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24560. {
  24561. if (initialised)
  24562. {
  24563. AudioUnitUninitialize (audioUnit);
  24564. initialised = false;
  24565. }
  24566. Float64 sr = sampleRate_;
  24567. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24568. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24569. }
  24570. }
  24571. initialise();
  24572. if (initialised)
  24573. {
  24574. int numIns, numOuts;
  24575. getNumChannels (numIns, numOuts);
  24576. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24577. Float64 latencySecs = 0.0;
  24578. UInt32 latencySize = sizeof (latencySecs);
  24579. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24580. 0, &latencySecs, &latencySize);
  24581. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24582. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24583. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24584. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24585. AudioStreamBasicDescription stream;
  24586. zerostruct (stream);
  24587. stream.mSampleRate = sampleRate_;
  24588. stream.mFormatID = kAudioFormatLinearPCM;
  24589. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24590. stream.mFramesPerPacket = 1;
  24591. stream.mBytesPerPacket = 4;
  24592. stream.mBytesPerFrame = 4;
  24593. stream.mBitsPerChannel = 32;
  24594. stream.mChannelsPerFrame = numIns;
  24595. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24596. 0, &stream, sizeof (stream));
  24597. stream.mChannelsPerFrame = numOuts;
  24598. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24599. 0, &stream, sizeof (stream));
  24600. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24601. outputBufferList->mNumberBuffers = numOuts;
  24602. for (int i = numOuts; --i >= 0;)
  24603. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24604. zerostruct (timeStamp);
  24605. timeStamp.mSampleTime = 0;
  24606. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24607. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24608. currentBuffer = 0;
  24609. wasPlaying = false;
  24610. }
  24611. }
  24612. void AudioUnitPluginInstance::releaseResources()
  24613. {
  24614. if (initialised)
  24615. {
  24616. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24617. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24618. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24619. outputBufferList.free();
  24620. currentBuffer = 0;
  24621. }
  24622. }
  24623. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24624. const AudioTimeStamp* inTimeStamp,
  24625. UInt32 inBusNumber,
  24626. UInt32 inNumberFrames,
  24627. AudioBufferList* ioData) const
  24628. {
  24629. if (inBusNumber == 0
  24630. && currentBuffer != 0)
  24631. {
  24632. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24633. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24634. {
  24635. if (i < currentBuffer->getNumChannels())
  24636. {
  24637. memcpy (ioData->mBuffers[i].mData,
  24638. currentBuffer->getSampleData (i, 0),
  24639. sizeof (float) * inNumberFrames);
  24640. }
  24641. else
  24642. {
  24643. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24644. }
  24645. }
  24646. }
  24647. return noErr;
  24648. }
  24649. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24650. MidiBuffer& midiMessages)
  24651. {
  24652. const int numSamples = buffer.getNumSamples();
  24653. if (initialised)
  24654. {
  24655. AudioUnitRenderActionFlags flags = 0;
  24656. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24657. for (int i = getNumOutputChannels(); --i >= 0;)
  24658. {
  24659. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24660. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24661. }
  24662. currentBuffer = &buffer;
  24663. if (wantsMidiMessages)
  24664. {
  24665. const uint8* midiEventData;
  24666. int midiEventSize, midiEventPosition;
  24667. MidiBuffer::Iterator i (midiMessages);
  24668. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24669. {
  24670. if (midiEventSize <= 3)
  24671. MusicDeviceMIDIEvent (audioUnit,
  24672. midiEventData[0], midiEventData[1], midiEventData[2],
  24673. midiEventPosition);
  24674. else
  24675. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24676. }
  24677. midiMessages.clear();
  24678. }
  24679. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24680. 0, numSamples, outputBufferList);
  24681. timeStamp.mSampleTime += numSamples;
  24682. }
  24683. else
  24684. {
  24685. // Not initialised, so just bypass..
  24686. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24687. buffer.clear (i, 0, buffer.getNumSamples());
  24688. }
  24689. }
  24690. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24691. {
  24692. AudioPlayHead* const ph = getPlayHead();
  24693. AudioPlayHead::CurrentPositionInfo result;
  24694. if (ph != 0 && ph->getCurrentPosition (result))
  24695. {
  24696. if (outCurrentBeat != 0)
  24697. *outCurrentBeat = result.ppqPosition;
  24698. if (outCurrentTempo != 0)
  24699. *outCurrentTempo = result.bpm;
  24700. }
  24701. else
  24702. {
  24703. if (outCurrentBeat != 0)
  24704. *outCurrentBeat = 0;
  24705. if (outCurrentTempo != 0)
  24706. *outCurrentTempo = 120.0;
  24707. }
  24708. return noErr;
  24709. }
  24710. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24711. Float32* outTimeSig_Numerator,
  24712. UInt32* outTimeSig_Denominator,
  24713. Float64* outCurrentMeasureDownBeat) const
  24714. {
  24715. AudioPlayHead* const ph = getPlayHead();
  24716. AudioPlayHead::CurrentPositionInfo result;
  24717. if (ph != 0 && ph->getCurrentPosition (result))
  24718. {
  24719. if (outTimeSig_Numerator != 0)
  24720. *outTimeSig_Numerator = result.timeSigNumerator;
  24721. if (outTimeSig_Denominator != 0)
  24722. *outTimeSig_Denominator = result.timeSigDenominator;
  24723. if (outDeltaSampleOffsetToNextBeat != 0)
  24724. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24725. if (outCurrentMeasureDownBeat != 0)
  24726. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24727. }
  24728. else
  24729. {
  24730. if (outDeltaSampleOffsetToNextBeat != 0)
  24731. *outDeltaSampleOffsetToNextBeat = 0;
  24732. if (outTimeSig_Numerator != 0)
  24733. *outTimeSig_Numerator = 4;
  24734. if (outTimeSig_Denominator != 0)
  24735. *outTimeSig_Denominator = 4;
  24736. if (outCurrentMeasureDownBeat != 0)
  24737. *outCurrentMeasureDownBeat = 0;
  24738. }
  24739. return noErr;
  24740. }
  24741. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24742. Boolean* outTransportStateChanged,
  24743. Float64* outCurrentSampleInTimeLine,
  24744. Boolean* outIsCycling,
  24745. Float64* outCycleStartBeat,
  24746. Float64* outCycleEndBeat)
  24747. {
  24748. AudioPlayHead* const ph = getPlayHead();
  24749. AudioPlayHead::CurrentPositionInfo result;
  24750. if (ph != 0 && ph->getCurrentPosition (result))
  24751. {
  24752. if (outIsPlaying != 0)
  24753. *outIsPlaying = result.isPlaying;
  24754. if (outTransportStateChanged != 0)
  24755. {
  24756. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24757. wasPlaying = result.isPlaying;
  24758. }
  24759. if (outCurrentSampleInTimeLine != 0)
  24760. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24761. if (outIsCycling != 0)
  24762. *outIsCycling = false;
  24763. if (outCycleStartBeat != 0)
  24764. *outCycleStartBeat = 0;
  24765. if (outCycleEndBeat != 0)
  24766. *outCycleEndBeat = 0;
  24767. }
  24768. else
  24769. {
  24770. if (outIsPlaying != 0)
  24771. *outIsPlaying = false;
  24772. if (outTransportStateChanged != 0)
  24773. *outTransportStateChanged = false;
  24774. if (outCurrentSampleInTimeLine != 0)
  24775. *outCurrentSampleInTimeLine = 0;
  24776. if (outIsCycling != 0)
  24777. *outIsCycling = false;
  24778. if (outCycleStartBeat != 0)
  24779. *outCycleStartBeat = 0;
  24780. if (outCycleEndBeat != 0)
  24781. *outCycleEndBeat = 0;
  24782. }
  24783. return noErr;
  24784. }
  24785. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24786. {
  24787. public:
  24788. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24789. : AudioProcessorEditor (&plugin_),
  24790. plugin (plugin_),
  24791. wrapper (0)
  24792. {
  24793. addAndMakeVisible (wrapper = new NSViewComponent());
  24794. setOpaque (true);
  24795. setVisible (true);
  24796. setSize (100, 100);
  24797. createView (createGenericViewIfNeeded);
  24798. }
  24799. ~AudioUnitPluginWindowCocoa()
  24800. {
  24801. const bool wasValid = isValid();
  24802. wrapper->setView (0);
  24803. if (wasValid)
  24804. plugin.editorBeingDeleted (this);
  24805. delete wrapper;
  24806. }
  24807. bool isValid() const { return wrapper->getView() != 0; }
  24808. void paint (Graphics& g)
  24809. {
  24810. g.fillAll (Colours::white);
  24811. }
  24812. void resized()
  24813. {
  24814. wrapper->setSize (getWidth(), getHeight());
  24815. }
  24816. private:
  24817. AudioUnitPluginInstance& plugin;
  24818. NSViewComponent* wrapper;
  24819. bool createView (const bool createGenericViewIfNeeded)
  24820. {
  24821. NSView* pluginView = 0;
  24822. UInt32 dataSize = 0;
  24823. Boolean isWritable = false;
  24824. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24825. 0, &dataSize, &isWritable) == noErr
  24826. && dataSize != 0
  24827. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24828. 0, &dataSize, &isWritable) == noErr)
  24829. {
  24830. HeapBlock <AudioUnitCocoaViewInfo> info;
  24831. info.calloc (dataSize, 1);
  24832. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24833. 0, info, &dataSize) == noErr)
  24834. {
  24835. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24836. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24837. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24838. Class viewClass = [viewBundle classNamed: viewClassName];
  24839. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24840. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24841. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24842. {
  24843. id factory = [[[viewClass alloc] init] autorelease];
  24844. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24845. withSize: NSMakeSize (getWidth(), getHeight())];
  24846. }
  24847. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24848. {
  24849. CFRelease (info->mCocoaAUViewClass[i]);
  24850. CFRelease (info->mCocoaAUViewBundleLocation);
  24851. }
  24852. }
  24853. }
  24854. if (createGenericViewIfNeeded && (pluginView == 0))
  24855. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24856. wrapper->setView (pluginView);
  24857. if (pluginView != 0)
  24858. setSize ([pluginView frame].size.width,
  24859. [pluginView frame].size.height);
  24860. return pluginView != 0;
  24861. }
  24862. };
  24863. #if JUCE_SUPPORT_CARBON
  24864. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24865. {
  24866. public:
  24867. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24868. : AudioProcessorEditor (&plugin_),
  24869. plugin (plugin_),
  24870. viewComponent (0)
  24871. {
  24872. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24873. setOpaque (true);
  24874. setVisible (true);
  24875. setSize (400, 300);
  24876. ComponentDescription viewList [16];
  24877. UInt32 viewListSize = sizeof (viewList);
  24878. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24879. 0, &viewList, &viewListSize);
  24880. componentRecord = FindNextComponent (0, &viewList[0]);
  24881. }
  24882. ~AudioUnitPluginWindowCarbon()
  24883. {
  24884. innerWrapper = 0;
  24885. if (isValid())
  24886. plugin.editorBeingDeleted (this);
  24887. }
  24888. bool isValid() const throw() { return componentRecord != 0; }
  24889. void paint (Graphics& g)
  24890. {
  24891. g.fillAll (Colours::black);
  24892. }
  24893. void resized()
  24894. {
  24895. innerWrapper->setSize (getWidth(), getHeight());
  24896. }
  24897. bool keyStateChanged (bool)
  24898. {
  24899. return false;
  24900. }
  24901. bool keyPressed (const KeyPress&)
  24902. {
  24903. return false;
  24904. }
  24905. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24906. AudioUnitCarbonView getViewComponent()
  24907. {
  24908. if (viewComponent == 0 && componentRecord != 0)
  24909. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24910. return viewComponent;
  24911. }
  24912. void closeViewComponent()
  24913. {
  24914. if (viewComponent != 0)
  24915. {
  24916. CloseComponent (viewComponent);
  24917. viewComponent = 0;
  24918. }
  24919. }
  24920. juce_UseDebuggingNewOperator
  24921. private:
  24922. AudioUnitPluginInstance& plugin;
  24923. ComponentRecord* componentRecord;
  24924. AudioUnitCarbonView viewComponent;
  24925. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24926. {
  24927. public:
  24928. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24929. : owner (owner_)
  24930. {
  24931. }
  24932. ~InnerWrapperComponent()
  24933. {
  24934. deleteWindow();
  24935. }
  24936. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24937. {
  24938. log ("Opening AU GUI: " + owner->plugin.getName());
  24939. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24940. if (viewComponent == 0)
  24941. return 0;
  24942. Float32Point pos = { 0, 0 };
  24943. Float32Point size = { 250, 200 };
  24944. HIViewRef pluginView = 0;
  24945. AudioUnitCarbonViewCreate (viewComponent,
  24946. owner->getAudioUnit(),
  24947. windowRef,
  24948. rootView,
  24949. &pos,
  24950. &size,
  24951. (ControlRef*) &pluginView);
  24952. return pluginView;
  24953. }
  24954. void removeView (HIViewRef)
  24955. {
  24956. log ("Closing AU GUI: " + owner->plugin.getName());
  24957. owner->closeViewComponent();
  24958. }
  24959. private:
  24960. AudioUnitPluginWindowCarbon* const owner;
  24961. };
  24962. friend class InnerWrapperComponent;
  24963. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24964. };
  24965. #endif
  24966. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24967. {
  24968. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24969. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24970. w = 0;
  24971. #if JUCE_SUPPORT_CARBON
  24972. if (w == 0)
  24973. {
  24974. w = new AudioUnitPluginWindowCarbon (*this);
  24975. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24976. w = 0;
  24977. }
  24978. #endif
  24979. if (w == 0)
  24980. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24981. return w.release();
  24982. }
  24983. const String AudioUnitPluginInstance::getCategory() const
  24984. {
  24985. const char* result = 0;
  24986. switch (componentDesc.componentType)
  24987. {
  24988. case kAudioUnitType_Effect:
  24989. case kAudioUnitType_MusicEffect:
  24990. result = "Effect";
  24991. break;
  24992. case kAudioUnitType_MusicDevice:
  24993. result = "Synth";
  24994. break;
  24995. case kAudioUnitType_Generator:
  24996. result = "Generator";
  24997. break;
  24998. case kAudioUnitType_Panner:
  24999. result = "Panner";
  25000. break;
  25001. default:
  25002. break;
  25003. }
  25004. return result;
  25005. }
  25006. int AudioUnitPluginInstance::getNumParameters()
  25007. {
  25008. return parameterIds.size();
  25009. }
  25010. float AudioUnitPluginInstance::getParameter (int index)
  25011. {
  25012. const ScopedLock sl (lock);
  25013. Float32 value = 0.0f;
  25014. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25015. {
  25016. AudioUnitGetParameter (audioUnit,
  25017. (UInt32) parameterIds.getUnchecked (index),
  25018. kAudioUnitScope_Global, 0,
  25019. &value);
  25020. }
  25021. return value;
  25022. }
  25023. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25024. {
  25025. const ScopedLock sl (lock);
  25026. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25027. {
  25028. AudioUnitSetParameter (audioUnit,
  25029. (UInt32) parameterIds.getUnchecked (index),
  25030. kAudioUnitScope_Global, 0,
  25031. newValue, 0);
  25032. }
  25033. }
  25034. const String AudioUnitPluginInstance::getParameterName (int index)
  25035. {
  25036. AudioUnitParameterInfo info;
  25037. zerostruct (info);
  25038. UInt32 sz = sizeof (info);
  25039. String name;
  25040. if (AudioUnitGetProperty (audioUnit,
  25041. kAudioUnitProperty_ParameterInfo,
  25042. kAudioUnitScope_Global,
  25043. parameterIds [index], &info, &sz) == noErr)
  25044. {
  25045. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25046. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25047. else
  25048. name = String (info.name, sizeof (info.name));
  25049. }
  25050. return name;
  25051. }
  25052. const String AudioUnitPluginInstance::getParameterText (int index)
  25053. {
  25054. return String (getParameter (index));
  25055. }
  25056. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25057. {
  25058. AudioUnitParameterInfo info;
  25059. UInt32 sz = sizeof (info);
  25060. if (AudioUnitGetProperty (audioUnit,
  25061. kAudioUnitProperty_ParameterInfo,
  25062. kAudioUnitScope_Global,
  25063. parameterIds [index], &info, &sz) == noErr)
  25064. {
  25065. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25066. }
  25067. return true;
  25068. }
  25069. int AudioUnitPluginInstance::getNumPrograms()
  25070. {
  25071. CFArrayRef presets;
  25072. UInt32 sz = sizeof (CFArrayRef);
  25073. int num = 0;
  25074. if (AudioUnitGetProperty (audioUnit,
  25075. kAudioUnitProperty_FactoryPresets,
  25076. kAudioUnitScope_Global,
  25077. 0, &presets, &sz) == noErr)
  25078. {
  25079. num = (int) CFArrayGetCount (presets);
  25080. CFRelease (presets);
  25081. }
  25082. return num;
  25083. }
  25084. int AudioUnitPluginInstance::getCurrentProgram()
  25085. {
  25086. AUPreset current;
  25087. current.presetNumber = 0;
  25088. UInt32 sz = sizeof (AUPreset);
  25089. AudioUnitGetProperty (audioUnit,
  25090. kAudioUnitProperty_FactoryPresets,
  25091. kAudioUnitScope_Global,
  25092. 0, &current, &sz);
  25093. return current.presetNumber;
  25094. }
  25095. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25096. {
  25097. AUPreset current;
  25098. current.presetNumber = newIndex;
  25099. current.presetName = 0;
  25100. AudioUnitSetProperty (audioUnit,
  25101. kAudioUnitProperty_FactoryPresets,
  25102. kAudioUnitScope_Global,
  25103. 0, &current, sizeof (AUPreset));
  25104. }
  25105. const String AudioUnitPluginInstance::getProgramName (int index)
  25106. {
  25107. String s;
  25108. CFArrayRef presets;
  25109. UInt32 sz = sizeof (CFArrayRef);
  25110. if (AudioUnitGetProperty (audioUnit,
  25111. kAudioUnitProperty_FactoryPresets,
  25112. kAudioUnitScope_Global,
  25113. 0, &presets, &sz) == noErr)
  25114. {
  25115. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25116. {
  25117. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25118. if (p != 0 && p->presetNumber == index)
  25119. {
  25120. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25121. break;
  25122. }
  25123. }
  25124. CFRelease (presets);
  25125. }
  25126. return s;
  25127. }
  25128. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25129. {
  25130. jassertfalse; // xxx not implemented!
  25131. }
  25132. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25133. {
  25134. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25135. return "Input " + String (index + 1);
  25136. return String::empty;
  25137. }
  25138. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25139. {
  25140. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25141. return false;
  25142. return true;
  25143. }
  25144. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25145. {
  25146. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25147. return "Output " + String (index + 1);
  25148. return String::empty;
  25149. }
  25150. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25151. {
  25152. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25153. return false;
  25154. return true;
  25155. }
  25156. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25157. {
  25158. getCurrentProgramStateInformation (destData);
  25159. }
  25160. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25161. {
  25162. CFPropertyListRef propertyList = 0;
  25163. UInt32 sz = sizeof (CFPropertyListRef);
  25164. if (AudioUnitGetProperty (audioUnit,
  25165. kAudioUnitProperty_ClassInfo,
  25166. kAudioUnitScope_Global,
  25167. 0, &propertyList, &sz) == noErr)
  25168. {
  25169. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25170. CFWriteStreamOpen (stream);
  25171. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25172. CFWriteStreamClose (stream);
  25173. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25174. destData.setSize (bytesWritten);
  25175. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25176. CFRelease (data);
  25177. CFRelease (stream);
  25178. CFRelease (propertyList);
  25179. }
  25180. }
  25181. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25182. {
  25183. setCurrentProgramStateInformation (data, sizeInBytes);
  25184. }
  25185. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25186. {
  25187. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25188. (const UInt8*) data,
  25189. sizeInBytes,
  25190. kCFAllocatorNull);
  25191. CFReadStreamOpen (stream);
  25192. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25193. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25194. stream,
  25195. 0,
  25196. kCFPropertyListImmutable,
  25197. &format,
  25198. 0);
  25199. CFRelease (stream);
  25200. if (propertyList != 0)
  25201. AudioUnitSetProperty (audioUnit,
  25202. kAudioUnitProperty_ClassInfo,
  25203. kAudioUnitScope_Global,
  25204. 0, &propertyList, sizeof (propertyList));
  25205. }
  25206. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25207. {
  25208. }
  25209. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25210. {
  25211. }
  25212. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25213. const String& fileOrIdentifier)
  25214. {
  25215. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25216. return;
  25217. PluginDescription desc;
  25218. desc.fileOrIdentifier = fileOrIdentifier;
  25219. desc.uid = 0;
  25220. try
  25221. {
  25222. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25223. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25224. if (auInstance != 0)
  25225. {
  25226. auInstance->fillInPluginDescription (desc);
  25227. results.add (new PluginDescription (desc));
  25228. }
  25229. }
  25230. catch (...)
  25231. {
  25232. // crashed while loading...
  25233. }
  25234. }
  25235. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25236. {
  25237. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25238. {
  25239. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25240. if (result->audioUnit != 0)
  25241. {
  25242. result->initialise();
  25243. return result.release();
  25244. }
  25245. }
  25246. return 0;
  25247. }
  25248. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25249. const bool /*recursive*/)
  25250. {
  25251. StringArray result;
  25252. ComponentRecord* comp = 0;
  25253. ComponentDescription desc;
  25254. zerostruct (desc);
  25255. for (;;)
  25256. {
  25257. zerostruct (desc);
  25258. comp = FindNextComponent (comp, &desc);
  25259. if (comp == 0)
  25260. break;
  25261. GetComponentInfo (comp, &desc, 0, 0, 0);
  25262. if (desc.componentType == kAudioUnitType_MusicDevice
  25263. || desc.componentType == kAudioUnitType_MusicEffect
  25264. || desc.componentType == kAudioUnitType_Effect
  25265. || desc.componentType == kAudioUnitType_Generator
  25266. || desc.componentType == kAudioUnitType_Panner)
  25267. {
  25268. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  25269. DBG (s);
  25270. result.add (s);
  25271. }
  25272. }
  25273. return result;
  25274. }
  25275. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25276. {
  25277. ComponentDescription desc;
  25278. String name, version, manufacturer;
  25279. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25280. return FindNextComponent (0, &desc) != 0;
  25281. const File f (fileOrIdentifier);
  25282. return f.hasFileExtension (".component")
  25283. && f.isDirectory();
  25284. }
  25285. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25286. {
  25287. ComponentDescription desc;
  25288. String name, version, manufacturer;
  25289. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25290. if (name.isEmpty())
  25291. name = fileOrIdentifier;
  25292. return name;
  25293. }
  25294. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25295. {
  25296. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  25297. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25298. else
  25299. return File (desc.fileOrIdentifier).exists();
  25300. }
  25301. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25302. {
  25303. return FileSearchPath ("/(Default AudioUnit locations)");
  25304. }
  25305. #endif
  25306. END_JUCE_NAMESPACE
  25307. #undef log
  25308. #endif
  25309. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25310. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25311. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25312. #define JUCE_MAC_VST_INCLUDED 1
  25313. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25314. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  25315. #if JUCE_WINDOWS
  25316. #undef _WIN32_WINNT
  25317. #define _WIN32_WINNT 0x500
  25318. #undef STRICT
  25319. #define STRICT
  25320. #include <windows.h>
  25321. #include <float.h>
  25322. #pragma warning (disable : 4312 4355)
  25323. #elif JUCE_LINUX
  25324. #include <float.h>
  25325. #include <sys/time.h>
  25326. #include <X11/Xlib.h>
  25327. #include <X11/Xutil.h>
  25328. #include <X11/Xatom.h>
  25329. #undef Font
  25330. #undef KeyPress
  25331. #undef Drawable
  25332. #undef Time
  25333. #else
  25334. #include <Cocoa/Cocoa.h>
  25335. #include <Carbon/Carbon.h>
  25336. #endif
  25337. #if ! (JUCE_MAC && JUCE_64BIT)
  25338. BEGIN_JUCE_NAMESPACE
  25339. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25340. #endif
  25341. #undef PRAGMA_ALIGN_SUPPORTED
  25342. #define VST_FORCE_DEPRECATED 0
  25343. #if JUCE_MSVC
  25344. #pragma warning (push)
  25345. #pragma warning (disable: 4996)
  25346. #endif
  25347. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25348. your include path if you want to add VST support.
  25349. If you're not interested in VSTs, you can disable them by changing the
  25350. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25351. */
  25352. #include "pluginterfaces/vst2.x/aeffectx.h"
  25353. #if JUCE_MSVC
  25354. #pragma warning (pop)
  25355. #endif
  25356. #if JUCE_LINUX
  25357. #define Font JUCE_NAMESPACE::Font
  25358. #define KeyPress JUCE_NAMESPACE::KeyPress
  25359. #define Drawable JUCE_NAMESPACE::Drawable
  25360. #define Time JUCE_NAMESPACE::Time
  25361. #endif
  25362. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25363. #ifdef __aeffect__
  25364. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25365. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25366. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25367. events to the list.
  25368. This is used by both the VST hosting code and the plugin wrapper.
  25369. */
  25370. class VSTMidiEventList
  25371. {
  25372. public:
  25373. VSTMidiEventList()
  25374. : numEventsUsed (0), numEventsAllocated (0)
  25375. {
  25376. }
  25377. ~VSTMidiEventList()
  25378. {
  25379. freeEvents();
  25380. }
  25381. void clear()
  25382. {
  25383. numEventsUsed = 0;
  25384. if (events != 0)
  25385. events->numEvents = 0;
  25386. }
  25387. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25388. {
  25389. ensureSize (numEventsUsed + 1);
  25390. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25391. events->numEvents = ++numEventsUsed;
  25392. if (numBytes <= 4)
  25393. {
  25394. if (e->type == kVstSysExType)
  25395. {
  25396. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25397. e->type = kVstMidiType;
  25398. e->byteSize = sizeof (VstMidiEvent);
  25399. e->noteLength = 0;
  25400. e->noteOffset = 0;
  25401. e->detune = 0;
  25402. e->noteOffVelocity = 0;
  25403. }
  25404. e->deltaFrames = frameOffset;
  25405. memcpy (e->midiData, midiData, numBytes);
  25406. }
  25407. else
  25408. {
  25409. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25410. if (se->type == kVstSysExType)
  25411. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25412. else
  25413. se->sysexDump = (char*) juce_malloc (numBytes);
  25414. memcpy (se->sysexDump, midiData, numBytes);
  25415. se->type = kVstSysExType;
  25416. se->byteSize = sizeof (VstMidiSysexEvent);
  25417. se->deltaFrames = frameOffset;
  25418. se->flags = 0;
  25419. se->dumpBytes = numBytes;
  25420. se->resvd1 = 0;
  25421. se->resvd2 = 0;
  25422. }
  25423. }
  25424. // Handy method to pull the events out of an event buffer supplied by the host
  25425. // or plugin.
  25426. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25427. {
  25428. for (int i = 0; i < events->numEvents; ++i)
  25429. {
  25430. const VstEvent* const e = events->events[i];
  25431. if (e != 0)
  25432. {
  25433. if (e->type == kVstMidiType)
  25434. {
  25435. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25436. 4, e->deltaFrames);
  25437. }
  25438. else if (e->type == kVstSysExType)
  25439. {
  25440. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25441. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25442. e->deltaFrames);
  25443. }
  25444. }
  25445. }
  25446. }
  25447. void ensureSize (int numEventsNeeded)
  25448. {
  25449. if (numEventsNeeded > numEventsAllocated)
  25450. {
  25451. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25452. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25453. if (events == 0)
  25454. events.calloc (size, 1);
  25455. else
  25456. events.realloc (size, 1);
  25457. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25458. {
  25459. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25460. (int) sizeof (VstMidiSysexEvent)));
  25461. e->type = kVstMidiType;
  25462. e->byteSize = sizeof (VstMidiEvent);
  25463. events->events[i] = (VstEvent*) e;
  25464. }
  25465. numEventsAllocated = numEventsNeeded;
  25466. }
  25467. }
  25468. void freeEvents()
  25469. {
  25470. if (events != 0)
  25471. {
  25472. for (int i = numEventsAllocated; --i >= 0;)
  25473. {
  25474. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25475. if (e->type == kVstSysExType)
  25476. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25477. juce_free (e);
  25478. }
  25479. events.free();
  25480. numEventsUsed = 0;
  25481. numEventsAllocated = 0;
  25482. }
  25483. }
  25484. HeapBlock <VstEvents> events;
  25485. private:
  25486. int numEventsUsed, numEventsAllocated;
  25487. };
  25488. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25489. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25490. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25491. #if ! JUCE_WINDOWS
  25492. static void _fpreset() {}
  25493. static void _clearfp() {}
  25494. #endif
  25495. extern void juce_callAnyTimersSynchronously();
  25496. const int fxbVersionNum = 1;
  25497. struct fxProgram
  25498. {
  25499. long chunkMagic; // 'CcnK'
  25500. long byteSize; // of this chunk, excl. magic + byteSize
  25501. long fxMagic; // 'FxCk'
  25502. long version;
  25503. long fxID; // fx unique id
  25504. long fxVersion;
  25505. long numParams;
  25506. char prgName[28];
  25507. float params[1]; // variable no. of parameters
  25508. };
  25509. struct fxSet
  25510. {
  25511. long chunkMagic; // 'CcnK'
  25512. long byteSize; // of this chunk, excl. magic + byteSize
  25513. long fxMagic; // 'FxBk'
  25514. long version;
  25515. long fxID; // fx unique id
  25516. long fxVersion;
  25517. long numPrograms;
  25518. char future[128];
  25519. fxProgram programs[1]; // variable no. of programs
  25520. };
  25521. struct fxChunkSet
  25522. {
  25523. long chunkMagic; // 'CcnK'
  25524. long byteSize; // of this chunk, excl. magic + byteSize
  25525. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25526. long version;
  25527. long fxID; // fx unique id
  25528. long fxVersion;
  25529. long numPrograms;
  25530. char future[128];
  25531. long chunkSize;
  25532. char chunk[8]; // variable
  25533. };
  25534. struct fxProgramSet
  25535. {
  25536. long chunkMagic; // 'CcnK'
  25537. long byteSize; // of this chunk, excl. magic + byteSize
  25538. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25539. long version;
  25540. long fxID; // fx unique id
  25541. long fxVersion;
  25542. long numPrograms;
  25543. char name[28];
  25544. long chunkSize;
  25545. char chunk[8]; // variable
  25546. };
  25547. static long vst_swap (const long x) throw()
  25548. {
  25549. #ifdef JUCE_LITTLE_ENDIAN
  25550. return (long) ByteOrder::swap ((uint32) x);
  25551. #else
  25552. return x;
  25553. #endif
  25554. }
  25555. static float vst_swapFloat (const float x) throw()
  25556. {
  25557. #ifdef JUCE_LITTLE_ENDIAN
  25558. union { uint32 asInt; float asFloat; } n;
  25559. n.asFloat = x;
  25560. n.asInt = ByteOrder::swap (n.asInt);
  25561. return n.asFloat;
  25562. #else
  25563. return x;
  25564. #endif
  25565. }
  25566. typedef AEffect* (*MainCall) (audioMasterCallback);
  25567. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25568. static int shellUIDToCreate = 0;
  25569. static int insideVSTCallback = 0;
  25570. class VSTPluginWindow;
  25571. // Change this to disable logging of various VST activities
  25572. #ifndef VST_LOGGING
  25573. #define VST_LOGGING 1
  25574. #endif
  25575. #if VST_LOGGING
  25576. #define log(a) Logger::writeToLog(a);
  25577. #else
  25578. #define log(a)
  25579. #endif
  25580. #if JUCE_MAC && JUCE_PPC
  25581. static void* NewCFMFromMachO (void* const machofp) throw()
  25582. {
  25583. void* result = juce_malloc (8);
  25584. ((void**) result)[0] = machofp;
  25585. ((void**) result)[1] = result;
  25586. return result;
  25587. }
  25588. #endif
  25589. #if JUCE_LINUX
  25590. extern Display* display;
  25591. extern XContext windowHandleXContext;
  25592. typedef void (*EventProcPtr) (XEvent* ev);
  25593. static bool xErrorTriggered;
  25594. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25595. {
  25596. xErrorTriggered = true;
  25597. return 0;
  25598. }
  25599. static int getPropertyFromXWindow (Window handle, Atom atom)
  25600. {
  25601. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25602. xErrorTriggered = false;
  25603. int userSize;
  25604. unsigned long bytes, userCount;
  25605. unsigned char* data;
  25606. Atom userType;
  25607. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25608. &userType, &userSize, &userCount, &bytes, &data);
  25609. XSetErrorHandler (oldErrorHandler);
  25610. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25611. : 0;
  25612. }
  25613. static Window getChildWindow (Window windowToCheck)
  25614. {
  25615. Window rootWindow, parentWindow;
  25616. Window* childWindows;
  25617. unsigned int numChildren;
  25618. XQueryTree (display,
  25619. windowToCheck,
  25620. &rootWindow,
  25621. &parentWindow,
  25622. &childWindows,
  25623. &numChildren);
  25624. if (numChildren > 0)
  25625. return childWindows [0];
  25626. return 0;
  25627. }
  25628. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25629. {
  25630. if (e.mods.isLeftButtonDown())
  25631. {
  25632. ev.xbutton.button = Button1;
  25633. ev.xbutton.state |= Button1Mask;
  25634. }
  25635. else if (e.mods.isRightButtonDown())
  25636. {
  25637. ev.xbutton.button = Button3;
  25638. ev.xbutton.state |= Button3Mask;
  25639. }
  25640. else if (e.mods.isMiddleButtonDown())
  25641. {
  25642. ev.xbutton.button = Button2;
  25643. ev.xbutton.state |= Button2Mask;
  25644. }
  25645. }
  25646. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25647. {
  25648. if (e.mods.isLeftButtonDown())
  25649. ev.xmotion.state |= Button1Mask;
  25650. else if (e.mods.isRightButtonDown())
  25651. ev.xmotion.state |= Button3Mask;
  25652. else if (e.mods.isMiddleButtonDown())
  25653. ev.xmotion.state |= Button2Mask;
  25654. }
  25655. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25656. {
  25657. if (e.mods.isLeftButtonDown())
  25658. ev.xcrossing.state |= Button1Mask;
  25659. else if (e.mods.isRightButtonDown())
  25660. ev.xcrossing.state |= Button3Mask;
  25661. else if (e.mods.isMiddleButtonDown())
  25662. ev.xcrossing.state |= Button2Mask;
  25663. }
  25664. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25665. {
  25666. if (increment < 0)
  25667. {
  25668. ev.xbutton.button = Button5;
  25669. ev.xbutton.state |= Button5Mask;
  25670. }
  25671. else if (increment > 0)
  25672. {
  25673. ev.xbutton.button = Button4;
  25674. ev.xbutton.state |= Button4Mask;
  25675. }
  25676. }
  25677. #endif
  25678. class ModuleHandle : public ReferenceCountedObject
  25679. {
  25680. public:
  25681. File file;
  25682. MainCall moduleMain;
  25683. String pluginName;
  25684. static Array <ModuleHandle*>& getActiveModules()
  25685. {
  25686. static Array <ModuleHandle*> activeModules;
  25687. return activeModules;
  25688. }
  25689. static ModuleHandle* findOrCreateModule (const File& file)
  25690. {
  25691. for (int i = getActiveModules().size(); --i >= 0;)
  25692. {
  25693. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  25694. if (module->file == file)
  25695. return module;
  25696. }
  25697. _fpreset(); // (doesn't do any harm)
  25698. ++insideVSTCallback;
  25699. shellUIDToCreate = 0;
  25700. log ("Attempting to load VST: " + file.getFullPathName());
  25701. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25702. if (! m->open())
  25703. m = 0;
  25704. --insideVSTCallback;
  25705. _fpreset(); // (doesn't do any harm)
  25706. return m.release();
  25707. }
  25708. ModuleHandle (const File& file_)
  25709. : file (file_),
  25710. moduleMain (0),
  25711. #if JUCE_WINDOWS || JUCE_LINUX
  25712. hModule (0)
  25713. #elif JUCE_MAC
  25714. fragId (0),
  25715. resHandle (0),
  25716. bundleRef (0),
  25717. resFileId (0)
  25718. #endif
  25719. {
  25720. getActiveModules().add (this);
  25721. #if JUCE_WINDOWS || JUCE_LINUX
  25722. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25723. #elif JUCE_MAC
  25724. FSRef ref;
  25725. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25726. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25727. #endif
  25728. }
  25729. ~ModuleHandle()
  25730. {
  25731. getActiveModules().removeValue (this);
  25732. close();
  25733. }
  25734. juce_UseDebuggingNewOperator
  25735. #if JUCE_WINDOWS || JUCE_LINUX
  25736. void* hModule;
  25737. String fullParentDirectoryPathName;
  25738. bool open()
  25739. {
  25740. #if JUCE_WINDOWS
  25741. static bool timePeriodSet = false;
  25742. if (! timePeriodSet)
  25743. {
  25744. timePeriodSet = true;
  25745. timeBeginPeriod (2);
  25746. }
  25747. #endif
  25748. pluginName = file.getFileNameWithoutExtension();
  25749. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25750. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25751. if (moduleMain == 0)
  25752. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25753. return moduleMain != 0;
  25754. }
  25755. void close()
  25756. {
  25757. _fpreset(); // (doesn't do any harm)
  25758. PlatformUtilities::freeDynamicLibrary (hModule);
  25759. }
  25760. void closeEffect (AEffect* eff)
  25761. {
  25762. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25763. }
  25764. #else
  25765. CFragConnectionID fragId;
  25766. Handle resHandle;
  25767. CFBundleRef bundleRef;
  25768. FSSpec parentDirFSSpec;
  25769. short resFileId;
  25770. bool open()
  25771. {
  25772. bool ok = false;
  25773. const String filename (file.getFullPathName());
  25774. if (file.hasFileExtension (".vst"))
  25775. {
  25776. const char* const utf8 = filename.toUTF8();
  25777. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25778. strlen (utf8), file.isDirectory());
  25779. if (url != 0)
  25780. {
  25781. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25782. CFRelease (url);
  25783. if (bundleRef != 0)
  25784. {
  25785. if (CFBundleLoadExecutable (bundleRef))
  25786. {
  25787. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25788. if (moduleMain == 0)
  25789. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25790. if (moduleMain != 0)
  25791. {
  25792. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25793. if (name != 0)
  25794. {
  25795. if (CFGetTypeID (name) == CFStringGetTypeID())
  25796. {
  25797. char buffer[1024];
  25798. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25799. pluginName = buffer;
  25800. }
  25801. }
  25802. if (pluginName.isEmpty())
  25803. pluginName = file.getFileNameWithoutExtension();
  25804. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25805. ok = true;
  25806. }
  25807. }
  25808. if (! ok)
  25809. {
  25810. CFBundleUnloadExecutable (bundleRef);
  25811. CFRelease (bundleRef);
  25812. bundleRef = 0;
  25813. }
  25814. }
  25815. }
  25816. }
  25817. #if JUCE_PPC
  25818. else
  25819. {
  25820. FSRef fn;
  25821. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25822. {
  25823. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25824. if (resFileId != -1)
  25825. {
  25826. const int numEffs = Count1Resources ('aEff');
  25827. for (int i = 0; i < numEffs; ++i)
  25828. {
  25829. resHandle = Get1IndResource ('aEff', i + 1);
  25830. if (resHandle != 0)
  25831. {
  25832. OSType type;
  25833. Str255 name;
  25834. SInt16 id;
  25835. GetResInfo (resHandle, &id, &type, name);
  25836. pluginName = String ((const char*) name + 1, name[0]);
  25837. DetachResource (resHandle);
  25838. HLock (resHandle);
  25839. Ptr ptr;
  25840. Str255 errorText;
  25841. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25842. name, kPrivateCFragCopy,
  25843. &fragId, &ptr, errorText);
  25844. if (err == noErr)
  25845. {
  25846. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25847. ok = true;
  25848. }
  25849. else
  25850. {
  25851. HUnlock (resHandle);
  25852. }
  25853. break;
  25854. }
  25855. }
  25856. if (! ok)
  25857. CloseResFile (resFileId);
  25858. }
  25859. }
  25860. }
  25861. #endif
  25862. return ok;
  25863. }
  25864. void close()
  25865. {
  25866. #if JUCE_PPC
  25867. if (fragId != 0)
  25868. {
  25869. if (moduleMain != 0)
  25870. disposeMachOFromCFM ((void*) moduleMain);
  25871. CloseConnection (&fragId);
  25872. HUnlock (resHandle);
  25873. if (resFileId != 0)
  25874. CloseResFile (resFileId);
  25875. }
  25876. else
  25877. #endif
  25878. if (bundleRef != 0)
  25879. {
  25880. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25881. if (CFGetRetainCount (bundleRef) == 1)
  25882. CFBundleUnloadExecutable (bundleRef);
  25883. if (CFGetRetainCount (bundleRef) > 0)
  25884. CFRelease (bundleRef);
  25885. }
  25886. }
  25887. void closeEffect (AEffect* eff)
  25888. {
  25889. #if JUCE_PPC
  25890. if (fragId != 0)
  25891. {
  25892. Array<void*> thingsToDelete;
  25893. thingsToDelete.add ((void*) eff->dispatcher);
  25894. thingsToDelete.add ((void*) eff->process);
  25895. thingsToDelete.add ((void*) eff->setParameter);
  25896. thingsToDelete.add ((void*) eff->getParameter);
  25897. thingsToDelete.add ((void*) eff->processReplacing);
  25898. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25899. for (int i = thingsToDelete.size(); --i >= 0;)
  25900. disposeMachOFromCFM (thingsToDelete[i]);
  25901. }
  25902. else
  25903. #endif
  25904. {
  25905. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25906. }
  25907. }
  25908. #if JUCE_PPC
  25909. static void* newMachOFromCFM (void* cfmfp)
  25910. {
  25911. if (cfmfp == 0)
  25912. return 0;
  25913. UInt32* const mfp = new UInt32[6];
  25914. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25915. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25916. mfp[2] = 0x800c0000;
  25917. mfp[3] = 0x804c0004;
  25918. mfp[4] = 0x7c0903a6;
  25919. mfp[5] = 0x4e800420;
  25920. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25921. return mfp;
  25922. }
  25923. static void disposeMachOFromCFM (void* ptr)
  25924. {
  25925. delete[] static_cast <UInt32*> (ptr);
  25926. }
  25927. void coerceAEffectFunctionCalls (AEffect* eff)
  25928. {
  25929. if (fragId != 0)
  25930. {
  25931. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25932. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25933. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25934. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25935. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25936. }
  25937. }
  25938. #endif
  25939. #endif
  25940. };
  25941. /**
  25942. An instance of a plugin, created by a VSTPluginFormat.
  25943. */
  25944. class VSTPluginInstance : public AudioPluginInstance,
  25945. private Timer,
  25946. private AsyncUpdater
  25947. {
  25948. public:
  25949. ~VSTPluginInstance();
  25950. // AudioPluginInstance methods:
  25951. void fillInPluginDescription (PluginDescription& desc) const
  25952. {
  25953. desc.name = name;
  25954. desc.fileOrIdentifier = module->file.getFullPathName();
  25955. desc.uid = getUID();
  25956. desc.lastFileModTime = module->file.getLastModificationTime();
  25957. desc.pluginFormatName = "VST";
  25958. desc.category = getCategory();
  25959. {
  25960. char buffer [kVstMaxVendorStrLen + 8];
  25961. zerostruct (buffer);
  25962. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25963. desc.manufacturerName = buffer;
  25964. }
  25965. desc.version = getVersion();
  25966. desc.numInputChannels = getNumInputChannels();
  25967. desc.numOutputChannels = getNumOutputChannels();
  25968. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25969. }
  25970. const String getName() const { return name; }
  25971. int getUID() const throw();
  25972. bool acceptsMidi() const { return wantsMidiMessages; }
  25973. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25974. // AudioProcessor methods:
  25975. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25976. void releaseResources();
  25977. void processBlock (AudioSampleBuffer& buffer,
  25978. MidiBuffer& midiMessages);
  25979. AudioProcessorEditor* createEditor();
  25980. const String getInputChannelName (const int index) const;
  25981. bool isInputChannelStereoPair (int index) const;
  25982. const String getOutputChannelName (const int index) const;
  25983. bool isOutputChannelStereoPair (int index) const;
  25984. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25985. float getParameter (int index);
  25986. void setParameter (int index, float newValue);
  25987. const String getParameterName (int index);
  25988. const String getParameterText (int index);
  25989. bool isParameterAutomatable (int index) const;
  25990. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25991. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25992. void setCurrentProgram (int index);
  25993. const String getProgramName (int index);
  25994. void changeProgramName (int index, const String& newName);
  25995. void getStateInformation (MemoryBlock& destData);
  25996. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25997. void setStateInformation (const void* data, int sizeInBytes);
  25998. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25999. void timerCallback();
  26000. void handleAsyncUpdate();
  26001. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26002. juce_UseDebuggingNewOperator
  26003. private:
  26004. friend class VSTPluginWindow;
  26005. friend class VSTPluginFormat;
  26006. AEffect* effect;
  26007. String name;
  26008. CriticalSection lock;
  26009. bool wantsMidiMessages, initialised, isPowerOn;
  26010. mutable StringArray programNames;
  26011. AudioSampleBuffer tempBuffer;
  26012. CriticalSection midiInLock;
  26013. MidiBuffer incomingMidi;
  26014. VSTMidiEventList midiEventsToSend;
  26015. VstTimeInfo vstHostTime;
  26016. HeapBlock <float*> channels;
  26017. ReferenceCountedObjectPtr <ModuleHandle> module;
  26018. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26019. bool restoreProgramSettings (const fxProgram* const prog);
  26020. const String getCurrentProgramName();
  26021. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26022. void updateStoredProgramNames();
  26023. void initialise();
  26024. void handleMidiFromPlugin (const VstEvents* const events);
  26025. void createTempParameterStore (MemoryBlock& dest);
  26026. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26027. const String getParameterLabel (int index) const;
  26028. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26029. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26030. void setChunkData (const char* data, int size, bool isPreset);
  26031. bool loadFromFXBFile (const void* data, int numBytes);
  26032. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26033. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26034. const String getVersion() const throw();
  26035. const String getCategory() const throw();
  26036. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26037. void setPower (const bool on);
  26038. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26039. };
  26040. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26041. : effect (0),
  26042. wantsMidiMessages (false),
  26043. initialised (false),
  26044. isPowerOn (false),
  26045. tempBuffer (1, 1),
  26046. module (module_)
  26047. {
  26048. try
  26049. {
  26050. _fpreset();
  26051. ++insideVSTCallback;
  26052. name = module->pluginName;
  26053. log ("Creating VST instance: " + name);
  26054. #if JUCE_MAC
  26055. if (module->resFileId != 0)
  26056. UseResFile (module->resFileId);
  26057. #if JUCE_PPC
  26058. if (module->fragId != 0)
  26059. {
  26060. static void* audioMasterCoerced = 0;
  26061. if (audioMasterCoerced == 0)
  26062. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26063. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26064. }
  26065. else
  26066. #endif
  26067. #endif
  26068. {
  26069. effect = module->moduleMain (&audioMaster);
  26070. }
  26071. --insideVSTCallback;
  26072. if (effect != 0 && effect->magic == kEffectMagic)
  26073. {
  26074. #if JUCE_PPC
  26075. module->coerceAEffectFunctionCalls (effect);
  26076. #endif
  26077. jassert (effect->resvd2 == 0);
  26078. jassert (effect->object != 0);
  26079. _fpreset(); // some dodgy plugs fuck around with this
  26080. }
  26081. else
  26082. {
  26083. effect = 0;
  26084. }
  26085. }
  26086. catch (...)
  26087. {
  26088. --insideVSTCallback;
  26089. }
  26090. }
  26091. VSTPluginInstance::~VSTPluginInstance()
  26092. {
  26093. {
  26094. const ScopedLock sl (lock);
  26095. jassert (insideVSTCallback == 0);
  26096. if (effect != 0 && effect->magic == kEffectMagic)
  26097. {
  26098. try
  26099. {
  26100. #if JUCE_MAC
  26101. if (module->resFileId != 0)
  26102. UseResFile (module->resFileId);
  26103. #endif
  26104. // Must delete any editors before deleting the plugin instance!
  26105. jassert (getActiveEditor() == 0);
  26106. _fpreset(); // some dodgy plugs fuck around with this
  26107. module->closeEffect (effect);
  26108. }
  26109. catch (...)
  26110. {}
  26111. }
  26112. module = 0;
  26113. effect = 0;
  26114. }
  26115. }
  26116. void VSTPluginInstance::initialise()
  26117. {
  26118. if (initialised || effect == 0)
  26119. return;
  26120. log ("Initialising VST: " + module->pluginName);
  26121. initialised = true;
  26122. dispatch (effIdentify, 0, 0, 0, 0);
  26123. // this code would ask the plugin for its name, but so few plugins
  26124. // actually bother implementing this correctly, that it's better to
  26125. // just ignore it and use the file name instead.
  26126. /* {
  26127. char buffer [256];
  26128. zerostruct (buffer);
  26129. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26130. name = String (buffer).trim();
  26131. if (name.isEmpty())
  26132. name = module->pluginName;
  26133. }
  26134. */
  26135. if (getSampleRate() > 0)
  26136. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26137. if (getBlockSize() > 0)
  26138. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26139. dispatch (effOpen, 0, 0, 0, 0);
  26140. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26141. getSampleRate(), getBlockSize());
  26142. if (getNumPrograms() > 1)
  26143. setCurrentProgram (0);
  26144. else
  26145. dispatch (effSetProgram, 0, 0, 0, 0);
  26146. int i;
  26147. for (i = effect->numInputs; --i >= 0;)
  26148. dispatch (effConnectInput, i, 1, 0, 0);
  26149. for (i = effect->numOutputs; --i >= 0;)
  26150. dispatch (effConnectOutput, i, 1, 0, 0);
  26151. updateStoredProgramNames();
  26152. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26153. setLatencySamples (effect->initialDelay);
  26154. }
  26155. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26156. int samplesPerBlockExpected)
  26157. {
  26158. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26159. sampleRate_, samplesPerBlockExpected);
  26160. setLatencySamples (effect->initialDelay);
  26161. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26162. vstHostTime.tempo = 120.0;
  26163. vstHostTime.timeSigNumerator = 4;
  26164. vstHostTime.timeSigDenominator = 4;
  26165. vstHostTime.sampleRate = sampleRate_;
  26166. vstHostTime.samplePos = 0;
  26167. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26168. initialise();
  26169. if (initialised)
  26170. {
  26171. wantsMidiMessages = wantsMidiMessages
  26172. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26173. if (wantsMidiMessages)
  26174. midiEventsToSend.ensureSize (256);
  26175. else
  26176. midiEventsToSend.freeEvents();
  26177. incomingMidi.clear();
  26178. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26179. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26180. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26181. if (! isPowerOn)
  26182. setPower (true);
  26183. // dodgy hack to force some plugins to initialise the sample rate..
  26184. if ((! hasEditor()) && getNumParameters() > 0)
  26185. {
  26186. const float old = getParameter (0);
  26187. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26188. setParameter (0, old);
  26189. }
  26190. dispatch (effStartProcess, 0, 0, 0, 0);
  26191. }
  26192. }
  26193. void VSTPluginInstance::releaseResources()
  26194. {
  26195. if (initialised)
  26196. {
  26197. dispatch (effStopProcess, 0, 0, 0, 0);
  26198. setPower (false);
  26199. }
  26200. tempBuffer.setSize (1, 1);
  26201. incomingMidi.clear();
  26202. midiEventsToSend.freeEvents();
  26203. channels.free();
  26204. }
  26205. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26206. MidiBuffer& midiMessages)
  26207. {
  26208. const int numSamples = buffer.getNumSamples();
  26209. if (initialised)
  26210. {
  26211. AudioPlayHead* playHead = getPlayHead();
  26212. if (playHead != 0)
  26213. {
  26214. AudioPlayHead::CurrentPositionInfo position;
  26215. playHead->getCurrentPosition (position);
  26216. vstHostTime.tempo = position.bpm;
  26217. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26218. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26219. vstHostTime.ppqPos = position.ppqPosition;
  26220. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26221. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26222. if (position.isPlaying)
  26223. vstHostTime.flags |= kVstTransportPlaying;
  26224. else
  26225. vstHostTime.flags &= ~kVstTransportPlaying;
  26226. }
  26227. #if JUCE_WINDOWS
  26228. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26229. #elif JUCE_LINUX
  26230. timeval micro;
  26231. gettimeofday (&micro, 0);
  26232. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26233. #elif JUCE_MAC
  26234. UnsignedWide micro;
  26235. Microseconds (&micro);
  26236. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26237. #endif
  26238. if (wantsMidiMessages)
  26239. {
  26240. midiEventsToSend.clear();
  26241. midiEventsToSend.ensureSize (1);
  26242. MidiBuffer::Iterator iter (midiMessages);
  26243. const uint8* midiData;
  26244. int numBytesOfMidiData, samplePosition;
  26245. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26246. {
  26247. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26248. jlimit (0, numSamples - 1, samplePosition));
  26249. }
  26250. try
  26251. {
  26252. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26253. }
  26254. catch (...)
  26255. {}
  26256. }
  26257. int i;
  26258. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26259. for (i = 0; i < maxChans; ++i)
  26260. channels[i] = buffer.getSampleData (i);
  26261. channels [maxChans] = 0;
  26262. _clearfp();
  26263. if ((effect->flags & effFlagsCanReplacing) != 0)
  26264. {
  26265. try
  26266. {
  26267. effect->processReplacing (effect, channels, channels, numSamples);
  26268. }
  26269. catch (...)
  26270. {}
  26271. }
  26272. else
  26273. {
  26274. tempBuffer.setSize (effect->numOutputs, numSamples);
  26275. tempBuffer.clear();
  26276. float* outs [64];
  26277. for (i = effect->numOutputs; --i >= 0;)
  26278. outs[i] = tempBuffer.getSampleData (i);
  26279. outs [effect->numOutputs] = 0;
  26280. try
  26281. {
  26282. effect->process (effect, channels, outs, numSamples);
  26283. }
  26284. catch (...)
  26285. {}
  26286. for (i = effect->numOutputs; --i >= 0;)
  26287. buffer.copyFrom (i, 0, outs[i], numSamples);
  26288. }
  26289. }
  26290. else
  26291. {
  26292. // Not initialised, so just bypass..
  26293. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26294. buffer.clear (i, 0, buffer.getNumSamples());
  26295. }
  26296. {
  26297. // copy any incoming midi..
  26298. const ScopedLock sl (midiInLock);
  26299. midiMessages.swapWith (incomingMidi);
  26300. incomingMidi.clear();
  26301. }
  26302. }
  26303. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26304. {
  26305. if (events != 0)
  26306. {
  26307. const ScopedLock sl (midiInLock);
  26308. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26309. }
  26310. }
  26311. static Array <VSTPluginWindow*> activeVSTWindows;
  26312. class VSTPluginWindow : public AudioProcessorEditor,
  26313. #if ! JUCE_MAC
  26314. public ComponentMovementWatcher,
  26315. #endif
  26316. public Timer
  26317. {
  26318. public:
  26319. VSTPluginWindow (VSTPluginInstance& plugin_)
  26320. : AudioProcessorEditor (&plugin_),
  26321. #if ! JUCE_MAC
  26322. ComponentMovementWatcher (this),
  26323. #endif
  26324. plugin (plugin_),
  26325. isOpen (false),
  26326. wasShowing (false),
  26327. pluginRefusesToResize (false),
  26328. pluginWantsKeys (false),
  26329. alreadyInside (false),
  26330. recursiveResize (false)
  26331. {
  26332. #if JUCE_WINDOWS
  26333. sizeCheckCount = 0;
  26334. pluginHWND = 0;
  26335. #elif JUCE_LINUX
  26336. pluginWindow = None;
  26337. pluginProc = None;
  26338. #else
  26339. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26340. #endif
  26341. activeVSTWindows.add (this);
  26342. setSize (1, 1);
  26343. setOpaque (true);
  26344. setVisible (true);
  26345. }
  26346. ~VSTPluginWindow()
  26347. {
  26348. #if JUCE_MAC
  26349. innerWrapper = 0;
  26350. #else
  26351. closePluginWindow();
  26352. #endif
  26353. activeVSTWindows.removeValue (this);
  26354. plugin.editorBeingDeleted (this);
  26355. }
  26356. #if ! JUCE_MAC
  26357. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26358. {
  26359. if (recursiveResize)
  26360. return;
  26361. Component* const topComp = getTopLevelComponent();
  26362. if (topComp->getPeer() != 0)
  26363. {
  26364. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26365. recursiveResize = true;
  26366. #if JUCE_WINDOWS
  26367. if (pluginHWND != 0)
  26368. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26369. #elif JUCE_LINUX
  26370. if (pluginWindow != 0)
  26371. {
  26372. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26373. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26374. XMapRaised (display, pluginWindow);
  26375. }
  26376. #endif
  26377. recursiveResize = false;
  26378. }
  26379. }
  26380. void componentVisibilityChanged (Component&)
  26381. {
  26382. const bool isShowingNow = isShowing();
  26383. if (wasShowing != isShowingNow)
  26384. {
  26385. wasShowing = isShowingNow;
  26386. if (isShowingNow)
  26387. openPluginWindow();
  26388. else
  26389. closePluginWindow();
  26390. }
  26391. componentMovedOrResized (true, true);
  26392. }
  26393. void componentPeerChanged()
  26394. {
  26395. closePluginWindow();
  26396. openPluginWindow();
  26397. }
  26398. #endif
  26399. bool keyStateChanged (bool)
  26400. {
  26401. return pluginWantsKeys;
  26402. }
  26403. bool keyPressed (const KeyPress&)
  26404. {
  26405. return pluginWantsKeys;
  26406. }
  26407. #if JUCE_MAC
  26408. void paint (Graphics& g)
  26409. {
  26410. g.fillAll (Colours::black);
  26411. }
  26412. #else
  26413. void paint (Graphics& g)
  26414. {
  26415. if (isOpen)
  26416. {
  26417. ComponentPeer* const peer = getPeer();
  26418. if (peer != 0)
  26419. {
  26420. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26421. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26422. #if JUCE_LINUX
  26423. if (pluginWindow != 0)
  26424. {
  26425. const Rectangle<int> clip (g.getClipBounds());
  26426. XEvent ev;
  26427. zerostruct (ev);
  26428. ev.xexpose.type = Expose;
  26429. ev.xexpose.display = display;
  26430. ev.xexpose.window = pluginWindow;
  26431. ev.xexpose.x = clip.getX();
  26432. ev.xexpose.y = clip.getY();
  26433. ev.xexpose.width = clip.getWidth();
  26434. ev.xexpose.height = clip.getHeight();
  26435. sendEventToChild (&ev);
  26436. }
  26437. #endif
  26438. }
  26439. }
  26440. else
  26441. {
  26442. g.fillAll (Colours::black);
  26443. }
  26444. }
  26445. #endif
  26446. void timerCallback()
  26447. {
  26448. #if JUCE_WINDOWS
  26449. if (--sizeCheckCount <= 0)
  26450. {
  26451. sizeCheckCount = 10;
  26452. checkPluginWindowSize();
  26453. }
  26454. #endif
  26455. try
  26456. {
  26457. static bool reentrant = false;
  26458. if (! reentrant)
  26459. {
  26460. reentrant = true;
  26461. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26462. reentrant = false;
  26463. }
  26464. }
  26465. catch (...)
  26466. {}
  26467. }
  26468. void mouseDown (const MouseEvent& e)
  26469. {
  26470. #if JUCE_LINUX
  26471. if (pluginWindow == 0)
  26472. return;
  26473. toFront (true);
  26474. XEvent ev;
  26475. zerostruct (ev);
  26476. ev.xbutton.display = display;
  26477. ev.xbutton.type = ButtonPress;
  26478. ev.xbutton.window = pluginWindow;
  26479. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26480. ev.xbutton.time = CurrentTime;
  26481. ev.xbutton.x = e.x;
  26482. ev.xbutton.y = e.y;
  26483. ev.xbutton.x_root = e.getScreenX();
  26484. ev.xbutton.y_root = e.getScreenY();
  26485. translateJuceToXButtonModifiers (e, ev);
  26486. sendEventToChild (&ev);
  26487. #elif JUCE_WINDOWS
  26488. (void) e;
  26489. toFront (true);
  26490. #endif
  26491. }
  26492. void broughtToFront()
  26493. {
  26494. activeVSTWindows.removeValue (this);
  26495. activeVSTWindows.add (this);
  26496. #if JUCE_MAC
  26497. dispatch (effEditTop, 0, 0, 0, 0);
  26498. #endif
  26499. }
  26500. juce_UseDebuggingNewOperator
  26501. private:
  26502. VSTPluginInstance& plugin;
  26503. bool isOpen, wasShowing, recursiveResize;
  26504. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26505. #if JUCE_WINDOWS
  26506. HWND pluginHWND;
  26507. void* originalWndProc;
  26508. int sizeCheckCount;
  26509. #elif JUCE_LINUX
  26510. Window pluginWindow;
  26511. EventProcPtr pluginProc;
  26512. #endif
  26513. #if JUCE_MAC
  26514. void openPluginWindow (WindowRef parentWindow)
  26515. {
  26516. if (isOpen || parentWindow == 0)
  26517. return;
  26518. isOpen = true;
  26519. ERect* rect = 0;
  26520. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26521. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26522. // do this before and after like in the steinberg example
  26523. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26524. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26525. // Install keyboard hooks
  26526. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26527. // double-check it's not too tiny
  26528. int w = 250, h = 150;
  26529. if (rect != 0)
  26530. {
  26531. w = rect->right - rect->left;
  26532. h = rect->bottom - rect->top;
  26533. if (w == 0 || h == 0)
  26534. {
  26535. w = 250;
  26536. h = 150;
  26537. }
  26538. }
  26539. w = jmax (w, 32);
  26540. h = jmax (h, 32);
  26541. setSize (w, h);
  26542. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26543. repaint();
  26544. }
  26545. #else
  26546. void openPluginWindow()
  26547. {
  26548. if (isOpen || getWindowHandle() == 0)
  26549. return;
  26550. log ("Opening VST UI: " + plugin.name);
  26551. isOpen = true;
  26552. ERect* rect = 0;
  26553. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26554. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26555. // do this before and after like in the steinberg example
  26556. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26557. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26558. // Install keyboard hooks
  26559. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26560. #if JUCE_WINDOWS
  26561. originalWndProc = 0;
  26562. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26563. if (pluginHWND == 0)
  26564. {
  26565. isOpen = false;
  26566. setSize (300, 150);
  26567. return;
  26568. }
  26569. #pragma warning (push)
  26570. #pragma warning (disable: 4244)
  26571. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26572. if (! pluginWantsKeys)
  26573. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26574. #pragma warning (pop)
  26575. int w, h;
  26576. RECT r;
  26577. GetWindowRect (pluginHWND, &r);
  26578. w = r.right - r.left;
  26579. h = r.bottom - r.top;
  26580. if (rect != 0)
  26581. {
  26582. const int rw = rect->right - rect->left;
  26583. const int rh = rect->bottom - rect->top;
  26584. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26585. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26586. {
  26587. // very dodgy logic to decide which size is right.
  26588. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26589. {
  26590. SetWindowPos (pluginHWND, 0,
  26591. 0, 0, rw, rh,
  26592. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26593. GetWindowRect (pluginHWND, &r);
  26594. w = r.right - r.left;
  26595. h = r.bottom - r.top;
  26596. pluginRefusesToResize = (w != rw) || (h != rh);
  26597. w = rw;
  26598. h = rh;
  26599. }
  26600. }
  26601. }
  26602. #elif JUCE_LINUX
  26603. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26604. if (pluginWindow != 0)
  26605. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26606. XInternAtom (display, "_XEventProc", False));
  26607. int w = 250, h = 150;
  26608. if (rect != 0)
  26609. {
  26610. w = rect->right - rect->left;
  26611. h = rect->bottom - rect->top;
  26612. if (w == 0 || h == 0)
  26613. {
  26614. w = 250;
  26615. h = 150;
  26616. }
  26617. }
  26618. if (pluginWindow != 0)
  26619. XMapRaised (display, pluginWindow);
  26620. #endif
  26621. // double-check it's not too tiny
  26622. w = jmax (w, 32);
  26623. h = jmax (h, 32);
  26624. setSize (w, h);
  26625. #if JUCE_WINDOWS
  26626. checkPluginWindowSize();
  26627. #endif
  26628. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26629. repaint();
  26630. }
  26631. #endif
  26632. #if ! JUCE_MAC
  26633. void closePluginWindow()
  26634. {
  26635. if (isOpen)
  26636. {
  26637. log ("Closing VST UI: " + plugin.getName());
  26638. isOpen = false;
  26639. dispatch (effEditClose, 0, 0, 0, 0);
  26640. #if JUCE_WINDOWS
  26641. #pragma warning (push)
  26642. #pragma warning (disable: 4244)
  26643. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26644. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26645. #pragma warning (pop)
  26646. stopTimer();
  26647. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26648. DestroyWindow (pluginHWND);
  26649. pluginHWND = 0;
  26650. #elif JUCE_LINUX
  26651. stopTimer();
  26652. pluginWindow = 0;
  26653. pluginProc = 0;
  26654. #endif
  26655. }
  26656. }
  26657. #endif
  26658. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26659. {
  26660. return plugin.dispatch (opcode, index, value, ptr, opt);
  26661. }
  26662. #if JUCE_WINDOWS
  26663. void checkPluginWindowSize() throw()
  26664. {
  26665. RECT r;
  26666. GetWindowRect (pluginHWND, &r);
  26667. const int w = r.right - r.left;
  26668. const int h = r.bottom - r.top;
  26669. if (isShowing() && w > 0 && h > 0
  26670. && (w != getWidth() || h != getHeight())
  26671. && ! pluginRefusesToResize)
  26672. {
  26673. setSize (w, h);
  26674. sizeCheckCount = 0;
  26675. }
  26676. }
  26677. // hooks to get keyboard events from VST windows..
  26678. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26679. {
  26680. for (int i = activeVSTWindows.size(); --i >= 0;)
  26681. {
  26682. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26683. if (w->pluginHWND == hW)
  26684. {
  26685. if (message == WM_CHAR
  26686. || message == WM_KEYDOWN
  26687. || message == WM_SYSKEYDOWN
  26688. || message == WM_KEYUP
  26689. || message == WM_SYSKEYUP
  26690. || message == WM_APPCOMMAND)
  26691. {
  26692. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26693. message, wParam, lParam);
  26694. }
  26695. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26696. (HWND) w->pluginHWND,
  26697. message,
  26698. wParam,
  26699. lParam);
  26700. }
  26701. }
  26702. return DefWindowProc (hW, message, wParam, lParam);
  26703. }
  26704. #endif
  26705. #if JUCE_LINUX
  26706. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26707. void sendEventToChild (XEvent* event)
  26708. {
  26709. if (pluginProc != 0)
  26710. {
  26711. // if the plugin publishes an event procedure, pass the event directly..
  26712. pluginProc (event);
  26713. }
  26714. else if (pluginWindow != 0)
  26715. {
  26716. // if the plugin has a window, then send the event to the window so that
  26717. // its message thread will pick it up..
  26718. XSendEvent (display, pluginWindow, False, 0L, event);
  26719. XFlush (display);
  26720. }
  26721. }
  26722. void mouseEnter (const MouseEvent& e)
  26723. {
  26724. if (pluginWindow != 0)
  26725. {
  26726. XEvent ev;
  26727. zerostruct (ev);
  26728. ev.xcrossing.display = display;
  26729. ev.xcrossing.type = EnterNotify;
  26730. ev.xcrossing.window = pluginWindow;
  26731. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26732. ev.xcrossing.time = CurrentTime;
  26733. ev.xcrossing.x = e.x;
  26734. ev.xcrossing.y = e.y;
  26735. ev.xcrossing.x_root = e.getScreenX();
  26736. ev.xcrossing.y_root = e.getScreenY();
  26737. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26738. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26739. translateJuceToXCrossingModifiers (e, ev);
  26740. sendEventToChild (&ev);
  26741. }
  26742. }
  26743. void mouseExit (const MouseEvent& e)
  26744. {
  26745. if (pluginWindow != 0)
  26746. {
  26747. XEvent ev;
  26748. zerostruct (ev);
  26749. ev.xcrossing.display = display;
  26750. ev.xcrossing.type = LeaveNotify;
  26751. ev.xcrossing.window = pluginWindow;
  26752. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26753. ev.xcrossing.time = CurrentTime;
  26754. ev.xcrossing.x = e.x;
  26755. ev.xcrossing.y = e.y;
  26756. ev.xcrossing.x_root = e.getScreenX();
  26757. ev.xcrossing.y_root = e.getScreenY();
  26758. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26759. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26760. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26761. translateJuceToXCrossingModifiers (e, ev);
  26762. sendEventToChild (&ev);
  26763. }
  26764. }
  26765. void mouseMove (const MouseEvent& e)
  26766. {
  26767. if (pluginWindow != 0)
  26768. {
  26769. XEvent ev;
  26770. zerostruct (ev);
  26771. ev.xmotion.display = display;
  26772. ev.xmotion.type = MotionNotify;
  26773. ev.xmotion.window = pluginWindow;
  26774. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26775. ev.xmotion.time = CurrentTime;
  26776. ev.xmotion.is_hint = NotifyNormal;
  26777. ev.xmotion.x = e.x;
  26778. ev.xmotion.y = e.y;
  26779. ev.xmotion.x_root = e.getScreenX();
  26780. ev.xmotion.y_root = e.getScreenY();
  26781. sendEventToChild (&ev);
  26782. }
  26783. }
  26784. void mouseDrag (const MouseEvent& e)
  26785. {
  26786. if (pluginWindow != 0)
  26787. {
  26788. XEvent ev;
  26789. zerostruct (ev);
  26790. ev.xmotion.display = display;
  26791. ev.xmotion.type = MotionNotify;
  26792. ev.xmotion.window = pluginWindow;
  26793. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26794. ev.xmotion.time = CurrentTime;
  26795. ev.xmotion.x = e.x ;
  26796. ev.xmotion.y = e.y;
  26797. ev.xmotion.x_root = e.getScreenX();
  26798. ev.xmotion.y_root = e.getScreenY();
  26799. ev.xmotion.is_hint = NotifyNormal;
  26800. translateJuceToXMotionModifiers (e, ev);
  26801. sendEventToChild (&ev);
  26802. }
  26803. }
  26804. void mouseUp (const MouseEvent& e)
  26805. {
  26806. if (pluginWindow != 0)
  26807. {
  26808. XEvent ev;
  26809. zerostruct (ev);
  26810. ev.xbutton.display = display;
  26811. ev.xbutton.type = ButtonRelease;
  26812. ev.xbutton.window = pluginWindow;
  26813. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26814. ev.xbutton.time = CurrentTime;
  26815. ev.xbutton.x = e.x;
  26816. ev.xbutton.y = e.y;
  26817. ev.xbutton.x_root = e.getScreenX();
  26818. ev.xbutton.y_root = e.getScreenY();
  26819. translateJuceToXButtonModifiers (e, ev);
  26820. sendEventToChild (&ev);
  26821. }
  26822. }
  26823. void mouseWheelMove (const MouseEvent& e,
  26824. float incrementX,
  26825. float incrementY)
  26826. {
  26827. if (pluginWindow != 0)
  26828. {
  26829. XEvent ev;
  26830. zerostruct (ev);
  26831. ev.xbutton.display = display;
  26832. ev.xbutton.type = ButtonPress;
  26833. ev.xbutton.window = pluginWindow;
  26834. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26835. ev.xbutton.time = CurrentTime;
  26836. ev.xbutton.x = e.x;
  26837. ev.xbutton.y = e.y;
  26838. ev.xbutton.x_root = e.getScreenX();
  26839. ev.xbutton.y_root = e.getScreenY();
  26840. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26841. sendEventToChild (&ev);
  26842. // TODO - put a usleep here ?
  26843. ev.xbutton.type = ButtonRelease;
  26844. sendEventToChild (&ev);
  26845. }
  26846. }
  26847. #endif
  26848. #if JUCE_MAC
  26849. #if ! JUCE_SUPPORT_CARBON
  26850. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26851. #endif
  26852. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26853. {
  26854. public:
  26855. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26856. : owner (owner_),
  26857. alreadyInside (false)
  26858. {
  26859. }
  26860. ~InnerWrapperComponent()
  26861. {
  26862. deleteWindow();
  26863. }
  26864. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26865. {
  26866. owner->openPluginWindow (windowRef);
  26867. return 0;
  26868. }
  26869. void removeView (HIViewRef)
  26870. {
  26871. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26872. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26873. }
  26874. bool getEmbeddedViewSize (int& w, int& h)
  26875. {
  26876. ERect* rect = 0;
  26877. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26878. w = rect->right - rect->left;
  26879. h = rect->bottom - rect->top;
  26880. return true;
  26881. }
  26882. void mouseDown (int x, int y)
  26883. {
  26884. if (! alreadyInside)
  26885. {
  26886. alreadyInside = true;
  26887. getTopLevelComponent()->toFront (true);
  26888. owner->dispatch (effEditMouse, x, y, 0, 0);
  26889. alreadyInside = false;
  26890. }
  26891. else
  26892. {
  26893. PostEvent (::mouseDown, 0);
  26894. }
  26895. }
  26896. void paint()
  26897. {
  26898. ComponentPeer* const peer = getPeer();
  26899. if (peer != 0)
  26900. {
  26901. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26902. ERect r;
  26903. r.left = pos.getX();
  26904. r.right = r.left + getWidth();
  26905. r.top = pos.getY();
  26906. r.bottom = r.top + getHeight();
  26907. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26908. }
  26909. }
  26910. private:
  26911. VSTPluginWindow* const owner;
  26912. bool alreadyInside;
  26913. };
  26914. friend class InnerWrapperComponent;
  26915. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26916. void resized()
  26917. {
  26918. innerWrapper->setSize (getWidth(), getHeight());
  26919. }
  26920. #endif
  26921. };
  26922. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26923. {
  26924. if (hasEditor())
  26925. return new VSTPluginWindow (*this);
  26926. return 0;
  26927. }
  26928. void VSTPluginInstance::handleAsyncUpdate()
  26929. {
  26930. // indicates that something about the plugin has changed..
  26931. updateHostDisplay();
  26932. }
  26933. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26934. {
  26935. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26936. {
  26937. changeProgramName (getCurrentProgram(), prog->prgName);
  26938. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26939. setParameter (i, vst_swapFloat (prog->params[i]));
  26940. return true;
  26941. }
  26942. return false;
  26943. }
  26944. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26945. const int dataSize)
  26946. {
  26947. if (dataSize < 28)
  26948. return false;
  26949. const fxSet* const set = (const fxSet*) data;
  26950. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26951. || vst_swap (set->version) > fxbVersionNum)
  26952. return false;
  26953. if (vst_swap (set->fxMagic) == 'FxBk')
  26954. {
  26955. // bank of programs
  26956. if (vst_swap (set->numPrograms) >= 0)
  26957. {
  26958. const int oldProg = getCurrentProgram();
  26959. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26960. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26961. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26962. {
  26963. if (i != oldProg)
  26964. {
  26965. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26966. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26967. return false;
  26968. if (vst_swap (set->numPrograms) > 0)
  26969. setCurrentProgram (i);
  26970. if (! restoreProgramSettings (prog))
  26971. return false;
  26972. }
  26973. }
  26974. if (vst_swap (set->numPrograms) > 0)
  26975. setCurrentProgram (oldProg);
  26976. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26977. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26978. return false;
  26979. if (! restoreProgramSettings (prog))
  26980. return false;
  26981. }
  26982. }
  26983. else if (vst_swap (set->fxMagic) == 'FxCk')
  26984. {
  26985. // single program
  26986. const fxProgram* const prog = (const fxProgram*) data;
  26987. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26988. return false;
  26989. changeProgramName (getCurrentProgram(), prog->prgName);
  26990. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26991. setParameter (i, vst_swapFloat (prog->params[i]));
  26992. }
  26993. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26994. {
  26995. // non-preset chunk
  26996. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26997. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26998. return false;
  26999. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27000. }
  27001. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27002. {
  27003. // preset chunk
  27004. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27005. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27006. return false;
  27007. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27008. changeProgramName (getCurrentProgram(), cset->name);
  27009. }
  27010. else
  27011. {
  27012. return false;
  27013. }
  27014. return true;
  27015. }
  27016. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27017. {
  27018. const int numParams = getNumParameters();
  27019. prog->chunkMagic = vst_swap ('CcnK');
  27020. prog->byteSize = 0;
  27021. prog->fxMagic = vst_swap ('FxCk');
  27022. prog->version = vst_swap (fxbVersionNum);
  27023. prog->fxID = vst_swap (getUID());
  27024. prog->fxVersion = vst_swap (getVersionNumber());
  27025. prog->numParams = vst_swap (numParams);
  27026. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27027. for (int i = 0; i < numParams; ++i)
  27028. prog->params[i] = vst_swapFloat (getParameter (i));
  27029. }
  27030. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27031. {
  27032. const int numPrograms = getNumPrograms();
  27033. const int numParams = getNumParameters();
  27034. if (usesChunks())
  27035. {
  27036. if (isFXB)
  27037. {
  27038. MemoryBlock chunk;
  27039. getChunkData (chunk, false, maxSizeMB);
  27040. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27041. dest.setSize (totalLen, true);
  27042. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27043. set->chunkMagic = vst_swap ('CcnK');
  27044. set->byteSize = 0;
  27045. set->fxMagic = vst_swap ('FBCh');
  27046. set->version = vst_swap (fxbVersionNum);
  27047. set->fxID = vst_swap (getUID());
  27048. set->fxVersion = vst_swap (getVersionNumber());
  27049. set->numPrograms = vst_swap (numPrograms);
  27050. set->chunkSize = vst_swap ((long) chunk.getSize());
  27051. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27052. }
  27053. else
  27054. {
  27055. MemoryBlock chunk;
  27056. getChunkData (chunk, true, maxSizeMB);
  27057. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27058. dest.setSize (totalLen, true);
  27059. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27060. set->chunkMagic = vst_swap ('CcnK');
  27061. set->byteSize = 0;
  27062. set->fxMagic = vst_swap ('FPCh');
  27063. set->version = vst_swap (fxbVersionNum);
  27064. set->fxID = vst_swap (getUID());
  27065. set->fxVersion = vst_swap (getVersionNumber());
  27066. set->numPrograms = vst_swap (numPrograms);
  27067. set->chunkSize = vst_swap ((long) chunk.getSize());
  27068. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27069. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27070. }
  27071. }
  27072. else
  27073. {
  27074. if (isFXB)
  27075. {
  27076. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27077. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27078. dest.setSize (len, true);
  27079. fxSet* const set = (fxSet*) dest.getData();
  27080. set->chunkMagic = vst_swap ('CcnK');
  27081. set->byteSize = 0;
  27082. set->fxMagic = vst_swap ('FxBk');
  27083. set->version = vst_swap (fxbVersionNum);
  27084. set->fxID = vst_swap (getUID());
  27085. set->fxVersion = vst_swap (getVersionNumber());
  27086. set->numPrograms = vst_swap (numPrograms);
  27087. const int oldProgram = getCurrentProgram();
  27088. MemoryBlock oldSettings;
  27089. createTempParameterStore (oldSettings);
  27090. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27091. for (int i = 0; i < numPrograms; ++i)
  27092. {
  27093. if (i != oldProgram)
  27094. {
  27095. setCurrentProgram (i);
  27096. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27097. }
  27098. }
  27099. setCurrentProgram (oldProgram);
  27100. restoreFromTempParameterStore (oldSettings);
  27101. }
  27102. else
  27103. {
  27104. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27105. dest.setSize (totalLen, true);
  27106. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27107. }
  27108. }
  27109. return true;
  27110. }
  27111. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27112. {
  27113. if (usesChunks())
  27114. {
  27115. void* data = 0;
  27116. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27117. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27118. {
  27119. mb.setSize (bytes);
  27120. mb.copyFrom (data, 0, bytes);
  27121. }
  27122. }
  27123. }
  27124. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27125. {
  27126. if (size > 0 && usesChunks())
  27127. {
  27128. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27129. if (! isPreset)
  27130. updateStoredProgramNames();
  27131. }
  27132. }
  27133. void VSTPluginInstance::timerCallback()
  27134. {
  27135. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27136. stopTimer();
  27137. }
  27138. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27139. {
  27140. const ScopedLock sl (lock);
  27141. ++insideVSTCallback;
  27142. int result = 0;
  27143. try
  27144. {
  27145. if (effect != 0)
  27146. {
  27147. #if JUCE_MAC
  27148. if (module->resFileId != 0)
  27149. UseResFile (module->resFileId);
  27150. CGrafPtr oldPort;
  27151. if (getActiveEditor() != 0)
  27152. {
  27153. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27154. GetPort (&oldPort);
  27155. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27156. SetOrigin (-pos.getX(), -pos.getY());
  27157. }
  27158. #endif
  27159. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27160. #if JUCE_MAC
  27161. if (getActiveEditor() != 0)
  27162. SetPort (oldPort);
  27163. module->resFileId = CurResFile();
  27164. #endif
  27165. --insideVSTCallback;
  27166. return result;
  27167. }
  27168. }
  27169. catch (...)
  27170. {
  27171. }
  27172. --insideVSTCallback;
  27173. return result;
  27174. }
  27175. // handles non plugin-specific callbacks..
  27176. static const int defaultVSTSampleRateValue = 16384;
  27177. static const int defaultVSTBlockSizeValue = 512;
  27178. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27179. {
  27180. (void) index;
  27181. (void) value;
  27182. (void) opt;
  27183. switch (opcode)
  27184. {
  27185. case audioMasterCanDo:
  27186. {
  27187. static const char* canDos[] = { "supplyIdle",
  27188. "sendVstEvents",
  27189. "sendVstMidiEvent",
  27190. "sendVstTimeInfo",
  27191. "receiveVstEvents",
  27192. "receiveVstMidiEvent",
  27193. "supportShell",
  27194. "shellCategory" };
  27195. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27196. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27197. return 1;
  27198. return 0;
  27199. }
  27200. case audioMasterVersion:
  27201. return 0x2400;
  27202. case audioMasterCurrentId:
  27203. return shellUIDToCreate;
  27204. case audioMasterGetNumAutomatableParameters:
  27205. return 0;
  27206. case audioMasterGetAutomationState:
  27207. return 1;
  27208. case audioMasterGetVendorVersion:
  27209. return 0x0101;
  27210. case audioMasterGetVendorString:
  27211. case audioMasterGetProductString:
  27212. {
  27213. String hostName ("Juce VST Host");
  27214. if (JUCEApplication::getInstance() != 0)
  27215. hostName = JUCEApplication::getInstance()->getApplicationName();
  27216. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27217. }
  27218. break;
  27219. case audioMasterGetSampleRate:
  27220. return (VstIntPtr) defaultVSTSampleRateValue;
  27221. case audioMasterGetBlockSize:
  27222. return (VstIntPtr) defaultVSTBlockSizeValue;
  27223. case audioMasterSetOutputSampleRate:
  27224. return 0;
  27225. default:
  27226. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27227. break;
  27228. }
  27229. return 0;
  27230. }
  27231. // handles callbacks for a specific plugin
  27232. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27233. {
  27234. switch (opcode)
  27235. {
  27236. case audioMasterAutomate:
  27237. sendParamChangeMessageToListeners (index, opt);
  27238. break;
  27239. case audioMasterProcessEvents:
  27240. handleMidiFromPlugin ((const VstEvents*) ptr);
  27241. break;
  27242. case audioMasterGetTime:
  27243. #if JUCE_MSVC
  27244. #pragma warning (push)
  27245. #pragma warning (disable: 4311)
  27246. #endif
  27247. return (VstIntPtr) &vstHostTime;
  27248. #if JUCE_MSVC
  27249. #pragma warning (pop)
  27250. #endif
  27251. break;
  27252. case audioMasterIdle:
  27253. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27254. {
  27255. ++insideVSTCallback;
  27256. #if JUCE_MAC
  27257. if (getActiveEditor() != 0)
  27258. dispatch (effEditIdle, 0, 0, 0, 0);
  27259. #endif
  27260. juce_callAnyTimersSynchronously();
  27261. handleUpdateNowIfNeeded();
  27262. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27263. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27264. --insideVSTCallback;
  27265. }
  27266. break;
  27267. case audioMasterUpdateDisplay:
  27268. triggerAsyncUpdate();
  27269. break;
  27270. case audioMasterTempoAt:
  27271. // returns (10000 * bpm)
  27272. break;
  27273. case audioMasterNeedIdle:
  27274. startTimer (50);
  27275. break;
  27276. case audioMasterSizeWindow:
  27277. if (getActiveEditor() != 0)
  27278. getActiveEditor()->setSize (index, value);
  27279. return 1;
  27280. case audioMasterGetSampleRate:
  27281. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27282. case audioMasterGetBlockSize:
  27283. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27284. case audioMasterWantMidi:
  27285. wantsMidiMessages = true;
  27286. break;
  27287. case audioMasterGetDirectory:
  27288. #if JUCE_MAC
  27289. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27290. #else
  27291. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27292. #endif
  27293. case audioMasterGetAutomationState:
  27294. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27295. break;
  27296. // none of these are handled (yet)..
  27297. case audioMasterBeginEdit:
  27298. case audioMasterEndEdit:
  27299. case audioMasterSetTime:
  27300. case audioMasterPinConnected:
  27301. case audioMasterGetParameterQuantization:
  27302. case audioMasterIOChanged:
  27303. case audioMasterGetInputLatency:
  27304. case audioMasterGetOutputLatency:
  27305. case audioMasterGetPreviousPlug:
  27306. case audioMasterGetNextPlug:
  27307. case audioMasterWillReplaceOrAccumulate:
  27308. case audioMasterGetCurrentProcessLevel:
  27309. case audioMasterOfflineStart:
  27310. case audioMasterOfflineRead:
  27311. case audioMasterOfflineWrite:
  27312. case audioMasterOfflineGetCurrentPass:
  27313. case audioMasterOfflineGetCurrentMetaPass:
  27314. case audioMasterVendorSpecific:
  27315. case audioMasterSetIcon:
  27316. case audioMasterGetLanguage:
  27317. case audioMasterOpenWindow:
  27318. case audioMasterCloseWindow:
  27319. break;
  27320. default:
  27321. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27322. }
  27323. return 0;
  27324. }
  27325. // entry point for all callbacks from the plugin
  27326. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27327. {
  27328. try
  27329. {
  27330. if (effect != 0 && effect->resvd2 != 0)
  27331. {
  27332. return ((VSTPluginInstance*)(effect->resvd2))
  27333. ->handleCallback (opcode, index, value, ptr, opt);
  27334. }
  27335. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27336. }
  27337. catch (...)
  27338. {
  27339. return 0;
  27340. }
  27341. }
  27342. const String VSTPluginInstance::getVersion() const throw()
  27343. {
  27344. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27345. String s;
  27346. if (v == 0 || v == -1)
  27347. v = getVersionNumber();
  27348. if (v != 0)
  27349. {
  27350. int versionBits[4];
  27351. int n = 0;
  27352. while (v != 0)
  27353. {
  27354. versionBits [n++] = (v & 0xff);
  27355. v >>= 8;
  27356. }
  27357. s << 'V';
  27358. while (n > 0)
  27359. {
  27360. s << versionBits [--n];
  27361. if (n > 0)
  27362. s << '.';
  27363. }
  27364. }
  27365. return s;
  27366. }
  27367. int VSTPluginInstance::getUID() const throw()
  27368. {
  27369. int uid = effect != 0 ? effect->uniqueID : 0;
  27370. if (uid == 0)
  27371. uid = module->file.hashCode();
  27372. return uid;
  27373. }
  27374. const String VSTPluginInstance::getCategory() const throw()
  27375. {
  27376. const char* result = 0;
  27377. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27378. {
  27379. case kPlugCategEffect:
  27380. result = "Effect";
  27381. break;
  27382. case kPlugCategSynth:
  27383. result = "Synth";
  27384. break;
  27385. case kPlugCategAnalysis:
  27386. result = "Anaylsis";
  27387. break;
  27388. case kPlugCategMastering:
  27389. result = "Mastering";
  27390. break;
  27391. case kPlugCategSpacializer:
  27392. result = "Spacial";
  27393. break;
  27394. case kPlugCategRoomFx:
  27395. result = "Reverb";
  27396. break;
  27397. case kPlugSurroundFx:
  27398. result = "Surround";
  27399. break;
  27400. case kPlugCategRestoration:
  27401. result = "Restoration";
  27402. break;
  27403. case kPlugCategGenerator:
  27404. result = "Tone generation";
  27405. break;
  27406. default:
  27407. break;
  27408. }
  27409. return result;
  27410. }
  27411. float VSTPluginInstance::getParameter (int index)
  27412. {
  27413. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27414. {
  27415. try
  27416. {
  27417. const ScopedLock sl (lock);
  27418. return effect->getParameter (effect, index);
  27419. }
  27420. catch (...)
  27421. {
  27422. }
  27423. }
  27424. return 0.0f;
  27425. }
  27426. void VSTPluginInstance::setParameter (int index, float newValue)
  27427. {
  27428. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27429. {
  27430. try
  27431. {
  27432. const ScopedLock sl (lock);
  27433. if (effect->getParameter (effect, index) != newValue)
  27434. effect->setParameter (effect, index, newValue);
  27435. }
  27436. catch (...)
  27437. {
  27438. }
  27439. }
  27440. }
  27441. const String VSTPluginInstance::getParameterName (int index)
  27442. {
  27443. if (effect != 0)
  27444. {
  27445. jassert (index >= 0 && index < effect->numParams);
  27446. char nm [256];
  27447. zerostruct (nm);
  27448. dispatch (effGetParamName, index, 0, nm, 0);
  27449. return String (nm).trim();
  27450. }
  27451. return String::empty;
  27452. }
  27453. const String VSTPluginInstance::getParameterLabel (int index) const
  27454. {
  27455. if (effect != 0)
  27456. {
  27457. jassert (index >= 0 && index < effect->numParams);
  27458. char nm [256];
  27459. zerostruct (nm);
  27460. dispatch (effGetParamLabel, index, 0, nm, 0);
  27461. return String (nm).trim();
  27462. }
  27463. return String::empty;
  27464. }
  27465. const String VSTPluginInstance::getParameterText (int index)
  27466. {
  27467. if (effect != 0)
  27468. {
  27469. jassert (index >= 0 && index < effect->numParams);
  27470. char nm [256];
  27471. zerostruct (nm);
  27472. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27473. return String (nm).trim();
  27474. }
  27475. return String::empty;
  27476. }
  27477. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27478. {
  27479. if (effect != 0)
  27480. {
  27481. jassert (index >= 0 && index < effect->numParams);
  27482. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27483. }
  27484. return false;
  27485. }
  27486. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27487. {
  27488. dest.setSize (64 + 4 * getNumParameters());
  27489. dest.fillWith (0);
  27490. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27491. float* const p = (float*) (((char*) dest.getData()) + 64);
  27492. for (int i = 0; i < getNumParameters(); ++i)
  27493. p[i] = getParameter(i);
  27494. }
  27495. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27496. {
  27497. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27498. float* p = (float*) (((char*) m.getData()) + 64);
  27499. for (int i = 0; i < getNumParameters(); ++i)
  27500. setParameter (i, p[i]);
  27501. }
  27502. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27503. {
  27504. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27505. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27506. }
  27507. const String VSTPluginInstance::getProgramName (int index)
  27508. {
  27509. if (index == getCurrentProgram())
  27510. {
  27511. return getCurrentProgramName();
  27512. }
  27513. else if (effect != 0)
  27514. {
  27515. char nm [256];
  27516. zerostruct (nm);
  27517. if (dispatch (effGetProgramNameIndexed,
  27518. jlimit (0, getNumPrograms(), index),
  27519. -1, nm, 0) != 0)
  27520. {
  27521. return String (nm).trim();
  27522. }
  27523. }
  27524. return programNames [index];
  27525. }
  27526. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27527. {
  27528. if (index == getCurrentProgram())
  27529. {
  27530. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27531. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27532. }
  27533. else
  27534. {
  27535. jassertfalse; // xxx not implemented!
  27536. }
  27537. }
  27538. void VSTPluginInstance::updateStoredProgramNames()
  27539. {
  27540. if (effect != 0 && getNumPrograms() > 0)
  27541. {
  27542. char nm [256];
  27543. zerostruct (nm);
  27544. // only do this if the plugin can't use indexed names..
  27545. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27546. {
  27547. const int oldProgram = getCurrentProgram();
  27548. MemoryBlock oldSettings;
  27549. createTempParameterStore (oldSettings);
  27550. for (int i = 0; i < getNumPrograms(); ++i)
  27551. {
  27552. setCurrentProgram (i);
  27553. getCurrentProgramName(); // (this updates the list)
  27554. }
  27555. setCurrentProgram (oldProgram);
  27556. restoreFromTempParameterStore (oldSettings);
  27557. }
  27558. }
  27559. }
  27560. const String VSTPluginInstance::getCurrentProgramName()
  27561. {
  27562. if (effect != 0)
  27563. {
  27564. char nm [256];
  27565. zerostruct (nm);
  27566. dispatch (effGetProgramName, 0, 0, nm, 0);
  27567. const int index = getCurrentProgram();
  27568. if (programNames[index].isEmpty())
  27569. {
  27570. while (programNames.size() < index)
  27571. programNames.add (String::empty);
  27572. programNames.set (index, String (nm).trim());
  27573. }
  27574. return String (nm).trim();
  27575. }
  27576. return String::empty;
  27577. }
  27578. const String VSTPluginInstance::getInputChannelName (const int index) const
  27579. {
  27580. if (index >= 0 && index < getNumInputChannels())
  27581. {
  27582. VstPinProperties pinProps;
  27583. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27584. return String (pinProps.label, sizeof (pinProps.label));
  27585. }
  27586. return String::empty;
  27587. }
  27588. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27589. {
  27590. if (index < 0 || index >= getNumInputChannels())
  27591. return false;
  27592. VstPinProperties pinProps;
  27593. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27594. return (pinProps.flags & kVstPinIsStereo) != 0;
  27595. return true;
  27596. }
  27597. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27598. {
  27599. if (index >= 0 && index < getNumOutputChannels())
  27600. {
  27601. VstPinProperties pinProps;
  27602. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27603. return String (pinProps.label, sizeof (pinProps.label));
  27604. }
  27605. return String::empty;
  27606. }
  27607. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27608. {
  27609. if (index < 0 || index >= getNumOutputChannels())
  27610. return false;
  27611. VstPinProperties pinProps;
  27612. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27613. return (pinProps.flags & kVstPinIsStereo) != 0;
  27614. return true;
  27615. }
  27616. void VSTPluginInstance::setPower (const bool on)
  27617. {
  27618. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27619. isPowerOn = on;
  27620. }
  27621. const int defaultMaxSizeMB = 64;
  27622. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27623. {
  27624. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27625. }
  27626. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27627. {
  27628. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27629. }
  27630. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27631. {
  27632. loadFromFXBFile (data, sizeInBytes);
  27633. }
  27634. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27635. {
  27636. loadFromFXBFile (data, sizeInBytes);
  27637. }
  27638. VSTPluginFormat::VSTPluginFormat()
  27639. {
  27640. }
  27641. VSTPluginFormat::~VSTPluginFormat()
  27642. {
  27643. }
  27644. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27645. const String& fileOrIdentifier)
  27646. {
  27647. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27648. return;
  27649. PluginDescription desc;
  27650. desc.fileOrIdentifier = fileOrIdentifier;
  27651. desc.uid = 0;
  27652. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27653. if (instance == 0)
  27654. return;
  27655. try
  27656. {
  27657. #if JUCE_MAC
  27658. if (instance->module->resFileId != 0)
  27659. UseResFile (instance->module->resFileId);
  27660. #endif
  27661. instance->fillInPluginDescription (desc);
  27662. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27663. if (category != kPlugCategShell)
  27664. {
  27665. // Normal plugin...
  27666. results.add (new PluginDescription (desc));
  27667. ++insideVSTCallback;
  27668. instance->dispatch (effOpen, 0, 0, 0, 0);
  27669. --insideVSTCallback;
  27670. }
  27671. else
  27672. {
  27673. // It's a shell plugin, so iterate all the subtypes...
  27674. char shellEffectName [64];
  27675. for (;;)
  27676. {
  27677. zerostruct (shellEffectName);
  27678. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27679. if (uid == 0)
  27680. {
  27681. break;
  27682. }
  27683. else
  27684. {
  27685. desc.uid = uid;
  27686. desc.name = shellEffectName;
  27687. bool alreadyThere = false;
  27688. for (int i = results.size(); --i >= 0;)
  27689. {
  27690. PluginDescription* const d = results.getUnchecked(i);
  27691. if (d->isDuplicateOf (desc))
  27692. {
  27693. alreadyThere = true;
  27694. break;
  27695. }
  27696. }
  27697. if (! alreadyThere)
  27698. results.add (new PluginDescription (desc));
  27699. }
  27700. }
  27701. }
  27702. }
  27703. catch (...)
  27704. {
  27705. // crashed while loading...
  27706. }
  27707. }
  27708. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27709. {
  27710. ScopedPointer <VSTPluginInstance> result;
  27711. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27712. {
  27713. File file (desc.fileOrIdentifier);
  27714. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27715. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27716. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27717. if (module != 0)
  27718. {
  27719. shellUIDToCreate = desc.uid;
  27720. result = new VSTPluginInstance (module);
  27721. if (result->effect != 0)
  27722. {
  27723. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27724. result->initialise();
  27725. }
  27726. else
  27727. {
  27728. result = 0;
  27729. }
  27730. }
  27731. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27732. }
  27733. return result.release();
  27734. }
  27735. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27736. {
  27737. const File f (fileOrIdentifier);
  27738. #if JUCE_MAC
  27739. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27740. return true;
  27741. #if JUCE_PPC
  27742. FSRef fileRef;
  27743. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27744. {
  27745. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27746. if (resFileId != -1)
  27747. {
  27748. const int numEffects = Count1Resources ('aEff');
  27749. CloseResFile (resFileId);
  27750. if (numEffects > 0)
  27751. return true;
  27752. }
  27753. }
  27754. #endif
  27755. return false;
  27756. #elif JUCE_WINDOWS
  27757. return f.existsAsFile()
  27758. && f.hasFileExtension (".dll");
  27759. #elif JUCE_LINUX
  27760. return f.existsAsFile()
  27761. && f.hasFileExtension (".so");
  27762. #endif
  27763. }
  27764. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27765. {
  27766. return fileOrIdentifier;
  27767. }
  27768. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27769. {
  27770. return File (desc.fileOrIdentifier).exists();
  27771. }
  27772. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27773. {
  27774. StringArray results;
  27775. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27776. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27777. return results;
  27778. }
  27779. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27780. {
  27781. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27782. // .component or .vst directories.
  27783. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27784. while (iter.next())
  27785. {
  27786. const File f (iter.getFile());
  27787. bool isPlugin = false;
  27788. if (fileMightContainThisPluginType (f.getFullPathName()))
  27789. {
  27790. isPlugin = true;
  27791. results.add (f.getFullPathName());
  27792. }
  27793. if (recursive && (! isPlugin) && f.isDirectory())
  27794. recursiveFileSearch (results, f, true);
  27795. }
  27796. }
  27797. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27798. {
  27799. #if JUCE_MAC
  27800. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27801. #elif JUCE_WINDOWS
  27802. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27803. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27804. #elif JUCE_LINUX
  27805. return FileSearchPath ("/usr/lib/vst");
  27806. #endif
  27807. }
  27808. END_JUCE_NAMESPACE
  27809. #endif
  27810. #undef log
  27811. #endif
  27812. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27813. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27814. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27815. BEGIN_JUCE_NAMESPACE
  27816. AudioProcessor::AudioProcessor()
  27817. : playHead (0),
  27818. activeEditor (0),
  27819. sampleRate (0),
  27820. blockSize (0),
  27821. numInputChannels (0),
  27822. numOutputChannels (0),
  27823. latencySamples (0),
  27824. suspended (false),
  27825. nonRealtime (false)
  27826. {
  27827. }
  27828. AudioProcessor::~AudioProcessor()
  27829. {
  27830. // ooh, nasty - the editor should have been deleted before the filter
  27831. // that it refers to is deleted..
  27832. jassert (activeEditor == 0);
  27833. #if JUCE_DEBUG
  27834. // This will fail if you've called beginParameterChangeGesture() for one
  27835. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27836. jassert (changingParams.countNumberOfSetBits() == 0);
  27837. #endif
  27838. }
  27839. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27840. {
  27841. playHead = newPlayHead;
  27842. }
  27843. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27844. {
  27845. const ScopedLock sl (listenerLock);
  27846. listeners.addIfNotAlreadyThere (newListener);
  27847. }
  27848. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27849. {
  27850. const ScopedLock sl (listenerLock);
  27851. listeners.removeValue (listenerToRemove);
  27852. }
  27853. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27854. const int numOuts,
  27855. const double sampleRate_,
  27856. const int blockSize_) throw()
  27857. {
  27858. numInputChannels = numIns;
  27859. numOutputChannels = numOuts;
  27860. sampleRate = sampleRate_;
  27861. blockSize = blockSize_;
  27862. }
  27863. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27864. {
  27865. nonRealtime = nonRealtime_;
  27866. }
  27867. void AudioProcessor::setLatencySamples (const int newLatency)
  27868. {
  27869. if (latencySamples != newLatency)
  27870. {
  27871. latencySamples = newLatency;
  27872. updateHostDisplay();
  27873. }
  27874. }
  27875. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27876. const float newValue)
  27877. {
  27878. setParameter (parameterIndex, newValue);
  27879. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27880. }
  27881. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27882. {
  27883. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27884. for (int i = listeners.size(); --i >= 0;)
  27885. {
  27886. AudioProcessorListener* l;
  27887. {
  27888. const ScopedLock sl (listenerLock);
  27889. l = listeners [i];
  27890. }
  27891. if (l != 0)
  27892. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27893. }
  27894. }
  27895. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27896. {
  27897. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27898. #if JUCE_DEBUG
  27899. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27900. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27901. jassert (! changingParams [parameterIndex]);
  27902. changingParams.setBit (parameterIndex);
  27903. #endif
  27904. for (int i = listeners.size(); --i >= 0;)
  27905. {
  27906. AudioProcessorListener* l;
  27907. {
  27908. const ScopedLock sl (listenerLock);
  27909. l = listeners [i];
  27910. }
  27911. if (l != 0)
  27912. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27913. }
  27914. }
  27915. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27916. {
  27917. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27918. #if JUCE_DEBUG
  27919. // This means you've called endParameterChangeGesture without having previously called
  27920. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27921. // calls matched correctly.
  27922. jassert (changingParams [parameterIndex]);
  27923. changingParams.clearBit (parameterIndex);
  27924. #endif
  27925. for (int i = listeners.size(); --i >= 0;)
  27926. {
  27927. AudioProcessorListener* l;
  27928. {
  27929. const ScopedLock sl (listenerLock);
  27930. l = listeners [i];
  27931. }
  27932. if (l != 0)
  27933. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27934. }
  27935. }
  27936. void AudioProcessor::updateHostDisplay()
  27937. {
  27938. for (int i = listeners.size(); --i >= 0;)
  27939. {
  27940. AudioProcessorListener* l;
  27941. {
  27942. const ScopedLock sl (listenerLock);
  27943. l = listeners [i];
  27944. }
  27945. if (l != 0)
  27946. l->audioProcessorChanged (this);
  27947. }
  27948. }
  27949. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27950. {
  27951. return true;
  27952. }
  27953. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27954. {
  27955. return false;
  27956. }
  27957. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27958. {
  27959. const ScopedLock sl (callbackLock);
  27960. suspended = shouldBeSuspended;
  27961. }
  27962. void AudioProcessor::reset()
  27963. {
  27964. }
  27965. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27966. {
  27967. const ScopedLock sl (callbackLock);
  27968. jassert (activeEditor == editor);
  27969. if (activeEditor == editor)
  27970. activeEditor = 0;
  27971. }
  27972. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27973. {
  27974. if (activeEditor != 0)
  27975. return activeEditor;
  27976. AudioProcessorEditor* const ed = createEditor();
  27977. if (ed != 0)
  27978. {
  27979. // you must give your editor comp a size before returning it..
  27980. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27981. const ScopedLock sl (callbackLock);
  27982. activeEditor = ed;
  27983. }
  27984. return ed;
  27985. }
  27986. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27987. {
  27988. getStateInformation (destData);
  27989. }
  27990. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27991. {
  27992. setStateInformation (data, sizeInBytes);
  27993. }
  27994. // magic number to identify memory blocks that we've stored as XML
  27995. const uint32 magicXmlNumber = 0x21324356;
  27996. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27997. JUCE_NAMESPACE::MemoryBlock& destData)
  27998. {
  27999. const String xmlString (xml.createDocument (String::empty, true, false));
  28000. const int stringLength = xmlString.getNumBytesAsUTF8();
  28001. destData.setSize (stringLength + 10);
  28002. char* const d = (char*) destData.getData();
  28003. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28004. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28005. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28006. }
  28007. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28008. const int sizeInBytes)
  28009. {
  28010. if (sizeInBytes > 8
  28011. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28012. {
  28013. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28014. if (stringLength > 0)
  28015. {
  28016. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28017. jmin ((sizeInBytes - 8), stringLength)));
  28018. return doc.getDocumentElement();
  28019. }
  28020. }
  28021. return 0;
  28022. }
  28023. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28024. {
  28025. }
  28026. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28027. {
  28028. }
  28029. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28030. {
  28031. return timeInSeconds == other.timeInSeconds
  28032. && ppqPosition == other.ppqPosition
  28033. && editOriginTime == other.editOriginTime
  28034. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28035. && frameRate == other.frameRate
  28036. && isPlaying == other.isPlaying
  28037. && isRecording == other.isRecording
  28038. && bpm == other.bpm
  28039. && timeSigNumerator == other.timeSigNumerator
  28040. && timeSigDenominator == other.timeSigDenominator;
  28041. }
  28042. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28043. {
  28044. return ! operator== (other);
  28045. }
  28046. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28047. {
  28048. zerostruct (*this);
  28049. timeSigNumerator = 4;
  28050. timeSigDenominator = 4;
  28051. bpm = 120;
  28052. }
  28053. END_JUCE_NAMESPACE
  28054. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28055. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28056. BEGIN_JUCE_NAMESPACE
  28057. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28058. : owner (owner_)
  28059. {
  28060. // the filter must be valid..
  28061. jassert (owner != 0);
  28062. }
  28063. AudioProcessorEditor::~AudioProcessorEditor()
  28064. {
  28065. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28066. // filter for some reason..
  28067. jassert (owner->getActiveEditor() != this);
  28068. }
  28069. END_JUCE_NAMESPACE
  28070. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28071. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28072. BEGIN_JUCE_NAMESPACE
  28073. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28074. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28075. : id (id_),
  28076. processor (processor_),
  28077. isPrepared (false)
  28078. {
  28079. jassert (processor_ != 0);
  28080. }
  28081. AudioProcessorGraph::Node::~Node()
  28082. {
  28083. delete processor;
  28084. }
  28085. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28086. AudioProcessorGraph* const graph)
  28087. {
  28088. if (! isPrepared)
  28089. {
  28090. isPrepared = true;
  28091. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28092. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28093. if (ioProc != 0)
  28094. ioProc->setParentGraph (graph);
  28095. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28096. processor->getNumOutputChannels(),
  28097. sampleRate, blockSize);
  28098. processor->prepareToPlay (sampleRate, blockSize);
  28099. }
  28100. }
  28101. void AudioProcessorGraph::Node::unprepare()
  28102. {
  28103. if (isPrepared)
  28104. {
  28105. isPrepared = false;
  28106. processor->releaseResources();
  28107. }
  28108. }
  28109. AudioProcessorGraph::AudioProcessorGraph()
  28110. : lastNodeId (0),
  28111. renderingBuffers (1, 1),
  28112. currentAudioOutputBuffer (1, 1)
  28113. {
  28114. }
  28115. AudioProcessorGraph::~AudioProcessorGraph()
  28116. {
  28117. clearRenderingSequence();
  28118. clear();
  28119. }
  28120. const String AudioProcessorGraph::getName() const
  28121. {
  28122. return "Audio Graph";
  28123. }
  28124. void AudioProcessorGraph::clear()
  28125. {
  28126. nodes.clear();
  28127. connections.clear();
  28128. triggerAsyncUpdate();
  28129. }
  28130. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28131. {
  28132. for (int i = nodes.size(); --i >= 0;)
  28133. if (nodes.getUnchecked(i)->id == nodeId)
  28134. return nodes.getUnchecked(i);
  28135. return 0;
  28136. }
  28137. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28138. uint32 nodeId)
  28139. {
  28140. if (newProcessor == 0)
  28141. {
  28142. jassertfalse;
  28143. return 0;
  28144. }
  28145. if (nodeId == 0)
  28146. {
  28147. nodeId = ++lastNodeId;
  28148. }
  28149. else
  28150. {
  28151. // you can't add a node with an id that already exists in the graph..
  28152. jassert (getNodeForId (nodeId) == 0);
  28153. removeNode (nodeId);
  28154. }
  28155. lastNodeId = nodeId;
  28156. Node* const n = new Node (nodeId, newProcessor);
  28157. nodes.add (n);
  28158. triggerAsyncUpdate();
  28159. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28160. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28161. if (ioProc != 0)
  28162. ioProc->setParentGraph (this);
  28163. return n;
  28164. }
  28165. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28166. {
  28167. disconnectNode (nodeId);
  28168. for (int i = nodes.size(); --i >= 0;)
  28169. {
  28170. if (nodes.getUnchecked(i)->id == nodeId)
  28171. {
  28172. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28173. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28174. if (ioProc != 0)
  28175. ioProc->setParentGraph (0);
  28176. nodes.remove (i);
  28177. triggerAsyncUpdate();
  28178. return true;
  28179. }
  28180. }
  28181. return false;
  28182. }
  28183. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28184. const int sourceChannelIndex,
  28185. const uint32 destNodeId,
  28186. const int destChannelIndex) const
  28187. {
  28188. for (int i = connections.size(); --i >= 0;)
  28189. {
  28190. const Connection* const c = connections.getUnchecked(i);
  28191. if (c->sourceNodeId == sourceNodeId
  28192. && c->destNodeId == destNodeId
  28193. && c->sourceChannelIndex == sourceChannelIndex
  28194. && c->destChannelIndex == destChannelIndex)
  28195. {
  28196. return c;
  28197. }
  28198. }
  28199. return 0;
  28200. }
  28201. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28202. const uint32 possibleDestNodeId) const
  28203. {
  28204. for (int i = connections.size(); --i >= 0;)
  28205. {
  28206. const Connection* const c = connections.getUnchecked(i);
  28207. if (c->sourceNodeId == possibleSourceNodeId
  28208. && c->destNodeId == possibleDestNodeId)
  28209. {
  28210. return true;
  28211. }
  28212. }
  28213. return false;
  28214. }
  28215. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28216. const int sourceChannelIndex,
  28217. const uint32 destNodeId,
  28218. const int destChannelIndex) const
  28219. {
  28220. if (sourceChannelIndex < 0
  28221. || destChannelIndex < 0
  28222. || sourceNodeId == destNodeId
  28223. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28224. return false;
  28225. const Node* const source = getNodeForId (sourceNodeId);
  28226. if (source == 0
  28227. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28228. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28229. return false;
  28230. const Node* const dest = getNodeForId (destNodeId);
  28231. if (dest == 0
  28232. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28233. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28234. return false;
  28235. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28236. destNodeId, destChannelIndex) == 0;
  28237. }
  28238. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28239. const int sourceChannelIndex,
  28240. const uint32 destNodeId,
  28241. const int destChannelIndex)
  28242. {
  28243. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28244. return false;
  28245. Connection* const c = new Connection();
  28246. c->sourceNodeId = sourceNodeId;
  28247. c->sourceChannelIndex = sourceChannelIndex;
  28248. c->destNodeId = destNodeId;
  28249. c->destChannelIndex = destChannelIndex;
  28250. connections.add (c);
  28251. triggerAsyncUpdate();
  28252. return true;
  28253. }
  28254. void AudioProcessorGraph::removeConnection (const int index)
  28255. {
  28256. connections.remove (index);
  28257. triggerAsyncUpdate();
  28258. }
  28259. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28260. const uint32 destNodeId, const int destChannelIndex)
  28261. {
  28262. bool doneAnything = false;
  28263. for (int i = connections.size(); --i >= 0;)
  28264. {
  28265. const Connection* const c = connections.getUnchecked(i);
  28266. if (c->sourceNodeId == sourceNodeId
  28267. && c->destNodeId == destNodeId
  28268. && c->sourceChannelIndex == sourceChannelIndex
  28269. && c->destChannelIndex == destChannelIndex)
  28270. {
  28271. removeConnection (i);
  28272. doneAnything = true;
  28273. triggerAsyncUpdate();
  28274. }
  28275. }
  28276. return doneAnything;
  28277. }
  28278. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28279. {
  28280. bool doneAnything = false;
  28281. for (int i = connections.size(); --i >= 0;)
  28282. {
  28283. const Connection* const c = connections.getUnchecked(i);
  28284. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28285. {
  28286. removeConnection (i);
  28287. doneAnything = true;
  28288. triggerAsyncUpdate();
  28289. }
  28290. }
  28291. return doneAnything;
  28292. }
  28293. bool AudioProcessorGraph::removeIllegalConnections()
  28294. {
  28295. bool doneAnything = false;
  28296. for (int i = connections.size(); --i >= 0;)
  28297. {
  28298. const Connection* const c = connections.getUnchecked(i);
  28299. const Node* const source = getNodeForId (c->sourceNodeId);
  28300. const Node* const dest = getNodeForId (c->destNodeId);
  28301. if (source == 0 || dest == 0
  28302. || (c->sourceChannelIndex != midiChannelIndex
  28303. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28304. || (c->sourceChannelIndex == midiChannelIndex
  28305. && ! source->processor->producesMidi())
  28306. || (c->destChannelIndex != midiChannelIndex
  28307. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28308. || (c->destChannelIndex == midiChannelIndex
  28309. && ! dest->processor->acceptsMidi()))
  28310. {
  28311. removeConnection (i);
  28312. doneAnything = true;
  28313. triggerAsyncUpdate();
  28314. }
  28315. }
  28316. return doneAnything;
  28317. }
  28318. namespace GraphRenderingOps
  28319. {
  28320. class AudioGraphRenderingOp
  28321. {
  28322. public:
  28323. AudioGraphRenderingOp() {}
  28324. virtual ~AudioGraphRenderingOp() {}
  28325. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28326. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28327. const int numSamples) = 0;
  28328. juce_UseDebuggingNewOperator
  28329. };
  28330. class ClearChannelOp : public AudioGraphRenderingOp
  28331. {
  28332. public:
  28333. ClearChannelOp (const int channelNum_)
  28334. : channelNum (channelNum_)
  28335. {}
  28336. ~ClearChannelOp() {}
  28337. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28338. {
  28339. sharedBufferChans.clear (channelNum, 0, numSamples);
  28340. }
  28341. private:
  28342. const int channelNum;
  28343. ClearChannelOp (const ClearChannelOp&);
  28344. ClearChannelOp& operator= (const ClearChannelOp&);
  28345. };
  28346. class CopyChannelOp : public AudioGraphRenderingOp
  28347. {
  28348. public:
  28349. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28350. : srcChannelNum (srcChannelNum_),
  28351. dstChannelNum (dstChannelNum_)
  28352. {}
  28353. ~CopyChannelOp() {}
  28354. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28355. {
  28356. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28357. }
  28358. private:
  28359. const int srcChannelNum, dstChannelNum;
  28360. CopyChannelOp (const CopyChannelOp&);
  28361. CopyChannelOp& operator= (const CopyChannelOp&);
  28362. };
  28363. class AddChannelOp : public AudioGraphRenderingOp
  28364. {
  28365. public:
  28366. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28367. : srcChannelNum (srcChannelNum_),
  28368. dstChannelNum (dstChannelNum_)
  28369. {}
  28370. ~AddChannelOp() {}
  28371. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28372. {
  28373. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28374. }
  28375. private:
  28376. const int srcChannelNum, dstChannelNum;
  28377. AddChannelOp (const AddChannelOp&);
  28378. AddChannelOp& operator= (const AddChannelOp&);
  28379. };
  28380. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28381. {
  28382. public:
  28383. ClearMidiBufferOp (const int bufferNum_)
  28384. : bufferNum (bufferNum_)
  28385. {}
  28386. ~ClearMidiBufferOp() {}
  28387. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28388. {
  28389. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28390. }
  28391. private:
  28392. const int bufferNum;
  28393. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28394. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28395. };
  28396. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28397. {
  28398. public:
  28399. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28400. : srcBufferNum (srcBufferNum_),
  28401. dstBufferNum (dstBufferNum_)
  28402. {}
  28403. ~CopyMidiBufferOp() {}
  28404. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28405. {
  28406. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28407. }
  28408. private:
  28409. const int srcBufferNum, dstBufferNum;
  28410. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28411. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28412. };
  28413. class AddMidiBufferOp : public AudioGraphRenderingOp
  28414. {
  28415. public:
  28416. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28417. : srcBufferNum (srcBufferNum_),
  28418. dstBufferNum (dstBufferNum_)
  28419. {}
  28420. ~AddMidiBufferOp() {}
  28421. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28422. {
  28423. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28424. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28425. }
  28426. private:
  28427. const int srcBufferNum, dstBufferNum;
  28428. AddMidiBufferOp (const AddMidiBufferOp&);
  28429. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28430. };
  28431. class ProcessBufferOp : public AudioGraphRenderingOp
  28432. {
  28433. public:
  28434. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28435. const Array <int>& audioChannelsToUse_,
  28436. const int totalChans_,
  28437. const int midiBufferToUse_)
  28438. : node (node_),
  28439. processor (node_->processor),
  28440. audioChannelsToUse (audioChannelsToUse_),
  28441. totalChans (jmax (1, totalChans_)),
  28442. midiBufferToUse (midiBufferToUse_)
  28443. {
  28444. channels.calloc (totalChans);
  28445. while (audioChannelsToUse.size() < totalChans)
  28446. audioChannelsToUse.add (0);
  28447. }
  28448. ~ProcessBufferOp()
  28449. {
  28450. }
  28451. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28452. {
  28453. for (int i = totalChans; --i >= 0;)
  28454. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28455. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28456. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28457. }
  28458. const AudioProcessorGraph::Node::Ptr node;
  28459. AudioProcessor* const processor;
  28460. private:
  28461. Array <int> audioChannelsToUse;
  28462. HeapBlock <float*> channels;
  28463. int totalChans;
  28464. int midiBufferToUse;
  28465. ProcessBufferOp (const ProcessBufferOp&);
  28466. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28467. };
  28468. /** Used to calculate the correct sequence of rendering ops needed, based on
  28469. the best re-use of shared buffers at each stage.
  28470. */
  28471. class RenderingOpSequenceCalculator
  28472. {
  28473. public:
  28474. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28475. const Array<void*>& orderedNodes_,
  28476. Array<void*>& renderingOps)
  28477. : graph (graph_),
  28478. orderedNodes (orderedNodes_)
  28479. {
  28480. nodeIds.add (-2); // first buffer is read-only zeros
  28481. channels.add (0);
  28482. midiNodeIds.add (-2);
  28483. for (int i = 0; i < orderedNodes.size(); ++i)
  28484. {
  28485. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28486. renderingOps, i);
  28487. markAnyUnusedBuffersAsFree (i);
  28488. }
  28489. }
  28490. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28491. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28492. juce_UseDebuggingNewOperator
  28493. private:
  28494. AudioProcessorGraph& graph;
  28495. const Array<void*>& orderedNodes;
  28496. Array <int> nodeIds, channels, midiNodeIds;
  28497. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28498. Array<void*>& renderingOps,
  28499. const int ourRenderingIndex)
  28500. {
  28501. const int numIns = node->processor->getNumInputChannels();
  28502. const int numOuts = node->processor->getNumOutputChannels();
  28503. const int totalChans = jmax (numIns, numOuts);
  28504. Array <int> audioChannelsToUse;
  28505. int midiBufferToUse = -1;
  28506. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28507. {
  28508. // get a list of all the inputs to this node
  28509. Array <int> sourceNodes, sourceOutputChans;
  28510. for (int i = graph.getNumConnections(); --i >= 0;)
  28511. {
  28512. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28513. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28514. {
  28515. sourceNodes.add (c->sourceNodeId);
  28516. sourceOutputChans.add (c->sourceChannelIndex);
  28517. }
  28518. }
  28519. int bufIndex = -1;
  28520. if (sourceNodes.size() == 0)
  28521. {
  28522. // unconnected input channel
  28523. if (inputChan >= numOuts)
  28524. {
  28525. bufIndex = getReadOnlyEmptyBuffer();
  28526. jassert (bufIndex >= 0);
  28527. }
  28528. else
  28529. {
  28530. bufIndex = getFreeBuffer (false);
  28531. renderingOps.add (new ClearChannelOp (bufIndex));
  28532. }
  28533. }
  28534. else if (sourceNodes.size() == 1)
  28535. {
  28536. // channel with a straightforward single input..
  28537. const int srcNode = sourceNodes.getUnchecked(0);
  28538. const int srcChan = sourceOutputChans.getUnchecked(0);
  28539. bufIndex = getBufferContaining (srcNode, srcChan);
  28540. if (bufIndex < 0)
  28541. {
  28542. // if not found, this is probably a feedback loop
  28543. bufIndex = getReadOnlyEmptyBuffer();
  28544. jassert (bufIndex >= 0);
  28545. }
  28546. if (inputChan < numOuts
  28547. && isBufferNeededLater (ourRenderingIndex,
  28548. inputChan,
  28549. srcNode, srcChan))
  28550. {
  28551. // can't mess up this channel because it's needed later by another node, so we
  28552. // need to use a copy of it..
  28553. const int newFreeBuffer = getFreeBuffer (false);
  28554. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28555. bufIndex = newFreeBuffer;
  28556. }
  28557. }
  28558. else
  28559. {
  28560. // channel with a mix of several inputs..
  28561. // try to find a re-usable channel from our inputs..
  28562. int reusableInputIndex = -1;
  28563. for (int i = 0; i < sourceNodes.size(); ++i)
  28564. {
  28565. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28566. sourceOutputChans.getUnchecked(i));
  28567. if (sourceBufIndex >= 0
  28568. && ! isBufferNeededLater (ourRenderingIndex,
  28569. inputChan,
  28570. sourceNodes.getUnchecked(i),
  28571. sourceOutputChans.getUnchecked(i)))
  28572. {
  28573. // we've found one of our input chans that can be re-used..
  28574. reusableInputIndex = i;
  28575. bufIndex = sourceBufIndex;
  28576. break;
  28577. }
  28578. }
  28579. if (reusableInputIndex < 0)
  28580. {
  28581. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28582. bufIndex = getFreeBuffer (false);
  28583. jassert (bufIndex != 0);
  28584. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28585. sourceOutputChans.getUnchecked (0));
  28586. if (srcIndex < 0)
  28587. {
  28588. // if not found, this is probably a feedback loop
  28589. renderingOps.add (new ClearChannelOp (bufIndex));
  28590. }
  28591. else
  28592. {
  28593. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28594. }
  28595. reusableInputIndex = 0;
  28596. }
  28597. for (int j = 0; j < sourceNodes.size(); ++j)
  28598. {
  28599. if (j != reusableInputIndex)
  28600. {
  28601. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28602. sourceOutputChans.getUnchecked(j));
  28603. if (srcIndex >= 0)
  28604. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28605. }
  28606. }
  28607. }
  28608. jassert (bufIndex >= 0);
  28609. audioChannelsToUse.add (bufIndex);
  28610. if (inputChan < numOuts)
  28611. markBufferAsContaining (bufIndex, node->id, inputChan);
  28612. }
  28613. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28614. {
  28615. const int bufIndex = getFreeBuffer (false);
  28616. jassert (bufIndex != 0);
  28617. audioChannelsToUse.add (bufIndex);
  28618. markBufferAsContaining (bufIndex, node->id, outputChan);
  28619. }
  28620. // Now the same thing for midi..
  28621. Array <int> midiSourceNodes;
  28622. for (int i = graph.getNumConnections(); --i >= 0;)
  28623. {
  28624. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28625. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28626. midiSourceNodes.add (c->sourceNodeId);
  28627. }
  28628. if (midiSourceNodes.size() == 0)
  28629. {
  28630. // No midi inputs..
  28631. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28632. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28633. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28634. }
  28635. else if (midiSourceNodes.size() == 1)
  28636. {
  28637. // One midi input..
  28638. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28639. AudioProcessorGraph::midiChannelIndex);
  28640. if (midiBufferToUse >= 0)
  28641. {
  28642. if (isBufferNeededLater (ourRenderingIndex,
  28643. AudioProcessorGraph::midiChannelIndex,
  28644. midiSourceNodes.getUnchecked(0),
  28645. AudioProcessorGraph::midiChannelIndex))
  28646. {
  28647. // can't mess up this channel because it's needed later by another node, so we
  28648. // need to use a copy of it..
  28649. const int newFreeBuffer = getFreeBuffer (true);
  28650. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28651. midiBufferToUse = newFreeBuffer;
  28652. }
  28653. }
  28654. else
  28655. {
  28656. // probably a feedback loop, so just use an empty one..
  28657. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28658. }
  28659. }
  28660. else
  28661. {
  28662. // More than one midi input being mixed..
  28663. int reusableInputIndex = -1;
  28664. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28665. {
  28666. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28667. AudioProcessorGraph::midiChannelIndex);
  28668. if (sourceBufIndex >= 0
  28669. && ! isBufferNeededLater (ourRenderingIndex,
  28670. AudioProcessorGraph::midiChannelIndex,
  28671. midiSourceNodes.getUnchecked(i),
  28672. AudioProcessorGraph::midiChannelIndex))
  28673. {
  28674. // we've found one of our input buffers that can be re-used..
  28675. reusableInputIndex = i;
  28676. midiBufferToUse = sourceBufIndex;
  28677. break;
  28678. }
  28679. }
  28680. if (reusableInputIndex < 0)
  28681. {
  28682. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28683. midiBufferToUse = getFreeBuffer (true);
  28684. jassert (midiBufferToUse >= 0);
  28685. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28686. AudioProcessorGraph::midiChannelIndex);
  28687. if (srcIndex >= 0)
  28688. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28689. else
  28690. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28691. reusableInputIndex = 0;
  28692. }
  28693. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28694. {
  28695. if (j != reusableInputIndex)
  28696. {
  28697. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28698. AudioProcessorGraph::midiChannelIndex);
  28699. if (srcIndex >= 0)
  28700. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28701. }
  28702. }
  28703. }
  28704. if (node->processor->producesMidi())
  28705. markBufferAsContaining (midiBufferToUse, node->id,
  28706. AudioProcessorGraph::midiChannelIndex);
  28707. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28708. totalChans, midiBufferToUse));
  28709. }
  28710. int getFreeBuffer (const bool forMidi)
  28711. {
  28712. if (forMidi)
  28713. {
  28714. for (int i = 1; i < midiNodeIds.size(); ++i)
  28715. if (midiNodeIds.getUnchecked(i) < 0)
  28716. return i;
  28717. midiNodeIds.add (-1);
  28718. return midiNodeIds.size() - 1;
  28719. }
  28720. else
  28721. {
  28722. for (int i = 1; i < nodeIds.size(); ++i)
  28723. if (nodeIds.getUnchecked(i) < 0)
  28724. return i;
  28725. nodeIds.add (-1);
  28726. channels.add (0);
  28727. return nodeIds.size() - 1;
  28728. }
  28729. }
  28730. int getReadOnlyEmptyBuffer() const
  28731. {
  28732. return 0;
  28733. }
  28734. int getBufferContaining (const int nodeId, const int outputChannel) const
  28735. {
  28736. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28737. {
  28738. for (int i = midiNodeIds.size(); --i >= 0;)
  28739. if (midiNodeIds.getUnchecked(i) == nodeId)
  28740. return i;
  28741. }
  28742. else
  28743. {
  28744. for (int i = nodeIds.size(); --i >= 0;)
  28745. if (nodeIds.getUnchecked(i) == nodeId
  28746. && channels.getUnchecked(i) == outputChannel)
  28747. return i;
  28748. }
  28749. return -1;
  28750. }
  28751. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28752. {
  28753. int i;
  28754. for (i = 0; i < nodeIds.size(); ++i)
  28755. {
  28756. if (nodeIds.getUnchecked(i) >= 0
  28757. && ! isBufferNeededLater (stepIndex, -1,
  28758. nodeIds.getUnchecked(i),
  28759. channels.getUnchecked(i)))
  28760. {
  28761. nodeIds.set (i, -1);
  28762. }
  28763. }
  28764. for (i = 0; i < midiNodeIds.size(); ++i)
  28765. {
  28766. if (midiNodeIds.getUnchecked(i) >= 0
  28767. && ! isBufferNeededLater (stepIndex, -1,
  28768. midiNodeIds.getUnchecked(i),
  28769. AudioProcessorGraph::midiChannelIndex))
  28770. {
  28771. midiNodeIds.set (i, -1);
  28772. }
  28773. }
  28774. }
  28775. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28776. int inputChannelOfIndexToIgnore,
  28777. const int nodeId,
  28778. const int outputChanIndex) const
  28779. {
  28780. while (stepIndexToSearchFrom < orderedNodes.size())
  28781. {
  28782. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28783. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28784. {
  28785. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28786. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28787. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28788. return true;
  28789. }
  28790. else
  28791. {
  28792. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28793. if (i != inputChannelOfIndexToIgnore
  28794. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28795. node->id, i) != 0)
  28796. return true;
  28797. }
  28798. inputChannelOfIndexToIgnore = -1;
  28799. ++stepIndexToSearchFrom;
  28800. }
  28801. return false;
  28802. }
  28803. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28804. {
  28805. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28806. {
  28807. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28808. midiNodeIds.set (bufferNum, nodeId);
  28809. }
  28810. else
  28811. {
  28812. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28813. nodeIds.set (bufferNum, nodeId);
  28814. channels.set (bufferNum, outputIndex);
  28815. }
  28816. }
  28817. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28818. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28819. };
  28820. }
  28821. void AudioProcessorGraph::clearRenderingSequence()
  28822. {
  28823. const ScopedLock sl (renderLock);
  28824. for (int i = renderingOps.size(); --i >= 0;)
  28825. {
  28826. GraphRenderingOps::AudioGraphRenderingOp* const r
  28827. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28828. renderingOps.remove (i);
  28829. delete r;
  28830. }
  28831. }
  28832. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28833. const uint32 possibleDestinationId,
  28834. const int recursionCheck) const
  28835. {
  28836. if (recursionCheck > 0)
  28837. {
  28838. for (int i = connections.size(); --i >= 0;)
  28839. {
  28840. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28841. if (c->destNodeId == possibleDestinationId
  28842. && (c->sourceNodeId == possibleInputId
  28843. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28844. return true;
  28845. }
  28846. }
  28847. return false;
  28848. }
  28849. void AudioProcessorGraph::buildRenderingSequence()
  28850. {
  28851. Array<void*> newRenderingOps;
  28852. int numRenderingBuffersNeeded = 2;
  28853. int numMidiBuffersNeeded = 1;
  28854. {
  28855. MessageManagerLock mml;
  28856. Array<void*> orderedNodes;
  28857. int i;
  28858. for (i = 0; i < nodes.size(); ++i)
  28859. {
  28860. Node* const node = nodes.getUnchecked(i);
  28861. node->prepare (getSampleRate(), getBlockSize(), this);
  28862. int j = 0;
  28863. for (; j < orderedNodes.size(); ++j)
  28864. if (isAnInputTo (node->id,
  28865. ((Node*) orderedNodes.getUnchecked (j))->id,
  28866. nodes.size() + 1))
  28867. break;
  28868. orderedNodes.insert (j, node);
  28869. }
  28870. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28871. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28872. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28873. }
  28874. Array<void*> oldRenderingOps (renderingOps);
  28875. {
  28876. // swap over to the new rendering sequence..
  28877. const ScopedLock sl (renderLock);
  28878. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28879. renderingBuffers.clear();
  28880. for (int i = midiBuffers.size(); --i >= 0;)
  28881. midiBuffers.getUnchecked(i)->clear();
  28882. while (midiBuffers.size() < numMidiBuffersNeeded)
  28883. midiBuffers.add (new MidiBuffer());
  28884. renderingOps = newRenderingOps;
  28885. }
  28886. for (int i = oldRenderingOps.size(); --i >= 0;)
  28887. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28888. }
  28889. void AudioProcessorGraph::handleAsyncUpdate()
  28890. {
  28891. buildRenderingSequence();
  28892. }
  28893. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28894. {
  28895. currentAudioInputBuffer = 0;
  28896. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28897. currentMidiInputBuffer = 0;
  28898. currentMidiOutputBuffer.clear();
  28899. clearRenderingSequence();
  28900. buildRenderingSequence();
  28901. }
  28902. void AudioProcessorGraph::releaseResources()
  28903. {
  28904. for (int i = 0; i < nodes.size(); ++i)
  28905. nodes.getUnchecked(i)->unprepare();
  28906. renderingBuffers.setSize (1, 1);
  28907. midiBuffers.clear();
  28908. currentAudioInputBuffer = 0;
  28909. currentAudioOutputBuffer.setSize (1, 1);
  28910. currentMidiInputBuffer = 0;
  28911. currentMidiOutputBuffer.clear();
  28912. }
  28913. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28914. {
  28915. const int numSamples = buffer.getNumSamples();
  28916. const ScopedLock sl (renderLock);
  28917. currentAudioInputBuffer = &buffer;
  28918. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28919. currentAudioOutputBuffer.clear();
  28920. currentMidiInputBuffer = &midiMessages;
  28921. currentMidiOutputBuffer.clear();
  28922. int i;
  28923. for (i = 0; i < renderingOps.size(); ++i)
  28924. {
  28925. GraphRenderingOps::AudioGraphRenderingOp* const op
  28926. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28927. op->perform (renderingBuffers, midiBuffers, numSamples);
  28928. }
  28929. for (i = 0; i < buffer.getNumChannels(); ++i)
  28930. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28931. midiMessages.clear();
  28932. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28933. }
  28934. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28935. {
  28936. return "Input " + String (channelIndex + 1);
  28937. }
  28938. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28939. {
  28940. return "Output " + String (channelIndex + 1);
  28941. }
  28942. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28943. {
  28944. return true;
  28945. }
  28946. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28947. {
  28948. return true;
  28949. }
  28950. bool AudioProcessorGraph::acceptsMidi() const
  28951. {
  28952. return true;
  28953. }
  28954. bool AudioProcessorGraph::producesMidi() const
  28955. {
  28956. return true;
  28957. }
  28958. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28959. {
  28960. }
  28961. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28962. {
  28963. }
  28964. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28965. : type (type_),
  28966. graph (0)
  28967. {
  28968. }
  28969. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28970. {
  28971. }
  28972. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28973. {
  28974. switch (type)
  28975. {
  28976. case audioOutputNode:
  28977. return "Audio Output";
  28978. case audioInputNode:
  28979. return "Audio Input";
  28980. case midiOutputNode:
  28981. return "Midi Output";
  28982. case midiInputNode:
  28983. return "Midi Input";
  28984. default:
  28985. break;
  28986. }
  28987. return String::empty;
  28988. }
  28989. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28990. {
  28991. d.name = getName();
  28992. d.uid = d.name.hashCode();
  28993. d.category = "I/O devices";
  28994. d.pluginFormatName = "Internal";
  28995. d.manufacturerName = "Raw Material Software";
  28996. d.version = "1.0";
  28997. d.isInstrument = false;
  28998. d.numInputChannels = getNumInputChannels();
  28999. if (type == audioOutputNode && graph != 0)
  29000. d.numInputChannels = graph->getNumInputChannels();
  29001. d.numOutputChannels = getNumOutputChannels();
  29002. if (type == audioInputNode && graph != 0)
  29003. d.numOutputChannels = graph->getNumOutputChannels();
  29004. }
  29005. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29006. {
  29007. jassert (graph != 0);
  29008. }
  29009. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29010. {
  29011. }
  29012. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29013. MidiBuffer& midiMessages)
  29014. {
  29015. jassert (graph != 0);
  29016. switch (type)
  29017. {
  29018. case audioOutputNode:
  29019. {
  29020. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29021. buffer.getNumChannels()); --i >= 0;)
  29022. {
  29023. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29024. }
  29025. break;
  29026. }
  29027. case audioInputNode:
  29028. {
  29029. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29030. buffer.getNumChannels()); --i >= 0;)
  29031. {
  29032. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29033. }
  29034. break;
  29035. }
  29036. case midiOutputNode:
  29037. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29038. break;
  29039. case midiInputNode:
  29040. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29041. break;
  29042. default:
  29043. break;
  29044. }
  29045. }
  29046. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29047. {
  29048. return type == midiOutputNode;
  29049. }
  29050. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29051. {
  29052. return type == midiInputNode;
  29053. }
  29054. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29055. {
  29056. switch (type)
  29057. {
  29058. case audioOutputNode:
  29059. return "Output " + String (channelIndex + 1);
  29060. case midiOutputNode:
  29061. return "Midi Output";
  29062. default:
  29063. break;
  29064. }
  29065. return String::empty;
  29066. }
  29067. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29068. {
  29069. switch (type)
  29070. {
  29071. case audioInputNode:
  29072. return "Input " + String (channelIndex + 1);
  29073. case midiInputNode:
  29074. return "Midi Input";
  29075. default:
  29076. break;
  29077. }
  29078. return String::empty;
  29079. }
  29080. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29081. {
  29082. return type == audioInputNode || type == audioOutputNode;
  29083. }
  29084. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29085. {
  29086. return isInputChannelStereoPair (index);
  29087. }
  29088. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29089. {
  29090. return type == audioInputNode || type == midiInputNode;
  29091. }
  29092. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29093. {
  29094. return type == audioOutputNode || type == midiOutputNode;
  29095. }
  29096. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29097. {
  29098. return 0;
  29099. }
  29100. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29101. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29102. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29103. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29104. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29105. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29106. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29107. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29108. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29109. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29110. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29111. {
  29112. }
  29113. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29114. {
  29115. }
  29116. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29117. {
  29118. graph = newGraph;
  29119. if (graph != 0)
  29120. {
  29121. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29122. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29123. getSampleRate(),
  29124. getBlockSize());
  29125. updateHostDisplay();
  29126. }
  29127. }
  29128. END_JUCE_NAMESPACE
  29129. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29130. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29131. BEGIN_JUCE_NAMESPACE
  29132. AudioProcessorPlayer::AudioProcessorPlayer()
  29133. : processor (0),
  29134. sampleRate (0),
  29135. blockSize (0),
  29136. isPrepared (false),
  29137. numInputChans (0),
  29138. numOutputChans (0),
  29139. tempBuffer (1, 1)
  29140. {
  29141. }
  29142. AudioProcessorPlayer::~AudioProcessorPlayer()
  29143. {
  29144. setProcessor (0);
  29145. }
  29146. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29147. {
  29148. if (processor != processorToPlay)
  29149. {
  29150. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29151. {
  29152. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29153. sampleRate, blockSize);
  29154. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29155. }
  29156. AudioProcessor* oldOne;
  29157. {
  29158. const ScopedLock sl (lock);
  29159. oldOne = isPrepared ? processor : 0;
  29160. processor = processorToPlay;
  29161. isPrepared = true;
  29162. }
  29163. if (oldOne != 0)
  29164. oldOne->releaseResources();
  29165. }
  29166. }
  29167. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29168. const int numInputChannels,
  29169. float** const outputChannelData,
  29170. const int numOutputChannels,
  29171. const int numSamples)
  29172. {
  29173. // these should have been prepared by audioDeviceAboutToStart()...
  29174. jassert (sampleRate > 0 && blockSize > 0);
  29175. incomingMidi.clear();
  29176. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29177. int i, totalNumChans = 0;
  29178. if (numInputChannels > numOutputChannels)
  29179. {
  29180. // if there aren't enough output channels for the number of
  29181. // inputs, we need to create some temporary extra ones (can't
  29182. // use the input data in case it gets written to)
  29183. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29184. false, false, true);
  29185. for (i = 0; i < numOutputChannels; ++i)
  29186. {
  29187. channels[totalNumChans] = outputChannelData[i];
  29188. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29189. ++totalNumChans;
  29190. }
  29191. for (i = numOutputChannels; i < numInputChannels; ++i)
  29192. {
  29193. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29194. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29195. ++totalNumChans;
  29196. }
  29197. }
  29198. else
  29199. {
  29200. for (i = 0; i < numInputChannels; ++i)
  29201. {
  29202. channels[totalNumChans] = outputChannelData[i];
  29203. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29204. ++totalNumChans;
  29205. }
  29206. for (i = numInputChannels; i < numOutputChannels; ++i)
  29207. {
  29208. channels[totalNumChans] = outputChannelData[i];
  29209. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29210. ++totalNumChans;
  29211. }
  29212. }
  29213. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29214. const ScopedLock sl (lock);
  29215. if (processor != 0)
  29216. {
  29217. const ScopedLock sl (processor->getCallbackLock());
  29218. if (processor->isSuspended())
  29219. {
  29220. for (i = 0; i < numOutputChannels; ++i)
  29221. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29222. }
  29223. else
  29224. {
  29225. processor->processBlock (buffer, incomingMidi);
  29226. }
  29227. }
  29228. }
  29229. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29230. {
  29231. const ScopedLock sl (lock);
  29232. sampleRate = device->getCurrentSampleRate();
  29233. blockSize = device->getCurrentBufferSizeSamples();
  29234. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29235. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29236. messageCollector.reset (sampleRate);
  29237. zeromem (channels, sizeof (channels));
  29238. if (processor != 0)
  29239. {
  29240. if (isPrepared)
  29241. processor->releaseResources();
  29242. AudioProcessor* const oldProcessor = processor;
  29243. setProcessor (0);
  29244. setProcessor (oldProcessor);
  29245. }
  29246. }
  29247. void AudioProcessorPlayer::audioDeviceStopped()
  29248. {
  29249. const ScopedLock sl (lock);
  29250. if (processor != 0 && isPrepared)
  29251. processor->releaseResources();
  29252. sampleRate = 0.0;
  29253. blockSize = 0;
  29254. isPrepared = false;
  29255. tempBuffer.setSize (1, 1);
  29256. }
  29257. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29258. {
  29259. messageCollector.addMessageToQueue (message);
  29260. }
  29261. END_JUCE_NAMESPACE
  29262. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29263. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29264. BEGIN_JUCE_NAMESPACE
  29265. class ProcessorParameterPropertyComp : public PropertyComponent,
  29266. public AudioProcessorListener,
  29267. public AsyncUpdater
  29268. {
  29269. public:
  29270. ProcessorParameterPropertyComp (const String& name,
  29271. AudioProcessor* const owner_,
  29272. const int index_)
  29273. : PropertyComponent (name),
  29274. owner (owner_),
  29275. index (index_)
  29276. {
  29277. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29278. owner_->addListener (this);
  29279. }
  29280. ~ProcessorParameterPropertyComp()
  29281. {
  29282. owner->removeListener (this);
  29283. deleteAllChildren();
  29284. }
  29285. void refresh()
  29286. {
  29287. slider->setValue (owner->getParameter (index), false);
  29288. }
  29289. void audioProcessorChanged (AudioProcessor*) {}
  29290. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29291. {
  29292. if (parameterIndex == index)
  29293. triggerAsyncUpdate();
  29294. }
  29295. void handleAsyncUpdate()
  29296. {
  29297. refresh();
  29298. }
  29299. juce_UseDebuggingNewOperator
  29300. private:
  29301. AudioProcessor* const owner;
  29302. const int index;
  29303. Slider* slider;
  29304. class ParamSlider : public Slider
  29305. {
  29306. public:
  29307. ParamSlider (AudioProcessor* const owner_, const int index_)
  29308. : Slider (String::empty),
  29309. owner (owner_),
  29310. index (index_)
  29311. {
  29312. setRange (0.0, 1.0, 0.0);
  29313. setSliderStyle (Slider::LinearBar);
  29314. setTextBoxIsEditable (false);
  29315. setScrollWheelEnabled (false);
  29316. }
  29317. ~ParamSlider()
  29318. {
  29319. }
  29320. void valueChanged()
  29321. {
  29322. const float newVal = (float) getValue();
  29323. if (owner->getParameter (index) != newVal)
  29324. owner->setParameter (index, newVal);
  29325. }
  29326. const String getTextFromValue (double /*value*/)
  29327. {
  29328. return owner->getParameterText (index);
  29329. }
  29330. juce_UseDebuggingNewOperator
  29331. private:
  29332. AudioProcessor* const owner;
  29333. const int index;
  29334. ParamSlider (const ParamSlider&);
  29335. ParamSlider& operator= (const ParamSlider&);
  29336. };
  29337. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29338. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29339. };
  29340. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29341. : AudioProcessorEditor (owner_)
  29342. {
  29343. setOpaque (true);
  29344. addAndMakeVisible (panel = new PropertyPanel());
  29345. Array <PropertyComponent*> params;
  29346. const int numParams = owner_->getNumParameters();
  29347. int totalHeight = 0;
  29348. for (int i = 0; i < numParams; ++i)
  29349. {
  29350. String name (owner_->getParameterName (i));
  29351. if (name.trim().isEmpty())
  29352. name = "Unnamed";
  29353. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29354. params.add (pc);
  29355. totalHeight += pc->getPreferredHeight();
  29356. }
  29357. panel->addProperties (params);
  29358. setSize (400, jlimit (25, 400, totalHeight));
  29359. }
  29360. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29361. {
  29362. deleteAllChildren();
  29363. }
  29364. void GenericAudioProcessorEditor::paint (Graphics& g)
  29365. {
  29366. g.fillAll (Colours::white);
  29367. }
  29368. void GenericAudioProcessorEditor::resized()
  29369. {
  29370. panel->setSize (getWidth(), getHeight());
  29371. }
  29372. END_JUCE_NAMESPACE
  29373. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29374. /*** Start of inlined file: juce_Sampler.cpp ***/
  29375. BEGIN_JUCE_NAMESPACE
  29376. SamplerSound::SamplerSound (const String& name_,
  29377. AudioFormatReader& source,
  29378. const BigInteger& midiNotes_,
  29379. const int midiNoteForNormalPitch,
  29380. const double attackTimeSecs,
  29381. const double releaseTimeSecs,
  29382. const double maxSampleLengthSeconds)
  29383. : name (name_),
  29384. midiNotes (midiNotes_),
  29385. midiRootNote (midiNoteForNormalPitch)
  29386. {
  29387. sourceSampleRate = source.sampleRate;
  29388. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29389. {
  29390. length = 0;
  29391. attackSamples = 0;
  29392. releaseSamples = 0;
  29393. }
  29394. else
  29395. {
  29396. length = jmin ((int) source.lengthInSamples,
  29397. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29398. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29399. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29400. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29401. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29402. }
  29403. }
  29404. SamplerSound::~SamplerSound()
  29405. {
  29406. }
  29407. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29408. {
  29409. return midiNotes [midiNoteNumber];
  29410. }
  29411. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29412. {
  29413. return true;
  29414. }
  29415. SamplerVoice::SamplerVoice()
  29416. : pitchRatio (0.0),
  29417. sourceSamplePosition (0.0),
  29418. lgain (0.0f),
  29419. rgain (0.0f),
  29420. isInAttack (false),
  29421. isInRelease (false)
  29422. {
  29423. }
  29424. SamplerVoice::~SamplerVoice()
  29425. {
  29426. }
  29427. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29428. {
  29429. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29430. }
  29431. void SamplerVoice::startNote (const int midiNoteNumber,
  29432. const float velocity,
  29433. SynthesiserSound* s,
  29434. const int /*currentPitchWheelPosition*/)
  29435. {
  29436. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29437. jassert (sound != 0); // this object can only play SamplerSounds!
  29438. if (sound != 0)
  29439. {
  29440. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29441. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29442. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29443. sourceSamplePosition = 0.0;
  29444. lgain = velocity;
  29445. rgain = velocity;
  29446. isInAttack = (sound->attackSamples > 0);
  29447. isInRelease = false;
  29448. if (isInAttack)
  29449. {
  29450. attackReleaseLevel = 0.0f;
  29451. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29452. }
  29453. else
  29454. {
  29455. attackReleaseLevel = 1.0f;
  29456. attackDelta = 0.0f;
  29457. }
  29458. if (sound->releaseSamples > 0)
  29459. {
  29460. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29461. }
  29462. else
  29463. {
  29464. releaseDelta = 0.0f;
  29465. }
  29466. }
  29467. }
  29468. void SamplerVoice::stopNote (const bool allowTailOff)
  29469. {
  29470. if (allowTailOff)
  29471. {
  29472. isInAttack = false;
  29473. isInRelease = true;
  29474. }
  29475. else
  29476. {
  29477. clearCurrentNote();
  29478. }
  29479. }
  29480. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29481. {
  29482. }
  29483. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29484. const int /*newValue*/)
  29485. {
  29486. }
  29487. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29488. {
  29489. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29490. if (playingSound != 0)
  29491. {
  29492. const float* const inL = playingSound->data->getSampleData (0, 0);
  29493. const float* const inR = playingSound->data->getNumChannels() > 1
  29494. ? playingSound->data->getSampleData (1, 0) : 0;
  29495. float* outL = outputBuffer.getSampleData (0, startSample);
  29496. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29497. while (--numSamples >= 0)
  29498. {
  29499. const int pos = (int) sourceSamplePosition;
  29500. const float alpha = (float) (sourceSamplePosition - pos);
  29501. const float invAlpha = 1.0f - alpha;
  29502. // just using a very simple linear interpolation here..
  29503. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29504. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29505. : l;
  29506. l *= lgain;
  29507. r *= rgain;
  29508. if (isInAttack)
  29509. {
  29510. l *= attackReleaseLevel;
  29511. r *= attackReleaseLevel;
  29512. attackReleaseLevel += attackDelta;
  29513. if (attackReleaseLevel >= 1.0f)
  29514. {
  29515. attackReleaseLevel = 1.0f;
  29516. isInAttack = false;
  29517. }
  29518. }
  29519. else if (isInRelease)
  29520. {
  29521. l *= attackReleaseLevel;
  29522. r *= attackReleaseLevel;
  29523. attackReleaseLevel += releaseDelta;
  29524. if (attackReleaseLevel <= 0.0f)
  29525. {
  29526. stopNote (false);
  29527. break;
  29528. }
  29529. }
  29530. if (outR != 0)
  29531. {
  29532. *outL++ += l;
  29533. *outR++ += r;
  29534. }
  29535. else
  29536. {
  29537. *outL++ += (l + r) * 0.5f;
  29538. }
  29539. sourceSamplePosition += pitchRatio;
  29540. if (sourceSamplePosition > playingSound->length)
  29541. {
  29542. stopNote (false);
  29543. break;
  29544. }
  29545. }
  29546. }
  29547. }
  29548. END_JUCE_NAMESPACE
  29549. /*** End of inlined file: juce_Sampler.cpp ***/
  29550. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29551. BEGIN_JUCE_NAMESPACE
  29552. SynthesiserSound::SynthesiserSound()
  29553. {
  29554. }
  29555. SynthesiserSound::~SynthesiserSound()
  29556. {
  29557. }
  29558. SynthesiserVoice::SynthesiserVoice()
  29559. : currentSampleRate (44100.0),
  29560. currentlyPlayingNote (-1),
  29561. noteOnTime (0),
  29562. currentlyPlayingSound (0)
  29563. {
  29564. }
  29565. SynthesiserVoice::~SynthesiserVoice()
  29566. {
  29567. }
  29568. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29569. {
  29570. return currentlyPlayingSound != 0
  29571. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29572. }
  29573. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29574. {
  29575. currentSampleRate = newRate;
  29576. }
  29577. void SynthesiserVoice::clearCurrentNote()
  29578. {
  29579. currentlyPlayingNote = -1;
  29580. currentlyPlayingSound = 0;
  29581. }
  29582. Synthesiser::Synthesiser()
  29583. : sampleRate (0),
  29584. lastNoteOnCounter (0),
  29585. shouldStealNotes (true)
  29586. {
  29587. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29588. lastPitchWheelValues[i] = 0x2000;
  29589. }
  29590. Synthesiser::~Synthesiser()
  29591. {
  29592. }
  29593. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29594. {
  29595. const ScopedLock sl (lock);
  29596. return voices [index];
  29597. }
  29598. void Synthesiser::clearVoices()
  29599. {
  29600. const ScopedLock sl (lock);
  29601. voices.clear();
  29602. }
  29603. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29604. {
  29605. const ScopedLock sl (lock);
  29606. voices.add (newVoice);
  29607. }
  29608. void Synthesiser::removeVoice (const int index)
  29609. {
  29610. const ScopedLock sl (lock);
  29611. voices.remove (index);
  29612. }
  29613. void Synthesiser::clearSounds()
  29614. {
  29615. const ScopedLock sl (lock);
  29616. sounds.clear();
  29617. }
  29618. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29619. {
  29620. const ScopedLock sl (lock);
  29621. sounds.add (newSound);
  29622. }
  29623. void Synthesiser::removeSound (const int index)
  29624. {
  29625. const ScopedLock sl (lock);
  29626. sounds.remove (index);
  29627. }
  29628. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29629. {
  29630. shouldStealNotes = shouldStealNotes_;
  29631. }
  29632. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29633. {
  29634. if (sampleRate != newRate)
  29635. {
  29636. const ScopedLock sl (lock);
  29637. allNotesOff (0, false);
  29638. sampleRate = newRate;
  29639. for (int i = voices.size(); --i >= 0;)
  29640. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29641. }
  29642. }
  29643. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29644. const MidiBuffer& midiData,
  29645. int startSample,
  29646. int numSamples)
  29647. {
  29648. // must set the sample rate before using this!
  29649. jassert (sampleRate != 0);
  29650. const ScopedLock sl (lock);
  29651. MidiBuffer::Iterator midiIterator (midiData);
  29652. midiIterator.setNextSamplePosition (startSample);
  29653. MidiMessage m (0xf4, 0.0);
  29654. while (numSamples > 0)
  29655. {
  29656. int midiEventPos;
  29657. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29658. && midiEventPos < startSample + numSamples;
  29659. const int numThisTime = useEvent ? midiEventPos - startSample
  29660. : numSamples;
  29661. if (numThisTime > 0)
  29662. {
  29663. for (int i = voices.size(); --i >= 0;)
  29664. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29665. }
  29666. if (useEvent)
  29667. {
  29668. if (m.isNoteOn())
  29669. {
  29670. const int channel = m.getChannel();
  29671. noteOn (channel,
  29672. m.getNoteNumber(),
  29673. m.getFloatVelocity());
  29674. }
  29675. else if (m.isNoteOff())
  29676. {
  29677. noteOff (m.getChannel(),
  29678. m.getNoteNumber(),
  29679. true);
  29680. }
  29681. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29682. {
  29683. allNotesOff (m.getChannel(), true);
  29684. }
  29685. else if (m.isPitchWheel())
  29686. {
  29687. const int channel = m.getChannel();
  29688. const int wheelPos = m.getPitchWheelValue();
  29689. lastPitchWheelValues [channel - 1] = wheelPos;
  29690. handlePitchWheel (channel, wheelPos);
  29691. }
  29692. else if (m.isController())
  29693. {
  29694. handleController (m.getChannel(),
  29695. m.getControllerNumber(),
  29696. m.getControllerValue());
  29697. }
  29698. }
  29699. startSample += numThisTime;
  29700. numSamples -= numThisTime;
  29701. }
  29702. }
  29703. void Synthesiser::noteOn (const int midiChannel,
  29704. const int midiNoteNumber,
  29705. const float velocity)
  29706. {
  29707. const ScopedLock sl (lock);
  29708. for (int i = sounds.size(); --i >= 0;)
  29709. {
  29710. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29711. if (sound->appliesToNote (midiNoteNumber)
  29712. && sound->appliesToChannel (midiChannel))
  29713. {
  29714. startVoice (findFreeVoice (sound, shouldStealNotes),
  29715. sound, midiChannel, midiNoteNumber, velocity);
  29716. }
  29717. }
  29718. }
  29719. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29720. SynthesiserSound* const sound,
  29721. const int midiChannel,
  29722. const int midiNoteNumber,
  29723. const float velocity)
  29724. {
  29725. if (voice != 0 && sound != 0)
  29726. {
  29727. if (voice->currentlyPlayingSound != 0)
  29728. voice->stopNote (false);
  29729. voice->startNote (midiNoteNumber,
  29730. velocity,
  29731. sound,
  29732. lastPitchWheelValues [midiChannel - 1]);
  29733. voice->currentlyPlayingNote = midiNoteNumber;
  29734. voice->noteOnTime = ++lastNoteOnCounter;
  29735. voice->currentlyPlayingSound = sound;
  29736. }
  29737. }
  29738. void Synthesiser::noteOff (const int midiChannel,
  29739. const int midiNoteNumber,
  29740. const bool allowTailOff)
  29741. {
  29742. const ScopedLock sl (lock);
  29743. for (int i = voices.size(); --i >= 0;)
  29744. {
  29745. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29746. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29747. {
  29748. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29749. if (sound != 0
  29750. && sound->appliesToNote (midiNoteNumber)
  29751. && sound->appliesToChannel (midiChannel))
  29752. {
  29753. voice->stopNote (allowTailOff);
  29754. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29755. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29756. }
  29757. }
  29758. }
  29759. }
  29760. void Synthesiser::allNotesOff (const int midiChannel,
  29761. const bool allowTailOff)
  29762. {
  29763. const ScopedLock sl (lock);
  29764. for (int i = voices.size(); --i >= 0;)
  29765. {
  29766. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29767. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29768. voice->stopNote (allowTailOff);
  29769. }
  29770. }
  29771. void Synthesiser::handlePitchWheel (const int midiChannel,
  29772. const int wheelValue)
  29773. {
  29774. const ScopedLock sl (lock);
  29775. for (int i = voices.size(); --i >= 0;)
  29776. {
  29777. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29778. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29779. {
  29780. voice->pitchWheelMoved (wheelValue);
  29781. }
  29782. }
  29783. }
  29784. void Synthesiser::handleController (const int midiChannel,
  29785. const int controllerNumber,
  29786. const int controllerValue)
  29787. {
  29788. const ScopedLock sl (lock);
  29789. for (int i = voices.size(); --i >= 0;)
  29790. {
  29791. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29792. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29793. voice->controllerMoved (controllerNumber, controllerValue);
  29794. }
  29795. }
  29796. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29797. const bool stealIfNoneAvailable) const
  29798. {
  29799. const ScopedLock sl (lock);
  29800. for (int i = voices.size(); --i >= 0;)
  29801. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29802. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29803. return voices.getUnchecked (i);
  29804. if (stealIfNoneAvailable)
  29805. {
  29806. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29807. SynthesiserVoice* oldest = 0;
  29808. for (int i = voices.size(); --i >= 0;)
  29809. {
  29810. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29811. if (voice->canPlaySound (soundToPlay)
  29812. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29813. oldest = voice;
  29814. }
  29815. jassert (oldest != 0);
  29816. return oldest;
  29817. }
  29818. return 0;
  29819. }
  29820. END_JUCE_NAMESPACE
  29821. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29822. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29823. BEGIN_JUCE_NAMESPACE
  29824. ActionBroadcaster::ActionBroadcaster() throw()
  29825. {
  29826. // are you trying to create this object before or after juce has been intialised??
  29827. jassert (MessageManager::instance != 0);
  29828. }
  29829. ActionBroadcaster::~ActionBroadcaster()
  29830. {
  29831. // all event-based objects must be deleted BEFORE juce is shut down!
  29832. jassert (MessageManager::instance != 0);
  29833. }
  29834. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29835. {
  29836. actionListenerList.addActionListener (listener);
  29837. }
  29838. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29839. {
  29840. jassert (actionListenerList.isValidMessageListener());
  29841. if (actionListenerList.isValidMessageListener())
  29842. actionListenerList.removeActionListener (listener);
  29843. }
  29844. void ActionBroadcaster::removeAllActionListeners()
  29845. {
  29846. actionListenerList.removeAllActionListeners();
  29847. }
  29848. void ActionBroadcaster::sendActionMessage (const String& message) const
  29849. {
  29850. actionListenerList.sendActionMessage (message);
  29851. }
  29852. END_JUCE_NAMESPACE
  29853. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29854. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29855. BEGIN_JUCE_NAMESPACE
  29856. // special message of our own with a string in it
  29857. class ActionMessage : public Message
  29858. {
  29859. public:
  29860. const String message;
  29861. ActionMessage (const String& messageText,
  29862. void* const listener_) throw()
  29863. : message (messageText)
  29864. {
  29865. pointerParameter = listener_;
  29866. }
  29867. ~ActionMessage() throw()
  29868. {
  29869. }
  29870. private:
  29871. ActionMessage (const ActionMessage&);
  29872. ActionMessage& operator= (const ActionMessage&);
  29873. };
  29874. ActionListenerList::ActionListenerList() throw()
  29875. {
  29876. }
  29877. ActionListenerList::~ActionListenerList() throw()
  29878. {
  29879. }
  29880. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29881. {
  29882. const ScopedLock sl (actionListenerLock_);
  29883. jassert (listener != 0);
  29884. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29885. if (listener != 0)
  29886. actionListeners_.add (listener);
  29887. }
  29888. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29889. {
  29890. const ScopedLock sl (actionListenerLock_);
  29891. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29892. actionListeners_.removeValue (listener);
  29893. }
  29894. void ActionListenerList::removeAllActionListeners() throw()
  29895. {
  29896. const ScopedLock sl (actionListenerLock_);
  29897. actionListeners_.clear();
  29898. }
  29899. void ActionListenerList::sendActionMessage (const String& message) const
  29900. {
  29901. const ScopedLock sl (actionListenerLock_);
  29902. for (int i = actionListeners_.size(); --i >= 0;)
  29903. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29904. }
  29905. void ActionListenerList::handleMessage (const Message& message)
  29906. {
  29907. const ActionMessage& am = (const ActionMessage&) message;
  29908. if (actionListeners_.contains (am.pointerParameter))
  29909. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29910. }
  29911. END_JUCE_NAMESPACE
  29912. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29913. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29914. BEGIN_JUCE_NAMESPACE
  29915. AsyncUpdater::AsyncUpdater() throw()
  29916. : asyncMessagePending (false)
  29917. {
  29918. internalAsyncHandler.owner = this;
  29919. }
  29920. AsyncUpdater::~AsyncUpdater()
  29921. {
  29922. }
  29923. void AsyncUpdater::triggerAsyncUpdate() throw()
  29924. {
  29925. if (! asyncMessagePending)
  29926. {
  29927. asyncMessagePending = true;
  29928. internalAsyncHandler.postMessage (new Message());
  29929. }
  29930. }
  29931. void AsyncUpdater::cancelPendingUpdate() throw()
  29932. {
  29933. asyncMessagePending = false;
  29934. }
  29935. void AsyncUpdater::handleUpdateNowIfNeeded()
  29936. {
  29937. if (asyncMessagePending)
  29938. {
  29939. asyncMessagePending = false;
  29940. handleAsyncUpdate();
  29941. }
  29942. }
  29943. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29944. {
  29945. owner->handleUpdateNowIfNeeded();
  29946. }
  29947. END_JUCE_NAMESPACE
  29948. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29949. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29950. BEGIN_JUCE_NAMESPACE
  29951. ChangeBroadcaster::ChangeBroadcaster() throw()
  29952. {
  29953. // are you trying to create this object before or after juce has been intialised??
  29954. jassert (MessageManager::instance != 0);
  29955. }
  29956. ChangeBroadcaster::~ChangeBroadcaster()
  29957. {
  29958. // all event-based objects must be deleted BEFORE juce is shut down!
  29959. jassert (MessageManager::instance != 0);
  29960. }
  29961. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29962. {
  29963. changeListenerList.addChangeListener (listener);
  29964. }
  29965. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29966. {
  29967. jassert (changeListenerList.isValidMessageListener());
  29968. if (changeListenerList.isValidMessageListener())
  29969. changeListenerList.removeChangeListener (listener);
  29970. }
  29971. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29972. {
  29973. changeListenerList.removeAllChangeListeners();
  29974. }
  29975. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29976. {
  29977. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29978. }
  29979. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29980. {
  29981. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29982. }
  29983. void ChangeBroadcaster::dispatchPendingMessages()
  29984. {
  29985. changeListenerList.dispatchPendingMessages();
  29986. }
  29987. END_JUCE_NAMESPACE
  29988. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29989. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29990. BEGIN_JUCE_NAMESPACE
  29991. ChangeListenerList::ChangeListenerList() throw()
  29992. : lastChangedObject (0),
  29993. messagePending (false)
  29994. {
  29995. }
  29996. ChangeListenerList::~ChangeListenerList() throw()
  29997. {
  29998. }
  29999. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  30000. {
  30001. const ScopedLock sl (lock);
  30002. jassert (listener != 0);
  30003. if (listener != 0)
  30004. listeners.add (listener);
  30005. }
  30006. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  30007. {
  30008. const ScopedLock sl (lock);
  30009. listeners.removeValue (listener);
  30010. }
  30011. void ChangeListenerList::removeAllChangeListeners() throw()
  30012. {
  30013. const ScopedLock sl (lock);
  30014. listeners.clear();
  30015. }
  30016. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  30017. {
  30018. const ScopedLock sl (lock);
  30019. if ((! messagePending) && (listeners.size() > 0))
  30020. {
  30021. lastChangedObject = objectThatHasChanged;
  30022. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30023. messagePending = true;
  30024. }
  30025. }
  30026. void ChangeListenerList::handleMessage (const Message& message)
  30027. {
  30028. sendSynchronousChangeMessage (message.pointerParameter);
  30029. }
  30030. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30031. {
  30032. const ScopedLock sl (lock);
  30033. messagePending = false;
  30034. for (int i = listeners.size(); --i >= 0;)
  30035. {
  30036. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30037. {
  30038. const ScopedUnlock tempUnlocker (lock);
  30039. l->changeListenerCallback (objectThatHasChanged);
  30040. }
  30041. i = jmin (i, listeners.size());
  30042. }
  30043. }
  30044. void ChangeListenerList::dispatchPendingMessages()
  30045. {
  30046. if (messagePending)
  30047. sendSynchronousChangeMessage (lastChangedObject);
  30048. }
  30049. END_JUCE_NAMESPACE
  30050. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30051. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30052. BEGIN_JUCE_NAMESPACE
  30053. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30054. const uint32 magicMessageHeaderNumber)
  30055. : Thread ("Juce IPC connection"),
  30056. callbackConnectionState (false),
  30057. useMessageThread (callbacksOnMessageThread),
  30058. magicMessageHeader (magicMessageHeaderNumber),
  30059. pipeReceiveMessageTimeout (-1)
  30060. {
  30061. }
  30062. InterprocessConnection::~InterprocessConnection()
  30063. {
  30064. callbackConnectionState = false;
  30065. disconnect();
  30066. }
  30067. bool InterprocessConnection::connectToSocket (const String& hostName,
  30068. const int portNumber,
  30069. const int timeOutMillisecs)
  30070. {
  30071. disconnect();
  30072. const ScopedLock sl (pipeAndSocketLock);
  30073. socket = new StreamingSocket();
  30074. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30075. {
  30076. connectionMadeInt();
  30077. startThread();
  30078. return true;
  30079. }
  30080. else
  30081. {
  30082. socket = 0;
  30083. return false;
  30084. }
  30085. }
  30086. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30087. const int pipeReceiveMessageTimeoutMs)
  30088. {
  30089. disconnect();
  30090. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30091. if (newPipe->openExisting (pipeName))
  30092. {
  30093. const ScopedLock sl (pipeAndSocketLock);
  30094. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30095. initialiseWithPipe (newPipe.release());
  30096. return true;
  30097. }
  30098. return false;
  30099. }
  30100. bool InterprocessConnection::createPipe (const String& pipeName,
  30101. const int pipeReceiveMessageTimeoutMs)
  30102. {
  30103. disconnect();
  30104. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30105. if (newPipe->createNewPipe (pipeName))
  30106. {
  30107. const ScopedLock sl (pipeAndSocketLock);
  30108. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30109. initialiseWithPipe (newPipe.release());
  30110. return true;
  30111. }
  30112. return false;
  30113. }
  30114. void InterprocessConnection::disconnect()
  30115. {
  30116. if (socket != 0)
  30117. socket->close();
  30118. if (pipe != 0)
  30119. {
  30120. pipe->cancelPendingReads();
  30121. pipe->close();
  30122. }
  30123. stopThread (4000);
  30124. {
  30125. const ScopedLock sl (pipeAndSocketLock);
  30126. socket = 0;
  30127. pipe = 0;
  30128. }
  30129. connectionLostInt();
  30130. }
  30131. bool InterprocessConnection::isConnected() const
  30132. {
  30133. const ScopedLock sl (pipeAndSocketLock);
  30134. return ((socket != 0 && socket->isConnected())
  30135. || (pipe != 0 && pipe->isOpen()))
  30136. && isThreadRunning();
  30137. }
  30138. const String InterprocessConnection::getConnectedHostName() const
  30139. {
  30140. if (pipe != 0)
  30141. {
  30142. return "localhost";
  30143. }
  30144. else if (socket != 0)
  30145. {
  30146. if (! socket->isLocal())
  30147. return socket->getHostName();
  30148. return "localhost";
  30149. }
  30150. return String::empty;
  30151. }
  30152. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30153. {
  30154. uint32 messageHeader[2];
  30155. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30156. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30157. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30158. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30159. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30160. size_t bytesWritten = 0;
  30161. const ScopedLock sl (pipeAndSocketLock);
  30162. if (socket != 0)
  30163. {
  30164. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30165. }
  30166. else if (pipe != 0)
  30167. {
  30168. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30169. }
  30170. if (bytesWritten < 0)
  30171. {
  30172. // error..
  30173. return false;
  30174. }
  30175. return (bytesWritten == messageData.getSize());
  30176. }
  30177. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30178. {
  30179. jassert (socket == 0);
  30180. socket = socket_;
  30181. connectionMadeInt();
  30182. startThread();
  30183. }
  30184. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30185. {
  30186. jassert (pipe == 0);
  30187. pipe = pipe_;
  30188. connectionMadeInt();
  30189. startThread();
  30190. }
  30191. const int messageMagicNumber = 0xb734128b;
  30192. void InterprocessConnection::handleMessage (const Message& message)
  30193. {
  30194. if (message.intParameter1 == messageMagicNumber)
  30195. {
  30196. switch (message.intParameter2)
  30197. {
  30198. case 0:
  30199. {
  30200. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30201. messageReceived (*data);
  30202. break;
  30203. }
  30204. case 1:
  30205. connectionMade();
  30206. break;
  30207. case 2:
  30208. connectionLost();
  30209. break;
  30210. }
  30211. }
  30212. }
  30213. void InterprocessConnection::connectionMadeInt()
  30214. {
  30215. if (! callbackConnectionState)
  30216. {
  30217. callbackConnectionState = true;
  30218. if (useMessageThread)
  30219. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30220. else
  30221. connectionMade();
  30222. }
  30223. }
  30224. void InterprocessConnection::connectionLostInt()
  30225. {
  30226. if (callbackConnectionState)
  30227. {
  30228. callbackConnectionState = false;
  30229. if (useMessageThread)
  30230. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30231. else
  30232. connectionLost();
  30233. }
  30234. }
  30235. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30236. {
  30237. jassert (callbackConnectionState);
  30238. if (useMessageThread)
  30239. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30240. else
  30241. messageReceived (data);
  30242. }
  30243. bool InterprocessConnection::readNextMessageInt()
  30244. {
  30245. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30246. uint32 messageHeader[2];
  30247. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30248. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30249. if (bytes == sizeof (messageHeader)
  30250. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30251. {
  30252. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30253. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30254. {
  30255. MemoryBlock messageData (bytesInMessage, true);
  30256. int bytesRead = 0;
  30257. while (bytesInMessage > 0)
  30258. {
  30259. if (threadShouldExit())
  30260. return false;
  30261. const int numThisTime = jmin (bytesInMessage, 65536);
  30262. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30263. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30264. if (bytesIn <= 0)
  30265. break;
  30266. bytesRead += bytesIn;
  30267. bytesInMessage -= bytesIn;
  30268. }
  30269. if (bytesRead >= 0)
  30270. deliverDataInt (messageData);
  30271. }
  30272. }
  30273. else if (bytes < 0)
  30274. {
  30275. {
  30276. const ScopedLock sl (pipeAndSocketLock);
  30277. socket = 0;
  30278. }
  30279. connectionLostInt();
  30280. return false;
  30281. }
  30282. return true;
  30283. }
  30284. void InterprocessConnection::run()
  30285. {
  30286. while (! threadShouldExit())
  30287. {
  30288. if (socket != 0)
  30289. {
  30290. const int ready = socket->waitUntilReady (true, 0);
  30291. if (ready < 0)
  30292. {
  30293. {
  30294. const ScopedLock sl (pipeAndSocketLock);
  30295. socket = 0;
  30296. }
  30297. connectionLostInt();
  30298. break;
  30299. }
  30300. else if (ready > 0)
  30301. {
  30302. if (! readNextMessageInt())
  30303. break;
  30304. }
  30305. else
  30306. {
  30307. Thread::sleep (2);
  30308. }
  30309. }
  30310. else if (pipe != 0)
  30311. {
  30312. if (! pipe->isOpen())
  30313. {
  30314. {
  30315. const ScopedLock sl (pipeAndSocketLock);
  30316. pipe = 0;
  30317. }
  30318. connectionLostInt();
  30319. break;
  30320. }
  30321. else
  30322. {
  30323. if (! readNextMessageInt())
  30324. break;
  30325. }
  30326. }
  30327. else
  30328. {
  30329. break;
  30330. }
  30331. }
  30332. }
  30333. END_JUCE_NAMESPACE
  30334. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30335. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30336. BEGIN_JUCE_NAMESPACE
  30337. InterprocessConnectionServer::InterprocessConnectionServer()
  30338. : Thread ("Juce IPC server")
  30339. {
  30340. }
  30341. InterprocessConnectionServer::~InterprocessConnectionServer()
  30342. {
  30343. stop();
  30344. }
  30345. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30346. {
  30347. stop();
  30348. socket = new StreamingSocket();
  30349. if (socket->createListener (portNumber))
  30350. {
  30351. startThread();
  30352. return true;
  30353. }
  30354. socket = 0;
  30355. return false;
  30356. }
  30357. void InterprocessConnectionServer::stop()
  30358. {
  30359. signalThreadShouldExit();
  30360. if (socket != 0)
  30361. socket->close();
  30362. stopThread (4000);
  30363. socket = 0;
  30364. }
  30365. void InterprocessConnectionServer::run()
  30366. {
  30367. while ((! threadShouldExit()) && socket != 0)
  30368. {
  30369. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30370. if (clientSocket != 0)
  30371. {
  30372. InterprocessConnection* newConnection = createConnectionObject();
  30373. if (newConnection != 0)
  30374. newConnection->initialiseWithSocket (clientSocket.release());
  30375. }
  30376. }
  30377. }
  30378. END_JUCE_NAMESPACE
  30379. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30380. /*** Start of inlined file: juce_Message.cpp ***/
  30381. BEGIN_JUCE_NAMESPACE
  30382. Message::Message() throw()
  30383. : intParameter1 (0),
  30384. intParameter2 (0),
  30385. intParameter3 (0),
  30386. pointerParameter (0)
  30387. {
  30388. }
  30389. Message::Message (const int intParameter1_,
  30390. const int intParameter2_,
  30391. const int intParameter3_,
  30392. void* const pointerParameter_) throw()
  30393. : intParameter1 (intParameter1_),
  30394. intParameter2 (intParameter2_),
  30395. intParameter3 (intParameter3_),
  30396. pointerParameter (pointerParameter_)
  30397. {
  30398. }
  30399. Message::~Message() throw()
  30400. {
  30401. }
  30402. END_JUCE_NAMESPACE
  30403. /*** End of inlined file: juce_Message.cpp ***/
  30404. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30405. BEGIN_JUCE_NAMESPACE
  30406. MessageListener::MessageListener() throw()
  30407. {
  30408. // are you trying to create a messagelistener before or after juce has been intialised??
  30409. jassert (MessageManager::instance != 0);
  30410. if (MessageManager::instance != 0)
  30411. MessageManager::instance->messageListeners.add (this);
  30412. }
  30413. MessageListener::~MessageListener()
  30414. {
  30415. if (MessageManager::instance != 0)
  30416. MessageManager::instance->messageListeners.removeValue (this);
  30417. }
  30418. void MessageListener::postMessage (Message* const message) const throw()
  30419. {
  30420. message->messageRecipient = const_cast <MessageListener*> (this);
  30421. if (MessageManager::instance == 0)
  30422. MessageManager::getInstance();
  30423. MessageManager::instance->postMessageToQueue (message);
  30424. }
  30425. bool MessageListener::isValidMessageListener() const throw()
  30426. {
  30427. return (MessageManager::instance != 0)
  30428. && MessageManager::instance->messageListeners.contains (this);
  30429. }
  30430. END_JUCE_NAMESPACE
  30431. /*** End of inlined file: juce_MessageListener.cpp ***/
  30432. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30433. BEGIN_JUCE_NAMESPACE
  30434. // platform-specific functions..
  30435. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30436. bool juce_postMessageToSystemQueue (Message* message);
  30437. MessageManager* MessageManager::instance = 0;
  30438. static const int quitMessageId = 0xfffff321;
  30439. MessageManager::MessageManager() throw()
  30440. : quitMessagePosted (false),
  30441. quitMessageReceived (false),
  30442. threadWithLock (0)
  30443. {
  30444. messageThreadId = Thread::getCurrentThreadId();
  30445. }
  30446. MessageManager::~MessageManager() throw()
  30447. {
  30448. broadcastListeners = 0;
  30449. doPlatformSpecificShutdown();
  30450. // If you hit this assertion, then you've probably leaked a Component or some other
  30451. // kind of MessageListener object...
  30452. jassert (messageListeners.size() == 0);
  30453. jassert (instance == this);
  30454. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30455. }
  30456. MessageManager* MessageManager::getInstance() throw()
  30457. {
  30458. if (instance == 0)
  30459. {
  30460. instance = new MessageManager();
  30461. doPlatformSpecificInitialisation();
  30462. }
  30463. return instance;
  30464. }
  30465. void MessageManager::postMessageToQueue (Message* const message)
  30466. {
  30467. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30468. delete message;
  30469. }
  30470. CallbackMessage::CallbackMessage() throw() {}
  30471. CallbackMessage::~CallbackMessage() throw() {}
  30472. void CallbackMessage::post()
  30473. {
  30474. if (MessageManager::instance != 0)
  30475. MessageManager::instance->postCallbackMessage (this);
  30476. }
  30477. void MessageManager::postCallbackMessage (Message* const message)
  30478. {
  30479. message->messageRecipient = 0;
  30480. postMessageToQueue (message);
  30481. }
  30482. // not for public use..
  30483. void MessageManager::deliverMessage (Message* const message)
  30484. {
  30485. const ScopedPointer <Message> messageDeleter (message);
  30486. MessageListener* const recipient = message->messageRecipient;
  30487. JUCE_TRY
  30488. {
  30489. if (messageListeners.contains (recipient))
  30490. {
  30491. recipient->handleMessage (*message);
  30492. }
  30493. else if (recipient == 0)
  30494. {
  30495. if (message->intParameter1 == quitMessageId)
  30496. {
  30497. quitMessageReceived = true;
  30498. }
  30499. else
  30500. {
  30501. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  30502. if (cm != 0)
  30503. cm->messageCallback();
  30504. }
  30505. }
  30506. }
  30507. JUCE_CATCH_EXCEPTION
  30508. }
  30509. #if ! (JUCE_MAC || JUCE_IOS)
  30510. void MessageManager::runDispatchLoop()
  30511. {
  30512. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30513. runDispatchLoopUntil (-1);
  30514. }
  30515. void MessageManager::stopDispatchLoop()
  30516. {
  30517. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30518. m->messageRecipient = 0;
  30519. postMessageToQueue (m);
  30520. quitMessagePosted = true;
  30521. }
  30522. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30523. {
  30524. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30525. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30526. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30527. && ! quitMessageReceived)
  30528. {
  30529. JUCE_TRY
  30530. {
  30531. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30532. {
  30533. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30534. if (msToWait > 0)
  30535. Thread::sleep (jmin (5, msToWait));
  30536. }
  30537. }
  30538. JUCE_CATCH_EXCEPTION
  30539. }
  30540. return ! quitMessageReceived;
  30541. }
  30542. #endif
  30543. void MessageManager::deliverBroadcastMessage (const String& value)
  30544. {
  30545. if (broadcastListeners != 0)
  30546. broadcastListeners->sendActionMessage (value);
  30547. }
  30548. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30549. {
  30550. if (broadcastListeners == 0)
  30551. broadcastListeners = new ActionListenerList();
  30552. broadcastListeners->addActionListener (listener);
  30553. }
  30554. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30555. {
  30556. if (broadcastListeners != 0)
  30557. broadcastListeners->removeActionListener (listener);
  30558. }
  30559. bool MessageManager::isThisTheMessageThread() const throw()
  30560. {
  30561. return Thread::getCurrentThreadId() == messageThreadId;
  30562. }
  30563. void MessageManager::setCurrentThreadAsMessageThread()
  30564. {
  30565. if (messageThreadId != Thread::getCurrentThreadId())
  30566. {
  30567. messageThreadId = Thread::getCurrentThreadId();
  30568. // This is needed on windows to make sure the message window is created by this thread
  30569. doPlatformSpecificShutdown();
  30570. doPlatformSpecificInitialisation();
  30571. }
  30572. }
  30573. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30574. {
  30575. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30576. return thisThread == messageThreadId || thisThread == threadWithLock;
  30577. }
  30578. /* The only safe way to lock the message thread while another thread does
  30579. some work is by posting a special message, whose purpose is to tie up the event
  30580. loop until the other thread has finished its business.
  30581. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30582. get locked before making an event callback, because if the same OS lock gets indirectly
  30583. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30584. in Cocoa).
  30585. */
  30586. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30587. {
  30588. public:
  30589. SharedEvents() {}
  30590. ~SharedEvents() {}
  30591. /* This class just holds a couple of events to communicate between the BlockingMessage
  30592. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30593. this shared data must be kept in a separate, ref-counted container. */
  30594. WaitableEvent lockedEvent, releaseEvent;
  30595. private:
  30596. SharedEvents (const SharedEvents&);
  30597. SharedEvents& operator= (const SharedEvents&);
  30598. };
  30599. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30600. {
  30601. public:
  30602. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30603. ~BlockingMessage() throw() {}
  30604. void messageCallback()
  30605. {
  30606. events->lockedEvent.signal();
  30607. events->releaseEvent.wait();
  30608. }
  30609. juce_UseDebuggingNewOperator
  30610. private:
  30611. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30612. BlockingMessage (const BlockingMessage&);
  30613. BlockingMessage& operator= (const BlockingMessage&);
  30614. };
  30615. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30616. : sharedEvents (0),
  30617. locked (false)
  30618. {
  30619. init (threadToCheck, 0);
  30620. }
  30621. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30622. : sharedEvents (0),
  30623. locked (false)
  30624. {
  30625. init (0, jobToCheckForExitSignal);
  30626. }
  30627. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30628. {
  30629. if (MessageManager::instance != 0)
  30630. {
  30631. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30632. {
  30633. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30634. }
  30635. else
  30636. {
  30637. if (threadToCheck == 0 && job == 0)
  30638. {
  30639. MessageManager::instance->lockingLock.enter();
  30640. }
  30641. else
  30642. {
  30643. while (! MessageManager::instance->lockingLock.tryEnter())
  30644. {
  30645. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30646. || (job != 0 && job->shouldExit()))
  30647. return;
  30648. Thread::sleep (1);
  30649. }
  30650. }
  30651. sharedEvents = new SharedEvents();
  30652. sharedEvents->incReferenceCount();
  30653. (new BlockingMessage (sharedEvents))->post();
  30654. while (! sharedEvents->lockedEvent.wait (50))
  30655. {
  30656. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30657. || (job != 0 && job->shouldExit()))
  30658. {
  30659. sharedEvents->releaseEvent.signal();
  30660. sharedEvents->decReferenceCount();
  30661. sharedEvents = 0;
  30662. MessageManager::instance->lockingLock.exit();
  30663. return;
  30664. }
  30665. }
  30666. jassert (MessageManager::instance->threadWithLock == 0);
  30667. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30668. locked = true;
  30669. }
  30670. }
  30671. }
  30672. MessageManagerLock::~MessageManagerLock() throw()
  30673. {
  30674. if (sharedEvents != 0)
  30675. {
  30676. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30677. sharedEvents->releaseEvent.signal();
  30678. sharedEvents->decReferenceCount();
  30679. if (MessageManager::instance != 0)
  30680. {
  30681. MessageManager::instance->threadWithLock = 0;
  30682. MessageManager::instance->lockingLock.exit();
  30683. }
  30684. }
  30685. }
  30686. END_JUCE_NAMESPACE
  30687. /*** End of inlined file: juce_MessageManager.cpp ***/
  30688. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30689. BEGIN_JUCE_NAMESPACE
  30690. class MultiTimer::MultiTimerCallback : public Timer
  30691. {
  30692. public:
  30693. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30694. : timerId (timerId_),
  30695. owner (owner_)
  30696. {
  30697. }
  30698. ~MultiTimerCallback()
  30699. {
  30700. }
  30701. void timerCallback()
  30702. {
  30703. owner.timerCallback (timerId);
  30704. }
  30705. const int timerId;
  30706. private:
  30707. MultiTimer& owner;
  30708. };
  30709. MultiTimer::MultiTimer() throw()
  30710. {
  30711. }
  30712. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30713. {
  30714. }
  30715. MultiTimer::~MultiTimer()
  30716. {
  30717. const ScopedLock sl (timerListLock);
  30718. timers.clear();
  30719. }
  30720. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30721. {
  30722. const ScopedLock sl (timerListLock);
  30723. for (int i = timers.size(); --i >= 0;)
  30724. {
  30725. MultiTimerCallback* const t = timers.getUnchecked(i);
  30726. if (t->timerId == timerId)
  30727. {
  30728. t->startTimer (intervalInMilliseconds);
  30729. return;
  30730. }
  30731. }
  30732. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30733. timers.add (newTimer);
  30734. newTimer->startTimer (intervalInMilliseconds);
  30735. }
  30736. void MultiTimer::stopTimer (const int timerId) throw()
  30737. {
  30738. const ScopedLock sl (timerListLock);
  30739. for (int i = timers.size(); --i >= 0;)
  30740. {
  30741. MultiTimerCallback* const t = timers.getUnchecked(i);
  30742. if (t->timerId == timerId)
  30743. t->stopTimer();
  30744. }
  30745. }
  30746. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30747. {
  30748. const ScopedLock sl (timerListLock);
  30749. for (int i = timers.size(); --i >= 0;)
  30750. {
  30751. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30752. if (t->timerId == timerId)
  30753. return t->isTimerRunning();
  30754. }
  30755. return false;
  30756. }
  30757. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30758. {
  30759. const ScopedLock sl (timerListLock);
  30760. for (int i = timers.size(); --i >= 0;)
  30761. {
  30762. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30763. if (t->timerId == timerId)
  30764. return t->getTimerInterval();
  30765. }
  30766. return 0;
  30767. }
  30768. END_JUCE_NAMESPACE
  30769. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30770. /*** Start of inlined file: juce_Timer.cpp ***/
  30771. BEGIN_JUCE_NAMESPACE
  30772. class InternalTimerThread : private Thread,
  30773. private MessageListener,
  30774. private DeletedAtShutdown,
  30775. private AsyncUpdater
  30776. {
  30777. public:
  30778. InternalTimerThread()
  30779. : Thread ("Juce Timer"),
  30780. firstTimer (0),
  30781. callbackNeeded (0)
  30782. {
  30783. triggerAsyncUpdate();
  30784. }
  30785. ~InternalTimerThread() throw()
  30786. {
  30787. stopThread (4000);
  30788. jassert (instance == this || instance == 0);
  30789. if (instance == this)
  30790. instance = 0;
  30791. }
  30792. void run()
  30793. {
  30794. uint32 lastTime = Time::getMillisecondCounter();
  30795. while (! threadShouldExit())
  30796. {
  30797. const uint32 now = Time::getMillisecondCounter();
  30798. if (now <= lastTime)
  30799. {
  30800. wait (2);
  30801. continue;
  30802. }
  30803. const int elapsed = now - lastTime;
  30804. lastTime = now;
  30805. int timeUntilFirstTimer = 1000;
  30806. {
  30807. const ScopedLock sl (lock);
  30808. decrementAllCounters (elapsed);
  30809. if (firstTimer != 0)
  30810. timeUntilFirstTimer = firstTimer->countdownMs;
  30811. }
  30812. if (timeUntilFirstTimer <= 0)
  30813. {
  30814. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30815. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30816. but if it fails it means the message-thread changed the value from under us so at least
  30817. some processing is happenening and we can just loop around and try again
  30818. */
  30819. if (callbackNeeded.compareAndSetBool (1, 0))
  30820. {
  30821. postMessage (new Message());
  30822. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30823. when the app has a modal loop), so this is how long to wait before assuming the
  30824. message has been lost and trying again.
  30825. */
  30826. const uint32 messageDeliveryTimeout = now + 2000;
  30827. while (callbackNeeded.get() != 0)
  30828. {
  30829. wait (4);
  30830. if (threadShouldExit())
  30831. return;
  30832. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30833. break;
  30834. }
  30835. }
  30836. }
  30837. else
  30838. {
  30839. // don't wait for too long because running this loop also helps keep the
  30840. // Time::getApproximateMillisecondTimer value stay up-to-date
  30841. wait (jlimit (1, 50, timeUntilFirstTimer));
  30842. }
  30843. }
  30844. }
  30845. void callTimers()
  30846. {
  30847. const ScopedLock sl (lock);
  30848. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30849. {
  30850. Timer* const t = firstTimer;
  30851. t->countdownMs = t->periodMs;
  30852. removeTimer (t);
  30853. addTimer (t);
  30854. const ScopedUnlock ul (lock);
  30855. JUCE_TRY
  30856. {
  30857. t->timerCallback();
  30858. }
  30859. JUCE_CATCH_EXCEPTION
  30860. }
  30861. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30862. before the boolean is set. This set should never fail since if it was false in the first place,
  30863. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30864. get a message then the value is true and the other thread can only set it to true again and
  30865. we will get another callback to set it to false.
  30866. */
  30867. callbackNeeded.set (0);
  30868. }
  30869. void handleMessage (const Message&)
  30870. {
  30871. callTimers();
  30872. }
  30873. void callTimersSynchronously()
  30874. {
  30875. if (! isThreadRunning())
  30876. {
  30877. // (This is relied on by some plugins in cases where the MM has
  30878. // had to restart and the async callback never started)
  30879. cancelPendingUpdate();
  30880. triggerAsyncUpdate();
  30881. }
  30882. callTimers();
  30883. }
  30884. static void callAnyTimersSynchronously()
  30885. {
  30886. if (InternalTimerThread::instance != 0)
  30887. InternalTimerThread::instance->callTimersSynchronously();
  30888. }
  30889. static inline void add (Timer* const tim) throw()
  30890. {
  30891. if (instance == 0)
  30892. instance = new InternalTimerThread();
  30893. const ScopedLock sl (instance->lock);
  30894. instance->addTimer (tim);
  30895. }
  30896. static inline void remove (Timer* const tim) throw()
  30897. {
  30898. if (instance != 0)
  30899. {
  30900. const ScopedLock sl (instance->lock);
  30901. instance->removeTimer (tim);
  30902. }
  30903. }
  30904. static inline void resetCounter (Timer* const tim,
  30905. const int newCounter) throw()
  30906. {
  30907. if (instance != 0)
  30908. {
  30909. tim->countdownMs = newCounter;
  30910. tim->periodMs = newCounter;
  30911. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30912. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30913. {
  30914. const ScopedLock sl (instance->lock);
  30915. instance->removeTimer (tim);
  30916. instance->addTimer (tim);
  30917. }
  30918. }
  30919. }
  30920. private:
  30921. friend class Timer;
  30922. static InternalTimerThread* instance;
  30923. static CriticalSection lock;
  30924. Timer* volatile firstTimer;
  30925. Atomic <int> callbackNeeded;
  30926. void addTimer (Timer* const t) throw()
  30927. {
  30928. #if JUCE_DEBUG
  30929. Timer* tt = firstTimer;
  30930. while (tt != 0)
  30931. {
  30932. // trying to add a timer that's already here - shouldn't get to this point,
  30933. // so if you get this assertion, let me know!
  30934. jassert (tt != t);
  30935. tt = tt->next;
  30936. }
  30937. jassert (t->previous == 0 && t->next == 0);
  30938. #endif
  30939. Timer* i = firstTimer;
  30940. if (i == 0 || i->countdownMs > t->countdownMs)
  30941. {
  30942. t->next = firstTimer;
  30943. firstTimer = t;
  30944. }
  30945. else
  30946. {
  30947. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30948. i = i->next;
  30949. jassert (i != 0);
  30950. t->next = i->next;
  30951. t->previous = i;
  30952. i->next = t;
  30953. }
  30954. if (t->next != 0)
  30955. t->next->previous = t;
  30956. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30957. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30958. notify();
  30959. }
  30960. void removeTimer (Timer* const t) throw()
  30961. {
  30962. #if JUCE_DEBUG
  30963. Timer* tt = firstTimer;
  30964. bool found = false;
  30965. while (tt != 0)
  30966. {
  30967. if (tt == t)
  30968. {
  30969. found = true;
  30970. break;
  30971. }
  30972. tt = tt->next;
  30973. }
  30974. // trying to remove a timer that's not here - shouldn't get to this point,
  30975. // so if you get this assertion, let me know!
  30976. jassert (found);
  30977. #endif
  30978. if (t->previous != 0)
  30979. {
  30980. jassert (firstTimer != t);
  30981. t->previous->next = t->next;
  30982. }
  30983. else
  30984. {
  30985. jassert (firstTimer == t);
  30986. firstTimer = t->next;
  30987. }
  30988. if (t->next != 0)
  30989. t->next->previous = t->previous;
  30990. t->next = 0;
  30991. t->previous = 0;
  30992. }
  30993. void decrementAllCounters (const int numMillisecs) const
  30994. {
  30995. Timer* t = firstTimer;
  30996. while (t != 0)
  30997. {
  30998. t->countdownMs -= numMillisecs;
  30999. t = t->next;
  31000. }
  31001. }
  31002. void handleAsyncUpdate()
  31003. {
  31004. startThread (7);
  31005. }
  31006. InternalTimerThread (const InternalTimerThread&);
  31007. InternalTimerThread& operator= (const InternalTimerThread&);
  31008. };
  31009. InternalTimerThread* InternalTimerThread::instance = 0;
  31010. CriticalSection InternalTimerThread::lock;
  31011. void juce_callAnyTimersSynchronously()
  31012. {
  31013. InternalTimerThread::callAnyTimersSynchronously();
  31014. }
  31015. #if JUCE_DEBUG
  31016. static SortedSet <Timer*> activeTimers;
  31017. #endif
  31018. Timer::Timer() throw()
  31019. : countdownMs (0),
  31020. periodMs (0),
  31021. previous (0),
  31022. next (0)
  31023. {
  31024. #if JUCE_DEBUG
  31025. activeTimers.add (this);
  31026. #endif
  31027. }
  31028. Timer::Timer (const Timer&) throw()
  31029. : countdownMs (0),
  31030. periodMs (0),
  31031. previous (0),
  31032. next (0)
  31033. {
  31034. #if JUCE_DEBUG
  31035. activeTimers.add (this);
  31036. #endif
  31037. }
  31038. Timer::~Timer()
  31039. {
  31040. stopTimer();
  31041. #if JUCE_DEBUG
  31042. activeTimers.removeValue (this);
  31043. #endif
  31044. }
  31045. void Timer::startTimer (const int interval) throw()
  31046. {
  31047. const ScopedLock sl (InternalTimerThread::lock);
  31048. #if JUCE_DEBUG
  31049. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31050. jassert (activeTimers.contains (this));
  31051. #endif
  31052. if (periodMs == 0)
  31053. {
  31054. countdownMs = interval;
  31055. periodMs = jmax (1, interval);
  31056. InternalTimerThread::add (this);
  31057. }
  31058. else
  31059. {
  31060. InternalTimerThread::resetCounter (this, interval);
  31061. }
  31062. }
  31063. void Timer::stopTimer() throw()
  31064. {
  31065. const ScopedLock sl (InternalTimerThread::lock);
  31066. #if JUCE_DEBUG
  31067. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31068. jassert (activeTimers.contains (this));
  31069. #endif
  31070. if (periodMs > 0)
  31071. {
  31072. InternalTimerThread::remove (this);
  31073. periodMs = 0;
  31074. }
  31075. }
  31076. END_JUCE_NAMESPACE
  31077. /*** End of inlined file: juce_Timer.cpp ***/
  31078. #endif
  31079. #if JUCE_BUILD_GUI
  31080. /*** Start of inlined file: juce_Component.cpp ***/
  31081. BEGIN_JUCE_NAMESPACE
  31082. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31083. enum ComponentMessageNumbers
  31084. {
  31085. customCommandMessage = 0x7fff0001,
  31086. exitModalStateMessage = 0x7fff0002
  31087. };
  31088. static uint32 nextComponentUID = 0;
  31089. Component* Component::currentlyFocusedComponent = 0;
  31090. Component::Component()
  31091. : parentComponent_ (0),
  31092. componentUID (++nextComponentUID),
  31093. numDeepMouseListeners (0),
  31094. lookAndFeel_ (0),
  31095. effect_ (0),
  31096. bufferedImage_ (0),
  31097. mouseListeners_ (0),
  31098. keyListeners_ (0),
  31099. componentFlags_ (0)
  31100. {
  31101. }
  31102. Component::Component (const String& name)
  31103. : componentName_ (name),
  31104. parentComponent_ (0),
  31105. componentUID (++nextComponentUID),
  31106. numDeepMouseListeners (0),
  31107. lookAndFeel_ (0),
  31108. effect_ (0),
  31109. bufferedImage_ (0),
  31110. mouseListeners_ (0),
  31111. keyListeners_ (0),
  31112. componentFlags_ (0)
  31113. {
  31114. }
  31115. Component::~Component()
  31116. {
  31117. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31118. if (parentComponent_ != 0)
  31119. {
  31120. parentComponent_->removeChildComponent (this);
  31121. }
  31122. else if ((currentlyFocusedComponent == this)
  31123. || isParentOf (currentlyFocusedComponent))
  31124. {
  31125. giveAwayFocus();
  31126. }
  31127. if (flags.hasHeavyweightPeerFlag)
  31128. removeFromDesktop();
  31129. for (int i = childComponentList_.size(); --i >= 0;)
  31130. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31131. delete mouseListeners_;
  31132. delete keyListeners_;
  31133. }
  31134. void Component::setName (const String& name)
  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. if (componentName_ != name)
  31140. {
  31141. componentName_ = name;
  31142. if (flags.hasHeavyweightPeerFlag)
  31143. {
  31144. ComponentPeer* const peer = getPeer();
  31145. jassert (peer != 0);
  31146. if (peer != 0)
  31147. peer->setTitle (name);
  31148. }
  31149. BailOutChecker checker (this);
  31150. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31151. }
  31152. }
  31153. void Component::setVisible (bool shouldBeVisible)
  31154. {
  31155. if (flags.visibleFlag != shouldBeVisible)
  31156. {
  31157. // if component methods are being called from threads other than the message
  31158. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31159. checkMessageManagerIsLocked
  31160. SafePointer<Component> safePointer (this);
  31161. flags.visibleFlag = shouldBeVisible;
  31162. internalRepaint (0, 0, getWidth(), getHeight());
  31163. sendFakeMouseMove();
  31164. if (! shouldBeVisible)
  31165. {
  31166. if (currentlyFocusedComponent == this
  31167. || isParentOf (currentlyFocusedComponent))
  31168. {
  31169. if (parentComponent_ != 0)
  31170. parentComponent_->grabKeyboardFocus();
  31171. else
  31172. giveAwayFocus();
  31173. }
  31174. }
  31175. if (safePointer != 0)
  31176. {
  31177. sendVisibilityChangeMessage();
  31178. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31179. {
  31180. ComponentPeer* const peer = getPeer();
  31181. jassert (peer != 0);
  31182. if (peer != 0)
  31183. {
  31184. peer->setVisible (shouldBeVisible);
  31185. internalHierarchyChanged();
  31186. }
  31187. }
  31188. }
  31189. }
  31190. }
  31191. void Component::visibilityChanged()
  31192. {
  31193. }
  31194. void Component::sendVisibilityChangeMessage()
  31195. {
  31196. BailOutChecker checker (this);
  31197. visibilityChanged();
  31198. if (! checker.shouldBailOut())
  31199. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31200. }
  31201. bool Component::isShowing() const
  31202. {
  31203. if (flags.visibleFlag)
  31204. {
  31205. if (parentComponent_ != 0)
  31206. {
  31207. return parentComponent_->isShowing();
  31208. }
  31209. else
  31210. {
  31211. const ComponentPeer* const peer = getPeer();
  31212. return peer != 0 && ! peer->isMinimised();
  31213. }
  31214. }
  31215. return false;
  31216. }
  31217. class FadeOutProxyComponent : public Component,
  31218. public Timer
  31219. {
  31220. public:
  31221. FadeOutProxyComponent (Component* comp,
  31222. const int fadeLengthMs,
  31223. const int deltaXToMove,
  31224. const int deltaYToMove,
  31225. const float scaleFactorAtEnd)
  31226. : lastTime (0),
  31227. alpha (1.0f),
  31228. scale (1.0f)
  31229. {
  31230. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31231. setBounds (comp->getBounds());
  31232. comp->getParentComponent()->addAndMakeVisible (this);
  31233. toBehind (comp);
  31234. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31235. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31236. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31237. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31238. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31239. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31240. setInterceptsMouseClicks (false, false);
  31241. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31242. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31243. }
  31244. ~FadeOutProxyComponent()
  31245. {
  31246. }
  31247. void paint (Graphics& g)
  31248. {
  31249. g.setOpacity (alpha);
  31250. g.drawImage (image,
  31251. 0, 0, getWidth(), getHeight(),
  31252. 0, 0, image.getWidth(), image.getHeight());
  31253. }
  31254. void timerCallback()
  31255. {
  31256. const uint32 now = Time::getMillisecondCounter();
  31257. if (lastTime == 0)
  31258. lastTime = now;
  31259. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31260. lastTime = now;
  31261. alpha += alphaChangePerMs * msPassed;
  31262. if (alpha > 0)
  31263. {
  31264. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31265. {
  31266. centreX += xChangePerMs * msPassed;
  31267. centreY += yChangePerMs * msPassed;
  31268. scale += scaleChangePerMs * msPassed;
  31269. const int w = roundToInt (image.getWidth() * scale);
  31270. const int h = roundToInt (image.getHeight() * scale);
  31271. setBounds (roundToInt (centreX) - w / 2,
  31272. roundToInt (centreY) - h / 2,
  31273. w, h);
  31274. }
  31275. repaint();
  31276. }
  31277. else
  31278. {
  31279. delete this;
  31280. }
  31281. }
  31282. juce_UseDebuggingNewOperator
  31283. private:
  31284. Image image;
  31285. uint32 lastTime;
  31286. float alpha, alphaChangePerMs;
  31287. float centreX, xChangePerMs;
  31288. float centreY, yChangePerMs;
  31289. float scale, scaleChangePerMs;
  31290. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31291. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31292. };
  31293. void Component::fadeOutComponent (const int millisecondsToFade,
  31294. const int deltaXToMove,
  31295. const int deltaYToMove,
  31296. const float scaleFactorAtEnd)
  31297. {
  31298. //xxx won't work for comps without parents
  31299. if (isShowing() && millisecondsToFade > 0)
  31300. new FadeOutProxyComponent (this, millisecondsToFade,
  31301. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31302. setVisible (false);
  31303. }
  31304. bool Component::isValidComponent() const
  31305. {
  31306. return (this != 0) && isValidMessageListener();
  31307. }
  31308. void* Component::getWindowHandle() const
  31309. {
  31310. const ComponentPeer* const peer = getPeer();
  31311. if (peer != 0)
  31312. return peer->getNativeHandle();
  31313. return 0;
  31314. }
  31315. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31316. {
  31317. // if component methods are being called from threads other than the message
  31318. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31319. checkMessageManagerIsLocked
  31320. if (isOpaque())
  31321. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31322. else
  31323. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31324. int currentStyleFlags = 0;
  31325. // don't use getPeer(), so that we only get the peer that's specifically
  31326. // for this comp, and not for one of its parents.
  31327. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31328. if (peer != 0)
  31329. currentStyleFlags = peer->getStyleFlags();
  31330. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31331. {
  31332. SafePointer<Component> safePointer (this);
  31333. #if JUCE_LINUX
  31334. // it's wise to give the component a non-zero size before
  31335. // putting it on the desktop, as X windows get confused by this, and
  31336. // a (1, 1) minimum size is enforced here.
  31337. setSize (jmax (1, getWidth()),
  31338. jmax (1, getHeight()));
  31339. #endif
  31340. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31341. bool wasFullscreen = false;
  31342. bool wasMinimised = false;
  31343. ComponentBoundsConstrainer* currentConstainer = 0;
  31344. Rectangle<int> oldNonFullScreenBounds;
  31345. if (peer != 0)
  31346. {
  31347. wasFullscreen = peer->isFullScreen();
  31348. wasMinimised = peer->isMinimised();
  31349. currentConstainer = peer->getConstrainer();
  31350. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31351. removeFromDesktop();
  31352. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31353. }
  31354. if (parentComponent_ != 0)
  31355. parentComponent_->removeChildComponent (this);
  31356. if (safePointer != 0)
  31357. {
  31358. flags.hasHeavyweightPeerFlag = true;
  31359. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31360. Desktop::getInstance().addDesktopComponent (this);
  31361. bounds_.setPosition (topLeft);
  31362. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31363. peer->setVisible (isVisible());
  31364. if (wasFullscreen)
  31365. {
  31366. peer->setFullScreen (true);
  31367. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31368. }
  31369. if (wasMinimised)
  31370. peer->setMinimised (true);
  31371. if (isAlwaysOnTop())
  31372. peer->setAlwaysOnTop (true);
  31373. peer->setConstrainer (currentConstainer);
  31374. repaint();
  31375. }
  31376. internalHierarchyChanged();
  31377. }
  31378. }
  31379. void Component::removeFromDesktop()
  31380. {
  31381. // if component methods are being called from threads other than the message
  31382. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31383. checkMessageManagerIsLocked
  31384. if (flags.hasHeavyweightPeerFlag)
  31385. {
  31386. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31387. flags.hasHeavyweightPeerFlag = false;
  31388. jassert (peer != 0);
  31389. delete peer;
  31390. Desktop::getInstance().removeDesktopComponent (this);
  31391. }
  31392. }
  31393. bool Component::isOnDesktop() const throw()
  31394. {
  31395. return flags.hasHeavyweightPeerFlag;
  31396. }
  31397. void Component::userTriedToCloseWindow()
  31398. {
  31399. /* This means that the user's trying to get rid of your window with the 'close window' system
  31400. menu option (on windows) or possibly the task manager - you should really handle this
  31401. and delete or hide your component in an appropriate way.
  31402. If you want to ignore the event and don't want to trigger this assertion, just override
  31403. this method and do nothing.
  31404. */
  31405. jassertfalse;
  31406. }
  31407. void Component::minimisationStateChanged (bool)
  31408. {
  31409. }
  31410. void Component::setOpaque (const bool shouldBeOpaque)
  31411. {
  31412. if (shouldBeOpaque != flags.opaqueFlag)
  31413. {
  31414. flags.opaqueFlag = shouldBeOpaque;
  31415. if (flags.hasHeavyweightPeerFlag)
  31416. {
  31417. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31418. if (peer != 0)
  31419. {
  31420. // to make it recreate the heavyweight window
  31421. addToDesktop (peer->getStyleFlags());
  31422. }
  31423. }
  31424. repaint();
  31425. }
  31426. }
  31427. bool Component::isOpaque() const throw()
  31428. {
  31429. return flags.opaqueFlag;
  31430. }
  31431. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31432. {
  31433. if (shouldBeBuffered != flags.bufferToImageFlag)
  31434. {
  31435. bufferedImage_ = Image::null;
  31436. flags.bufferToImageFlag = shouldBeBuffered;
  31437. }
  31438. }
  31439. void Component::toFront (const bool setAsForeground)
  31440. {
  31441. // if component methods are being called from threads other than the message
  31442. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31443. checkMessageManagerIsLocked
  31444. if (flags.hasHeavyweightPeerFlag)
  31445. {
  31446. ComponentPeer* const peer = getPeer();
  31447. if (peer != 0)
  31448. {
  31449. peer->toFront (setAsForeground);
  31450. if (setAsForeground && ! hasKeyboardFocus (true))
  31451. grabKeyboardFocus();
  31452. }
  31453. }
  31454. else if (parentComponent_ != 0)
  31455. {
  31456. Array<Component*>& childList = parentComponent_->childComponentList_;
  31457. if (childList.getLast() != this)
  31458. {
  31459. const int index = childList.indexOf (this);
  31460. if (index >= 0)
  31461. {
  31462. int insertIndex = -1;
  31463. if (! flags.alwaysOnTopFlag)
  31464. {
  31465. insertIndex = childList.size() - 1;
  31466. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31467. --insertIndex;
  31468. }
  31469. if (index != insertIndex)
  31470. {
  31471. childList.move (index, insertIndex);
  31472. sendFakeMouseMove();
  31473. repaintParent();
  31474. }
  31475. }
  31476. }
  31477. if (setAsForeground)
  31478. {
  31479. internalBroughtToFront();
  31480. grabKeyboardFocus();
  31481. }
  31482. }
  31483. }
  31484. void Component::toBehind (Component* const other)
  31485. {
  31486. if (other != 0 && other != this)
  31487. {
  31488. // the two components must belong to the same parent..
  31489. jassert (parentComponent_ == other->parentComponent_);
  31490. if (parentComponent_ != 0)
  31491. {
  31492. Array<Component*>& childList = parentComponent_->childComponentList_;
  31493. const int index = childList.indexOf (this);
  31494. if (index >= 0 && childList [index + 1] != other)
  31495. {
  31496. int otherIndex = childList.indexOf (other);
  31497. if (otherIndex >= 0)
  31498. {
  31499. if (index < otherIndex)
  31500. --otherIndex;
  31501. childList.move (index, otherIndex);
  31502. sendFakeMouseMove();
  31503. repaintParent();
  31504. }
  31505. }
  31506. }
  31507. else if (isOnDesktop())
  31508. {
  31509. jassert (other->isOnDesktop());
  31510. if (other->isOnDesktop())
  31511. {
  31512. ComponentPeer* const us = getPeer();
  31513. ComponentPeer* const them = other->getPeer();
  31514. jassert (us != 0 && them != 0);
  31515. if (us != 0 && them != 0)
  31516. us->toBehind (them);
  31517. }
  31518. }
  31519. }
  31520. }
  31521. void Component::toBack()
  31522. {
  31523. Array<Component*>& childList = parentComponent_->childComponentList_;
  31524. if (isOnDesktop())
  31525. {
  31526. jassertfalse; //xxx need to add this to native window
  31527. }
  31528. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31529. {
  31530. const int index = childList.indexOf (this);
  31531. if (index > 0)
  31532. {
  31533. int insertIndex = 0;
  31534. if (flags.alwaysOnTopFlag)
  31535. {
  31536. while (insertIndex < childList.size()
  31537. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31538. {
  31539. ++insertIndex;
  31540. }
  31541. }
  31542. if (index != insertIndex)
  31543. {
  31544. childList.move (index, insertIndex);
  31545. sendFakeMouseMove();
  31546. repaintParent();
  31547. }
  31548. }
  31549. }
  31550. }
  31551. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31552. {
  31553. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31554. {
  31555. flags.alwaysOnTopFlag = shouldStayOnTop;
  31556. if (isOnDesktop())
  31557. {
  31558. ComponentPeer* const peer = getPeer();
  31559. jassert (peer != 0);
  31560. if (peer != 0)
  31561. {
  31562. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31563. {
  31564. // some kinds of peer can't change their always-on-top status, so
  31565. // for these, we'll need to create a new window
  31566. const int oldFlags = peer->getStyleFlags();
  31567. removeFromDesktop();
  31568. addToDesktop (oldFlags);
  31569. }
  31570. }
  31571. }
  31572. if (shouldStayOnTop)
  31573. toFront (false);
  31574. internalHierarchyChanged();
  31575. }
  31576. }
  31577. bool Component::isAlwaysOnTop() const throw()
  31578. {
  31579. return flags.alwaysOnTopFlag;
  31580. }
  31581. int Component::proportionOfWidth (const float proportion) const throw()
  31582. {
  31583. return roundToInt (proportion * bounds_.getWidth());
  31584. }
  31585. int Component::proportionOfHeight (const float proportion) const throw()
  31586. {
  31587. return roundToInt (proportion * bounds_.getHeight());
  31588. }
  31589. int Component::getParentWidth() const throw()
  31590. {
  31591. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31592. : getParentMonitorArea().getWidth();
  31593. }
  31594. int Component::getParentHeight() const throw()
  31595. {
  31596. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31597. : getParentMonitorArea().getHeight();
  31598. }
  31599. int Component::getScreenX() const
  31600. {
  31601. return getScreenPosition().getX();
  31602. }
  31603. int Component::getScreenY() const
  31604. {
  31605. return getScreenPosition().getY();
  31606. }
  31607. const Point<int> Component::getScreenPosition() const
  31608. {
  31609. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31610. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31611. : getPosition());
  31612. }
  31613. const Rectangle<int> Component::getScreenBounds() const
  31614. {
  31615. return bounds_.withPosition (getScreenPosition());
  31616. }
  31617. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31618. {
  31619. const Component* c = this;
  31620. Point<int> p (relativePosition);
  31621. do
  31622. {
  31623. if (c->flags.hasHeavyweightPeerFlag)
  31624. return c->getPeer()->relativePositionToGlobal (p);
  31625. p += c->getPosition();
  31626. c = c->parentComponent_;
  31627. }
  31628. while (c != 0);
  31629. return p;
  31630. }
  31631. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31632. {
  31633. if (flags.hasHeavyweightPeerFlag)
  31634. {
  31635. return getPeer()->globalPositionToRelative (screenPosition);
  31636. }
  31637. else
  31638. {
  31639. if (parentComponent_ != 0)
  31640. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31641. return screenPosition - getPosition();
  31642. }
  31643. }
  31644. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31645. {
  31646. Point<int> p (positionRelativeToThis);
  31647. if (targetComponent != 0)
  31648. {
  31649. const Component* c = this;
  31650. do
  31651. {
  31652. if (c == targetComponent)
  31653. return p;
  31654. if (c->flags.hasHeavyweightPeerFlag)
  31655. {
  31656. p = c->getPeer()->relativePositionToGlobal (p);
  31657. break;
  31658. }
  31659. p += c->getPosition();
  31660. c = c->parentComponent_;
  31661. }
  31662. while (c != 0);
  31663. p = targetComponent->globalPositionToRelative (p);
  31664. }
  31665. return p;
  31666. }
  31667. void Component::setBounds (const int x, const int y, int w, int h)
  31668. {
  31669. // if component methods are being called from threads other than the message
  31670. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31671. checkMessageManagerIsLocked
  31672. if (w < 0) w = 0;
  31673. if (h < 0) h = 0;
  31674. const bool wasResized = (getWidth() != w || getHeight() != h);
  31675. const bool wasMoved = (getX() != x || getY() != y);
  31676. #if JUCE_DEBUG
  31677. // It's a very bad idea to try to resize a window during its paint() method!
  31678. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31679. #endif
  31680. if (wasMoved || wasResized)
  31681. {
  31682. if (flags.visibleFlag)
  31683. {
  31684. // send a fake mouse move to trigger enter/exit messages if needed..
  31685. sendFakeMouseMove();
  31686. if (! flags.hasHeavyweightPeerFlag)
  31687. repaintParent();
  31688. }
  31689. bounds_.setBounds (x, y, w, h);
  31690. if (wasResized)
  31691. repaint();
  31692. else if (! flags.hasHeavyweightPeerFlag)
  31693. repaintParent();
  31694. if (flags.hasHeavyweightPeerFlag)
  31695. {
  31696. ComponentPeer* const peer = getPeer();
  31697. if (peer != 0)
  31698. {
  31699. if (wasMoved && wasResized)
  31700. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31701. else if (wasMoved)
  31702. peer->setPosition (getX(), getY());
  31703. else if (wasResized)
  31704. peer->setSize (getWidth(), getHeight());
  31705. }
  31706. }
  31707. sendMovedResizedMessages (wasMoved, wasResized);
  31708. }
  31709. }
  31710. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31711. {
  31712. JUCE_TRY
  31713. {
  31714. if (wasMoved)
  31715. moved();
  31716. if (wasResized)
  31717. {
  31718. resized();
  31719. for (int i = childComponentList_.size(); --i >= 0;)
  31720. {
  31721. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31722. i = jmin (i, childComponentList_.size());
  31723. }
  31724. }
  31725. BailOutChecker checker (this);
  31726. if (parentComponent_ != 0)
  31727. parentComponent_->childBoundsChanged (this);
  31728. if (! checker.shouldBailOut())
  31729. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31730. *this, wasMoved, wasResized);
  31731. }
  31732. JUCE_CATCH_EXCEPTION
  31733. }
  31734. void Component::setSize (const int w, const int h)
  31735. {
  31736. setBounds (getX(), getY(), w, h);
  31737. }
  31738. void Component::setTopLeftPosition (const int x, const int y)
  31739. {
  31740. setBounds (x, y, getWidth(), getHeight());
  31741. }
  31742. void Component::setTopRightPosition (const int x, const int y)
  31743. {
  31744. setTopLeftPosition (x - getWidth(), y);
  31745. }
  31746. void Component::setBounds (const Rectangle<int>& r)
  31747. {
  31748. setBounds (r.getX(),
  31749. r.getY(),
  31750. r.getWidth(),
  31751. r.getHeight());
  31752. }
  31753. void Component::setBoundsRelative (const float x, const float y,
  31754. const float w, const float h)
  31755. {
  31756. const int pw = getParentWidth();
  31757. const int ph = getParentHeight();
  31758. setBounds (roundToInt (x * pw),
  31759. roundToInt (y * ph),
  31760. roundToInt (w * pw),
  31761. roundToInt (h * ph));
  31762. }
  31763. void Component::setCentrePosition (const int x, const int y)
  31764. {
  31765. setTopLeftPosition (x - getWidth() / 2,
  31766. y - getHeight() / 2);
  31767. }
  31768. void Component::setCentreRelative (const float x, const float y)
  31769. {
  31770. setCentrePosition (roundToInt (getParentWidth() * x),
  31771. roundToInt (getParentHeight() * y));
  31772. }
  31773. void Component::centreWithSize (const int width, const int height)
  31774. {
  31775. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  31776. setBounds (parentArea.getCentreX() - width / 2,
  31777. parentArea.getCentreY() - height / 2,
  31778. width, height);
  31779. }
  31780. void Component::setBoundsInset (const BorderSize& borders)
  31781. {
  31782. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  31783. }
  31784. void Component::setBoundsToFit (int x, int y, int width, int height,
  31785. const Justification& justification,
  31786. const bool onlyReduceInSize)
  31787. {
  31788. // it's no good calling this method unless both the component and
  31789. // target rectangle have a finite size.
  31790. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31791. if (getWidth() > 0 && getHeight() > 0
  31792. && width > 0 && height > 0)
  31793. {
  31794. int newW, newH;
  31795. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31796. {
  31797. newW = getWidth();
  31798. newH = getHeight();
  31799. }
  31800. else
  31801. {
  31802. const double imageRatio = getHeight() / (double) getWidth();
  31803. const double targetRatio = height / (double) width;
  31804. if (imageRatio <= targetRatio)
  31805. {
  31806. newW = width;
  31807. newH = jmin (height, roundToInt (newW * imageRatio));
  31808. }
  31809. else
  31810. {
  31811. newH = height;
  31812. newW = jmin (width, roundToInt (newH / imageRatio));
  31813. }
  31814. }
  31815. if (newW > 0 && newH > 0)
  31816. {
  31817. int newX, newY;
  31818. justification.applyToRectangle (newX, newY, newW, newH,
  31819. x, y, width, height);
  31820. setBounds (newX, newY, newW, newH);
  31821. }
  31822. }
  31823. }
  31824. bool Component::hitTest (int x, int y)
  31825. {
  31826. if (! flags.ignoresMouseClicksFlag)
  31827. return true;
  31828. if (flags.allowChildMouseClicksFlag)
  31829. {
  31830. for (int i = getNumChildComponents(); --i >= 0;)
  31831. {
  31832. Component* const c = getChildComponent (i);
  31833. if (c->isVisible()
  31834. && c->bounds_.contains (x, y)
  31835. && c->hitTest (x - c->getX(),
  31836. y - c->getY()))
  31837. {
  31838. return true;
  31839. }
  31840. }
  31841. }
  31842. return false;
  31843. }
  31844. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31845. const bool allowClicksOnChildComponents) throw()
  31846. {
  31847. flags.ignoresMouseClicksFlag = ! allowClicks;
  31848. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31849. }
  31850. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31851. bool& allowsClicksOnChildComponents) const throw()
  31852. {
  31853. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31854. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31855. }
  31856. bool Component::contains (const int x, const int y)
  31857. {
  31858. if (((unsigned int) x) < (unsigned int) getWidth()
  31859. && ((unsigned int) y) < (unsigned int) getHeight()
  31860. && hitTest (x, y))
  31861. {
  31862. if (parentComponent_ != 0)
  31863. {
  31864. return parentComponent_->contains (x + getX(),
  31865. y + getY());
  31866. }
  31867. else if (flags.hasHeavyweightPeerFlag)
  31868. {
  31869. const ComponentPeer* const peer = getPeer();
  31870. if (peer != 0)
  31871. return peer->contains (Point<int> (x, y), true);
  31872. }
  31873. }
  31874. return false;
  31875. }
  31876. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31877. {
  31878. if (! contains (x, y))
  31879. return false;
  31880. Component* p = this;
  31881. while (p->parentComponent_ != 0)
  31882. {
  31883. x += p->getX();
  31884. y += p->getY();
  31885. p = p->parentComponent_;
  31886. }
  31887. const Component* const c = p->getComponentAt (x, y);
  31888. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31889. }
  31890. Component* Component::getComponentAt (const Point<int>& position)
  31891. {
  31892. return getComponentAt (position.getX(), position.getY());
  31893. }
  31894. Component* Component::getComponentAt (const int x, const int y)
  31895. {
  31896. if (flags.visibleFlag
  31897. && ((unsigned int) x) < (unsigned int) getWidth()
  31898. && ((unsigned int) y) < (unsigned int) getHeight()
  31899. && hitTest (x, y))
  31900. {
  31901. for (int i = childComponentList_.size(); --i >= 0;)
  31902. {
  31903. Component* const child = childComponentList_.getUnchecked(i);
  31904. Component* const c = child->getComponentAt (x - child->getX(),
  31905. y - child->getY());
  31906. if (c != 0)
  31907. return c;
  31908. }
  31909. return this;
  31910. }
  31911. return 0;
  31912. }
  31913. void Component::addChildComponent (Component* const child, int zOrder)
  31914. {
  31915. // if component methods are being called from threads other than the message
  31916. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31917. checkMessageManagerIsLocked
  31918. if (child != 0 && child->parentComponent_ != this)
  31919. {
  31920. if (child->parentComponent_ != 0)
  31921. child->parentComponent_->removeChildComponent (child);
  31922. else
  31923. child->removeFromDesktop();
  31924. child->parentComponent_ = this;
  31925. if (child->isVisible())
  31926. child->repaintParent();
  31927. if (! child->isAlwaysOnTop())
  31928. {
  31929. if (zOrder < 0 || zOrder > childComponentList_.size())
  31930. zOrder = childComponentList_.size();
  31931. while (zOrder > 0)
  31932. {
  31933. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31934. break;
  31935. --zOrder;
  31936. }
  31937. }
  31938. childComponentList_.insert (zOrder, child);
  31939. child->internalHierarchyChanged();
  31940. internalChildrenChanged();
  31941. }
  31942. }
  31943. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31944. {
  31945. if (child != 0)
  31946. {
  31947. child->setVisible (true);
  31948. addChildComponent (child, zOrder);
  31949. }
  31950. }
  31951. void Component::removeChildComponent (Component* const child)
  31952. {
  31953. removeChildComponent (childComponentList_.indexOf (child));
  31954. }
  31955. Component* Component::removeChildComponent (const int index)
  31956. {
  31957. // if component methods are being called from threads other than the message
  31958. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31959. checkMessageManagerIsLocked
  31960. Component* const child = childComponentList_ [index];
  31961. if (child != 0)
  31962. {
  31963. sendFakeMouseMove();
  31964. child->repaintParent();
  31965. childComponentList_.remove (index);
  31966. child->parentComponent_ = 0;
  31967. JUCE_TRY
  31968. {
  31969. if ((currentlyFocusedComponent == child)
  31970. || child->isParentOf (currentlyFocusedComponent))
  31971. {
  31972. // get rid first to force the grabKeyboardFocus to change to us.
  31973. giveAwayFocus();
  31974. grabKeyboardFocus();
  31975. }
  31976. }
  31977. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31978. catch (const std::exception& e)
  31979. {
  31980. currentlyFocusedComponent = 0;
  31981. Desktop::getInstance().triggerFocusCallback();
  31982. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31983. }
  31984. catch (...)
  31985. {
  31986. currentlyFocusedComponent = 0;
  31987. Desktop::getInstance().triggerFocusCallback();
  31988. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31989. }
  31990. #endif
  31991. child->internalHierarchyChanged();
  31992. internalChildrenChanged();
  31993. }
  31994. return child;
  31995. }
  31996. void Component::removeAllChildren()
  31997. {
  31998. while (childComponentList_.size() > 0)
  31999. removeChildComponent (childComponentList_.size() - 1);
  32000. }
  32001. void Component::deleteAllChildren()
  32002. {
  32003. while (childComponentList_.size() > 0)
  32004. delete (removeChildComponent (childComponentList_.size() - 1));
  32005. }
  32006. int Component::getNumChildComponents() const throw()
  32007. {
  32008. return childComponentList_.size();
  32009. }
  32010. Component* Component::getChildComponent (const int index) const throw()
  32011. {
  32012. return childComponentList_ [index];
  32013. }
  32014. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32015. {
  32016. return childComponentList_.indexOf (const_cast <Component*> (child));
  32017. }
  32018. Component* Component::getTopLevelComponent() const throw()
  32019. {
  32020. const Component* comp = this;
  32021. while (comp->parentComponent_ != 0)
  32022. comp = comp->parentComponent_;
  32023. return const_cast <Component*> (comp);
  32024. }
  32025. bool Component::isParentOf (const Component* possibleChild) const throw()
  32026. {
  32027. if (! possibleChild->isValidComponent())
  32028. {
  32029. jassert (possibleChild == 0);
  32030. return false;
  32031. }
  32032. while (possibleChild != 0)
  32033. {
  32034. possibleChild = possibleChild->parentComponent_;
  32035. if (possibleChild == this)
  32036. return true;
  32037. }
  32038. return false;
  32039. }
  32040. void Component::parentHierarchyChanged()
  32041. {
  32042. }
  32043. void Component::childrenChanged()
  32044. {
  32045. }
  32046. void Component::internalChildrenChanged()
  32047. {
  32048. if (componentListeners.isEmpty())
  32049. {
  32050. childrenChanged();
  32051. }
  32052. else
  32053. {
  32054. BailOutChecker checker (this);
  32055. childrenChanged();
  32056. if (! checker.shouldBailOut())
  32057. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32058. }
  32059. }
  32060. void Component::internalHierarchyChanged()
  32061. {
  32062. BailOutChecker checker (this);
  32063. parentHierarchyChanged();
  32064. if (checker.shouldBailOut())
  32065. return;
  32066. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32067. if (checker.shouldBailOut())
  32068. return;
  32069. for (int i = childComponentList_.size(); --i >= 0;)
  32070. {
  32071. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32072. if (checker.shouldBailOut())
  32073. {
  32074. // you really shouldn't delete the parent component during a callback telling you
  32075. // that it's changed..
  32076. jassertfalse;
  32077. return;
  32078. }
  32079. i = jmin (i, childComponentList_.size());
  32080. }
  32081. }
  32082. void* Component::runModalLoopCallback (void* userData)
  32083. {
  32084. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32085. }
  32086. int Component::runModalLoop()
  32087. {
  32088. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32089. {
  32090. // use a callback so this can be called from non-gui threads
  32091. return (int) (pointer_sized_int) MessageManager::getInstance()
  32092. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32093. }
  32094. if (! isCurrentlyModal())
  32095. enterModalState (true);
  32096. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32097. }
  32098. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32099. {
  32100. // if component methods are being called from threads other than the message
  32101. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32102. checkMessageManagerIsLocked
  32103. // Check for an attempt to make a component modal when it already is!
  32104. // This can cause nasty problems..
  32105. jassert (! flags.currentlyModalFlag);
  32106. if (! isCurrentlyModal())
  32107. {
  32108. ModalComponentManager::getInstance()->startModal (this, callback);
  32109. flags.currentlyModalFlag = true;
  32110. setVisible (true);
  32111. if (takeKeyboardFocus_)
  32112. grabKeyboardFocus();
  32113. }
  32114. }
  32115. void Component::exitModalState (const int returnValue)
  32116. {
  32117. if (isCurrentlyModal())
  32118. {
  32119. if (MessageManager::getInstance()->isThisTheMessageThread())
  32120. {
  32121. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32122. flags.currentlyModalFlag = false;
  32123. bringModalComponentToFront();
  32124. }
  32125. else
  32126. {
  32127. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32128. }
  32129. }
  32130. }
  32131. bool Component::isCurrentlyModal() const throw()
  32132. {
  32133. return flags.currentlyModalFlag
  32134. && getCurrentlyModalComponent() == this;
  32135. }
  32136. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32137. {
  32138. Component* const mc = getCurrentlyModalComponent();
  32139. return mc != 0
  32140. && mc != this
  32141. && (! mc->isParentOf (this))
  32142. && ! mc->canModalEventBeSentToComponent (this);
  32143. }
  32144. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32145. {
  32146. return ModalComponentManager::getInstance()->getNumModalComponents();
  32147. }
  32148. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32149. {
  32150. return ModalComponentManager::getInstance()->getModalComponent (index);
  32151. }
  32152. void Component::bringModalComponentToFront()
  32153. {
  32154. ComponentPeer* lastOne = 0;
  32155. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32156. {
  32157. Component* const c = getCurrentlyModalComponent (i);
  32158. if (c == 0)
  32159. break;
  32160. ComponentPeer* peer = c->getPeer();
  32161. if (peer != 0 && peer != lastOne)
  32162. {
  32163. if (lastOne == 0)
  32164. {
  32165. peer->toFront (true);
  32166. peer->grabFocus();
  32167. }
  32168. else
  32169. peer->toBehind (lastOne);
  32170. lastOne = peer;
  32171. }
  32172. }
  32173. }
  32174. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32175. {
  32176. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32177. }
  32178. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32179. {
  32180. return flags.bringToFrontOnClickFlag;
  32181. }
  32182. void Component::setMouseCursor (const MouseCursor& cursor)
  32183. {
  32184. if (cursor_ != cursor)
  32185. {
  32186. cursor_ = cursor;
  32187. if (flags.visibleFlag)
  32188. updateMouseCursor();
  32189. }
  32190. }
  32191. const MouseCursor Component::getMouseCursor()
  32192. {
  32193. return cursor_;
  32194. }
  32195. void Component::updateMouseCursor() const
  32196. {
  32197. sendFakeMouseMove();
  32198. }
  32199. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32200. {
  32201. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32202. }
  32203. void Component::repaintParent()
  32204. {
  32205. if (flags.visibleFlag)
  32206. internalRepaint (0, 0, getWidth(), getHeight());
  32207. }
  32208. void Component::repaint()
  32209. {
  32210. repaint (0, 0, getWidth(), getHeight());
  32211. }
  32212. void Component::repaint (const int x, const int y,
  32213. const int w, const int h)
  32214. {
  32215. bufferedImage_ = Image::null;
  32216. if (flags.visibleFlag)
  32217. internalRepaint (x, y, w, h);
  32218. }
  32219. void Component::repaint (const Rectangle<int>& area)
  32220. {
  32221. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32222. }
  32223. void Component::internalRepaint (int x, int y, int w, int h)
  32224. {
  32225. // if component methods are being called from threads other than the message
  32226. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32227. checkMessageManagerIsLocked
  32228. if (x < 0)
  32229. {
  32230. w += x;
  32231. x = 0;
  32232. }
  32233. if (x + w > getWidth())
  32234. w = getWidth() - x;
  32235. if (w > 0)
  32236. {
  32237. if (y < 0)
  32238. {
  32239. h += y;
  32240. y = 0;
  32241. }
  32242. if (y + h > getHeight())
  32243. h = getHeight() - y;
  32244. if (h > 0)
  32245. {
  32246. if (parentComponent_ != 0)
  32247. {
  32248. x += getX();
  32249. y += getY();
  32250. if (parentComponent_->flags.visibleFlag)
  32251. parentComponent_->internalRepaint (x, y, w, h);
  32252. }
  32253. else if (flags.hasHeavyweightPeerFlag)
  32254. {
  32255. ComponentPeer* const peer = getPeer();
  32256. if (peer != 0)
  32257. peer->repaint (Rectangle<int> (x, y, w, h));
  32258. }
  32259. }
  32260. }
  32261. }
  32262. void Component::renderComponent (Graphics& g)
  32263. {
  32264. const Rectangle<int> clipBounds (g.getClipBounds());
  32265. g.saveState();
  32266. clipObscuredRegions (g, clipBounds, 0, 0);
  32267. if (! g.isClipEmpty())
  32268. {
  32269. if (flags.bufferToImageFlag)
  32270. {
  32271. if (bufferedImage_.isNull())
  32272. {
  32273. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32274. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32275. Graphics imG (bufferedImage_);
  32276. paint (imG);
  32277. }
  32278. g.setColour (Colours::black);
  32279. g.drawImageAt (bufferedImage_, 0, 0);
  32280. }
  32281. else
  32282. {
  32283. paint (g);
  32284. }
  32285. }
  32286. g.restoreState();
  32287. for (int i = 0; i < childComponentList_.size(); ++i)
  32288. {
  32289. Component* const child = childComponentList_.getUnchecked (i);
  32290. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32291. {
  32292. g.saveState();
  32293. if (g.reduceClipRegion (child->getX(), child->getY(),
  32294. child->getWidth(), child->getHeight()))
  32295. {
  32296. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32297. {
  32298. const Component* const sibling = childComponentList_.getUnchecked (j);
  32299. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32300. g.excludeClipRegion (sibling->getBounds());
  32301. }
  32302. if (! g.isClipEmpty())
  32303. {
  32304. g.setOrigin (child->getX(), child->getY());
  32305. child->paintEntireComponent (g);
  32306. }
  32307. }
  32308. g.restoreState();
  32309. }
  32310. }
  32311. g.saveState();
  32312. paintOverChildren (g);
  32313. g.restoreState();
  32314. }
  32315. void Component::paintEntireComponent (Graphics& g)
  32316. {
  32317. jassert (! g.isClipEmpty());
  32318. #if JUCE_DEBUG
  32319. flags.isInsidePaintCall = true;
  32320. #endif
  32321. if (effect_ != 0)
  32322. {
  32323. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32324. getWidth(), getHeight(),
  32325. ! flags.opaqueFlag, Image::NativeImage);
  32326. {
  32327. Graphics g2 (effectImage);
  32328. renderComponent (g2);
  32329. }
  32330. effect_->applyEffect (effectImage, g);
  32331. }
  32332. else
  32333. {
  32334. renderComponent (g);
  32335. }
  32336. #if JUCE_DEBUG
  32337. flags.isInsidePaintCall = false;
  32338. #endif
  32339. }
  32340. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32341. const bool clipImageToComponentBounds)
  32342. {
  32343. Rectangle<int> r (areaToGrab);
  32344. if (clipImageToComponentBounds)
  32345. r = r.getIntersection (getLocalBounds());
  32346. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32347. jmax (1, r.getWidth()),
  32348. jmax (1, r.getHeight()),
  32349. true);
  32350. Graphics imageContext (componentImage);
  32351. imageContext.setOrigin (-r.getX(), -r.getY());
  32352. paintEntireComponent (imageContext);
  32353. return componentImage;
  32354. }
  32355. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32356. {
  32357. if (effect_ != effect)
  32358. {
  32359. effect_ = effect;
  32360. repaint();
  32361. }
  32362. }
  32363. LookAndFeel& Component::getLookAndFeel() const throw()
  32364. {
  32365. const Component* c = this;
  32366. do
  32367. {
  32368. if (c->lookAndFeel_ != 0)
  32369. return *(c->lookAndFeel_);
  32370. c = c->parentComponent_;
  32371. }
  32372. while (c != 0);
  32373. return LookAndFeel::getDefaultLookAndFeel();
  32374. }
  32375. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32376. {
  32377. if (lookAndFeel_ != newLookAndFeel)
  32378. {
  32379. lookAndFeel_ = newLookAndFeel;
  32380. sendLookAndFeelChange();
  32381. }
  32382. }
  32383. void Component::lookAndFeelChanged()
  32384. {
  32385. }
  32386. void Component::sendLookAndFeelChange()
  32387. {
  32388. repaint();
  32389. lookAndFeelChanged();
  32390. // (it's not a great idea to do anything that would delete this component
  32391. // during the lookAndFeelChanged() callback)
  32392. jassert (isValidComponent());
  32393. SafePointer<Component> safePointer (this);
  32394. for (int i = childComponentList_.size(); --i >= 0;)
  32395. {
  32396. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32397. if (safePointer == 0)
  32398. return;
  32399. i = jmin (i, childComponentList_.size());
  32400. }
  32401. }
  32402. static const Identifier getColourPropertyId (const int colourId)
  32403. {
  32404. String s;
  32405. s.preallocateStorage (18);
  32406. s << "jcclr_" << String::toHexString (colourId);
  32407. return s;
  32408. }
  32409. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32410. {
  32411. var* v = properties.getItem (getColourPropertyId (colourId));
  32412. if (v != 0)
  32413. return Colour ((int) *v);
  32414. if (inheritFromParent && parentComponent_ != 0)
  32415. return parentComponent_->findColour (colourId, true);
  32416. return getLookAndFeel().findColour (colourId);
  32417. }
  32418. bool Component::isColourSpecified (const int colourId) const
  32419. {
  32420. return properties.contains (getColourPropertyId (colourId));
  32421. }
  32422. void Component::removeColour (const int colourId)
  32423. {
  32424. if (properties.remove (getColourPropertyId (colourId)))
  32425. colourChanged();
  32426. }
  32427. void Component::setColour (const int colourId, const Colour& colour)
  32428. {
  32429. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32430. colourChanged();
  32431. }
  32432. void Component::copyAllExplicitColoursTo (Component& target) const
  32433. {
  32434. bool changed = false;
  32435. for (int i = properties.size(); --i >= 0;)
  32436. {
  32437. const Identifier name (properties.getName(i));
  32438. if (name.toString().startsWith ("jcclr_"))
  32439. if (target.properties.set (name, properties [name]))
  32440. changed = true;
  32441. }
  32442. if (changed)
  32443. target.colourChanged();
  32444. }
  32445. void Component::colourChanged()
  32446. {
  32447. }
  32448. const Rectangle<int> Component::getLocalBounds() const throw()
  32449. {
  32450. return Rectangle<int> (getWidth(), getHeight());
  32451. }
  32452. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  32453. {
  32454. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  32455. : Desktop::getInstance().getMainMonitorArea();
  32456. }
  32457. const Rectangle<int> Component::getUnclippedArea() const
  32458. {
  32459. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32460. Component* p = parentComponent_;
  32461. int px = getX();
  32462. int py = getY();
  32463. while (p != 0)
  32464. {
  32465. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32466. return Rectangle<int>();
  32467. px += p->getX();
  32468. py += p->getY();
  32469. p = p->parentComponent_;
  32470. }
  32471. return Rectangle<int> (x, y, w, h);
  32472. }
  32473. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32474. const int deltaX, const int deltaY) const
  32475. {
  32476. for (int i = childComponentList_.size(); --i >= 0;)
  32477. {
  32478. const Component* const c = childComponentList_.getUnchecked(i);
  32479. if (c->isVisible())
  32480. {
  32481. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32482. if (! newClip.isEmpty())
  32483. {
  32484. if (c->isOpaque())
  32485. {
  32486. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32487. }
  32488. else
  32489. {
  32490. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32491. c->getX() + deltaX,
  32492. c->getY() + deltaY);
  32493. }
  32494. }
  32495. }
  32496. }
  32497. }
  32498. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32499. {
  32500. result.clear();
  32501. const Rectangle<int> unclipped (getUnclippedArea());
  32502. if (! unclipped.isEmpty())
  32503. {
  32504. result.add (unclipped);
  32505. if (includeSiblings)
  32506. {
  32507. const Component* const c = getTopLevelComponent();
  32508. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32509. c->getLocalBounds(), this);
  32510. }
  32511. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32512. result.consolidate();
  32513. }
  32514. }
  32515. void Component::subtractObscuredRegions (RectangleList& result,
  32516. const Point<int>& delta,
  32517. const Rectangle<int>& clipRect,
  32518. const Component* const compToAvoid) const
  32519. {
  32520. for (int i = childComponentList_.size(); --i >= 0;)
  32521. {
  32522. const Component* const c = childComponentList_.getUnchecked(i);
  32523. if (c != compToAvoid && c->isVisible())
  32524. {
  32525. if (c->isOpaque())
  32526. {
  32527. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32528. childBounds.translate (delta.getX(), delta.getY());
  32529. result.subtract (childBounds);
  32530. }
  32531. else
  32532. {
  32533. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32534. newClip.translate (-c->getX(), -c->getY());
  32535. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32536. newClip, compToAvoid);
  32537. }
  32538. }
  32539. }
  32540. }
  32541. void Component::mouseEnter (const MouseEvent&)
  32542. {
  32543. // base class does nothing
  32544. }
  32545. void Component::mouseExit (const MouseEvent&)
  32546. {
  32547. // base class does nothing
  32548. }
  32549. void Component::mouseDown (const MouseEvent&)
  32550. {
  32551. // base class does nothing
  32552. }
  32553. void Component::mouseUp (const MouseEvent&)
  32554. {
  32555. // base class does nothing
  32556. }
  32557. void Component::mouseDrag (const MouseEvent&)
  32558. {
  32559. // base class does nothing
  32560. }
  32561. void Component::mouseMove (const MouseEvent&)
  32562. {
  32563. // base class does nothing
  32564. }
  32565. void Component::mouseDoubleClick (const MouseEvent&)
  32566. {
  32567. // base class does nothing
  32568. }
  32569. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32570. {
  32571. // the base class just passes this event up to its parent..
  32572. if (parentComponent_ != 0)
  32573. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32574. wheelIncrementX, wheelIncrementY);
  32575. }
  32576. void Component::resized()
  32577. {
  32578. // base class does nothing
  32579. }
  32580. void Component::moved()
  32581. {
  32582. // base class does nothing
  32583. }
  32584. void Component::childBoundsChanged (Component*)
  32585. {
  32586. // base class does nothing
  32587. }
  32588. void Component::parentSizeChanged()
  32589. {
  32590. // base class does nothing
  32591. }
  32592. void Component::addComponentListener (ComponentListener* const newListener)
  32593. {
  32594. jassert (isValidComponent());
  32595. componentListeners.add (newListener);
  32596. }
  32597. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32598. {
  32599. jassert (isValidComponent());
  32600. componentListeners.remove (listenerToRemove);
  32601. }
  32602. void Component::inputAttemptWhenModal()
  32603. {
  32604. bringModalComponentToFront();
  32605. getLookAndFeel().playAlertSound();
  32606. }
  32607. bool Component::canModalEventBeSentToComponent (const Component*)
  32608. {
  32609. return false;
  32610. }
  32611. void Component::internalModalInputAttempt()
  32612. {
  32613. Component* const current = getCurrentlyModalComponent();
  32614. if (current != 0)
  32615. current->inputAttemptWhenModal();
  32616. }
  32617. void Component::paint (Graphics&)
  32618. {
  32619. // all painting is done in the subclasses
  32620. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32621. }
  32622. void Component::paintOverChildren (Graphics&)
  32623. {
  32624. // all painting is done in the subclasses
  32625. }
  32626. void Component::handleMessage (const Message& message)
  32627. {
  32628. if (message.intParameter1 == exitModalStateMessage)
  32629. {
  32630. exitModalState (message.intParameter2);
  32631. }
  32632. else if (message.intParameter1 == customCommandMessage)
  32633. {
  32634. handleCommandMessage (message.intParameter2);
  32635. }
  32636. }
  32637. void Component::postCommandMessage (const int commandId)
  32638. {
  32639. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32640. }
  32641. void Component::handleCommandMessage (int)
  32642. {
  32643. // used by subclasses
  32644. }
  32645. void Component::addMouseListener (MouseListener* const newListener,
  32646. const bool wantsEventsForAllNestedChildComponents)
  32647. {
  32648. // if component methods are being called from threads other than the message
  32649. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32650. checkMessageManagerIsLocked
  32651. if (mouseListeners_ == 0)
  32652. mouseListeners_ = new Array<MouseListener*>();
  32653. if (! mouseListeners_->contains (newListener))
  32654. {
  32655. if (wantsEventsForAllNestedChildComponents)
  32656. {
  32657. mouseListeners_->insert (0, newListener);
  32658. ++numDeepMouseListeners;
  32659. }
  32660. else
  32661. {
  32662. mouseListeners_->add (newListener);
  32663. }
  32664. }
  32665. }
  32666. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32667. {
  32668. // if component methods are being called from threads other than the message
  32669. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32670. checkMessageManagerIsLocked
  32671. if (mouseListeners_ != 0)
  32672. {
  32673. const int index = mouseListeners_->indexOf (listenerToRemove);
  32674. if (index >= 0)
  32675. {
  32676. if (index < numDeepMouseListeners)
  32677. --numDeepMouseListeners;
  32678. mouseListeners_->remove (index);
  32679. }
  32680. }
  32681. }
  32682. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32683. {
  32684. if (isCurrentlyBlockedByAnotherModalComponent())
  32685. {
  32686. // if something else is modal, always just show a normal mouse cursor
  32687. source.showMouseCursor (MouseCursor::NormalCursor);
  32688. return;
  32689. }
  32690. if (! flags.mouseInsideFlag)
  32691. {
  32692. flags.mouseInsideFlag = true;
  32693. flags.mouseOverFlag = true;
  32694. flags.draggingFlag = false;
  32695. BailOutChecker checker (this);
  32696. if (flags.repaintOnMouseActivityFlag)
  32697. repaint();
  32698. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32699. this, this, time, relativePos,
  32700. time, 0, false);
  32701. mouseEnter (me);
  32702. if (checker.shouldBailOut())
  32703. return;
  32704. Desktop::getInstance().resetTimer();
  32705. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32706. if (checker.shouldBailOut())
  32707. return;
  32708. if (mouseListeners_ != 0)
  32709. {
  32710. for (int i = mouseListeners_->size(); --i >= 0;)
  32711. {
  32712. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32713. if (checker.shouldBailOut())
  32714. return;
  32715. i = jmin (i, mouseListeners_->size());
  32716. }
  32717. }
  32718. Component* p = parentComponent_;
  32719. while (p != 0)
  32720. {
  32721. if (p->numDeepMouseListeners > 0)
  32722. {
  32723. BailOutChecker checker2 (this, p);
  32724. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32725. {
  32726. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32727. if (checker2.shouldBailOut())
  32728. return;
  32729. i = jmin (i, p->numDeepMouseListeners);
  32730. }
  32731. }
  32732. p = p->parentComponent_;
  32733. }
  32734. }
  32735. }
  32736. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32737. {
  32738. BailOutChecker checker (this);
  32739. if (flags.draggingFlag)
  32740. {
  32741. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32742. if (checker.shouldBailOut())
  32743. return;
  32744. }
  32745. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32746. {
  32747. flags.mouseInsideFlag = false;
  32748. flags.mouseOverFlag = false;
  32749. flags.draggingFlag = false;
  32750. if (flags.repaintOnMouseActivityFlag)
  32751. repaint();
  32752. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32753. this, this, time, relativePos,
  32754. time, 0, false);
  32755. mouseExit (me);
  32756. if (checker.shouldBailOut())
  32757. return;
  32758. Desktop::getInstance().resetTimer();
  32759. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32760. if (checker.shouldBailOut())
  32761. return;
  32762. if (mouseListeners_ != 0)
  32763. {
  32764. for (int i = mouseListeners_->size(); --i >= 0;)
  32765. {
  32766. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32767. if (checker.shouldBailOut())
  32768. return;
  32769. i = jmin (i, mouseListeners_->size());
  32770. }
  32771. }
  32772. Component* p = parentComponent_;
  32773. while (p != 0)
  32774. {
  32775. if (p->numDeepMouseListeners > 0)
  32776. {
  32777. BailOutChecker checker2 (this, p);
  32778. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32779. {
  32780. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32781. if (checker2.shouldBailOut())
  32782. return;
  32783. i = jmin (i, p->numDeepMouseListeners);
  32784. }
  32785. }
  32786. p = p->parentComponent_;
  32787. }
  32788. }
  32789. }
  32790. class InternalDragRepeater : public Timer
  32791. {
  32792. public:
  32793. InternalDragRepeater()
  32794. {}
  32795. ~InternalDragRepeater()
  32796. {
  32797. clearSingletonInstance();
  32798. }
  32799. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32800. void timerCallback()
  32801. {
  32802. Desktop& desktop = Desktop::getInstance();
  32803. int numMiceDown = 0;
  32804. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32805. {
  32806. MouseInputSource* const source = desktop.getMouseSource(i);
  32807. if (source->isDragging())
  32808. {
  32809. source->triggerFakeMove();
  32810. ++numMiceDown;
  32811. }
  32812. }
  32813. if (numMiceDown == 0)
  32814. deleteInstance();
  32815. }
  32816. juce_UseDebuggingNewOperator
  32817. private:
  32818. InternalDragRepeater (const InternalDragRepeater&);
  32819. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32820. };
  32821. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32822. void Component::beginDragAutoRepeat (const int interval)
  32823. {
  32824. if (interval > 0)
  32825. {
  32826. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32827. InternalDragRepeater::getInstance()->startTimer (interval);
  32828. }
  32829. else
  32830. {
  32831. InternalDragRepeater::deleteInstance();
  32832. }
  32833. }
  32834. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32835. {
  32836. Desktop& desktop = Desktop::getInstance();
  32837. BailOutChecker checker (this);
  32838. if (isCurrentlyBlockedByAnotherModalComponent())
  32839. {
  32840. internalModalInputAttempt();
  32841. if (checker.shouldBailOut())
  32842. return;
  32843. // If processing the input attempt has exited the modal loop, we'll allow the event
  32844. // to be delivered..
  32845. if (isCurrentlyBlockedByAnotherModalComponent())
  32846. {
  32847. // allow blocked mouse-events to go to global listeners..
  32848. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32849. this, this, time, relativePos, time,
  32850. source.getNumberOfMultipleClicks(), false);
  32851. desktop.resetTimer();
  32852. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32853. return;
  32854. }
  32855. }
  32856. {
  32857. Component* c = this;
  32858. while (c != 0)
  32859. {
  32860. if (c->isBroughtToFrontOnMouseClick())
  32861. {
  32862. c->toFront (true);
  32863. if (checker.shouldBailOut())
  32864. return;
  32865. }
  32866. c = c->parentComponent_;
  32867. }
  32868. }
  32869. if (! flags.dontFocusOnMouseClickFlag)
  32870. {
  32871. grabFocusInternal (focusChangedByMouseClick);
  32872. if (checker.shouldBailOut())
  32873. return;
  32874. }
  32875. flags.draggingFlag = true;
  32876. flags.mouseOverFlag = true;
  32877. if (flags.repaintOnMouseActivityFlag)
  32878. repaint();
  32879. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32880. this, this, time, relativePos, time,
  32881. source.getNumberOfMultipleClicks(), false);
  32882. mouseDown (me);
  32883. if (checker.shouldBailOut())
  32884. return;
  32885. desktop.resetTimer();
  32886. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32887. if (checker.shouldBailOut())
  32888. return;
  32889. if (mouseListeners_ != 0)
  32890. {
  32891. for (int i = mouseListeners_->size(); --i >= 0;)
  32892. {
  32893. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32894. if (checker.shouldBailOut())
  32895. return;
  32896. i = jmin (i, mouseListeners_->size());
  32897. }
  32898. }
  32899. Component* p = parentComponent_;
  32900. while (p != 0)
  32901. {
  32902. if (p->numDeepMouseListeners > 0)
  32903. {
  32904. BailOutChecker checker2 (this, p);
  32905. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32906. {
  32907. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32908. if (checker2.shouldBailOut())
  32909. return;
  32910. i = jmin (i, p->numDeepMouseListeners);
  32911. }
  32912. }
  32913. p = p->parentComponent_;
  32914. }
  32915. }
  32916. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32917. {
  32918. if (flags.draggingFlag)
  32919. {
  32920. Desktop& desktop = Desktop::getInstance();
  32921. flags.draggingFlag = false;
  32922. BailOutChecker checker (this);
  32923. if (flags.repaintOnMouseActivityFlag)
  32924. repaint();
  32925. const MouseEvent me (source, relativePos,
  32926. oldModifiers, this, this, time,
  32927. globalPositionToRelative (source.getLastMouseDownPosition()),
  32928. source.getLastMouseDownTime(),
  32929. source.getNumberOfMultipleClicks(),
  32930. source.hasMouseMovedSignificantlySincePressed());
  32931. mouseUp (me);
  32932. if (checker.shouldBailOut())
  32933. return;
  32934. desktop.resetTimer();
  32935. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32936. if (checker.shouldBailOut())
  32937. return;
  32938. if (mouseListeners_ != 0)
  32939. {
  32940. for (int i = mouseListeners_->size(); --i >= 0;)
  32941. {
  32942. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32943. if (checker.shouldBailOut())
  32944. return;
  32945. i = jmin (i, mouseListeners_->size());
  32946. }
  32947. }
  32948. {
  32949. Component* p = parentComponent_;
  32950. while (p != 0)
  32951. {
  32952. if (p->numDeepMouseListeners > 0)
  32953. {
  32954. BailOutChecker checker2 (this, p);
  32955. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32956. {
  32957. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32958. if (checker2.shouldBailOut())
  32959. return;
  32960. i = jmin (i, p->numDeepMouseListeners);
  32961. }
  32962. }
  32963. p = p->parentComponent_;
  32964. }
  32965. }
  32966. // check for double-click
  32967. if (me.getNumberOfClicks() >= 2)
  32968. {
  32969. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32970. mouseDoubleClick (me);
  32971. if (checker.shouldBailOut())
  32972. return;
  32973. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32974. if (checker.shouldBailOut())
  32975. return;
  32976. for (int i = numListeners; --i >= 0;)
  32977. {
  32978. if (checker.shouldBailOut())
  32979. return;
  32980. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32981. if (ml != 0)
  32982. ml->mouseDoubleClick (me);
  32983. }
  32984. if (checker.shouldBailOut())
  32985. return;
  32986. Component* p = parentComponent_;
  32987. while (p != 0)
  32988. {
  32989. if (p->numDeepMouseListeners > 0)
  32990. {
  32991. BailOutChecker checker2 (this, p);
  32992. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32993. {
  32994. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  32995. if (checker2.shouldBailOut())
  32996. return;
  32997. i = jmin (i, p->numDeepMouseListeners);
  32998. }
  32999. }
  33000. p = p->parentComponent_;
  33001. }
  33002. }
  33003. }
  33004. }
  33005. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33006. {
  33007. if (flags.draggingFlag)
  33008. {
  33009. Desktop& desktop = Desktop::getInstance();
  33010. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33011. BailOutChecker checker (this);
  33012. const MouseEvent me (source, relativePos,
  33013. source.getCurrentModifiers(), this, this, time,
  33014. globalPositionToRelative (source.getLastMouseDownPosition()),
  33015. source.getLastMouseDownTime(),
  33016. source.getNumberOfMultipleClicks(),
  33017. source.hasMouseMovedSignificantlySincePressed());
  33018. mouseDrag (me);
  33019. if (checker.shouldBailOut())
  33020. return;
  33021. desktop.resetTimer();
  33022. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33023. if (checker.shouldBailOut())
  33024. return;
  33025. if (mouseListeners_ != 0)
  33026. {
  33027. for (int i = mouseListeners_->size(); --i >= 0;)
  33028. {
  33029. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33030. if (checker.shouldBailOut())
  33031. return;
  33032. i = jmin (i, mouseListeners_->size());
  33033. }
  33034. }
  33035. Component* p = parentComponent_;
  33036. while (p != 0)
  33037. {
  33038. if (p->numDeepMouseListeners > 0)
  33039. {
  33040. BailOutChecker checker2 (this, p);
  33041. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33042. {
  33043. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33044. if (checker2.shouldBailOut())
  33045. return;
  33046. i = jmin (i, p->numDeepMouseListeners);
  33047. }
  33048. }
  33049. p = p->parentComponent_;
  33050. }
  33051. }
  33052. }
  33053. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33054. {
  33055. Desktop& desktop = Desktop::getInstance();
  33056. BailOutChecker checker (this);
  33057. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33058. this, this, time, relativePos,
  33059. time, 0, false);
  33060. if (isCurrentlyBlockedByAnotherModalComponent())
  33061. {
  33062. // allow blocked mouse-events to go to global listeners..
  33063. desktop.sendMouseMove();
  33064. }
  33065. else
  33066. {
  33067. flags.mouseOverFlag = true;
  33068. mouseMove (me);
  33069. if (checker.shouldBailOut())
  33070. return;
  33071. desktop.resetTimer();
  33072. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33073. if (checker.shouldBailOut())
  33074. return;
  33075. if (mouseListeners_ != 0)
  33076. {
  33077. for (int i = mouseListeners_->size(); --i >= 0;)
  33078. {
  33079. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33080. if (checker.shouldBailOut())
  33081. return;
  33082. i = jmin (i, mouseListeners_->size());
  33083. }
  33084. }
  33085. Component* p = parentComponent_;
  33086. while (p != 0)
  33087. {
  33088. if (p->numDeepMouseListeners > 0)
  33089. {
  33090. BailOutChecker checker2 (this, p);
  33091. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33092. {
  33093. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33094. if (checker2.shouldBailOut())
  33095. return;
  33096. i = jmin (i, p->numDeepMouseListeners);
  33097. }
  33098. }
  33099. p = p->parentComponent_;
  33100. }
  33101. }
  33102. }
  33103. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33104. const Time& time, const float amountX, const float amountY)
  33105. {
  33106. Desktop& desktop = Desktop::getInstance();
  33107. BailOutChecker checker (this);
  33108. const float wheelIncrementX = amountX / 256.0f;
  33109. const float wheelIncrementY = amountY / 256.0f;
  33110. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33111. this, this, time, relativePos, time, 0, false);
  33112. if (isCurrentlyBlockedByAnotherModalComponent())
  33113. {
  33114. // allow blocked mouse-events to go to global listeners..
  33115. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33116. }
  33117. else
  33118. {
  33119. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33120. if (checker.shouldBailOut())
  33121. return;
  33122. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33123. if (checker.shouldBailOut())
  33124. return;
  33125. if (mouseListeners_ != 0)
  33126. {
  33127. for (int i = mouseListeners_->size(); --i >= 0;)
  33128. {
  33129. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33130. if (checker.shouldBailOut())
  33131. return;
  33132. i = jmin (i, mouseListeners_->size());
  33133. }
  33134. }
  33135. Component* p = parentComponent_;
  33136. while (p != 0)
  33137. {
  33138. if (p->numDeepMouseListeners > 0)
  33139. {
  33140. BailOutChecker checker2 (this, p);
  33141. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33142. {
  33143. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33144. if (checker2.shouldBailOut())
  33145. return;
  33146. i = jmin (i, p->numDeepMouseListeners);
  33147. }
  33148. }
  33149. p = p->parentComponent_;
  33150. }
  33151. }
  33152. }
  33153. void Component::sendFakeMouseMove() const
  33154. {
  33155. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33156. }
  33157. void Component::broughtToFront()
  33158. {
  33159. }
  33160. void Component::internalBroughtToFront()
  33161. {
  33162. if (! isValidComponent())
  33163. return;
  33164. if (flags.hasHeavyweightPeerFlag)
  33165. Desktop::getInstance().componentBroughtToFront (this);
  33166. BailOutChecker checker (this);
  33167. broughtToFront();
  33168. if (checker.shouldBailOut())
  33169. return;
  33170. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33171. if (checker.shouldBailOut())
  33172. return;
  33173. // When brought to the front and there's a modal component blocking this one,
  33174. // we need to bring the modal one to the front instead..
  33175. Component* const cm = getCurrentlyModalComponent();
  33176. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33177. bringModalComponentToFront();
  33178. }
  33179. void Component::focusGained (FocusChangeType)
  33180. {
  33181. // base class does nothing
  33182. }
  33183. void Component::internalFocusGain (const FocusChangeType cause)
  33184. {
  33185. SafePointer<Component> safePointer (this);
  33186. focusGained (cause);
  33187. if (safePointer != 0)
  33188. internalChildFocusChange (cause);
  33189. }
  33190. void Component::focusLost (FocusChangeType)
  33191. {
  33192. // base class does nothing
  33193. }
  33194. void Component::internalFocusLoss (const FocusChangeType cause)
  33195. {
  33196. SafePointer<Component> safePointer (this);
  33197. focusLost (focusChangedDirectly);
  33198. if (safePointer != 0)
  33199. internalChildFocusChange (cause);
  33200. }
  33201. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33202. {
  33203. // base class does nothing
  33204. }
  33205. void Component::internalChildFocusChange (FocusChangeType cause)
  33206. {
  33207. const bool childIsNowFocused = hasKeyboardFocus (true);
  33208. if (flags.childCompFocusedFlag != childIsNowFocused)
  33209. {
  33210. flags.childCompFocusedFlag = childIsNowFocused;
  33211. SafePointer<Component> safePointer (this);
  33212. focusOfChildComponentChanged (cause);
  33213. if (safePointer == 0)
  33214. return;
  33215. }
  33216. if (parentComponent_ != 0)
  33217. parentComponent_->internalChildFocusChange (cause);
  33218. }
  33219. bool Component::isEnabled() const throw()
  33220. {
  33221. return (! flags.isDisabledFlag)
  33222. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33223. }
  33224. void Component::setEnabled (const bool shouldBeEnabled)
  33225. {
  33226. if (flags.isDisabledFlag == shouldBeEnabled)
  33227. {
  33228. flags.isDisabledFlag = ! shouldBeEnabled;
  33229. // if any parent components are disabled, setting our flag won't make a difference,
  33230. // so no need to send a change message
  33231. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33232. sendEnablementChangeMessage();
  33233. }
  33234. }
  33235. void Component::sendEnablementChangeMessage()
  33236. {
  33237. SafePointer<Component> safePointer (this);
  33238. enablementChanged();
  33239. if (safePointer == 0)
  33240. return;
  33241. for (int i = getNumChildComponents(); --i >= 0;)
  33242. {
  33243. Component* const c = getChildComponent (i);
  33244. if (c != 0)
  33245. {
  33246. c->sendEnablementChangeMessage();
  33247. if (safePointer == 0)
  33248. return;
  33249. }
  33250. }
  33251. }
  33252. void Component::enablementChanged()
  33253. {
  33254. }
  33255. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33256. {
  33257. flags.wantsFocusFlag = wantsFocus;
  33258. }
  33259. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33260. {
  33261. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33262. }
  33263. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33264. {
  33265. return ! flags.dontFocusOnMouseClickFlag;
  33266. }
  33267. bool Component::getWantsKeyboardFocus() const throw()
  33268. {
  33269. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33270. }
  33271. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33272. {
  33273. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33274. }
  33275. bool Component::isFocusContainer() const throw()
  33276. {
  33277. return flags.isFocusContainerFlag;
  33278. }
  33279. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33280. int Component::getExplicitFocusOrder() const
  33281. {
  33282. return properties [juce_explicitFocusOrderId];
  33283. }
  33284. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33285. {
  33286. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33287. }
  33288. KeyboardFocusTraverser* Component::createFocusTraverser()
  33289. {
  33290. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33291. return new KeyboardFocusTraverser();
  33292. return parentComponent_->createFocusTraverser();
  33293. }
  33294. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33295. {
  33296. // give the focus to this component
  33297. if (currentlyFocusedComponent != this)
  33298. {
  33299. JUCE_TRY
  33300. {
  33301. // get the focus onto our desktop window
  33302. ComponentPeer* const peer = getPeer();
  33303. if (peer != 0)
  33304. {
  33305. SafePointer<Component> safePointer (this);
  33306. peer->grabFocus();
  33307. if (peer->isFocused() && currentlyFocusedComponent != this)
  33308. {
  33309. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  33310. currentlyFocusedComponent = this;
  33311. Desktop::getInstance().triggerFocusCallback();
  33312. // call this after setting currentlyFocusedComponent so that the one that's
  33313. // losing it has a chance to see where focus is going
  33314. if (componentLosingFocus != 0)
  33315. componentLosingFocus->internalFocusLoss (cause);
  33316. if (currentlyFocusedComponent == this)
  33317. {
  33318. focusGained (cause);
  33319. if (safePointer != 0)
  33320. internalChildFocusChange (cause);
  33321. }
  33322. }
  33323. }
  33324. }
  33325. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33326. catch (const std::exception& e)
  33327. {
  33328. currentlyFocusedComponent = 0;
  33329. Desktop::getInstance().triggerFocusCallback();
  33330. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33331. }
  33332. catch (...)
  33333. {
  33334. currentlyFocusedComponent = 0;
  33335. Desktop::getInstance().triggerFocusCallback();
  33336. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33337. }
  33338. #endif
  33339. }
  33340. }
  33341. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33342. {
  33343. if (isShowing())
  33344. {
  33345. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33346. {
  33347. takeKeyboardFocus (cause);
  33348. }
  33349. else
  33350. {
  33351. if (isParentOf (currentlyFocusedComponent)
  33352. && currentlyFocusedComponent->isShowing())
  33353. {
  33354. // do nothing if the focused component is actually a child of ours..
  33355. }
  33356. else
  33357. {
  33358. // find the default child component..
  33359. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33360. if (traverser != 0)
  33361. {
  33362. Component* const defaultComp = traverser->getDefaultComponent (this);
  33363. traverser = 0;
  33364. if (defaultComp != 0)
  33365. {
  33366. defaultComp->grabFocusInternal (cause, false);
  33367. return;
  33368. }
  33369. }
  33370. if (canTryParent && parentComponent_ != 0)
  33371. {
  33372. // if no children want it and we're allowed to try our parent comp,
  33373. // then pass up to parent, which will try our siblings.
  33374. parentComponent_->grabFocusInternal (cause, true);
  33375. }
  33376. }
  33377. }
  33378. }
  33379. }
  33380. void Component::grabKeyboardFocus()
  33381. {
  33382. // if component methods are being called from threads other than the message
  33383. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33384. checkMessageManagerIsLocked
  33385. grabFocusInternal (focusChangedDirectly);
  33386. }
  33387. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33388. {
  33389. // if component methods are being called from threads other than the message
  33390. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33391. checkMessageManagerIsLocked
  33392. if (parentComponent_ != 0)
  33393. {
  33394. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33395. if (traverser != 0)
  33396. {
  33397. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33398. : traverser->getPreviousComponent (this);
  33399. traverser = 0;
  33400. if (nextComp != 0)
  33401. {
  33402. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33403. {
  33404. SafePointer<Component> nextCompPointer (nextComp);
  33405. internalModalInputAttempt();
  33406. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33407. return;
  33408. }
  33409. nextComp->grabFocusInternal (focusChangedByTabKey);
  33410. return;
  33411. }
  33412. }
  33413. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33414. }
  33415. }
  33416. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33417. {
  33418. return (currentlyFocusedComponent == this)
  33419. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33420. }
  33421. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33422. {
  33423. return currentlyFocusedComponent;
  33424. }
  33425. void Component::giveAwayFocus()
  33426. {
  33427. // use a copy so we can clear the value before the call
  33428. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  33429. currentlyFocusedComponent = 0;
  33430. Desktop::getInstance().triggerFocusCallback();
  33431. if (componentLosingFocus != 0)
  33432. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33433. }
  33434. bool Component::isMouseOver() const throw()
  33435. {
  33436. return flags.mouseOverFlag;
  33437. }
  33438. bool Component::isMouseButtonDown() const throw()
  33439. {
  33440. return flags.draggingFlag;
  33441. }
  33442. bool Component::isMouseOverOrDragging() const throw()
  33443. {
  33444. return flags.mouseOverFlag || flags.draggingFlag;
  33445. }
  33446. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33447. {
  33448. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33449. }
  33450. const Point<int> Component::getMouseXYRelative() const
  33451. {
  33452. return globalPositionToRelative (Desktop::getMousePosition());
  33453. }
  33454. const Rectangle<int> Component::getParentMonitorArea() const
  33455. {
  33456. return Desktop::getInstance()
  33457. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  33458. }
  33459. void Component::addKeyListener (KeyListener* const newListener)
  33460. {
  33461. if (keyListeners_ == 0)
  33462. keyListeners_ = new Array <KeyListener*>();
  33463. keyListeners_->addIfNotAlreadyThere (newListener);
  33464. }
  33465. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33466. {
  33467. if (keyListeners_ != 0)
  33468. keyListeners_->removeValue (listenerToRemove);
  33469. }
  33470. bool Component::keyPressed (const KeyPress&)
  33471. {
  33472. return false;
  33473. }
  33474. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33475. {
  33476. return false;
  33477. }
  33478. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33479. {
  33480. if (parentComponent_ != 0)
  33481. parentComponent_->modifierKeysChanged (modifiers);
  33482. }
  33483. void Component::internalModifierKeysChanged()
  33484. {
  33485. sendFakeMouseMove();
  33486. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33487. }
  33488. ComponentPeer* Component::getPeer() const
  33489. {
  33490. if (flags.hasHeavyweightPeerFlag)
  33491. return ComponentPeer::getPeerFor (this);
  33492. else if (parentComponent_ != 0)
  33493. return parentComponent_->getPeer();
  33494. else
  33495. return 0;
  33496. }
  33497. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33498. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33499. {
  33500. jassert (component1 != 0);
  33501. }
  33502. bool Component::BailOutChecker::shouldBailOut() const throw()
  33503. {
  33504. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33505. }
  33506. END_JUCE_NAMESPACE
  33507. /*** End of inlined file: juce_Component.cpp ***/
  33508. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33509. BEGIN_JUCE_NAMESPACE
  33510. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33511. void ComponentListener::componentBroughtToFront (Component&) {}
  33512. void ComponentListener::componentVisibilityChanged (Component&) {}
  33513. void ComponentListener::componentChildrenChanged (Component&) {}
  33514. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33515. void ComponentListener::componentNameChanged (Component&) {}
  33516. void ComponentListener::componentBeingDeleted (Component&) {}
  33517. END_JUCE_NAMESPACE
  33518. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33519. /*** Start of inlined file: juce_Desktop.cpp ***/
  33520. BEGIN_JUCE_NAMESPACE
  33521. Desktop::Desktop()
  33522. : mouseClickCounter (0),
  33523. kioskModeComponent (0)
  33524. {
  33525. createMouseInputSources();
  33526. refreshMonitorSizes();
  33527. }
  33528. Desktop::~Desktop()
  33529. {
  33530. jassert (instance == this);
  33531. instance = 0;
  33532. // doh! If you don't delete all your windows before exiting, you're going to
  33533. // be leaking memory!
  33534. jassert (desktopComponents.size() == 0);
  33535. }
  33536. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33537. {
  33538. if (instance == 0)
  33539. instance = new Desktop();
  33540. return *instance;
  33541. }
  33542. Desktop* Desktop::instance = 0;
  33543. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33544. const bool clipToWorkArea);
  33545. void Desktop::refreshMonitorSizes()
  33546. {
  33547. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33548. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33549. monitorCoordsClipped.clear();
  33550. monitorCoordsUnclipped.clear();
  33551. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33552. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33553. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33554. if (oldClipped != monitorCoordsClipped
  33555. || oldUnclipped != monitorCoordsUnclipped)
  33556. {
  33557. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33558. {
  33559. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33560. if (p != 0)
  33561. p->handleScreenSizeChange();
  33562. }
  33563. }
  33564. }
  33565. int Desktop::getNumDisplayMonitors() const throw()
  33566. {
  33567. return monitorCoordsClipped.size();
  33568. }
  33569. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33570. {
  33571. return clippedToWorkArea ? monitorCoordsClipped [index]
  33572. : monitorCoordsUnclipped [index];
  33573. }
  33574. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33575. {
  33576. RectangleList rl;
  33577. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33578. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33579. return rl;
  33580. }
  33581. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33582. {
  33583. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33584. }
  33585. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33586. {
  33587. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33588. double bestDistance = 1.0e10;
  33589. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33590. {
  33591. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33592. if (rect.contains (position))
  33593. return rect;
  33594. const double distance = rect.getCentre().getDistanceFrom (position);
  33595. if (distance < bestDistance)
  33596. {
  33597. bestDistance = distance;
  33598. best = rect;
  33599. }
  33600. }
  33601. return best;
  33602. }
  33603. int Desktop::getNumComponents() const throw()
  33604. {
  33605. return desktopComponents.size();
  33606. }
  33607. Component* Desktop::getComponent (const int index) const throw()
  33608. {
  33609. return desktopComponents [index];
  33610. }
  33611. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33612. {
  33613. for (int i = desktopComponents.size(); --i >= 0;)
  33614. {
  33615. Component* const c = desktopComponents.getUnchecked(i);
  33616. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33617. if (c->contains (relative.getX(), relative.getY()))
  33618. return c->getComponentAt (relative.getX(), relative.getY());
  33619. }
  33620. return 0;
  33621. }
  33622. void Desktop::addDesktopComponent (Component* const c)
  33623. {
  33624. jassert (c != 0);
  33625. jassert (! desktopComponents.contains (c));
  33626. desktopComponents.addIfNotAlreadyThere (c);
  33627. }
  33628. void Desktop::removeDesktopComponent (Component* const c)
  33629. {
  33630. desktopComponents.removeValue (c);
  33631. }
  33632. void Desktop::componentBroughtToFront (Component* const c)
  33633. {
  33634. const int index = desktopComponents.indexOf (c);
  33635. jassert (index >= 0);
  33636. if (index >= 0)
  33637. {
  33638. int newIndex = -1;
  33639. if (! c->isAlwaysOnTop())
  33640. {
  33641. newIndex = desktopComponents.size();
  33642. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33643. --newIndex;
  33644. --newIndex;
  33645. }
  33646. desktopComponents.move (index, newIndex);
  33647. }
  33648. }
  33649. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33650. {
  33651. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33652. }
  33653. int Desktop::getMouseButtonClickCounter() throw()
  33654. {
  33655. return getInstance().mouseClickCounter;
  33656. }
  33657. void Desktop::incrementMouseClickCounter() throw()
  33658. {
  33659. ++mouseClickCounter;
  33660. }
  33661. int Desktop::getNumDraggingMouseSources() const throw()
  33662. {
  33663. int num = 0;
  33664. for (int i = mouseSources.size(); --i >= 0;)
  33665. if (mouseSources.getUnchecked(i)->isDragging())
  33666. ++num;
  33667. return num;
  33668. }
  33669. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33670. {
  33671. int num = 0;
  33672. for (int i = mouseSources.size(); --i >= 0;)
  33673. {
  33674. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33675. if (mi->isDragging())
  33676. {
  33677. if (index == num)
  33678. return mi;
  33679. ++num;
  33680. }
  33681. }
  33682. return 0;
  33683. }
  33684. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33685. {
  33686. focusListeners.add (listener);
  33687. }
  33688. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33689. {
  33690. focusListeners.remove (listener);
  33691. }
  33692. void Desktop::triggerFocusCallback()
  33693. {
  33694. triggerAsyncUpdate();
  33695. }
  33696. void Desktop::handleAsyncUpdate()
  33697. {
  33698. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33699. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33700. }
  33701. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33702. {
  33703. mouseListeners.add (listener);
  33704. resetTimer();
  33705. }
  33706. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33707. {
  33708. mouseListeners.remove (listener);
  33709. resetTimer();
  33710. }
  33711. void Desktop::timerCallback()
  33712. {
  33713. if (lastFakeMouseMove != getMousePosition())
  33714. sendMouseMove();
  33715. }
  33716. void Desktop::sendMouseMove()
  33717. {
  33718. if (! mouseListeners.isEmpty())
  33719. {
  33720. startTimer (20);
  33721. lastFakeMouseMove = getMousePosition();
  33722. Component* const target = findComponentAt (lastFakeMouseMove);
  33723. if (target != 0)
  33724. {
  33725. Component::BailOutChecker checker (target);
  33726. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33727. const Time now (Time::getCurrentTime());
  33728. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33729. target, target, now, pos, now, 0, false);
  33730. if (me.mods.isAnyMouseButtonDown())
  33731. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33732. else
  33733. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33734. }
  33735. }
  33736. }
  33737. void Desktop::resetTimer()
  33738. {
  33739. if (mouseListeners.size() == 0)
  33740. stopTimer();
  33741. else
  33742. startTimer (100);
  33743. lastFakeMouseMove = getMousePosition();
  33744. }
  33745. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33746. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33747. {
  33748. if (kioskModeComponent != componentToUse)
  33749. {
  33750. // agh! Don't delete a component without first stopping it being the kiosk comp
  33751. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33752. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33753. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33754. if (kioskModeComponent->isValidComponent())
  33755. {
  33756. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33757. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33758. }
  33759. kioskModeComponent = componentToUse;
  33760. if (kioskModeComponent != 0)
  33761. {
  33762. jassert (kioskModeComponent->isValidComponent());
  33763. // Only components that are already on the desktop can be put into kiosk mode!
  33764. jassert (kioskModeComponent->isOnDesktop());
  33765. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33766. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33767. }
  33768. }
  33769. }
  33770. END_JUCE_NAMESPACE
  33771. /*** End of inlined file: juce_Desktop.cpp ***/
  33772. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  33773. BEGIN_JUCE_NAMESPACE
  33774. class ModalComponentManager::ModalItem : public ComponentListener
  33775. {
  33776. public:
  33777. ModalItem (Component* const comp, Callback* const callback)
  33778. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  33779. {
  33780. if (callback != 0)
  33781. callbacks.add (callback);
  33782. jassert (comp != 0);
  33783. component->addComponentListener (this);
  33784. }
  33785. ~ModalItem()
  33786. {
  33787. if (! isDeleted)
  33788. component->removeComponentListener (this);
  33789. }
  33790. void componentBeingDeleted (Component&)
  33791. {
  33792. isDeleted = true;
  33793. cancel();
  33794. }
  33795. void componentVisibilityChanged (Component&)
  33796. {
  33797. if (! component->isShowing())
  33798. cancel();
  33799. }
  33800. void componentParentHierarchyChanged (Component&)
  33801. {
  33802. if (! component->isShowing())
  33803. cancel();
  33804. }
  33805. void cancel()
  33806. {
  33807. if (isActive)
  33808. {
  33809. isActive = false;
  33810. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  33811. }
  33812. }
  33813. Component* component;
  33814. OwnedArray<Callback> callbacks;
  33815. int returnValue;
  33816. bool isActive, isDeleted;
  33817. private:
  33818. ModalItem (const ModalItem&);
  33819. ModalItem& operator= (const ModalItem&);
  33820. };
  33821. ModalComponentManager::ModalComponentManager()
  33822. {
  33823. }
  33824. ModalComponentManager::~ModalComponentManager()
  33825. {
  33826. clearSingletonInstance();
  33827. }
  33828. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  33829. void ModalComponentManager::startModal (Component* component, Callback* callback)
  33830. {
  33831. if (component != 0)
  33832. stack.add (new ModalItem (component, callback));
  33833. }
  33834. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  33835. {
  33836. if (callback != 0)
  33837. {
  33838. ScopedPointer<Callback> callbackDeleter (callback);
  33839. for (int i = stack.size(); --i >= 0;)
  33840. {
  33841. ModalItem* const item = stack.getUnchecked(i);
  33842. if (item->component == component)
  33843. {
  33844. item->callbacks.add (callback);
  33845. callbackDeleter.release();
  33846. break;
  33847. }
  33848. }
  33849. }
  33850. }
  33851. void ModalComponentManager::endModal (Component* component)
  33852. {
  33853. for (int i = stack.size(); --i >= 0;)
  33854. {
  33855. ModalItem* const item = stack.getUnchecked(i);
  33856. if (item->component == component)
  33857. item->cancel();
  33858. }
  33859. }
  33860. void ModalComponentManager::endModal (Component* component, int returnValue)
  33861. {
  33862. for (int i = stack.size(); --i >= 0;)
  33863. {
  33864. ModalItem* const item = stack.getUnchecked(i);
  33865. if (item->component == component)
  33866. {
  33867. item->returnValue = returnValue;
  33868. item->cancel();
  33869. }
  33870. }
  33871. }
  33872. int ModalComponentManager::getNumModalComponents() const
  33873. {
  33874. int n = 0;
  33875. for (int i = 0; i < stack.size(); ++i)
  33876. if (stack.getUnchecked(i)->isActive)
  33877. ++n;
  33878. return n;
  33879. }
  33880. Component* ModalComponentManager::getModalComponent (const int index) const
  33881. {
  33882. int n = 0;
  33883. for (int i = stack.size(); --i >= 0;)
  33884. {
  33885. const ModalItem* const item = stack.getUnchecked(i);
  33886. if (item->isActive)
  33887. if (n++ == index)
  33888. return item->component;
  33889. }
  33890. return 0;
  33891. }
  33892. bool ModalComponentManager::isModal (Component* const comp) const
  33893. {
  33894. for (int i = stack.size(); --i >= 0;)
  33895. {
  33896. const ModalItem* const item = stack.getUnchecked(i);
  33897. if (item->isActive && item->component == comp)
  33898. return true;
  33899. }
  33900. return false;
  33901. }
  33902. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  33903. {
  33904. return comp == getModalComponent (0);
  33905. }
  33906. void ModalComponentManager::handleAsyncUpdate()
  33907. {
  33908. for (int i = stack.size(); --i >= 0;)
  33909. {
  33910. const ModalItem* const item = stack.getUnchecked(i);
  33911. if (! item->isActive)
  33912. {
  33913. for (int j = item->callbacks.size(); --j >= 0;)
  33914. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  33915. stack.remove (i);
  33916. }
  33917. }
  33918. }
  33919. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  33920. {
  33921. public:
  33922. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  33923. ~ReturnValueRetriever() {}
  33924. void modalStateFinished (int returnValue)
  33925. {
  33926. finished = true;
  33927. value = returnValue;
  33928. }
  33929. private:
  33930. int& value;
  33931. bool& finished;
  33932. ReturnValueRetriever (const ReturnValueRetriever&);
  33933. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  33934. };
  33935. int ModalComponentManager::runEventLoopForCurrentComponent()
  33936. {
  33937. // This can only be run from the message thread!
  33938. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  33939. Component* currentlyModal = getModalComponent (0);
  33940. if (currentlyModal == 0)
  33941. return 0;
  33942. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  33943. int returnValue = 0;
  33944. bool finished = false;
  33945. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  33946. JUCE_TRY
  33947. {
  33948. while (! finished)
  33949. {
  33950. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  33951. break;
  33952. }
  33953. }
  33954. JUCE_CATCH_EXCEPTION
  33955. if (prevFocused != 0)
  33956. prevFocused->grabKeyboardFocus();
  33957. return returnValue;
  33958. }
  33959. END_JUCE_NAMESPACE
  33960. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  33961. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33962. BEGIN_JUCE_NAMESPACE
  33963. ArrowButton::ArrowButton (const String& name,
  33964. float arrowDirectionInRadians,
  33965. const Colour& arrowColour)
  33966. : Button (name),
  33967. colour (arrowColour)
  33968. {
  33969. path.lineTo (0.0f, 1.0f);
  33970. path.lineTo (1.0f, 0.5f);
  33971. path.closeSubPath();
  33972. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33973. 0.5f, 0.5f));
  33974. setComponentEffect (&shadow);
  33975. buttonStateChanged();
  33976. }
  33977. ArrowButton::~ArrowButton()
  33978. {
  33979. }
  33980. void ArrowButton::paintButton (Graphics& g,
  33981. bool /*isMouseOverButton*/,
  33982. bool /*isButtonDown*/)
  33983. {
  33984. g.setColour (colour);
  33985. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33986. (float) offset,
  33987. (float) (getWidth() - 3),
  33988. (float) (getHeight() - 3),
  33989. false));
  33990. }
  33991. void ArrowButton::buttonStateChanged()
  33992. {
  33993. offset = (isDown()) ? 1 : 0;
  33994. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33995. 0.3f, -1, 0);
  33996. }
  33997. END_JUCE_NAMESPACE
  33998. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33999. /*** Start of inlined file: juce_Button.cpp ***/
  34000. BEGIN_JUCE_NAMESPACE
  34001. class Button::RepeatTimer : public Timer
  34002. {
  34003. public:
  34004. RepeatTimer (Button& owner_) : owner (owner_) {}
  34005. void timerCallback() { owner.repeatTimerCallback(); }
  34006. juce_UseDebuggingNewOperator
  34007. private:
  34008. Button& owner;
  34009. RepeatTimer (const RepeatTimer&);
  34010. RepeatTimer& operator= (const RepeatTimer&);
  34011. };
  34012. Button::Button (const String& name)
  34013. : Component (name),
  34014. text (name),
  34015. buttonPressTime (0),
  34016. lastTimeCallbackTime (0),
  34017. commandManagerToUse (0),
  34018. autoRepeatDelay (-1),
  34019. autoRepeatSpeed (0),
  34020. autoRepeatMinimumDelay (-1),
  34021. radioGroupId (0),
  34022. commandID (0),
  34023. connectedEdgeFlags (0),
  34024. buttonState (buttonNormal),
  34025. lastToggleState (false),
  34026. clickTogglesState (false),
  34027. needsToRelease (false),
  34028. needsRepainting (false),
  34029. isKeyDown (false),
  34030. triggerOnMouseDown (false),
  34031. generateTooltip (false)
  34032. {
  34033. setWantsKeyboardFocus (true);
  34034. isOn.addListener (this);
  34035. }
  34036. Button::~Button()
  34037. {
  34038. isOn.removeListener (this);
  34039. if (commandManagerToUse != 0)
  34040. commandManagerToUse->removeListener (this);
  34041. repeatTimer = 0;
  34042. clearShortcuts();
  34043. }
  34044. void Button::setButtonText (const String& newText)
  34045. {
  34046. if (text != newText)
  34047. {
  34048. text = newText;
  34049. repaint();
  34050. }
  34051. }
  34052. void Button::setTooltip (const String& newTooltip)
  34053. {
  34054. SettableTooltipClient::setTooltip (newTooltip);
  34055. generateTooltip = false;
  34056. }
  34057. const String Button::getTooltip()
  34058. {
  34059. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34060. {
  34061. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34062. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34063. for (int i = 0; i < keyPresses.size(); ++i)
  34064. {
  34065. const String key (keyPresses.getReference(i).getTextDescription());
  34066. tt << " [";
  34067. if (key.length() == 1)
  34068. tt << TRANS("shortcut") << ": '" << key << "']";
  34069. else
  34070. tt << key << ']';
  34071. }
  34072. return tt;
  34073. }
  34074. return SettableTooltipClient::getTooltip();
  34075. }
  34076. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34077. {
  34078. if (connectedEdgeFlags != connectedEdgeFlags_)
  34079. {
  34080. connectedEdgeFlags = connectedEdgeFlags_;
  34081. repaint();
  34082. }
  34083. }
  34084. void Button::setToggleState (const bool shouldBeOn,
  34085. const bool sendChangeNotification)
  34086. {
  34087. if (shouldBeOn != lastToggleState)
  34088. {
  34089. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34090. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34091. lastToggleState = shouldBeOn;
  34092. repaint();
  34093. if (sendChangeNotification)
  34094. {
  34095. Component::SafePointer<Component> deletionWatcher (this);
  34096. sendClickMessage (ModifierKeys());
  34097. if (deletionWatcher == 0)
  34098. return;
  34099. }
  34100. if (lastToggleState)
  34101. turnOffOtherButtonsInGroup (sendChangeNotification);
  34102. }
  34103. }
  34104. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34105. {
  34106. clickTogglesState = shouldToggle;
  34107. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34108. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34109. // it is that this button represents, and the button will update its state to reflect this
  34110. // in the applicationCommandListChanged() method.
  34111. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34112. }
  34113. bool Button::getClickingTogglesState() const throw()
  34114. {
  34115. return clickTogglesState;
  34116. }
  34117. void Button::valueChanged (Value& value)
  34118. {
  34119. if (value.refersToSameSourceAs (isOn))
  34120. setToggleState (isOn.getValue(), true);
  34121. }
  34122. void Button::setRadioGroupId (const int newGroupId)
  34123. {
  34124. if (radioGroupId != newGroupId)
  34125. {
  34126. radioGroupId = newGroupId;
  34127. if (lastToggleState)
  34128. turnOffOtherButtonsInGroup (true);
  34129. }
  34130. }
  34131. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34132. {
  34133. Component* const p = getParentComponent();
  34134. if (p != 0 && radioGroupId != 0)
  34135. {
  34136. Component::SafePointer<Component> deletionWatcher (this);
  34137. for (int i = p->getNumChildComponents(); --i >= 0;)
  34138. {
  34139. Component* const c = p->getChildComponent (i);
  34140. if (c != this)
  34141. {
  34142. Button* const b = dynamic_cast <Button*> (c);
  34143. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34144. {
  34145. b->setToggleState (false, sendChangeNotification);
  34146. if (deletionWatcher == 0)
  34147. return;
  34148. }
  34149. }
  34150. }
  34151. }
  34152. }
  34153. void Button::enablementChanged()
  34154. {
  34155. updateState (0);
  34156. repaint();
  34157. }
  34158. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34159. {
  34160. ButtonState state = buttonNormal;
  34161. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34162. {
  34163. Point<int> mousePos;
  34164. if (e == 0)
  34165. mousePos = getMouseXYRelative();
  34166. else
  34167. mousePos = e->getEventRelativeTo (this).getPosition();
  34168. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34169. const bool down = isMouseButtonDown();
  34170. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34171. state = buttonDown;
  34172. else if (over)
  34173. state = buttonOver;
  34174. }
  34175. setState (state);
  34176. return state;
  34177. }
  34178. void Button::setState (const ButtonState newState)
  34179. {
  34180. if (buttonState != newState)
  34181. {
  34182. buttonState = newState;
  34183. repaint();
  34184. if (buttonState == buttonDown)
  34185. {
  34186. buttonPressTime = Time::getApproximateMillisecondCounter();
  34187. lastTimeCallbackTime = buttonPressTime;
  34188. }
  34189. sendStateMessage();
  34190. }
  34191. }
  34192. bool Button::isDown() const throw()
  34193. {
  34194. return buttonState == buttonDown;
  34195. }
  34196. bool Button::isOver() const throw()
  34197. {
  34198. return buttonState != buttonNormal;
  34199. }
  34200. void Button::buttonStateChanged()
  34201. {
  34202. }
  34203. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34204. {
  34205. const uint32 now = Time::getApproximateMillisecondCounter();
  34206. return now > buttonPressTime ? now - buttonPressTime : 0;
  34207. }
  34208. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34209. {
  34210. triggerOnMouseDown = isTriggeredOnMouseDown;
  34211. }
  34212. void Button::clicked()
  34213. {
  34214. }
  34215. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34216. {
  34217. clicked();
  34218. }
  34219. static const int clickMessageId = 0x2f3f4f99;
  34220. void Button::triggerClick()
  34221. {
  34222. postCommandMessage (clickMessageId);
  34223. }
  34224. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34225. {
  34226. if (clickTogglesState)
  34227. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34228. sendClickMessage (modifiers);
  34229. }
  34230. void Button::flashButtonState()
  34231. {
  34232. if (isEnabled())
  34233. {
  34234. needsToRelease = true;
  34235. setState (buttonDown);
  34236. getRepeatTimer().startTimer (100);
  34237. }
  34238. }
  34239. void Button::handleCommandMessage (int commandId)
  34240. {
  34241. if (commandId == clickMessageId)
  34242. {
  34243. if (isEnabled())
  34244. {
  34245. flashButtonState();
  34246. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34247. }
  34248. }
  34249. else
  34250. {
  34251. Component::handleCommandMessage (commandId);
  34252. }
  34253. }
  34254. void Button::addButtonListener (Listener* const newListener)
  34255. {
  34256. buttonListeners.add (newListener);
  34257. }
  34258. void Button::removeButtonListener (Listener* const listener)
  34259. {
  34260. buttonListeners.remove (listener);
  34261. }
  34262. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34263. {
  34264. Component::BailOutChecker checker (this);
  34265. if (commandManagerToUse != 0 && commandID != 0)
  34266. {
  34267. ApplicationCommandTarget::InvocationInfo info (commandID);
  34268. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34269. info.originatingComponent = this;
  34270. commandManagerToUse->invoke (info, true);
  34271. }
  34272. clicked (modifiers);
  34273. if (! checker.shouldBailOut())
  34274. buttonListeners.callChecked (checker, &Listener::buttonClicked, this);
  34275. }
  34276. void Button::sendStateMessage()
  34277. {
  34278. Component::BailOutChecker checker (this);
  34279. buttonStateChanged();
  34280. if (! checker.shouldBailOut())
  34281. buttonListeners.callChecked (checker, &Listener::buttonStateChanged, this);
  34282. }
  34283. void Button::paint (Graphics& g)
  34284. {
  34285. if (needsToRelease && isEnabled())
  34286. {
  34287. needsToRelease = false;
  34288. needsRepainting = true;
  34289. }
  34290. paintButton (g, isOver(), isDown());
  34291. }
  34292. void Button::mouseEnter (const MouseEvent& e)
  34293. {
  34294. updateState (&e);
  34295. }
  34296. void Button::mouseExit (const MouseEvent& e)
  34297. {
  34298. updateState (&e);
  34299. }
  34300. void Button::mouseDown (const MouseEvent& e)
  34301. {
  34302. updateState (&e);
  34303. if (isDown())
  34304. {
  34305. if (autoRepeatDelay >= 0)
  34306. getRepeatTimer().startTimer (autoRepeatDelay);
  34307. if (triggerOnMouseDown)
  34308. internalClickCallback (e.mods);
  34309. }
  34310. }
  34311. void Button::mouseUp (const MouseEvent& e)
  34312. {
  34313. const bool wasDown = isDown();
  34314. updateState (&e);
  34315. if (wasDown && isOver() && ! triggerOnMouseDown)
  34316. internalClickCallback (e.mods);
  34317. }
  34318. void Button::mouseDrag (const MouseEvent& e)
  34319. {
  34320. const ButtonState oldState = buttonState;
  34321. updateState (&e);
  34322. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34323. getRepeatTimer().startTimer (autoRepeatSpeed);
  34324. }
  34325. void Button::focusGained (FocusChangeType)
  34326. {
  34327. updateState (0);
  34328. repaint();
  34329. }
  34330. void Button::focusLost (FocusChangeType)
  34331. {
  34332. updateState (0);
  34333. repaint();
  34334. }
  34335. void Button::setVisible (bool shouldBeVisible)
  34336. {
  34337. if (shouldBeVisible != isVisible())
  34338. {
  34339. Component::setVisible (shouldBeVisible);
  34340. if (! shouldBeVisible)
  34341. needsToRelease = false;
  34342. updateState (0);
  34343. }
  34344. else
  34345. {
  34346. Component::setVisible (shouldBeVisible);
  34347. }
  34348. }
  34349. void Button::parentHierarchyChanged()
  34350. {
  34351. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34352. if (newKeySource != keySource.getComponent())
  34353. {
  34354. if (keySource != 0)
  34355. keySource->removeKeyListener (this);
  34356. keySource = newKeySource;
  34357. if (keySource != 0)
  34358. keySource->addKeyListener (this);
  34359. }
  34360. }
  34361. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34362. const int commandID_,
  34363. const bool generateTooltip_)
  34364. {
  34365. commandID = commandID_;
  34366. generateTooltip = generateTooltip_;
  34367. if (commandManagerToUse != commandManagerToUse_)
  34368. {
  34369. if (commandManagerToUse != 0)
  34370. commandManagerToUse->removeListener (this);
  34371. commandManagerToUse = commandManagerToUse_;
  34372. if (commandManagerToUse != 0)
  34373. commandManagerToUse->addListener (this);
  34374. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34375. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34376. // it is that this button represents, and the button will update its state to reflect this
  34377. // in the applicationCommandListChanged() method.
  34378. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34379. }
  34380. if (commandManagerToUse != 0)
  34381. applicationCommandListChanged();
  34382. else
  34383. setEnabled (true);
  34384. }
  34385. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34386. {
  34387. if (info.commandID == commandID
  34388. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34389. {
  34390. flashButtonState();
  34391. }
  34392. }
  34393. void Button::applicationCommandListChanged()
  34394. {
  34395. if (commandManagerToUse != 0)
  34396. {
  34397. ApplicationCommandInfo info (0);
  34398. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34399. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34400. if (target != 0)
  34401. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34402. }
  34403. }
  34404. void Button::addShortcut (const KeyPress& key)
  34405. {
  34406. if (key.isValid())
  34407. {
  34408. jassert (! isRegisteredForShortcut (key)); // already registered!
  34409. shortcuts.add (key);
  34410. parentHierarchyChanged();
  34411. }
  34412. }
  34413. void Button::clearShortcuts()
  34414. {
  34415. shortcuts.clear();
  34416. parentHierarchyChanged();
  34417. }
  34418. bool Button::isShortcutPressed() const
  34419. {
  34420. if (! isCurrentlyBlockedByAnotherModalComponent())
  34421. {
  34422. for (int i = shortcuts.size(); --i >= 0;)
  34423. if (shortcuts.getReference(i).isCurrentlyDown())
  34424. return true;
  34425. }
  34426. return false;
  34427. }
  34428. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34429. {
  34430. for (int i = shortcuts.size(); --i >= 0;)
  34431. if (key == shortcuts.getReference(i))
  34432. return true;
  34433. return false;
  34434. }
  34435. bool Button::keyStateChanged (const bool, Component*)
  34436. {
  34437. if (! isEnabled())
  34438. return false;
  34439. const bool wasDown = isKeyDown;
  34440. isKeyDown = isShortcutPressed();
  34441. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34442. getRepeatTimer().startTimer (autoRepeatDelay);
  34443. updateState (0);
  34444. if (isEnabled() && wasDown && ! isKeyDown)
  34445. {
  34446. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34447. // (return immediately - this button may now have been deleted)
  34448. return true;
  34449. }
  34450. return wasDown || isKeyDown;
  34451. }
  34452. bool Button::keyPressed (const KeyPress&, Component*)
  34453. {
  34454. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34455. return isShortcutPressed();
  34456. }
  34457. bool Button::keyPressed (const KeyPress& key)
  34458. {
  34459. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34460. {
  34461. triggerClick();
  34462. return true;
  34463. }
  34464. return false;
  34465. }
  34466. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34467. const int repeatMillisecs,
  34468. const int minimumDelayInMillisecs) throw()
  34469. {
  34470. autoRepeatDelay = initialDelayMillisecs;
  34471. autoRepeatSpeed = repeatMillisecs;
  34472. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34473. }
  34474. void Button::repeatTimerCallback()
  34475. {
  34476. if (needsRepainting)
  34477. {
  34478. getRepeatTimer().stopTimer();
  34479. updateState (0);
  34480. needsRepainting = false;
  34481. }
  34482. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34483. {
  34484. int repeatSpeed = autoRepeatSpeed;
  34485. if (autoRepeatMinimumDelay >= 0)
  34486. {
  34487. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34488. timeHeldDown *= timeHeldDown;
  34489. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34490. }
  34491. repeatSpeed = jmax (1, repeatSpeed);
  34492. getRepeatTimer().startTimer (repeatSpeed);
  34493. const uint32 now = Time::getApproximateMillisecondCounter();
  34494. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34495. lastTimeCallbackTime = now;
  34496. Component::SafePointer<Component> deletionWatcher (this);
  34497. for (int i = numTimesToCallback; --i >= 0;)
  34498. {
  34499. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34500. if (deletionWatcher == 0 || ! isDown())
  34501. return;
  34502. }
  34503. }
  34504. else if (! needsToRelease)
  34505. {
  34506. getRepeatTimer().stopTimer();
  34507. }
  34508. }
  34509. Button::RepeatTimer& Button::getRepeatTimer()
  34510. {
  34511. if (repeatTimer == 0)
  34512. repeatTimer = new RepeatTimer (*this);
  34513. return *repeatTimer;
  34514. }
  34515. END_JUCE_NAMESPACE
  34516. /*** End of inlined file: juce_Button.cpp ***/
  34517. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34518. BEGIN_JUCE_NAMESPACE
  34519. DrawableButton::DrawableButton (const String& name,
  34520. const DrawableButton::ButtonStyle buttonStyle)
  34521. : Button (name),
  34522. style (buttonStyle),
  34523. edgeIndent (3)
  34524. {
  34525. if (buttonStyle == ImageOnButtonBackground)
  34526. {
  34527. backgroundOff = Colour (0xffbbbbff);
  34528. backgroundOn = Colour (0xff3333ff);
  34529. }
  34530. else
  34531. {
  34532. backgroundOff = Colours::transparentBlack;
  34533. backgroundOn = Colour (0xaabbbbff);
  34534. }
  34535. }
  34536. DrawableButton::~DrawableButton()
  34537. {
  34538. deleteImages();
  34539. }
  34540. void DrawableButton::deleteImages()
  34541. {
  34542. }
  34543. void DrawableButton::setImages (const Drawable* normal,
  34544. const Drawable* over,
  34545. const Drawable* down,
  34546. const Drawable* disabled,
  34547. const Drawable* normalOn,
  34548. const Drawable* overOn,
  34549. const Drawable* downOn,
  34550. const Drawable* disabledOn)
  34551. {
  34552. deleteImages();
  34553. jassert (normal != 0); // you really need to give it at least a normal image..
  34554. if (normal != 0)
  34555. normalImage = normal->createCopy();
  34556. if (over != 0)
  34557. overImage = over->createCopy();
  34558. if (down != 0)
  34559. downImage = down->createCopy();
  34560. if (disabled != 0)
  34561. disabledImage = disabled->createCopy();
  34562. if (normalOn != 0)
  34563. normalImageOn = normalOn->createCopy();
  34564. if (overOn != 0)
  34565. overImageOn = overOn->createCopy();
  34566. if (downOn != 0)
  34567. downImageOn = downOn->createCopy();
  34568. if (disabledOn != 0)
  34569. disabledImageOn = disabledOn->createCopy();
  34570. repaint();
  34571. }
  34572. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34573. {
  34574. if (style != newStyle)
  34575. {
  34576. style = newStyle;
  34577. repaint();
  34578. }
  34579. }
  34580. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34581. const Colour& toggledOnColour)
  34582. {
  34583. if (backgroundOff != toggledOffColour
  34584. || backgroundOn != toggledOnColour)
  34585. {
  34586. backgroundOff = toggledOffColour;
  34587. backgroundOn = toggledOnColour;
  34588. repaint();
  34589. }
  34590. }
  34591. const Colour& DrawableButton::getBackgroundColour() const throw()
  34592. {
  34593. return getToggleState() ? backgroundOn
  34594. : backgroundOff;
  34595. }
  34596. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34597. {
  34598. edgeIndent = numPixelsIndent;
  34599. repaint();
  34600. }
  34601. void DrawableButton::paintButton (Graphics& g,
  34602. bool isMouseOverButton,
  34603. bool isButtonDown)
  34604. {
  34605. Rectangle<int> imageSpace;
  34606. if (style == ImageOnButtonBackground)
  34607. {
  34608. const int insetX = getWidth() / 4;
  34609. const int insetY = getHeight() / 4;
  34610. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34611. getLookAndFeel().drawButtonBackground (g, *this,
  34612. getBackgroundColour(),
  34613. isMouseOverButton,
  34614. isButtonDown);
  34615. }
  34616. else
  34617. {
  34618. g.fillAll (getBackgroundColour());
  34619. const int textH = (style == ImageAboveTextLabel)
  34620. ? jmin (16, proportionOfHeight (0.25f))
  34621. : 0;
  34622. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34623. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34624. imageSpace.setBounds (indentX, indentY,
  34625. getWidth() - indentX * 2,
  34626. getHeight() - indentY * 2 - textH);
  34627. if (textH > 0)
  34628. {
  34629. g.setFont ((float) textH);
  34630. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34631. g.drawFittedText (getButtonText(),
  34632. 2, getHeight() - textH - 1,
  34633. getWidth() - 4, textH,
  34634. Justification::centred, 1);
  34635. }
  34636. }
  34637. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34638. g.setOpacity (1.0f);
  34639. const Drawable* imageToDraw = 0;
  34640. if (isEnabled())
  34641. {
  34642. imageToDraw = getCurrentImage();
  34643. }
  34644. else
  34645. {
  34646. imageToDraw = getToggleState() ? disabledImageOn
  34647. : disabledImage;
  34648. if (imageToDraw == 0)
  34649. {
  34650. g.setOpacity (0.4f);
  34651. imageToDraw = getNormalImage();
  34652. }
  34653. }
  34654. if (imageToDraw != 0)
  34655. {
  34656. if (style == ImageRaw)
  34657. {
  34658. imageToDraw->draw (g, 1.0f);
  34659. }
  34660. else
  34661. {
  34662. imageToDraw->drawWithin (g,
  34663. imageSpace.getX(),
  34664. imageSpace.getY(),
  34665. imageSpace.getWidth(),
  34666. imageSpace.getHeight(),
  34667. RectanglePlacement::centred,
  34668. 1.0f);
  34669. }
  34670. }
  34671. }
  34672. const Drawable* DrawableButton::getCurrentImage() const throw()
  34673. {
  34674. if (isDown())
  34675. return getDownImage();
  34676. if (isOver())
  34677. return getOverImage();
  34678. return getNormalImage();
  34679. }
  34680. const Drawable* DrawableButton::getNormalImage() const throw()
  34681. {
  34682. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34683. : normalImage;
  34684. }
  34685. const Drawable* DrawableButton::getOverImage() const throw()
  34686. {
  34687. const Drawable* d = normalImage;
  34688. if (getToggleState())
  34689. {
  34690. if (overImageOn != 0)
  34691. d = overImageOn;
  34692. else if (normalImageOn != 0)
  34693. d = normalImageOn;
  34694. else if (overImage != 0)
  34695. d = overImage;
  34696. }
  34697. else
  34698. {
  34699. if (overImage != 0)
  34700. d = overImage;
  34701. }
  34702. return d;
  34703. }
  34704. const Drawable* DrawableButton::getDownImage() const throw()
  34705. {
  34706. const Drawable* d = normalImage;
  34707. if (getToggleState())
  34708. {
  34709. if (downImageOn != 0)
  34710. d = downImageOn;
  34711. else if (overImageOn != 0)
  34712. d = overImageOn;
  34713. else if (normalImageOn != 0)
  34714. d = normalImageOn;
  34715. else if (downImage != 0)
  34716. d = downImage;
  34717. else
  34718. d = getOverImage();
  34719. }
  34720. else
  34721. {
  34722. if (downImage != 0)
  34723. d = downImage;
  34724. else
  34725. d = getOverImage();
  34726. }
  34727. return d;
  34728. }
  34729. END_JUCE_NAMESPACE
  34730. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34731. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34732. BEGIN_JUCE_NAMESPACE
  34733. HyperlinkButton::HyperlinkButton (const String& linkText,
  34734. const URL& linkURL)
  34735. : Button (linkText),
  34736. url (linkURL),
  34737. font (14.0f, Font::underlined),
  34738. resizeFont (true),
  34739. justification (Justification::centred)
  34740. {
  34741. setMouseCursor (MouseCursor::PointingHandCursor);
  34742. setTooltip (linkURL.toString (false));
  34743. }
  34744. HyperlinkButton::~HyperlinkButton()
  34745. {
  34746. }
  34747. void HyperlinkButton::setFont (const Font& newFont,
  34748. const bool resizeToMatchComponentHeight,
  34749. const Justification& justificationType)
  34750. {
  34751. font = newFont;
  34752. resizeFont = resizeToMatchComponentHeight;
  34753. justification = justificationType;
  34754. repaint();
  34755. }
  34756. void HyperlinkButton::setURL (const URL& newURL) throw()
  34757. {
  34758. url = newURL;
  34759. setTooltip (newURL.toString (false));
  34760. }
  34761. const Font HyperlinkButton::getFontToUse() const
  34762. {
  34763. Font f (font);
  34764. if (resizeFont)
  34765. f.setHeight (getHeight() * 0.7f);
  34766. return f;
  34767. }
  34768. void HyperlinkButton::changeWidthToFitText()
  34769. {
  34770. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34771. }
  34772. void HyperlinkButton::colourChanged()
  34773. {
  34774. repaint();
  34775. }
  34776. void HyperlinkButton::clicked()
  34777. {
  34778. if (url.isWellFormed())
  34779. url.launchInDefaultBrowser();
  34780. }
  34781. void HyperlinkButton::paintButton (Graphics& g,
  34782. bool isMouseOverButton,
  34783. bool isButtonDown)
  34784. {
  34785. const Colour textColour (findColour (textColourId));
  34786. if (isEnabled())
  34787. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34788. : textColour);
  34789. else
  34790. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34791. g.setFont (getFontToUse());
  34792. g.drawText (getButtonText(),
  34793. 2, 0, getWidth() - 2, getHeight(),
  34794. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34795. true);
  34796. }
  34797. END_JUCE_NAMESPACE
  34798. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34799. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34800. BEGIN_JUCE_NAMESPACE
  34801. ImageButton::ImageButton (const String& text_)
  34802. : Button (text_),
  34803. scaleImageToFit (true),
  34804. preserveProportions (true),
  34805. alphaThreshold (0),
  34806. imageX (0),
  34807. imageY (0),
  34808. imageW (0),
  34809. imageH (0),
  34810. normalImage (0),
  34811. overImage (0),
  34812. downImage (0)
  34813. {
  34814. }
  34815. ImageButton::~ImageButton()
  34816. {
  34817. }
  34818. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34819. const bool rescaleImagesWhenButtonSizeChanges,
  34820. const bool preserveImageProportions,
  34821. const Image& normalImage_,
  34822. const float imageOpacityWhenNormal,
  34823. const Colour& overlayColourWhenNormal,
  34824. const Image& overImage_,
  34825. const float imageOpacityWhenOver,
  34826. const Colour& overlayColourWhenOver,
  34827. const Image& downImage_,
  34828. const float imageOpacityWhenDown,
  34829. const Colour& overlayColourWhenDown,
  34830. const float hitTestAlphaThreshold)
  34831. {
  34832. normalImage = normalImage_;
  34833. overImage = overImage_;
  34834. downImage = downImage_;
  34835. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  34836. {
  34837. imageW = normalImage.getWidth();
  34838. imageH = normalImage.getHeight();
  34839. setSize (imageW, imageH);
  34840. }
  34841. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34842. preserveProportions = preserveImageProportions;
  34843. normalOpacity = imageOpacityWhenNormal;
  34844. normalOverlay = overlayColourWhenNormal;
  34845. overOpacity = imageOpacityWhenOver;
  34846. overOverlay = overlayColourWhenOver;
  34847. downOpacity = imageOpacityWhenDown;
  34848. downOverlay = overlayColourWhenDown;
  34849. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34850. repaint();
  34851. }
  34852. const Image ImageButton::getCurrentImage() const
  34853. {
  34854. if (isDown() || getToggleState())
  34855. return getDownImage();
  34856. if (isOver())
  34857. return getOverImage();
  34858. return getNormalImage();
  34859. }
  34860. const Image ImageButton::getNormalImage() const
  34861. {
  34862. return normalImage;
  34863. }
  34864. const Image ImageButton::getOverImage() const
  34865. {
  34866. return overImage.isValid() ? overImage
  34867. : normalImage;
  34868. }
  34869. const Image ImageButton::getDownImage() const
  34870. {
  34871. return downImage.isValid() ? downImage
  34872. : getOverImage();
  34873. }
  34874. void ImageButton::paintButton (Graphics& g,
  34875. bool isMouseOverButton,
  34876. bool isButtonDown)
  34877. {
  34878. if (! isEnabled())
  34879. {
  34880. isMouseOverButton = false;
  34881. isButtonDown = false;
  34882. }
  34883. Image im (getCurrentImage());
  34884. if (im.isValid())
  34885. {
  34886. const int iw = im.getWidth();
  34887. const int ih = im.getHeight();
  34888. imageW = getWidth();
  34889. imageH = getHeight();
  34890. imageX = (imageW - iw) >> 1;
  34891. imageY = (imageH - ih) >> 1;
  34892. if (scaleImageToFit)
  34893. {
  34894. if (preserveProportions)
  34895. {
  34896. int newW, newH;
  34897. const float imRatio = ih / (float)iw;
  34898. const float destRatio = imageH / (float)imageW;
  34899. if (imRatio > destRatio)
  34900. {
  34901. newW = roundToInt (imageH / imRatio);
  34902. newH = imageH;
  34903. }
  34904. else
  34905. {
  34906. newW = imageW;
  34907. newH = roundToInt (imageW * imRatio);
  34908. }
  34909. imageX = (imageW - newW) / 2;
  34910. imageY = (imageH - newH) / 2;
  34911. imageW = newW;
  34912. imageH = newH;
  34913. }
  34914. else
  34915. {
  34916. imageX = 0;
  34917. imageY = 0;
  34918. }
  34919. }
  34920. if (! scaleImageToFit)
  34921. {
  34922. imageW = iw;
  34923. imageH = ih;
  34924. }
  34925. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  34926. isButtonDown ? downOverlay
  34927. : (isMouseOverButton ? overOverlay
  34928. : normalOverlay),
  34929. isButtonDown ? downOpacity
  34930. : (isMouseOverButton ? overOpacity
  34931. : normalOpacity),
  34932. *this);
  34933. }
  34934. }
  34935. bool ImageButton::hitTest (int x, int y)
  34936. {
  34937. if (alphaThreshold == 0)
  34938. return true;
  34939. Image im (getCurrentImage());
  34940. return im.isNull() || (imageW > 0 && imageH > 0
  34941. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  34942. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  34943. }
  34944. END_JUCE_NAMESPACE
  34945. /*** End of inlined file: juce_ImageButton.cpp ***/
  34946. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34947. BEGIN_JUCE_NAMESPACE
  34948. ShapeButton::ShapeButton (const String& text_,
  34949. const Colour& normalColour_,
  34950. const Colour& overColour_,
  34951. const Colour& downColour_)
  34952. : Button (text_),
  34953. normalColour (normalColour_),
  34954. overColour (overColour_),
  34955. downColour (downColour_),
  34956. maintainShapeProportions (false),
  34957. outlineWidth (0.0f)
  34958. {
  34959. }
  34960. ShapeButton::~ShapeButton()
  34961. {
  34962. }
  34963. void ShapeButton::setColours (const Colour& newNormalColour,
  34964. const Colour& newOverColour,
  34965. const Colour& newDownColour)
  34966. {
  34967. normalColour = newNormalColour;
  34968. overColour = newOverColour;
  34969. downColour = newDownColour;
  34970. }
  34971. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34972. const float newOutlineWidth)
  34973. {
  34974. outlineColour = newOutlineColour;
  34975. outlineWidth = newOutlineWidth;
  34976. }
  34977. void ShapeButton::setShape (const Path& newShape,
  34978. const bool resizeNowToFitThisShape,
  34979. const bool maintainShapeProportions_,
  34980. const bool hasShadow)
  34981. {
  34982. shape = newShape;
  34983. maintainShapeProportions = maintainShapeProportions_;
  34984. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34985. setComponentEffect ((hasShadow) ? &shadow : 0);
  34986. if (resizeNowToFitThisShape)
  34987. {
  34988. Rectangle<float> bounds (shape.getBounds());
  34989. if (hasShadow)
  34990. bounds.expand (4.0f, 4.0f);
  34991. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34992. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34993. 1 + (int) (bounds.getHeight() + outlineWidth));
  34994. }
  34995. }
  34996. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34997. {
  34998. if (! isEnabled())
  34999. {
  35000. isMouseOverButton = false;
  35001. isButtonDown = false;
  35002. }
  35003. g.setColour ((isButtonDown) ? downColour
  35004. : (isMouseOverButton) ? overColour
  35005. : normalColour);
  35006. int w = getWidth();
  35007. int h = getHeight();
  35008. if (getComponentEffect() != 0)
  35009. {
  35010. w -= 4;
  35011. h -= 4;
  35012. }
  35013. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35014. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35015. w - offset - outlineWidth,
  35016. h - offset - outlineWidth,
  35017. maintainShapeProportions));
  35018. g.fillPath (shape, trans);
  35019. if (outlineWidth > 0.0f)
  35020. {
  35021. g.setColour (outlineColour);
  35022. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35023. }
  35024. }
  35025. END_JUCE_NAMESPACE
  35026. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35027. /*** Start of inlined file: juce_TextButton.cpp ***/
  35028. BEGIN_JUCE_NAMESPACE
  35029. TextButton::TextButton (const String& name,
  35030. const String& toolTip)
  35031. : Button (name)
  35032. {
  35033. setTooltip (toolTip);
  35034. }
  35035. TextButton::~TextButton()
  35036. {
  35037. }
  35038. void TextButton::paintButton (Graphics& g,
  35039. bool isMouseOverButton,
  35040. bool isButtonDown)
  35041. {
  35042. getLookAndFeel().drawButtonBackground (g, *this,
  35043. findColour (getToggleState() ? buttonOnColourId
  35044. : buttonColourId),
  35045. isMouseOverButton,
  35046. isButtonDown);
  35047. getLookAndFeel().drawButtonText (g, *this,
  35048. isMouseOverButton,
  35049. isButtonDown);
  35050. }
  35051. void TextButton::colourChanged()
  35052. {
  35053. repaint();
  35054. }
  35055. const Font TextButton::getFont()
  35056. {
  35057. return Font (jmin (15.0f, getHeight() * 0.6f));
  35058. }
  35059. void TextButton::changeWidthToFitText (const int newHeight)
  35060. {
  35061. if (newHeight >= 0)
  35062. setSize (jmax (1, getWidth()), newHeight);
  35063. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35064. getHeight());
  35065. }
  35066. END_JUCE_NAMESPACE
  35067. /*** End of inlined file: juce_TextButton.cpp ***/
  35068. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35069. BEGIN_JUCE_NAMESPACE
  35070. ToggleButton::ToggleButton (const String& buttonText)
  35071. : Button (buttonText)
  35072. {
  35073. setClickingTogglesState (true);
  35074. }
  35075. ToggleButton::~ToggleButton()
  35076. {
  35077. }
  35078. void ToggleButton::paintButton (Graphics& g,
  35079. bool isMouseOverButton,
  35080. bool isButtonDown)
  35081. {
  35082. getLookAndFeel().drawToggleButton (g, *this,
  35083. isMouseOverButton,
  35084. isButtonDown);
  35085. }
  35086. void ToggleButton::changeWidthToFitText()
  35087. {
  35088. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35089. }
  35090. void ToggleButton::colourChanged()
  35091. {
  35092. repaint();
  35093. }
  35094. END_JUCE_NAMESPACE
  35095. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35096. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35097. BEGIN_JUCE_NAMESPACE
  35098. ToolbarButton::ToolbarButton (const int itemId_,
  35099. const String& buttonText,
  35100. Drawable* const normalImage_,
  35101. Drawable* const toggledOnImage_)
  35102. : ToolbarItemComponent (itemId_, buttonText, true),
  35103. normalImage (normalImage_),
  35104. toggledOnImage (toggledOnImage_)
  35105. {
  35106. jassert (normalImage_ != 0);
  35107. }
  35108. ToolbarButton::~ToolbarButton()
  35109. {
  35110. }
  35111. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35112. bool /*isToolbarVertical*/,
  35113. int& preferredSize,
  35114. int& minSize, int& maxSize)
  35115. {
  35116. preferredSize = minSize = maxSize = toolbarDepth;
  35117. return true;
  35118. }
  35119. void ToolbarButton::paintButtonArea (Graphics& g,
  35120. int width, int height,
  35121. bool /*isMouseOver*/,
  35122. bool /*isMouseDown*/)
  35123. {
  35124. Drawable* d = normalImage;
  35125. if (getToggleState() && toggledOnImage != 0)
  35126. d = toggledOnImage;
  35127. if (! isEnabled())
  35128. {
  35129. Image im (Image::ARGB, width, height, true);
  35130. {
  35131. Graphics g2 (im);
  35132. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35133. }
  35134. im.desaturate();
  35135. g.drawImageAt (im, 0, 0);
  35136. }
  35137. else
  35138. {
  35139. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35140. }
  35141. }
  35142. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35143. {
  35144. }
  35145. END_JUCE_NAMESPACE
  35146. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35147. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35148. BEGIN_JUCE_NAMESPACE
  35149. class CodeDocumentLine
  35150. {
  35151. public:
  35152. CodeDocumentLine (const juce_wchar* const line_,
  35153. const int lineLength_,
  35154. const int numNewLineChars,
  35155. const int lineStartInFile_)
  35156. : line (line_, lineLength_),
  35157. lineStartInFile (lineStartInFile_),
  35158. lineLength (lineLength_),
  35159. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35160. {
  35161. }
  35162. ~CodeDocumentLine()
  35163. {
  35164. }
  35165. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35166. {
  35167. const juce_wchar* const t = text;
  35168. int pos = 0;
  35169. while (t [pos] != 0)
  35170. {
  35171. const int startOfLine = pos;
  35172. int numNewLineChars = 0;
  35173. while (t[pos] != 0)
  35174. {
  35175. if (t[pos] == '\r')
  35176. {
  35177. ++numNewLineChars;
  35178. ++pos;
  35179. if (t[pos] == '\n')
  35180. {
  35181. ++numNewLineChars;
  35182. ++pos;
  35183. }
  35184. break;
  35185. }
  35186. if (t[pos] == '\n')
  35187. {
  35188. ++numNewLineChars;
  35189. ++pos;
  35190. break;
  35191. }
  35192. ++pos;
  35193. }
  35194. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35195. numNewLineChars, startOfLine));
  35196. }
  35197. jassert (pos == text.length());
  35198. }
  35199. bool endsWithLineBreak() const throw()
  35200. {
  35201. return lineLengthWithoutNewLines != lineLength;
  35202. }
  35203. void updateLength() throw()
  35204. {
  35205. lineLengthWithoutNewLines = lineLength = line.length();
  35206. while (lineLengthWithoutNewLines > 0
  35207. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35208. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35209. {
  35210. --lineLengthWithoutNewLines;
  35211. }
  35212. }
  35213. String line;
  35214. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35215. };
  35216. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35217. : document (document_),
  35218. currentLine (document_->lines[0]),
  35219. line (0),
  35220. position (0)
  35221. {
  35222. }
  35223. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35224. : document (other.document),
  35225. currentLine (other.currentLine),
  35226. line (other.line),
  35227. position (other.position)
  35228. {
  35229. }
  35230. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35231. {
  35232. document = other.document;
  35233. currentLine = other.currentLine;
  35234. line = other.line;
  35235. position = other.position;
  35236. return *this;
  35237. }
  35238. CodeDocument::Iterator::~Iterator() throw()
  35239. {
  35240. }
  35241. juce_wchar CodeDocument::Iterator::nextChar()
  35242. {
  35243. if (currentLine == 0)
  35244. return 0;
  35245. jassert (currentLine == document->lines.getUnchecked (line));
  35246. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35247. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35248. {
  35249. ++line;
  35250. currentLine = document->lines [line];
  35251. }
  35252. return result;
  35253. }
  35254. void CodeDocument::Iterator::skip()
  35255. {
  35256. if (currentLine != 0)
  35257. {
  35258. jassert (currentLine == document->lines.getUnchecked (line));
  35259. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35260. {
  35261. ++line;
  35262. currentLine = document->lines [line];
  35263. }
  35264. }
  35265. }
  35266. void CodeDocument::Iterator::skipToEndOfLine()
  35267. {
  35268. if (currentLine != 0)
  35269. {
  35270. jassert (currentLine == document->lines.getUnchecked (line));
  35271. ++line;
  35272. currentLine = document->lines [line];
  35273. if (currentLine != 0)
  35274. position = currentLine->lineStartInFile;
  35275. else
  35276. position = document->getNumCharacters();
  35277. }
  35278. }
  35279. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35280. {
  35281. if (currentLine == 0)
  35282. return 0;
  35283. jassert (currentLine == document->lines.getUnchecked (line));
  35284. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35285. }
  35286. void CodeDocument::Iterator::skipWhitespace()
  35287. {
  35288. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35289. skip();
  35290. }
  35291. bool CodeDocument::Iterator::isEOF() const throw()
  35292. {
  35293. return currentLine == 0;
  35294. }
  35295. CodeDocument::Position::Position() throw()
  35296. : owner (0), characterPos (0), line (0),
  35297. indexInLine (0), positionMaintained (false)
  35298. {
  35299. }
  35300. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35301. const int line_, const int indexInLine_) throw()
  35302. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35303. characterPos (0), line (line_),
  35304. indexInLine (indexInLine_), positionMaintained (false)
  35305. {
  35306. setLineAndIndex (line_, indexInLine_);
  35307. }
  35308. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35309. const int characterPos_) throw()
  35310. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35311. positionMaintained (false)
  35312. {
  35313. setPosition (characterPos_);
  35314. }
  35315. CodeDocument::Position::Position (const Position& other) throw()
  35316. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35317. indexInLine (other.indexInLine), positionMaintained (false)
  35318. {
  35319. jassert (*this == other);
  35320. }
  35321. CodeDocument::Position::~Position() throw()
  35322. {
  35323. setPositionMaintained (false);
  35324. }
  35325. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35326. {
  35327. if (this != &other)
  35328. {
  35329. const bool wasPositionMaintained = positionMaintained;
  35330. if (owner != other.owner)
  35331. setPositionMaintained (false);
  35332. owner = other.owner;
  35333. line = other.line;
  35334. indexInLine = other.indexInLine;
  35335. characterPos = other.characterPos;
  35336. setPositionMaintained (wasPositionMaintained);
  35337. jassert (*this == other);
  35338. }
  35339. return *this;
  35340. }
  35341. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35342. {
  35343. jassert ((characterPos == other.characterPos)
  35344. == (line == other.line && indexInLine == other.indexInLine));
  35345. return characterPos == other.characterPos
  35346. && line == other.line
  35347. && indexInLine == other.indexInLine
  35348. && owner == other.owner;
  35349. }
  35350. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35351. {
  35352. return ! operator== (other);
  35353. }
  35354. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35355. {
  35356. jassert (owner != 0);
  35357. if (owner->lines.size() == 0)
  35358. {
  35359. line = 0;
  35360. indexInLine = 0;
  35361. characterPos = 0;
  35362. }
  35363. else
  35364. {
  35365. if (newLine >= owner->lines.size())
  35366. {
  35367. line = owner->lines.size() - 1;
  35368. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35369. jassert (l != 0);
  35370. indexInLine = l->lineLengthWithoutNewLines;
  35371. characterPos = l->lineStartInFile + indexInLine;
  35372. }
  35373. else
  35374. {
  35375. line = jmax (0, newLine);
  35376. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35377. jassert (l != 0);
  35378. if (l->lineLengthWithoutNewLines > 0)
  35379. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35380. else
  35381. indexInLine = 0;
  35382. characterPos = l->lineStartInFile + indexInLine;
  35383. }
  35384. }
  35385. }
  35386. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35387. {
  35388. jassert (owner != 0);
  35389. line = 0;
  35390. indexInLine = 0;
  35391. characterPos = 0;
  35392. if (newPosition > 0)
  35393. {
  35394. int lineStart = 0;
  35395. int lineEnd = owner->lines.size();
  35396. for (;;)
  35397. {
  35398. if (lineEnd - lineStart < 4)
  35399. {
  35400. for (int i = lineStart; i < lineEnd; ++i)
  35401. {
  35402. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35403. int index = newPosition - l->lineStartInFile;
  35404. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35405. {
  35406. line = i;
  35407. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35408. characterPos = l->lineStartInFile + indexInLine;
  35409. }
  35410. }
  35411. break;
  35412. }
  35413. else
  35414. {
  35415. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35416. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35417. if (newPosition >= mid->lineStartInFile)
  35418. lineStart = midIndex;
  35419. else
  35420. lineEnd = midIndex;
  35421. }
  35422. }
  35423. }
  35424. }
  35425. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35426. {
  35427. jassert (owner != 0);
  35428. if (characterDelta == 1)
  35429. {
  35430. setPosition (getPosition());
  35431. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35432. if (line < owner->lines.size())
  35433. {
  35434. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35435. if (indexInLine + characterDelta < l->lineLength
  35436. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35437. ++characterDelta;
  35438. }
  35439. }
  35440. setPosition (characterPos + characterDelta);
  35441. }
  35442. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35443. {
  35444. CodeDocument::Position p (*this);
  35445. p.moveBy (characterDelta);
  35446. return p;
  35447. }
  35448. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35449. {
  35450. CodeDocument::Position p (*this);
  35451. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35452. return p;
  35453. }
  35454. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35455. {
  35456. const CodeDocumentLine* const l = owner->lines [line];
  35457. return l == 0 ? 0 : l->line [getIndexInLine()];
  35458. }
  35459. const String CodeDocument::Position::getLineText() const throw()
  35460. {
  35461. const CodeDocumentLine* const l = owner->lines [line];
  35462. return l == 0 ? String::empty : l->line;
  35463. }
  35464. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35465. {
  35466. if (isMaintained != positionMaintained)
  35467. {
  35468. positionMaintained = isMaintained;
  35469. if (owner != 0)
  35470. {
  35471. if (isMaintained)
  35472. {
  35473. jassert (! owner->positionsToMaintain.contains (this));
  35474. owner->positionsToMaintain.add (this);
  35475. }
  35476. else
  35477. {
  35478. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35479. jassert (owner->positionsToMaintain.contains (this));
  35480. owner->positionsToMaintain.removeValue (this);
  35481. }
  35482. }
  35483. }
  35484. }
  35485. CodeDocument::CodeDocument()
  35486. : undoManager (std::numeric_limits<int>::max(), 10000),
  35487. currentActionIndex (0),
  35488. indexOfSavedState (-1),
  35489. maximumLineLength (-1),
  35490. newLineChars ("\r\n")
  35491. {
  35492. }
  35493. CodeDocument::~CodeDocument()
  35494. {
  35495. }
  35496. const String CodeDocument::getAllContent() const throw()
  35497. {
  35498. return getTextBetween (Position (this, 0),
  35499. Position (this, lines.size(), 0));
  35500. }
  35501. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35502. {
  35503. if (end.getPosition() <= start.getPosition())
  35504. return String::empty;
  35505. const int startLine = start.getLineNumber();
  35506. const int endLine = end.getLineNumber();
  35507. if (startLine == endLine)
  35508. {
  35509. CodeDocumentLine* const line = lines [startLine];
  35510. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35511. }
  35512. String result;
  35513. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35514. String::Concatenator concatenator (result);
  35515. const int maxLine = jmin (lines.size() - 1, endLine);
  35516. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35517. {
  35518. const CodeDocumentLine* line = lines.getUnchecked(i);
  35519. int len = line->lineLength;
  35520. if (i == startLine)
  35521. {
  35522. const int index = start.getIndexInLine();
  35523. concatenator.append (line->line.substring (index, len));
  35524. }
  35525. else if (i == endLine)
  35526. {
  35527. len = end.getIndexInLine();
  35528. concatenator.append (line->line.substring (0, len));
  35529. }
  35530. else
  35531. {
  35532. concatenator.append (line->line);
  35533. }
  35534. }
  35535. return result;
  35536. }
  35537. int CodeDocument::getNumCharacters() const throw()
  35538. {
  35539. const CodeDocumentLine* const lastLine = lines.getLast();
  35540. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35541. }
  35542. const String CodeDocument::getLine (const int lineIndex) const throw()
  35543. {
  35544. const CodeDocumentLine* const line = lines [lineIndex];
  35545. return (line == 0) ? String::empty : line->line;
  35546. }
  35547. int CodeDocument::getMaximumLineLength() throw()
  35548. {
  35549. if (maximumLineLength < 0)
  35550. {
  35551. maximumLineLength = 0;
  35552. for (int i = lines.size(); --i >= 0;)
  35553. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35554. }
  35555. return maximumLineLength;
  35556. }
  35557. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35558. {
  35559. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35560. }
  35561. void CodeDocument::insertText (const Position& position, const String& text)
  35562. {
  35563. insert (text, position.getPosition(), true);
  35564. }
  35565. void CodeDocument::replaceAllContent (const String& newContent)
  35566. {
  35567. remove (0, getNumCharacters(), true);
  35568. insert (newContent, 0, true);
  35569. }
  35570. bool CodeDocument::loadFromStream (InputStream& stream)
  35571. {
  35572. replaceAllContent (stream.readEntireStreamAsString());
  35573. setSavePoint();
  35574. clearUndoHistory();
  35575. return true;
  35576. }
  35577. bool CodeDocument::writeToStream (OutputStream& stream)
  35578. {
  35579. for (int i = 0; i < lines.size(); ++i)
  35580. {
  35581. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35582. const char* utf8 = temp.toUTF8();
  35583. if (! stream.write (utf8, (int) strlen (utf8)))
  35584. return false;
  35585. }
  35586. return true;
  35587. }
  35588. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35589. {
  35590. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35591. newLineChars = newLine;
  35592. }
  35593. void CodeDocument::newTransaction()
  35594. {
  35595. undoManager.beginNewTransaction (String::empty);
  35596. }
  35597. void CodeDocument::undo()
  35598. {
  35599. newTransaction();
  35600. undoManager.undo();
  35601. }
  35602. void CodeDocument::redo()
  35603. {
  35604. undoManager.redo();
  35605. }
  35606. void CodeDocument::clearUndoHistory()
  35607. {
  35608. undoManager.clearUndoHistory();
  35609. }
  35610. void CodeDocument::setSavePoint() throw()
  35611. {
  35612. indexOfSavedState = currentActionIndex;
  35613. }
  35614. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35615. {
  35616. return currentActionIndex != indexOfSavedState;
  35617. }
  35618. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35619. {
  35620. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35621. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35622. }
  35623. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35624. {
  35625. Position p (position);
  35626. const int maxDistance = 256;
  35627. int i = 0;
  35628. while (i < maxDistance
  35629. && CharacterFunctions::isWhitespace (p.getCharacter())
  35630. && (i == 0 || (p.getCharacter() != '\n'
  35631. && p.getCharacter() != '\r')))
  35632. {
  35633. ++i;
  35634. p.moveBy (1);
  35635. }
  35636. if (i == 0)
  35637. {
  35638. const int type = getCodeCharacterCategory (p.getCharacter());
  35639. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35640. {
  35641. ++i;
  35642. p.moveBy (1);
  35643. }
  35644. while (i < maxDistance
  35645. && CharacterFunctions::isWhitespace (p.getCharacter())
  35646. && (i == 0 || (p.getCharacter() != '\n'
  35647. && p.getCharacter() != '\r')))
  35648. {
  35649. ++i;
  35650. p.moveBy (1);
  35651. }
  35652. }
  35653. return p;
  35654. }
  35655. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35656. {
  35657. Position p (position);
  35658. const int maxDistance = 256;
  35659. int i = 0;
  35660. bool stoppedAtLineStart = false;
  35661. while (i < maxDistance)
  35662. {
  35663. const juce_wchar c = p.movedBy (-1).getCharacter();
  35664. if (c == '\r' || c == '\n')
  35665. {
  35666. stoppedAtLineStart = true;
  35667. if (i > 0)
  35668. break;
  35669. }
  35670. if (! CharacterFunctions::isWhitespace (c))
  35671. break;
  35672. p.moveBy (-1);
  35673. ++i;
  35674. }
  35675. if (i < maxDistance && ! stoppedAtLineStart)
  35676. {
  35677. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35678. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35679. {
  35680. p.moveBy (-1);
  35681. ++i;
  35682. }
  35683. }
  35684. return p;
  35685. }
  35686. void CodeDocument::checkLastLineStatus()
  35687. {
  35688. while (lines.size() > 0
  35689. && lines.getLast()->lineLength == 0
  35690. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35691. {
  35692. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35693. lines.removeLast();
  35694. }
  35695. const CodeDocumentLine* const lastLine = lines.getLast();
  35696. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35697. {
  35698. // check that there's an empty line at the end if the preceding one ends in a newline..
  35699. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35700. }
  35701. }
  35702. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35703. {
  35704. listeners.add (listener);
  35705. }
  35706. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35707. {
  35708. listeners.remove (listener);
  35709. }
  35710. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35711. {
  35712. Position startPos (this, startLine, 0);
  35713. Position endPos (this, endLine, 0);
  35714. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35715. }
  35716. class CodeDocumentInsertAction : public UndoableAction
  35717. {
  35718. CodeDocument& owner;
  35719. const String text;
  35720. int insertPos;
  35721. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35722. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35723. public:
  35724. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35725. : owner (owner_),
  35726. text (text_),
  35727. insertPos (insertPos_)
  35728. {
  35729. }
  35730. ~CodeDocumentInsertAction() {}
  35731. bool perform()
  35732. {
  35733. owner.currentActionIndex++;
  35734. owner.insert (text, insertPos, false);
  35735. return true;
  35736. }
  35737. bool undo()
  35738. {
  35739. owner.currentActionIndex--;
  35740. owner.remove (insertPos, insertPos + text.length(), false);
  35741. return true;
  35742. }
  35743. int getSizeInUnits() { return text.length() + 32; }
  35744. };
  35745. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35746. {
  35747. if (text.isEmpty())
  35748. return;
  35749. if (undoable)
  35750. {
  35751. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35752. }
  35753. else
  35754. {
  35755. Position pos (this, insertPos);
  35756. const int firstAffectedLine = pos.getLineNumber();
  35757. int lastAffectedLine = firstAffectedLine + 1;
  35758. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35759. String textInsideOriginalLine (text);
  35760. if (firstLine != 0)
  35761. {
  35762. const int index = pos.getIndexInLine();
  35763. textInsideOriginalLine = firstLine->line.substring (0, index)
  35764. + textInsideOriginalLine
  35765. + firstLine->line.substring (index);
  35766. }
  35767. maximumLineLength = -1;
  35768. Array <CodeDocumentLine*> newLines;
  35769. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35770. jassert (newLines.size() > 0);
  35771. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35772. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35773. lines.set (firstAffectedLine, newFirstLine);
  35774. if (newLines.size() > 1)
  35775. {
  35776. for (int i = 1; i < newLines.size(); ++i)
  35777. {
  35778. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35779. lines.insert (firstAffectedLine + i, l);
  35780. }
  35781. lastAffectedLine = lines.size();
  35782. }
  35783. int i, lineStart = newFirstLine->lineStartInFile;
  35784. for (i = firstAffectedLine; i < lines.size(); ++i)
  35785. {
  35786. CodeDocumentLine* const l = lines.getUnchecked (i);
  35787. l->lineStartInFile = lineStart;
  35788. lineStart += l->lineLength;
  35789. }
  35790. checkLastLineStatus();
  35791. const int newTextLength = text.length();
  35792. for (i = 0; i < positionsToMaintain.size(); ++i)
  35793. {
  35794. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35795. if (p->getPosition() >= insertPos)
  35796. p->setPosition (p->getPosition() + newTextLength);
  35797. }
  35798. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35799. }
  35800. }
  35801. class CodeDocumentDeleteAction : public UndoableAction
  35802. {
  35803. CodeDocument& owner;
  35804. int startPos, endPos;
  35805. String removedText;
  35806. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35807. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35808. public:
  35809. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35810. : owner (owner_),
  35811. startPos (startPos_),
  35812. endPos (endPos_)
  35813. {
  35814. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35815. CodeDocument::Position (&owner, endPos));
  35816. }
  35817. ~CodeDocumentDeleteAction() {}
  35818. bool perform()
  35819. {
  35820. owner.currentActionIndex++;
  35821. owner.remove (startPos, endPos, false);
  35822. return true;
  35823. }
  35824. bool undo()
  35825. {
  35826. owner.currentActionIndex--;
  35827. owner.insert (removedText, startPos, false);
  35828. return true;
  35829. }
  35830. int getSizeInUnits() { return removedText.length() + 32; }
  35831. };
  35832. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35833. {
  35834. if (endPos <= startPos)
  35835. return;
  35836. if (undoable)
  35837. {
  35838. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35839. }
  35840. else
  35841. {
  35842. Position startPosition (this, startPos);
  35843. Position endPosition (this, endPos);
  35844. maximumLineLength = -1;
  35845. const int firstAffectedLine = startPosition.getLineNumber();
  35846. const int endLine = endPosition.getLineNumber();
  35847. int lastAffectedLine = firstAffectedLine + 1;
  35848. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35849. if (firstAffectedLine == endLine)
  35850. {
  35851. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35852. + firstLine->line.substring (endPosition.getIndexInLine());
  35853. firstLine->updateLength();
  35854. }
  35855. else
  35856. {
  35857. lastAffectedLine = lines.size();
  35858. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35859. jassert (lastLine != 0);
  35860. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35861. + lastLine->line.substring (endPosition.getIndexInLine());
  35862. firstLine->updateLength();
  35863. int numLinesToRemove = endLine - firstAffectedLine;
  35864. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35865. }
  35866. int i;
  35867. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35868. {
  35869. CodeDocumentLine* const l = lines.getUnchecked (i);
  35870. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35871. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35872. }
  35873. checkLastLineStatus();
  35874. const int totalChars = getNumCharacters();
  35875. for (i = 0; i < positionsToMaintain.size(); ++i)
  35876. {
  35877. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35878. if (p->getPosition() > startPosition.getPosition())
  35879. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35880. if (p->getPosition() > totalChars)
  35881. p->setPosition (totalChars);
  35882. }
  35883. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35884. }
  35885. }
  35886. END_JUCE_NAMESPACE
  35887. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35888. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35889. BEGIN_JUCE_NAMESPACE
  35890. class CodeEditorComponent::CaretComponent : public Component,
  35891. public Timer
  35892. {
  35893. public:
  35894. CaretComponent (CodeEditorComponent& owner_)
  35895. : owner (owner_)
  35896. {
  35897. setAlwaysOnTop (true);
  35898. setInterceptsMouseClicks (false, false);
  35899. }
  35900. ~CaretComponent()
  35901. {
  35902. }
  35903. void paint (Graphics& g)
  35904. {
  35905. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35906. }
  35907. void timerCallback()
  35908. {
  35909. setVisible (shouldBeShown() && ! isVisible());
  35910. }
  35911. void updatePosition()
  35912. {
  35913. startTimer (400);
  35914. setVisible (shouldBeShown());
  35915. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35916. }
  35917. private:
  35918. CodeEditorComponent& owner;
  35919. CaretComponent (const CaretComponent&);
  35920. CaretComponent& operator= (const CaretComponent&);
  35921. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35922. };
  35923. class CodeEditorComponent::CodeEditorLine
  35924. {
  35925. public:
  35926. CodeEditorLine() throw()
  35927. : highlightColumnStart (0), highlightColumnEnd (0)
  35928. {
  35929. }
  35930. ~CodeEditorLine() throw()
  35931. {
  35932. }
  35933. bool update (CodeDocument& document, int lineNum,
  35934. CodeDocument::Iterator& source,
  35935. CodeTokeniser* analyser, const int spacesPerTab,
  35936. const CodeDocument::Position& selectionStart,
  35937. const CodeDocument::Position& selectionEnd)
  35938. {
  35939. Array <SyntaxToken> newTokens;
  35940. newTokens.ensureStorageAllocated (8);
  35941. if (analyser == 0)
  35942. {
  35943. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35944. }
  35945. else if (lineNum < document.getNumLines())
  35946. {
  35947. const CodeDocument::Position pos (&document, lineNum, 0);
  35948. createTokens (pos.getPosition(), pos.getLineText(),
  35949. source, analyser, newTokens);
  35950. }
  35951. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35952. int newHighlightStart = 0;
  35953. int newHighlightEnd = 0;
  35954. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35955. {
  35956. const String line (document.getLine (lineNum));
  35957. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35958. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35959. line, spacesPerTab);
  35960. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35961. line, spacesPerTab);
  35962. }
  35963. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35964. {
  35965. highlightColumnStart = newHighlightStart;
  35966. highlightColumnEnd = newHighlightEnd;
  35967. }
  35968. else
  35969. {
  35970. if (tokens.size() == newTokens.size())
  35971. {
  35972. bool allTheSame = true;
  35973. for (int i = newTokens.size(); --i >= 0;)
  35974. {
  35975. if (tokens.getReference(i) != newTokens.getReference(i))
  35976. {
  35977. allTheSame = false;
  35978. break;
  35979. }
  35980. }
  35981. if (allTheSame)
  35982. return false;
  35983. }
  35984. }
  35985. tokens.swapWithArray (newTokens);
  35986. return true;
  35987. }
  35988. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35989. float x, const int y, const int baselineOffset, const int lineHeight,
  35990. const Colour& highlightColour) const throw()
  35991. {
  35992. if (highlightColumnStart < highlightColumnEnd)
  35993. {
  35994. g.setColour (highlightColour);
  35995. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35996. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35997. }
  35998. int lastType = std::numeric_limits<int>::min();
  35999. for (int i = 0; i < tokens.size(); ++i)
  36000. {
  36001. SyntaxToken& token = tokens.getReference(i);
  36002. if (lastType != token.tokenType)
  36003. {
  36004. lastType = token.tokenType;
  36005. g.setColour (owner.getColourForTokenType (lastType));
  36006. }
  36007. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36008. if (i < tokens.size() - 1)
  36009. {
  36010. if (token.width < 0)
  36011. token.width = font.getStringWidthFloat (token.text);
  36012. x += token.width;
  36013. }
  36014. }
  36015. }
  36016. private:
  36017. struct SyntaxToken
  36018. {
  36019. String text;
  36020. int tokenType;
  36021. float width;
  36022. SyntaxToken (const String& text_, const int type) throw()
  36023. : text (text_), tokenType (type), width (-1.0f)
  36024. {
  36025. }
  36026. bool operator!= (const SyntaxToken& other) const throw()
  36027. {
  36028. return text != other.text || tokenType != other.tokenType;
  36029. }
  36030. };
  36031. Array <SyntaxToken> tokens;
  36032. int highlightColumnStart, highlightColumnEnd;
  36033. static void createTokens (int startPosition, const String& lineText,
  36034. CodeDocument::Iterator& source,
  36035. CodeTokeniser* analyser,
  36036. Array <SyntaxToken>& newTokens)
  36037. {
  36038. CodeDocument::Iterator lastIterator (source);
  36039. const int lineLength = lineText.length();
  36040. for (;;)
  36041. {
  36042. int tokenType = analyser->readNextToken (source);
  36043. int tokenStart = lastIterator.getPosition();
  36044. int tokenEnd = source.getPosition();
  36045. if (tokenEnd <= tokenStart)
  36046. break;
  36047. tokenEnd -= startPosition;
  36048. if (tokenEnd > 0)
  36049. {
  36050. tokenStart -= startPosition;
  36051. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36052. tokenType));
  36053. if (tokenEnd >= lineLength)
  36054. break;
  36055. }
  36056. lastIterator = source;
  36057. }
  36058. source = lastIterator;
  36059. }
  36060. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  36061. {
  36062. int x = 0;
  36063. for (int i = 0; i < tokens.size(); ++i)
  36064. {
  36065. SyntaxToken& t = tokens.getReference(i);
  36066. for (;;)
  36067. {
  36068. int tabPos = t.text.indexOfChar ('\t');
  36069. if (tabPos < 0)
  36070. break;
  36071. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36072. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36073. }
  36074. x += t.text.length();
  36075. }
  36076. }
  36077. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36078. {
  36079. jassert (index <= line.length());
  36080. int col = 0;
  36081. for (int i = 0; i < index; ++i)
  36082. {
  36083. if (line[i] != '\t')
  36084. ++col;
  36085. else
  36086. col += spacesPerTab - (col % spacesPerTab);
  36087. }
  36088. return col;
  36089. }
  36090. };
  36091. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36092. CodeTokeniser* const codeTokeniser_)
  36093. : document (document_),
  36094. firstLineOnScreen (0),
  36095. gutter (5),
  36096. spacesPerTab (4),
  36097. lineHeight (0),
  36098. linesOnScreen (0),
  36099. columnsOnScreen (0),
  36100. scrollbarThickness (16),
  36101. columnToTryToMaintain (-1),
  36102. useSpacesForTabs (false),
  36103. xOffset (0),
  36104. codeTokeniser (codeTokeniser_)
  36105. {
  36106. caretPos = CodeDocument::Position (&document_, 0, 0);
  36107. caretPos.setPositionMaintained (true);
  36108. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36109. selectionStart.setPositionMaintained (true);
  36110. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36111. selectionEnd.setPositionMaintained (true);
  36112. setOpaque (true);
  36113. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36114. setWantsKeyboardFocus (true);
  36115. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36116. verticalScrollBar->setSingleStepSize (1.0);
  36117. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36118. horizontalScrollBar->setSingleStepSize (1.0);
  36119. addAndMakeVisible (caret = new CaretComponent (*this));
  36120. Font f (12.0f);
  36121. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36122. setFont (f);
  36123. resetToDefaultColours();
  36124. verticalScrollBar->addListener (this);
  36125. horizontalScrollBar->addListener (this);
  36126. document.addListener (this);
  36127. }
  36128. CodeEditorComponent::~CodeEditorComponent()
  36129. {
  36130. document.removeListener (this);
  36131. deleteAllChildren();
  36132. }
  36133. void CodeEditorComponent::loadContent (const String& newContent)
  36134. {
  36135. clearCachedIterators (0);
  36136. document.replaceAllContent (newContent);
  36137. document.clearUndoHistory();
  36138. document.setSavePoint();
  36139. caretPos.setPosition (0);
  36140. selectionStart.setPosition (0);
  36141. selectionEnd.setPosition (0);
  36142. scrollToLine (0);
  36143. }
  36144. bool CodeEditorComponent::isTextInputActive() const
  36145. {
  36146. return true;
  36147. }
  36148. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36149. const CodeDocument::Position& affectedTextEnd)
  36150. {
  36151. clearCachedIterators (affectedTextStart.getLineNumber());
  36152. triggerAsyncUpdate();
  36153. caret->updatePosition();
  36154. columnToTryToMaintain = -1;
  36155. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36156. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36157. deselectAll();
  36158. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36159. || caretPos.getPosition() < affectedTextStart.getPosition())
  36160. moveCaretTo (affectedTextStart, false);
  36161. updateScrollBars();
  36162. }
  36163. void CodeEditorComponent::resized()
  36164. {
  36165. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36166. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36167. lines.clear();
  36168. rebuildLineTokens();
  36169. caret->updatePosition();
  36170. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36171. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36172. updateScrollBars();
  36173. }
  36174. void CodeEditorComponent::paint (Graphics& g)
  36175. {
  36176. handleUpdateNowIfNeeded();
  36177. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36178. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36179. g.setFont (font);
  36180. const int baselineOffset = (int) font.getAscent();
  36181. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36182. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36183. const Rectangle<int> clip (g.getClipBounds());
  36184. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36185. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36186. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36187. {
  36188. lines.getUnchecked(j)->draw (*this, g, font,
  36189. (float) (gutter - xOffset * charWidth),
  36190. lineHeight * j, baselineOffset, lineHeight,
  36191. highlightColour);
  36192. }
  36193. }
  36194. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36195. {
  36196. if (scrollbarThickness != thickness)
  36197. {
  36198. scrollbarThickness = thickness;
  36199. resized();
  36200. }
  36201. }
  36202. void CodeEditorComponent::handleAsyncUpdate()
  36203. {
  36204. rebuildLineTokens();
  36205. }
  36206. void CodeEditorComponent::rebuildLineTokens()
  36207. {
  36208. cancelPendingUpdate();
  36209. const int numNeeded = linesOnScreen + 1;
  36210. int minLineToRepaint = numNeeded;
  36211. int maxLineToRepaint = 0;
  36212. if (numNeeded != lines.size())
  36213. {
  36214. lines.clear();
  36215. for (int i = numNeeded; --i >= 0;)
  36216. lines.add (new CodeEditorLine());
  36217. minLineToRepaint = 0;
  36218. maxLineToRepaint = numNeeded;
  36219. }
  36220. jassert (numNeeded == lines.size());
  36221. CodeDocument::Iterator source (&document);
  36222. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36223. for (int i = 0; i < numNeeded; ++i)
  36224. {
  36225. CodeEditorLine* const line = lines.getUnchecked(i);
  36226. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36227. selectionStart, selectionEnd))
  36228. {
  36229. minLineToRepaint = jmin (minLineToRepaint, i);
  36230. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36231. }
  36232. }
  36233. if (minLineToRepaint <= maxLineToRepaint)
  36234. {
  36235. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36236. verticalScrollBar->getX() - gutter,
  36237. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36238. }
  36239. }
  36240. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36241. {
  36242. caretPos = newPos;
  36243. columnToTryToMaintain = -1;
  36244. if (highlighting)
  36245. {
  36246. if (dragType == notDragging)
  36247. {
  36248. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36249. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36250. dragType = draggingSelectionStart;
  36251. else
  36252. dragType = draggingSelectionEnd;
  36253. }
  36254. if (dragType == draggingSelectionStart)
  36255. {
  36256. selectionStart = caretPos;
  36257. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36258. {
  36259. const CodeDocument::Position temp (selectionStart);
  36260. selectionStart = selectionEnd;
  36261. selectionEnd = temp;
  36262. dragType = draggingSelectionEnd;
  36263. }
  36264. }
  36265. else
  36266. {
  36267. selectionEnd = caretPos;
  36268. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36269. {
  36270. const CodeDocument::Position temp (selectionStart);
  36271. selectionStart = selectionEnd;
  36272. selectionEnd = temp;
  36273. dragType = draggingSelectionStart;
  36274. }
  36275. }
  36276. triggerAsyncUpdate();
  36277. }
  36278. else
  36279. {
  36280. deselectAll();
  36281. }
  36282. caret->updatePosition();
  36283. scrollToKeepCaretOnScreen();
  36284. updateScrollBars();
  36285. }
  36286. void CodeEditorComponent::deselectAll()
  36287. {
  36288. if (selectionStart != selectionEnd)
  36289. triggerAsyncUpdate();
  36290. selectionStart = caretPos;
  36291. selectionEnd = caretPos;
  36292. }
  36293. void CodeEditorComponent::updateScrollBars()
  36294. {
  36295. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36296. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36297. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36298. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36299. }
  36300. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36301. {
  36302. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36303. newFirstLineOnScreen);
  36304. if (newFirstLineOnScreen != firstLineOnScreen)
  36305. {
  36306. firstLineOnScreen = newFirstLineOnScreen;
  36307. caret->updatePosition();
  36308. updateCachedIterators (firstLineOnScreen);
  36309. triggerAsyncUpdate();
  36310. }
  36311. }
  36312. void CodeEditorComponent::scrollToColumnInternal (double column)
  36313. {
  36314. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36315. if (xOffset != newOffset)
  36316. {
  36317. xOffset = newOffset;
  36318. caret->updatePosition();
  36319. repaint();
  36320. }
  36321. }
  36322. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36323. {
  36324. scrollToLineInternal (newFirstLineOnScreen);
  36325. updateScrollBars();
  36326. }
  36327. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36328. {
  36329. scrollToColumnInternal (newFirstColumnOnScreen);
  36330. updateScrollBars();
  36331. }
  36332. void CodeEditorComponent::scrollBy (int deltaLines)
  36333. {
  36334. scrollToLine (firstLineOnScreen + deltaLines);
  36335. }
  36336. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36337. {
  36338. if (caretPos.getLineNumber() < firstLineOnScreen)
  36339. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36340. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36341. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36342. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36343. if (column >= xOffset + columnsOnScreen - 1)
  36344. scrollToColumn (column + 1 - columnsOnScreen);
  36345. else if (column < xOffset)
  36346. scrollToColumn (column);
  36347. }
  36348. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36349. {
  36350. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36351. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36352. roundToInt (charWidth),
  36353. lineHeight);
  36354. }
  36355. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36356. {
  36357. const int line = y / lineHeight + firstLineOnScreen;
  36358. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36359. const int index = columnToIndex (line, column);
  36360. return CodeDocument::Position (&document, line, index);
  36361. }
  36362. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36363. {
  36364. document.deleteSection (selectionStart, selectionEnd);
  36365. if (newText.isNotEmpty())
  36366. document.insertText (caretPos, newText);
  36367. scrollToKeepCaretOnScreen();
  36368. }
  36369. void CodeEditorComponent::insertTabAtCaret()
  36370. {
  36371. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36372. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36373. {
  36374. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36375. }
  36376. if (useSpacesForTabs)
  36377. {
  36378. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36379. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36380. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36381. }
  36382. else
  36383. {
  36384. insertTextAtCaret ("\t");
  36385. }
  36386. }
  36387. void CodeEditorComponent::cut()
  36388. {
  36389. insertTextAtCaret (String::empty);
  36390. }
  36391. void CodeEditorComponent::copy()
  36392. {
  36393. newTransaction();
  36394. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36395. if (selection.isNotEmpty())
  36396. SystemClipboard::copyTextToClipboard (selection);
  36397. }
  36398. void CodeEditorComponent::copyThenCut()
  36399. {
  36400. copy();
  36401. cut();
  36402. newTransaction();
  36403. }
  36404. void CodeEditorComponent::paste()
  36405. {
  36406. newTransaction();
  36407. const String clip (SystemClipboard::getTextFromClipboard());
  36408. if (clip.isNotEmpty())
  36409. insertTextAtCaret (clip);
  36410. newTransaction();
  36411. }
  36412. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36413. {
  36414. newTransaction();
  36415. if (moveInWholeWordSteps)
  36416. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36417. else
  36418. moveCaretTo (caretPos.movedBy (-1), selecting);
  36419. }
  36420. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36421. {
  36422. newTransaction();
  36423. if (moveInWholeWordSteps)
  36424. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36425. else
  36426. moveCaretTo (caretPos.movedBy (1), selecting);
  36427. }
  36428. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36429. {
  36430. CodeDocument::Position pos (caretPos);
  36431. const int newLineNum = pos.getLineNumber() + delta;
  36432. if (columnToTryToMaintain < 0)
  36433. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36434. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36435. const int colToMaintain = columnToTryToMaintain;
  36436. moveCaretTo (pos, selecting);
  36437. columnToTryToMaintain = colToMaintain;
  36438. }
  36439. void CodeEditorComponent::cursorDown (const bool selecting)
  36440. {
  36441. newTransaction();
  36442. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36443. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36444. else
  36445. moveLineDelta (1, selecting);
  36446. }
  36447. void CodeEditorComponent::cursorUp (const bool selecting)
  36448. {
  36449. newTransaction();
  36450. if (caretPos.getLineNumber() == 0)
  36451. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36452. else
  36453. moveLineDelta (-1, selecting);
  36454. }
  36455. void CodeEditorComponent::pageDown (const bool selecting)
  36456. {
  36457. newTransaction();
  36458. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36459. moveLineDelta (linesOnScreen, selecting);
  36460. }
  36461. void CodeEditorComponent::pageUp (const bool selecting)
  36462. {
  36463. newTransaction();
  36464. scrollBy (-linesOnScreen);
  36465. moveLineDelta (-linesOnScreen, selecting);
  36466. }
  36467. void CodeEditorComponent::scrollUp()
  36468. {
  36469. newTransaction();
  36470. scrollBy (1);
  36471. if (caretPos.getLineNumber() < firstLineOnScreen)
  36472. moveLineDelta (1, false);
  36473. }
  36474. void CodeEditorComponent::scrollDown()
  36475. {
  36476. newTransaction();
  36477. scrollBy (-1);
  36478. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36479. moveLineDelta (-1, false);
  36480. }
  36481. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36482. {
  36483. newTransaction();
  36484. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36485. }
  36486. static int findFirstNonWhitespaceChar (const String& line) throw()
  36487. {
  36488. const int len = line.length();
  36489. for (int i = 0; i < len; ++i)
  36490. if (! CharacterFunctions::isWhitespace (line [i]))
  36491. return i;
  36492. return 0;
  36493. }
  36494. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36495. {
  36496. newTransaction();
  36497. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36498. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36499. index = 0;
  36500. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36501. }
  36502. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36503. {
  36504. newTransaction();
  36505. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36506. }
  36507. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36508. {
  36509. newTransaction();
  36510. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36511. }
  36512. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36513. {
  36514. if (moveInWholeWordSteps)
  36515. {
  36516. cut(); // in case something is already highlighted
  36517. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36518. }
  36519. else
  36520. {
  36521. if (selectionStart == selectionEnd)
  36522. selectionStart.moveBy (-1);
  36523. }
  36524. cut();
  36525. }
  36526. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36527. {
  36528. if (moveInWholeWordSteps)
  36529. {
  36530. cut(); // in case something is already highlighted
  36531. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36532. }
  36533. else
  36534. {
  36535. if (selectionStart == selectionEnd)
  36536. selectionEnd.moveBy (1);
  36537. else
  36538. newTransaction();
  36539. }
  36540. cut();
  36541. }
  36542. void CodeEditorComponent::selectAll()
  36543. {
  36544. newTransaction();
  36545. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36546. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36547. }
  36548. void CodeEditorComponent::undo()
  36549. {
  36550. document.undo();
  36551. scrollToKeepCaretOnScreen();
  36552. }
  36553. void CodeEditorComponent::redo()
  36554. {
  36555. document.redo();
  36556. scrollToKeepCaretOnScreen();
  36557. }
  36558. void CodeEditorComponent::newTransaction()
  36559. {
  36560. document.newTransaction();
  36561. startTimer (600);
  36562. }
  36563. void CodeEditorComponent::timerCallback()
  36564. {
  36565. newTransaction();
  36566. }
  36567. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36568. {
  36569. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36570. }
  36571. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36572. {
  36573. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36574. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36575. }
  36576. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36577. {
  36578. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36579. CodeDocument::Position (&document, range.getEnd()));
  36580. }
  36581. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36582. {
  36583. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36584. const bool shiftDown = key.getModifiers().isShiftDown();
  36585. if (key.isKeyCode (KeyPress::leftKey))
  36586. {
  36587. cursorLeft (moveInWholeWordSteps, shiftDown);
  36588. }
  36589. else if (key.isKeyCode (KeyPress::rightKey))
  36590. {
  36591. cursorRight (moveInWholeWordSteps, shiftDown);
  36592. }
  36593. else if (key.isKeyCode (KeyPress::upKey))
  36594. {
  36595. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36596. scrollDown();
  36597. #if JUCE_MAC
  36598. else if (key.getModifiers().isCommandDown())
  36599. goToStartOfDocument (shiftDown);
  36600. #endif
  36601. else
  36602. cursorUp (shiftDown);
  36603. }
  36604. else if (key.isKeyCode (KeyPress::downKey))
  36605. {
  36606. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36607. scrollUp();
  36608. #if JUCE_MAC
  36609. else if (key.getModifiers().isCommandDown())
  36610. goToEndOfDocument (shiftDown);
  36611. #endif
  36612. else
  36613. cursorDown (shiftDown);
  36614. }
  36615. else if (key.isKeyCode (KeyPress::pageDownKey))
  36616. {
  36617. pageDown (shiftDown);
  36618. }
  36619. else if (key.isKeyCode (KeyPress::pageUpKey))
  36620. {
  36621. pageUp (shiftDown);
  36622. }
  36623. else if (key.isKeyCode (KeyPress::homeKey))
  36624. {
  36625. if (moveInWholeWordSteps)
  36626. goToStartOfDocument (shiftDown);
  36627. else
  36628. goToStartOfLine (shiftDown);
  36629. }
  36630. else if (key.isKeyCode (KeyPress::endKey))
  36631. {
  36632. if (moveInWholeWordSteps)
  36633. goToEndOfDocument (shiftDown);
  36634. else
  36635. goToEndOfLine (shiftDown);
  36636. }
  36637. else if (key.isKeyCode (KeyPress::backspaceKey))
  36638. {
  36639. backspace (moveInWholeWordSteps);
  36640. }
  36641. else if (key.isKeyCode (KeyPress::deleteKey))
  36642. {
  36643. deleteForward (moveInWholeWordSteps);
  36644. }
  36645. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36646. {
  36647. copy();
  36648. }
  36649. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36650. {
  36651. copyThenCut();
  36652. }
  36653. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36654. {
  36655. paste();
  36656. }
  36657. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36658. {
  36659. undo();
  36660. }
  36661. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36662. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36663. {
  36664. redo();
  36665. }
  36666. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36667. {
  36668. selectAll();
  36669. }
  36670. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36671. {
  36672. insertTabAtCaret();
  36673. }
  36674. else if (key == KeyPress::returnKey)
  36675. {
  36676. newTransaction();
  36677. insertTextAtCaret (document.getNewLineCharacters());
  36678. }
  36679. else if (key.isKeyCode (KeyPress::escapeKey))
  36680. {
  36681. newTransaction();
  36682. }
  36683. else if (key.getTextCharacter() >= ' ')
  36684. {
  36685. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36686. }
  36687. else
  36688. {
  36689. return false;
  36690. }
  36691. return true;
  36692. }
  36693. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36694. {
  36695. newTransaction();
  36696. dragType = notDragging;
  36697. if (! e.mods.isPopupMenu())
  36698. {
  36699. beginDragAutoRepeat (100);
  36700. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36701. }
  36702. else
  36703. {
  36704. /*PopupMenu m;
  36705. addPopupMenuItems (m, &e);
  36706. const int result = m.show();
  36707. if (result != 0)
  36708. performPopupMenuAction (result);
  36709. */
  36710. }
  36711. }
  36712. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36713. {
  36714. if (! e.mods.isPopupMenu())
  36715. moveCaretTo (getPositionAt (e.x, e.y), true);
  36716. }
  36717. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36718. {
  36719. newTransaction();
  36720. beginDragAutoRepeat (0);
  36721. dragType = notDragging;
  36722. }
  36723. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36724. {
  36725. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36726. CodeDocument::Position tokenEnd (tokenStart);
  36727. if (e.getNumberOfClicks() > 2)
  36728. {
  36729. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36730. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36731. }
  36732. else
  36733. {
  36734. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36735. tokenEnd.moveBy (1);
  36736. tokenStart = tokenEnd;
  36737. while (tokenStart.getIndexInLine() > 0
  36738. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36739. tokenStart.moveBy (-1);
  36740. }
  36741. moveCaretTo (tokenEnd, false);
  36742. moveCaretTo (tokenStart, true);
  36743. }
  36744. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36745. {
  36746. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36747. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36748. {
  36749. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36750. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36751. }
  36752. else
  36753. {
  36754. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36755. }
  36756. }
  36757. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36758. {
  36759. if (scrollBarThatHasMoved == verticalScrollBar)
  36760. scrollToLineInternal ((int) newRangeStart);
  36761. else
  36762. scrollToColumnInternal (newRangeStart);
  36763. }
  36764. void CodeEditorComponent::focusGained (FocusChangeType)
  36765. {
  36766. caret->updatePosition();
  36767. }
  36768. void CodeEditorComponent::focusLost (FocusChangeType)
  36769. {
  36770. caret->updatePosition();
  36771. }
  36772. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36773. {
  36774. useSpacesForTabs = insertSpaces;
  36775. if (spacesPerTab != numSpaces)
  36776. {
  36777. spacesPerTab = numSpaces;
  36778. triggerAsyncUpdate();
  36779. }
  36780. }
  36781. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36782. {
  36783. const String line (document.getLine (lineNum));
  36784. jassert (index <= line.length());
  36785. int col = 0;
  36786. for (int i = 0; i < index; ++i)
  36787. {
  36788. if (line[i] != '\t')
  36789. ++col;
  36790. else
  36791. col += getTabSize() - (col % getTabSize());
  36792. }
  36793. return col;
  36794. }
  36795. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36796. {
  36797. const String line (document.getLine (lineNum));
  36798. const int lineLength = line.length();
  36799. int i, col = 0;
  36800. for (i = 0; i < lineLength; ++i)
  36801. {
  36802. if (line[i] != '\t')
  36803. ++col;
  36804. else
  36805. col += getTabSize() - (col % getTabSize());
  36806. if (col > column)
  36807. break;
  36808. }
  36809. return i;
  36810. }
  36811. void CodeEditorComponent::setFont (const Font& newFont)
  36812. {
  36813. font = newFont;
  36814. charWidth = font.getStringWidthFloat ("0");
  36815. lineHeight = roundToInt (font.getHeight());
  36816. resized();
  36817. }
  36818. void CodeEditorComponent::resetToDefaultColours()
  36819. {
  36820. coloursForTokenCategories.clear();
  36821. if (codeTokeniser != 0)
  36822. {
  36823. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36824. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36825. }
  36826. }
  36827. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36828. {
  36829. jassert (tokenType < 256);
  36830. while (coloursForTokenCategories.size() < tokenType)
  36831. coloursForTokenCategories.add (Colours::black);
  36832. coloursForTokenCategories.set (tokenType, colour);
  36833. repaint();
  36834. }
  36835. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36836. {
  36837. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36838. return findColour (CodeEditorComponent::defaultTextColourId);
  36839. return coloursForTokenCategories.getReference (tokenType);
  36840. }
  36841. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36842. {
  36843. int i;
  36844. for (i = cachedIterators.size(); --i >= 0;)
  36845. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36846. break;
  36847. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36848. }
  36849. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36850. {
  36851. const int maxNumCachedPositions = 5000;
  36852. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36853. if (cachedIterators.size() == 0)
  36854. cachedIterators.add (new CodeDocument::Iterator (&document));
  36855. if (codeTokeniser == 0)
  36856. return;
  36857. for (;;)
  36858. {
  36859. CodeDocument::Iterator* last = cachedIterators.getLast();
  36860. if (last->getLine() >= maxLineNum)
  36861. break;
  36862. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36863. cachedIterators.add (t);
  36864. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36865. for (;;)
  36866. {
  36867. codeTokeniser->readNextToken (*t);
  36868. if (t->getLine() >= targetLine)
  36869. break;
  36870. if (t->isEOF())
  36871. return;
  36872. }
  36873. }
  36874. }
  36875. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36876. {
  36877. if (codeTokeniser == 0)
  36878. return;
  36879. for (int i = cachedIterators.size(); --i >= 0;)
  36880. {
  36881. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36882. if (t->getPosition() <= position)
  36883. {
  36884. source = *t;
  36885. break;
  36886. }
  36887. }
  36888. while (source.getPosition() < position)
  36889. {
  36890. const CodeDocument::Iterator original (source);
  36891. codeTokeniser->readNextToken (source);
  36892. if (source.getPosition() > position || source.isEOF())
  36893. {
  36894. source = original;
  36895. break;
  36896. }
  36897. }
  36898. }
  36899. END_JUCE_NAMESPACE
  36900. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36901. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36902. BEGIN_JUCE_NAMESPACE
  36903. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36904. {
  36905. }
  36906. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36907. {
  36908. }
  36909. namespace CppTokeniser
  36910. {
  36911. static bool isIdentifierStart (const juce_wchar c) throw()
  36912. {
  36913. return CharacterFunctions::isLetter (c)
  36914. || c == '_' || c == '@';
  36915. }
  36916. static bool isIdentifierBody (const juce_wchar c) throw()
  36917. {
  36918. return CharacterFunctions::isLetterOrDigit (c)
  36919. || c == '_' || c == '@';
  36920. }
  36921. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36922. {
  36923. static const juce_wchar* const keywords2Char[] =
  36924. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  36925. static const juce_wchar* const keywords3Char[] =
  36926. { JUCE_T("for"), JUCE_T("int"), JUCE_T("new"), JUCE_T("try"), JUCE_T("xor"), JUCE_T("and"), JUCE_T("asm"), JUCE_T("not"), 0 };
  36927. static const juce_wchar* const keywords4Char[] =
  36928. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  36929. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  36930. static const juce_wchar* const keywords5Char[] =
  36931. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  36932. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  36933. static const juce_wchar* const keywords6Char[] =
  36934. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  36935. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  36936. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  36937. static const juce_wchar* const keywordsOther[] =
  36938. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  36939. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  36940. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  36941. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  36942. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  36943. const juce_wchar* const* k;
  36944. switch (tokenLength)
  36945. {
  36946. case 2: k = keywords2Char; break;
  36947. case 3: k = keywords3Char; break;
  36948. case 4: k = keywords4Char; break;
  36949. case 5: k = keywords5Char; break;
  36950. case 6: k = keywords6Char; break;
  36951. default:
  36952. if (tokenLength < 2 || tokenLength > 16)
  36953. return false;
  36954. k = keywordsOther;
  36955. break;
  36956. }
  36957. int i = 0;
  36958. while (k[i] != 0)
  36959. {
  36960. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36961. return true;
  36962. ++i;
  36963. }
  36964. return false;
  36965. }
  36966. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36967. {
  36968. int tokenLength = 0;
  36969. juce_wchar possibleIdentifier [19];
  36970. while (isIdentifierBody (source.peekNextChar()))
  36971. {
  36972. const juce_wchar c = source.nextChar();
  36973. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36974. possibleIdentifier [tokenLength] = c;
  36975. ++tokenLength;
  36976. }
  36977. if (tokenLength > 1 && tokenLength <= 16)
  36978. {
  36979. possibleIdentifier [tokenLength] = 0;
  36980. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36981. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36982. }
  36983. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36984. }
  36985. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36986. {
  36987. const juce_wchar c = source.peekNextChar();
  36988. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36989. source.skip();
  36990. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36991. return false;
  36992. return true;
  36993. }
  36994. static bool isHexDigit (const juce_wchar c) throw()
  36995. {
  36996. return (c >= '0' && c <= '9')
  36997. || (c >= 'a' && c <= 'f')
  36998. || (c >= 'A' && c <= 'F');
  36999. }
  37000. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37001. {
  37002. if (source.nextChar() != '0')
  37003. return false;
  37004. juce_wchar c = source.nextChar();
  37005. if (c != 'x' && c != 'X')
  37006. return false;
  37007. int numDigits = 0;
  37008. while (isHexDigit (source.peekNextChar()))
  37009. {
  37010. ++numDigits;
  37011. source.skip();
  37012. }
  37013. if (numDigits == 0)
  37014. return false;
  37015. return skipNumberSuffix (source);
  37016. }
  37017. static bool isOctalDigit (const juce_wchar c) throw()
  37018. {
  37019. return c >= '0' && c <= '7';
  37020. }
  37021. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37022. {
  37023. if (source.nextChar() != '0')
  37024. return false;
  37025. if (! isOctalDigit (source.nextChar()))
  37026. return false;
  37027. while (isOctalDigit (source.peekNextChar()))
  37028. source.skip();
  37029. return skipNumberSuffix (source);
  37030. }
  37031. static bool isDecimalDigit (const juce_wchar c) throw()
  37032. {
  37033. return c >= '0' && c <= '9';
  37034. }
  37035. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37036. {
  37037. int numChars = 0;
  37038. while (isDecimalDigit (source.peekNextChar()))
  37039. {
  37040. ++numChars;
  37041. source.skip();
  37042. }
  37043. if (numChars == 0)
  37044. return false;
  37045. return skipNumberSuffix (source);
  37046. }
  37047. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37048. {
  37049. int numDigits = 0;
  37050. while (isDecimalDigit (source.peekNextChar()))
  37051. {
  37052. source.skip();
  37053. ++numDigits;
  37054. }
  37055. const bool hasPoint = (source.peekNextChar() == '.');
  37056. if (hasPoint)
  37057. {
  37058. source.skip();
  37059. while (isDecimalDigit (source.peekNextChar()))
  37060. {
  37061. source.skip();
  37062. ++numDigits;
  37063. }
  37064. }
  37065. if (numDigits == 0)
  37066. return false;
  37067. juce_wchar c = source.peekNextChar();
  37068. const bool hasExponent = (c == 'e' || c == 'E');
  37069. if (hasExponent)
  37070. {
  37071. source.skip();
  37072. c = source.peekNextChar();
  37073. if (c == '+' || c == '-')
  37074. source.skip();
  37075. int numExpDigits = 0;
  37076. while (isDecimalDigit (source.peekNextChar()))
  37077. {
  37078. source.skip();
  37079. ++numExpDigits;
  37080. }
  37081. if (numExpDigits == 0)
  37082. return false;
  37083. }
  37084. c = source.peekNextChar();
  37085. if (c == 'f' || c == 'F')
  37086. source.skip();
  37087. else if (! (hasExponent || hasPoint))
  37088. return false;
  37089. return true;
  37090. }
  37091. static int parseNumber (CodeDocument::Iterator& source)
  37092. {
  37093. const CodeDocument::Iterator original (source);
  37094. if (parseFloatLiteral (source))
  37095. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37096. source = original;
  37097. if (parseHexLiteral (source))
  37098. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37099. source = original;
  37100. if (parseOctalLiteral (source))
  37101. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37102. source = original;
  37103. if (parseDecimalLiteral (source))
  37104. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37105. source = original;
  37106. source.skip();
  37107. return CPlusPlusCodeTokeniser::tokenType_error;
  37108. }
  37109. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37110. {
  37111. const juce_wchar quote = source.nextChar();
  37112. for (;;)
  37113. {
  37114. const juce_wchar c = source.nextChar();
  37115. if (c == quote || c == 0)
  37116. break;
  37117. if (c == '\\')
  37118. source.skip();
  37119. }
  37120. }
  37121. static void skipComment (CodeDocument::Iterator& source) throw()
  37122. {
  37123. bool lastWasStar = false;
  37124. for (;;)
  37125. {
  37126. const juce_wchar c = source.nextChar();
  37127. if (c == 0 || (c == '/' && lastWasStar))
  37128. break;
  37129. lastWasStar = (c == '*');
  37130. }
  37131. }
  37132. }
  37133. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37134. {
  37135. int result = tokenType_error;
  37136. source.skipWhitespace();
  37137. juce_wchar firstChar = source.peekNextChar();
  37138. switch (firstChar)
  37139. {
  37140. case 0:
  37141. source.skip();
  37142. break;
  37143. case '0':
  37144. case '1':
  37145. case '2':
  37146. case '3':
  37147. case '4':
  37148. case '5':
  37149. case '6':
  37150. case '7':
  37151. case '8':
  37152. case '9':
  37153. result = CppTokeniser::parseNumber (source);
  37154. break;
  37155. case '.':
  37156. result = CppTokeniser::parseNumber (source);
  37157. if (result == tokenType_error)
  37158. result = tokenType_punctuation;
  37159. break;
  37160. case ',':
  37161. case ';':
  37162. case ':':
  37163. source.skip();
  37164. result = tokenType_punctuation;
  37165. break;
  37166. case '(':
  37167. case ')':
  37168. case '{':
  37169. case '}':
  37170. case '[':
  37171. case ']':
  37172. source.skip();
  37173. result = tokenType_bracket;
  37174. break;
  37175. case '"':
  37176. case '\'':
  37177. CppTokeniser::skipQuotedString (source);
  37178. result = tokenType_stringLiteral;
  37179. break;
  37180. case '+':
  37181. result = tokenType_operator;
  37182. source.skip();
  37183. if (source.peekNextChar() == '+')
  37184. source.skip();
  37185. else if (source.peekNextChar() == '=')
  37186. source.skip();
  37187. break;
  37188. case '-':
  37189. source.skip();
  37190. result = CppTokeniser::parseNumber (source);
  37191. if (result == tokenType_error)
  37192. {
  37193. result = tokenType_operator;
  37194. if (source.peekNextChar() == '-')
  37195. source.skip();
  37196. else if (source.peekNextChar() == '=')
  37197. source.skip();
  37198. }
  37199. break;
  37200. case '*':
  37201. case '%':
  37202. case '=':
  37203. case '!':
  37204. result = tokenType_operator;
  37205. source.skip();
  37206. if (source.peekNextChar() == '=')
  37207. source.skip();
  37208. break;
  37209. case '/':
  37210. result = tokenType_operator;
  37211. source.skip();
  37212. if (source.peekNextChar() == '=')
  37213. {
  37214. source.skip();
  37215. }
  37216. else if (source.peekNextChar() == '/')
  37217. {
  37218. result = tokenType_comment;
  37219. source.skipToEndOfLine();
  37220. }
  37221. else if (source.peekNextChar() == '*')
  37222. {
  37223. source.skip();
  37224. result = tokenType_comment;
  37225. CppTokeniser::skipComment (source);
  37226. }
  37227. break;
  37228. case '?':
  37229. case '~':
  37230. source.skip();
  37231. result = tokenType_operator;
  37232. break;
  37233. case '<':
  37234. source.skip();
  37235. result = tokenType_operator;
  37236. if (source.peekNextChar() == '=')
  37237. {
  37238. source.skip();
  37239. }
  37240. else if (source.peekNextChar() == '<')
  37241. {
  37242. source.skip();
  37243. if (source.peekNextChar() == '=')
  37244. source.skip();
  37245. }
  37246. break;
  37247. case '>':
  37248. source.skip();
  37249. result = tokenType_operator;
  37250. if (source.peekNextChar() == '=')
  37251. {
  37252. source.skip();
  37253. }
  37254. else if (source.peekNextChar() == '<')
  37255. {
  37256. source.skip();
  37257. if (source.peekNextChar() == '=')
  37258. source.skip();
  37259. }
  37260. break;
  37261. case '|':
  37262. source.skip();
  37263. result = tokenType_operator;
  37264. if (source.peekNextChar() == '=')
  37265. {
  37266. source.skip();
  37267. }
  37268. else if (source.peekNextChar() == '|')
  37269. {
  37270. source.skip();
  37271. if (source.peekNextChar() == '=')
  37272. source.skip();
  37273. }
  37274. break;
  37275. case '&':
  37276. source.skip();
  37277. result = tokenType_operator;
  37278. if (source.peekNextChar() == '=')
  37279. {
  37280. source.skip();
  37281. }
  37282. else if (source.peekNextChar() == '&')
  37283. {
  37284. source.skip();
  37285. if (source.peekNextChar() == '=')
  37286. source.skip();
  37287. }
  37288. break;
  37289. case '^':
  37290. source.skip();
  37291. result = tokenType_operator;
  37292. if (source.peekNextChar() == '=')
  37293. {
  37294. source.skip();
  37295. }
  37296. else if (source.peekNextChar() == '^')
  37297. {
  37298. source.skip();
  37299. if (source.peekNextChar() == '=')
  37300. source.skip();
  37301. }
  37302. break;
  37303. case '#':
  37304. result = tokenType_preprocessor;
  37305. source.skipToEndOfLine();
  37306. break;
  37307. default:
  37308. if (CppTokeniser::isIdentifierStart (firstChar))
  37309. result = CppTokeniser::parseIdentifier (source);
  37310. else
  37311. source.skip();
  37312. break;
  37313. }
  37314. return result;
  37315. }
  37316. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37317. {
  37318. const char* const types[] =
  37319. {
  37320. "Error",
  37321. "Comment",
  37322. "C++ keyword",
  37323. "Identifier",
  37324. "Integer literal",
  37325. "Float literal",
  37326. "String literal",
  37327. "Operator",
  37328. "Bracket",
  37329. "Punctuation",
  37330. "Preprocessor line",
  37331. 0
  37332. };
  37333. return StringArray (types);
  37334. }
  37335. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37336. {
  37337. const uint32 colours[] =
  37338. {
  37339. 0xffcc0000, // error
  37340. 0xff00aa00, // comment
  37341. 0xff0000cc, // keyword
  37342. 0xff000000, // identifier
  37343. 0xff880000, // int literal
  37344. 0xff885500, // float literal
  37345. 0xff990099, // string literal
  37346. 0xff225500, // operator
  37347. 0xff000055, // bracket
  37348. 0xff004400, // punctuation
  37349. 0xff660000 // preprocessor
  37350. };
  37351. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37352. return Colour (colours [tokenType]);
  37353. return Colours::black;
  37354. }
  37355. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37356. {
  37357. return CppTokeniser::isReservedKeyword (token, token.length());
  37358. }
  37359. END_JUCE_NAMESPACE
  37360. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37361. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37362. BEGIN_JUCE_NAMESPACE
  37363. ComboBox::ComboBox (const String& name)
  37364. : Component (name),
  37365. lastCurrentId (0),
  37366. isButtonDown (false),
  37367. separatorPending (false),
  37368. menuActive (false),
  37369. label (0)
  37370. {
  37371. noChoicesMessage = TRANS("(no choices)");
  37372. setRepaintsOnMouseActivity (true);
  37373. lookAndFeelChanged();
  37374. currentId.addListener (this);
  37375. }
  37376. ComboBox::~ComboBox()
  37377. {
  37378. currentId.removeListener (this);
  37379. if (menuActive)
  37380. PopupMenu::dismissAllActiveMenus();
  37381. label = 0;
  37382. deleteAllChildren();
  37383. }
  37384. void ComboBox::setEditableText (const bool isEditable)
  37385. {
  37386. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37387. {
  37388. label->setEditable (isEditable, isEditable, false);
  37389. setWantsKeyboardFocus (! isEditable);
  37390. resized();
  37391. }
  37392. }
  37393. bool ComboBox::isTextEditable() const throw()
  37394. {
  37395. return label->isEditable();
  37396. }
  37397. void ComboBox::setJustificationType (const Justification& justification) throw()
  37398. {
  37399. label->setJustificationType (justification);
  37400. }
  37401. const Justification ComboBox::getJustificationType() const throw()
  37402. {
  37403. return label->getJustificationType();
  37404. }
  37405. void ComboBox::setTooltip (const String& newTooltip)
  37406. {
  37407. SettableTooltipClient::setTooltip (newTooltip);
  37408. label->setTooltip (newTooltip);
  37409. }
  37410. void ComboBox::addItem (const String& newItemText,
  37411. const int newItemId) throw()
  37412. {
  37413. // you can't add empty strings to the list..
  37414. jassert (newItemText.isNotEmpty());
  37415. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37416. jassert (newItemId != 0);
  37417. // you shouldn't use duplicate item IDs!
  37418. jassert (getItemForId (newItemId) == 0);
  37419. if (newItemText.isNotEmpty() && newItemId != 0)
  37420. {
  37421. if (separatorPending)
  37422. {
  37423. separatorPending = false;
  37424. ItemInfo* const item = new ItemInfo();
  37425. item->itemId = 0;
  37426. item->isEnabled = false;
  37427. item->isHeading = false;
  37428. items.add (item);
  37429. }
  37430. ItemInfo* const item = new ItemInfo();
  37431. item->name = newItemText;
  37432. item->itemId = newItemId;
  37433. item->isEnabled = true;
  37434. item->isHeading = false;
  37435. items.add (item);
  37436. }
  37437. }
  37438. void ComboBox::addSeparator() throw()
  37439. {
  37440. separatorPending = (items.size() > 0);
  37441. }
  37442. void ComboBox::addSectionHeading (const String& headingName) throw()
  37443. {
  37444. // you can't add empty strings to the list..
  37445. jassert (headingName.isNotEmpty());
  37446. if (headingName.isNotEmpty())
  37447. {
  37448. if (separatorPending)
  37449. {
  37450. separatorPending = false;
  37451. ItemInfo* const item = new ItemInfo();
  37452. item->itemId = 0;
  37453. item->isEnabled = false;
  37454. item->isHeading = false;
  37455. items.add (item);
  37456. }
  37457. ItemInfo* const item = new ItemInfo();
  37458. item->name = headingName;
  37459. item->itemId = 0;
  37460. item->isEnabled = true;
  37461. item->isHeading = true;
  37462. items.add (item);
  37463. }
  37464. }
  37465. void ComboBox::setItemEnabled (const int itemId,
  37466. const bool shouldBeEnabled) throw()
  37467. {
  37468. ItemInfo* const item = getItemForId (itemId);
  37469. if (item != 0)
  37470. item->isEnabled = shouldBeEnabled;
  37471. }
  37472. void ComboBox::changeItemText (const int itemId,
  37473. const String& newText) throw()
  37474. {
  37475. ItemInfo* const item = getItemForId (itemId);
  37476. jassert (item != 0);
  37477. if (item != 0)
  37478. item->name = newText;
  37479. }
  37480. void ComboBox::clear (const bool dontSendChangeMessage)
  37481. {
  37482. items.clear();
  37483. separatorPending = false;
  37484. if (! label->isEditable())
  37485. setSelectedItemIndex (-1, dontSendChangeMessage);
  37486. }
  37487. bool ComboBox::ItemInfo::isSeparator() const throw()
  37488. {
  37489. return name.isEmpty();
  37490. }
  37491. bool ComboBox::ItemInfo::isRealItem() const throw()
  37492. {
  37493. return ! (isHeading || name.isEmpty());
  37494. }
  37495. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37496. {
  37497. if (itemId != 0)
  37498. {
  37499. for (int i = items.size(); --i >= 0;)
  37500. if (items.getUnchecked(i)->itemId == itemId)
  37501. return items.getUnchecked(i);
  37502. }
  37503. return 0;
  37504. }
  37505. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37506. {
  37507. int n = 0;
  37508. for (int i = 0; i < items.size(); ++i)
  37509. {
  37510. ItemInfo* const item = items.getUnchecked(i);
  37511. if (item->isRealItem())
  37512. if (n++ == index)
  37513. return item;
  37514. }
  37515. return 0;
  37516. }
  37517. int ComboBox::getNumItems() const throw()
  37518. {
  37519. int n = 0;
  37520. for (int i = items.size(); --i >= 0;)
  37521. if (items.getUnchecked(i)->isRealItem())
  37522. ++n;
  37523. return n;
  37524. }
  37525. const String ComboBox::getItemText (const int index) const throw()
  37526. {
  37527. const ItemInfo* const item = getItemForIndex (index);
  37528. if (item != 0)
  37529. return item->name;
  37530. return String::empty;
  37531. }
  37532. int ComboBox::getItemId (const int index) const throw()
  37533. {
  37534. const ItemInfo* const item = getItemForIndex (index);
  37535. return (item != 0) ? item->itemId : 0;
  37536. }
  37537. int ComboBox::indexOfItemId (const int itemId) const throw()
  37538. {
  37539. int n = 0;
  37540. for (int i = 0; i < items.size(); ++i)
  37541. {
  37542. const ItemInfo* const item = items.getUnchecked(i);
  37543. if (item->isRealItem())
  37544. {
  37545. if (item->itemId == itemId)
  37546. return n;
  37547. ++n;
  37548. }
  37549. }
  37550. return -1;
  37551. }
  37552. int ComboBox::getSelectedItemIndex() const throw()
  37553. {
  37554. int index = indexOfItemId (currentId.getValue());
  37555. if (getText() != getItemText (index))
  37556. index = -1;
  37557. return index;
  37558. }
  37559. void ComboBox::setSelectedItemIndex (const int index,
  37560. const bool dontSendChangeMessage) throw()
  37561. {
  37562. setSelectedId (getItemId (index), dontSendChangeMessage);
  37563. }
  37564. int ComboBox::getSelectedId() const throw()
  37565. {
  37566. const ItemInfo* const item = getItemForId (currentId.getValue());
  37567. return (item != 0 && getText() == item->name)
  37568. ? item->itemId
  37569. : 0;
  37570. }
  37571. void ComboBox::setSelectedId (const int newItemId,
  37572. const bool dontSendChangeMessage) throw()
  37573. {
  37574. const ItemInfo* const item = getItemForId (newItemId);
  37575. const String newItemText (item != 0 ? item->name : String::empty);
  37576. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37577. {
  37578. if (! dontSendChangeMessage)
  37579. triggerAsyncUpdate();
  37580. label->setText (newItemText, false);
  37581. lastCurrentId = newItemId;
  37582. currentId = newItemId;
  37583. repaint(); // for the benefit of the 'none selected' text
  37584. }
  37585. }
  37586. void ComboBox::valueChanged (Value&)
  37587. {
  37588. if (lastCurrentId != (int) currentId.getValue())
  37589. setSelectedId (currentId.getValue(), false);
  37590. }
  37591. const String ComboBox::getText() const throw()
  37592. {
  37593. return label->getText();
  37594. }
  37595. void ComboBox::setText (const String& newText,
  37596. const bool dontSendChangeMessage) throw()
  37597. {
  37598. for (int i = items.size(); --i >= 0;)
  37599. {
  37600. const ItemInfo* const item = items.getUnchecked(i);
  37601. if (item->isRealItem()
  37602. && item->name == newText)
  37603. {
  37604. setSelectedId (item->itemId, dontSendChangeMessage);
  37605. return;
  37606. }
  37607. }
  37608. lastCurrentId = 0;
  37609. currentId = 0;
  37610. if (label->getText() != newText)
  37611. {
  37612. label->setText (newText, false);
  37613. if (! dontSendChangeMessage)
  37614. triggerAsyncUpdate();
  37615. }
  37616. repaint();
  37617. }
  37618. void ComboBox::showEditor()
  37619. {
  37620. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37621. label->showEditor();
  37622. }
  37623. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37624. {
  37625. if (textWhenNothingSelected != newMessage)
  37626. {
  37627. textWhenNothingSelected = newMessage;
  37628. repaint();
  37629. }
  37630. }
  37631. const String ComboBox::getTextWhenNothingSelected() const throw()
  37632. {
  37633. return textWhenNothingSelected;
  37634. }
  37635. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37636. {
  37637. noChoicesMessage = newMessage;
  37638. }
  37639. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37640. {
  37641. return noChoicesMessage;
  37642. }
  37643. void ComboBox::paint (Graphics& g)
  37644. {
  37645. getLookAndFeel().drawComboBox (g,
  37646. getWidth(),
  37647. getHeight(),
  37648. isButtonDown,
  37649. label->getRight(),
  37650. 0,
  37651. getWidth() - label->getRight(),
  37652. getHeight(),
  37653. *this);
  37654. if (textWhenNothingSelected.isNotEmpty()
  37655. && label->getText().isEmpty()
  37656. && ! label->isBeingEdited())
  37657. {
  37658. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37659. g.setFont (label->getFont());
  37660. g.drawFittedText (textWhenNothingSelected,
  37661. label->getX() + 2, label->getY() + 1,
  37662. label->getWidth() - 4, label->getHeight() - 2,
  37663. label->getJustificationType(),
  37664. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37665. }
  37666. }
  37667. void ComboBox::resized()
  37668. {
  37669. if (getHeight() > 0 && getWidth() > 0)
  37670. getLookAndFeel().positionComboBoxText (*this, *label);
  37671. }
  37672. void ComboBox::enablementChanged()
  37673. {
  37674. repaint();
  37675. }
  37676. void ComboBox::lookAndFeelChanged()
  37677. {
  37678. repaint();
  37679. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37680. if (label != 0)
  37681. {
  37682. newLabel->setEditable (label->isEditable());
  37683. newLabel->setJustificationType (label->getJustificationType());
  37684. newLabel->setTooltip (label->getTooltip());
  37685. newLabel->setText (label->getText(), false);
  37686. }
  37687. label = newLabel;
  37688. addAndMakeVisible (newLabel);
  37689. newLabel->addListener (this);
  37690. newLabel->addMouseListener (this, false);
  37691. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37692. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37693. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37694. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37695. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37696. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37697. resized();
  37698. }
  37699. void ComboBox::colourChanged()
  37700. {
  37701. lookAndFeelChanged();
  37702. }
  37703. bool ComboBox::keyPressed (const KeyPress& key)
  37704. {
  37705. bool used = false;
  37706. if (key.isKeyCode (KeyPress::upKey)
  37707. || key.isKeyCode (KeyPress::leftKey))
  37708. {
  37709. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37710. used = true;
  37711. }
  37712. else if (key.isKeyCode (KeyPress::downKey)
  37713. || key.isKeyCode (KeyPress::rightKey))
  37714. {
  37715. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37716. used = true;
  37717. }
  37718. else if (key.isKeyCode (KeyPress::returnKey))
  37719. {
  37720. showPopup();
  37721. used = true;
  37722. }
  37723. return used;
  37724. }
  37725. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37726. {
  37727. // only forward key events that aren't used by this component
  37728. return isKeyDown
  37729. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37730. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37731. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37732. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37733. }
  37734. void ComboBox::focusGained (FocusChangeType)
  37735. {
  37736. repaint();
  37737. }
  37738. void ComboBox::focusLost (FocusChangeType)
  37739. {
  37740. repaint();
  37741. }
  37742. void ComboBox::labelTextChanged (Label*)
  37743. {
  37744. triggerAsyncUpdate();
  37745. }
  37746. class ComboBox::Callback : public ModalComponentManager::Callback
  37747. {
  37748. public:
  37749. Callback (ComboBox* const box_)
  37750. : box (box_)
  37751. {
  37752. }
  37753. void modalStateFinished (int returnValue)
  37754. {
  37755. if (box != 0)
  37756. {
  37757. box->menuActive = false;
  37758. if (returnValue != 0)
  37759. box->setSelectedId (returnValue);
  37760. }
  37761. }
  37762. private:
  37763. Component::SafePointer<ComboBox> box;
  37764. Callback (const Callback&);
  37765. Callback& operator= (const Callback&);
  37766. };
  37767. void ComboBox::showPopup()
  37768. {
  37769. if (! menuActive)
  37770. {
  37771. const int selectedId = getSelectedId();
  37772. PopupMenu menu;
  37773. menu.setLookAndFeel (&getLookAndFeel());
  37774. for (int i = 0; i < items.size(); ++i)
  37775. {
  37776. const ItemInfo* const item = items.getUnchecked(i);
  37777. if (item->isSeparator())
  37778. menu.addSeparator();
  37779. else if (item->isHeading)
  37780. menu.addSectionHeader (item->name);
  37781. else
  37782. menu.addItem (item->itemId, item->name,
  37783. item->isEnabled, item->itemId == selectedId);
  37784. }
  37785. if (items.size() == 0)
  37786. menu.addItem (1, noChoicesMessage, false);
  37787. menuActive = true;
  37788. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  37789. new Callback (this));
  37790. }
  37791. }
  37792. void ComboBox::mouseDown (const MouseEvent& e)
  37793. {
  37794. beginDragAutoRepeat (300);
  37795. isButtonDown = isEnabled();
  37796. if (isButtonDown
  37797. && (e.eventComponent == this || ! label->isEditable()))
  37798. {
  37799. showPopup();
  37800. }
  37801. }
  37802. void ComboBox::mouseDrag (const MouseEvent& e)
  37803. {
  37804. beginDragAutoRepeat (50);
  37805. if (isButtonDown && ! e.mouseWasClicked())
  37806. showPopup();
  37807. }
  37808. void ComboBox::mouseUp (const MouseEvent& e2)
  37809. {
  37810. if (isButtonDown)
  37811. {
  37812. isButtonDown = false;
  37813. repaint();
  37814. const MouseEvent e (e2.getEventRelativeTo (this));
  37815. if (reallyContains (e.x, e.y, true)
  37816. && (e2.eventComponent == this || ! label->isEditable()))
  37817. {
  37818. showPopup();
  37819. }
  37820. }
  37821. }
  37822. void ComboBox::addListener (Listener* const listener) throw()
  37823. {
  37824. listeners.add (listener);
  37825. }
  37826. void ComboBox::removeListener (Listener* const listener) throw()
  37827. {
  37828. listeners.remove (listener);
  37829. }
  37830. void ComboBox::handleAsyncUpdate()
  37831. {
  37832. Component::BailOutChecker checker (this);
  37833. listeners.callChecked (checker, &Listener::comboBoxChanged, this);
  37834. }
  37835. END_JUCE_NAMESPACE
  37836. /*** End of inlined file: juce_ComboBox.cpp ***/
  37837. /*** Start of inlined file: juce_Label.cpp ***/
  37838. BEGIN_JUCE_NAMESPACE
  37839. Label::Label (const String& componentName,
  37840. const String& labelText)
  37841. : Component (componentName),
  37842. textValue (labelText),
  37843. lastTextValue (labelText),
  37844. font (15.0f),
  37845. justification (Justification::centredLeft),
  37846. ownerComponent (0),
  37847. horizontalBorderSize (5),
  37848. verticalBorderSize (1),
  37849. minimumHorizontalScale (0.7f),
  37850. editSingleClick (false),
  37851. editDoubleClick (false),
  37852. lossOfFocusDiscardsChanges (false)
  37853. {
  37854. setColour (TextEditor::textColourId, Colours::black);
  37855. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37856. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37857. textValue.addListener (this);
  37858. }
  37859. Label::~Label()
  37860. {
  37861. textValue.removeListener (this);
  37862. if (ownerComponent != 0)
  37863. ownerComponent->removeComponentListener (this);
  37864. editor = 0;
  37865. }
  37866. void Label::setText (const String& newText,
  37867. const bool broadcastChangeMessage)
  37868. {
  37869. hideEditor (true);
  37870. if (lastTextValue != newText)
  37871. {
  37872. lastTextValue = newText;
  37873. textValue = newText;
  37874. repaint();
  37875. textWasChanged();
  37876. if (ownerComponent != 0)
  37877. componentMovedOrResized (*ownerComponent, true, true);
  37878. if (broadcastChangeMessage)
  37879. callChangeListeners();
  37880. }
  37881. }
  37882. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37883. {
  37884. return (returnActiveEditorContents && isBeingEdited())
  37885. ? editor->getText()
  37886. : textValue.toString();
  37887. }
  37888. void Label::valueChanged (Value&)
  37889. {
  37890. if (lastTextValue != textValue.toString())
  37891. setText (textValue.toString(), true);
  37892. }
  37893. void Label::setFont (const Font& newFont) throw()
  37894. {
  37895. if (font != newFont)
  37896. {
  37897. font = newFont;
  37898. repaint();
  37899. }
  37900. }
  37901. const Font& Label::getFont() const throw()
  37902. {
  37903. return font;
  37904. }
  37905. void Label::setEditable (const bool editOnSingleClick,
  37906. const bool editOnDoubleClick,
  37907. const bool lossOfFocusDiscardsChanges_) throw()
  37908. {
  37909. editSingleClick = editOnSingleClick;
  37910. editDoubleClick = editOnDoubleClick;
  37911. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37912. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37913. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37914. }
  37915. void Label::setJustificationType (const Justification& newJustification) throw()
  37916. {
  37917. if (justification != newJustification)
  37918. {
  37919. justification = newJustification;
  37920. repaint();
  37921. }
  37922. }
  37923. void Label::setBorderSize (int h, int v)
  37924. {
  37925. if (horizontalBorderSize != h || verticalBorderSize != v)
  37926. {
  37927. horizontalBorderSize = h;
  37928. verticalBorderSize = v;
  37929. repaint();
  37930. }
  37931. }
  37932. Component* Label::getAttachedComponent() const
  37933. {
  37934. return static_cast<Component*> (ownerComponent);
  37935. }
  37936. void Label::attachToComponent (Component* owner,
  37937. const bool onLeft)
  37938. {
  37939. if (ownerComponent != 0)
  37940. ownerComponent->removeComponentListener (this);
  37941. ownerComponent = owner;
  37942. leftOfOwnerComp = onLeft;
  37943. if (ownerComponent != 0)
  37944. {
  37945. setVisible (owner->isVisible());
  37946. ownerComponent->addComponentListener (this);
  37947. componentParentHierarchyChanged (*ownerComponent);
  37948. componentMovedOrResized (*ownerComponent, true, true);
  37949. }
  37950. }
  37951. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  37952. {
  37953. if (leftOfOwnerComp)
  37954. {
  37955. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37956. component.getHeight());
  37957. setTopRightPosition (component.getX(), component.getY());
  37958. }
  37959. else
  37960. {
  37961. setSize (component.getWidth(),
  37962. 8 + roundToInt (getFont().getHeight()));
  37963. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37964. }
  37965. }
  37966. void Label::componentParentHierarchyChanged (Component& component)
  37967. {
  37968. if (component.getParentComponent() != 0)
  37969. component.getParentComponent()->addChildComponent (this);
  37970. }
  37971. void Label::componentVisibilityChanged (Component& component)
  37972. {
  37973. setVisible (component.isVisible());
  37974. }
  37975. void Label::textWasEdited()
  37976. {
  37977. }
  37978. void Label::textWasChanged()
  37979. {
  37980. }
  37981. void Label::showEditor()
  37982. {
  37983. if (editor == 0)
  37984. {
  37985. addAndMakeVisible (editor = createEditorComponent());
  37986. editor->setText (getText(), false);
  37987. editor->addListener (this);
  37988. editor->grabKeyboardFocus();
  37989. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37990. editor->addListener (this);
  37991. resized();
  37992. repaint();
  37993. editorShown (editor);
  37994. enterModalState (false);
  37995. editor->grabKeyboardFocus();
  37996. }
  37997. }
  37998. void Label::editorShown (TextEditor* /*editorComponent*/)
  37999. {
  38000. }
  38001. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38002. {
  38003. }
  38004. bool Label::updateFromTextEditorContents()
  38005. {
  38006. jassert (editor != 0);
  38007. const String newText (editor->getText());
  38008. if (textValue.toString() != newText)
  38009. {
  38010. lastTextValue = newText;
  38011. textValue = newText;
  38012. repaint();
  38013. textWasChanged();
  38014. if (ownerComponent != 0)
  38015. componentMovedOrResized (*ownerComponent, true, true);
  38016. return true;
  38017. }
  38018. return false;
  38019. }
  38020. void Label::hideEditor (const bool discardCurrentEditorContents)
  38021. {
  38022. if (editor != 0)
  38023. {
  38024. Component::SafePointer<Component> deletionChecker (this);
  38025. editorAboutToBeHidden (editor);
  38026. const bool changed = (! discardCurrentEditorContents)
  38027. && updateFromTextEditorContents();
  38028. editor = 0;
  38029. repaint();
  38030. if (changed)
  38031. textWasEdited();
  38032. if (deletionChecker != 0)
  38033. exitModalState (0);
  38034. if (changed && deletionChecker != 0)
  38035. callChangeListeners();
  38036. }
  38037. }
  38038. void Label::inputAttemptWhenModal()
  38039. {
  38040. if (editor != 0)
  38041. {
  38042. if (lossOfFocusDiscardsChanges)
  38043. textEditorEscapeKeyPressed (*editor);
  38044. else
  38045. textEditorReturnKeyPressed (*editor);
  38046. }
  38047. }
  38048. bool Label::isBeingEdited() const throw()
  38049. {
  38050. return editor != 0;
  38051. }
  38052. TextEditor* Label::createEditorComponent()
  38053. {
  38054. TextEditor* const ed = new TextEditor (getName());
  38055. ed->setFont (font);
  38056. // copy these colours from our own settings..
  38057. const int cols[] = { TextEditor::backgroundColourId,
  38058. TextEditor::textColourId,
  38059. TextEditor::highlightColourId,
  38060. TextEditor::highlightedTextColourId,
  38061. TextEditor::caretColourId,
  38062. TextEditor::outlineColourId,
  38063. TextEditor::focusedOutlineColourId,
  38064. TextEditor::shadowColourId };
  38065. for (int i = 0; i < numElementsInArray (cols); ++i)
  38066. ed->setColour (cols[i], findColour (cols[i]));
  38067. return ed;
  38068. }
  38069. void Label::paint (Graphics& g)
  38070. {
  38071. getLookAndFeel().drawLabel (g, *this);
  38072. }
  38073. void Label::mouseUp (const MouseEvent& e)
  38074. {
  38075. if (editSingleClick
  38076. && e.mouseWasClicked()
  38077. && contains (e.x, e.y)
  38078. && ! e.mods.isPopupMenu())
  38079. {
  38080. showEditor();
  38081. }
  38082. }
  38083. void Label::mouseDoubleClick (const MouseEvent& e)
  38084. {
  38085. if (editDoubleClick && ! e.mods.isPopupMenu())
  38086. showEditor();
  38087. }
  38088. void Label::resized()
  38089. {
  38090. if (editor != 0)
  38091. editor->setBoundsInset (BorderSize (0));
  38092. }
  38093. void Label::focusGained (FocusChangeType cause)
  38094. {
  38095. if (editSingleClick && cause == focusChangedByTabKey)
  38096. showEditor();
  38097. }
  38098. void Label::enablementChanged()
  38099. {
  38100. repaint();
  38101. }
  38102. void Label::colourChanged()
  38103. {
  38104. repaint();
  38105. }
  38106. void Label::setMinimumHorizontalScale (const float newScale)
  38107. {
  38108. if (minimumHorizontalScale != newScale)
  38109. {
  38110. minimumHorizontalScale = newScale;
  38111. repaint();
  38112. }
  38113. }
  38114. // We'll use a custom focus traverser here to make sure focus goes from the
  38115. // text editor to another component rather than back to the label itself.
  38116. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38117. {
  38118. public:
  38119. LabelKeyboardFocusTraverser() {}
  38120. Component* getNextComponent (Component* current)
  38121. {
  38122. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38123. ? current->getParentComponent() : current);
  38124. }
  38125. Component* getPreviousComponent (Component* current)
  38126. {
  38127. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38128. ? current->getParentComponent() : current);
  38129. }
  38130. };
  38131. KeyboardFocusTraverser* Label::createFocusTraverser()
  38132. {
  38133. return new LabelKeyboardFocusTraverser();
  38134. }
  38135. void Label::addListener (Listener* const listener) throw()
  38136. {
  38137. listeners.add (listener);
  38138. }
  38139. void Label::removeListener (Listener* const listener) throw()
  38140. {
  38141. listeners.remove (listener);
  38142. }
  38143. void Label::callChangeListeners()
  38144. {
  38145. Component::BailOutChecker checker (this);
  38146. listeners.callChecked (checker, &Listener::labelTextChanged, this);
  38147. }
  38148. void Label::textEditorTextChanged (TextEditor& ed)
  38149. {
  38150. if (editor != 0)
  38151. {
  38152. jassert (&ed == editor);
  38153. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38154. {
  38155. if (lossOfFocusDiscardsChanges)
  38156. textEditorEscapeKeyPressed (ed);
  38157. else
  38158. textEditorReturnKeyPressed (ed);
  38159. }
  38160. }
  38161. }
  38162. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38163. {
  38164. if (editor != 0)
  38165. {
  38166. jassert (&ed == editor);
  38167. (void) ed;
  38168. const bool changed = updateFromTextEditorContents();
  38169. hideEditor (true);
  38170. if (changed)
  38171. {
  38172. Component::SafePointer<Component> deletionChecker (this);
  38173. textWasEdited();
  38174. if (deletionChecker != 0)
  38175. callChangeListeners();
  38176. }
  38177. }
  38178. }
  38179. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38180. {
  38181. if (editor != 0)
  38182. {
  38183. jassert (&ed == editor);
  38184. (void) ed;
  38185. editor->setText (textValue.toString(), false);
  38186. hideEditor (true);
  38187. }
  38188. }
  38189. void Label::textEditorFocusLost (TextEditor& ed)
  38190. {
  38191. textEditorTextChanged (ed);
  38192. }
  38193. END_JUCE_NAMESPACE
  38194. /*** End of inlined file: juce_Label.cpp ***/
  38195. /*** Start of inlined file: juce_ListBox.cpp ***/
  38196. BEGIN_JUCE_NAMESPACE
  38197. class ListBoxRowComponent : public Component,
  38198. public TooltipClient
  38199. {
  38200. public:
  38201. ListBoxRowComponent (ListBox& owner_)
  38202. : owner (owner_),
  38203. row (-1),
  38204. selected (false),
  38205. isDragging (false)
  38206. {
  38207. }
  38208. ~ListBoxRowComponent()
  38209. {
  38210. deleteAllChildren();
  38211. }
  38212. void paint (Graphics& g)
  38213. {
  38214. if (owner.getModel() != 0)
  38215. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38216. }
  38217. void update (const int row_, const bool selected_)
  38218. {
  38219. if (row != row_ || selected != selected_)
  38220. {
  38221. repaint();
  38222. row = row_;
  38223. selected = selected_;
  38224. }
  38225. if (owner.getModel() != 0)
  38226. {
  38227. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38228. if (customComp != 0)
  38229. {
  38230. addAndMakeVisible (customComp);
  38231. customComp->setBounds (getLocalBounds());
  38232. for (int i = getNumChildComponents(); --i >= 0;)
  38233. if (getChildComponent (i) != customComp)
  38234. delete getChildComponent (i);
  38235. }
  38236. else
  38237. {
  38238. deleteAllChildren();
  38239. }
  38240. }
  38241. }
  38242. void mouseDown (const MouseEvent& e)
  38243. {
  38244. isDragging = false;
  38245. selectRowOnMouseUp = false;
  38246. if (isEnabled())
  38247. {
  38248. if (! selected)
  38249. {
  38250. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38251. if (owner.getModel() != 0)
  38252. owner.getModel()->listBoxItemClicked (row, e);
  38253. }
  38254. else
  38255. {
  38256. selectRowOnMouseUp = true;
  38257. }
  38258. }
  38259. }
  38260. void mouseUp (const MouseEvent& e)
  38261. {
  38262. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38263. {
  38264. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38265. if (owner.getModel() != 0)
  38266. owner.getModel()->listBoxItemClicked (row, e);
  38267. }
  38268. }
  38269. void mouseDoubleClick (const MouseEvent& e)
  38270. {
  38271. if (owner.getModel() != 0 && isEnabled())
  38272. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38273. }
  38274. void mouseDrag (const MouseEvent& e)
  38275. {
  38276. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38277. {
  38278. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38279. if (selectedRows.size() > 0)
  38280. {
  38281. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38282. if (dragDescription.isNotEmpty())
  38283. {
  38284. isDragging = true;
  38285. owner.startDragAndDrop (e, dragDescription);
  38286. }
  38287. }
  38288. }
  38289. }
  38290. void resized()
  38291. {
  38292. if (getNumChildComponents() > 0)
  38293. getChildComponent(0)->setBounds (getLocalBounds());
  38294. }
  38295. const String getTooltip()
  38296. {
  38297. if (owner.getModel() != 0)
  38298. return owner.getModel()->getTooltipForRow (row);
  38299. return String::empty;
  38300. }
  38301. juce_UseDebuggingNewOperator
  38302. bool neededFlag;
  38303. private:
  38304. ListBox& owner;
  38305. int row;
  38306. bool selected, isDragging, selectRowOnMouseUp;
  38307. ListBoxRowComponent (const ListBoxRowComponent&);
  38308. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38309. };
  38310. class ListViewport : public Viewport
  38311. {
  38312. public:
  38313. int firstIndex, firstWholeIndex, lastWholeIndex;
  38314. bool hasUpdated;
  38315. ListViewport (ListBox& owner_)
  38316. : owner (owner_)
  38317. {
  38318. setWantsKeyboardFocus (false);
  38319. setViewedComponent (new Component());
  38320. getViewedComponent()->addMouseListener (this, false);
  38321. getViewedComponent()->setWantsKeyboardFocus (false);
  38322. }
  38323. ~ListViewport()
  38324. {
  38325. getViewedComponent()->removeMouseListener (this);
  38326. getViewedComponent()->deleteAllChildren();
  38327. }
  38328. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38329. {
  38330. return static_cast <ListBoxRowComponent*>
  38331. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38332. }
  38333. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38334. {
  38335. const int index = getIndexOfChildComponent (rowComponent);
  38336. const int num = getViewedComponent()->getNumChildComponents();
  38337. for (int i = num; --i >= 0;)
  38338. if (((firstIndex + i) % jmax (1, num)) == index)
  38339. return firstIndex + i;
  38340. return -1;
  38341. }
  38342. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38343. {
  38344. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38345. ? getComponentForRow (row) : 0;
  38346. }
  38347. void visibleAreaChanged (int, int, int, int)
  38348. {
  38349. updateVisibleArea (true);
  38350. if (owner.getModel() != 0)
  38351. owner.getModel()->listWasScrolled();
  38352. }
  38353. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38354. {
  38355. hasUpdated = false;
  38356. const int newX = getViewedComponent()->getX();
  38357. int newY = getViewedComponent()->getY();
  38358. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38359. const int newH = owner.totalItems * owner.getRowHeight();
  38360. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38361. newY = getMaximumVisibleHeight() - newH;
  38362. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38363. if (makeSureItUpdatesContent && ! hasUpdated)
  38364. updateContents();
  38365. }
  38366. void updateContents()
  38367. {
  38368. hasUpdated = true;
  38369. const int rowHeight = owner.getRowHeight();
  38370. if (rowHeight > 0)
  38371. {
  38372. const int y = getViewPositionY();
  38373. const int w = getViewedComponent()->getWidth();
  38374. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38375. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38376. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38377. jassert (numNeeded >= 0);
  38378. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38379. {
  38380. Component* const rowToRemove
  38381. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38382. delete rowToRemove;
  38383. }
  38384. firstIndex = y / rowHeight;
  38385. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38386. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38387. for (int i = 0; i < numNeeded; ++i)
  38388. {
  38389. const int row = i + firstIndex;
  38390. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38391. if (rowComp != 0)
  38392. {
  38393. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38394. rowComp->update (row, owner.isRowSelected (row));
  38395. }
  38396. }
  38397. }
  38398. if (owner.headerComponent != 0)
  38399. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38400. owner.outlineThickness,
  38401. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38402. getViewedComponent()->getWidth()),
  38403. owner.headerComponent->getHeight());
  38404. }
  38405. void paint (Graphics& g)
  38406. {
  38407. if (isOpaque())
  38408. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38409. }
  38410. bool keyPressed (const KeyPress& key)
  38411. {
  38412. if (key.isKeyCode (KeyPress::upKey)
  38413. || key.isKeyCode (KeyPress::downKey)
  38414. || key.isKeyCode (KeyPress::pageUpKey)
  38415. || key.isKeyCode (KeyPress::pageDownKey)
  38416. || key.isKeyCode (KeyPress::homeKey)
  38417. || key.isKeyCode (KeyPress::endKey))
  38418. {
  38419. // we want to avoid these keypresses going to the viewport, and instead allow
  38420. // them to pass up to our listbox..
  38421. return false;
  38422. }
  38423. return Viewport::keyPressed (key);
  38424. }
  38425. juce_UseDebuggingNewOperator
  38426. private:
  38427. ListBox& owner;
  38428. ListViewport (const ListViewport&);
  38429. ListViewport& operator= (const ListViewport&);
  38430. };
  38431. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38432. : Component (name),
  38433. model (model_),
  38434. totalItems (0),
  38435. rowHeight (22),
  38436. minimumRowWidth (0),
  38437. outlineThickness (0),
  38438. lastRowSelected (-1),
  38439. mouseMoveSelects (false),
  38440. multipleSelection (false),
  38441. hasDoneInitialUpdate (false)
  38442. {
  38443. addAndMakeVisible (viewport = new ListViewport (*this));
  38444. setWantsKeyboardFocus (true);
  38445. colourChanged();
  38446. }
  38447. ListBox::~ListBox()
  38448. {
  38449. headerComponent = 0;
  38450. viewport = 0;
  38451. }
  38452. void ListBox::setModel (ListBoxModel* const newModel)
  38453. {
  38454. if (model != newModel)
  38455. {
  38456. model = newModel;
  38457. updateContent();
  38458. }
  38459. }
  38460. void ListBox::setMultipleSelectionEnabled (bool b)
  38461. {
  38462. multipleSelection = b;
  38463. }
  38464. void ListBox::setMouseMoveSelectsRows (bool b)
  38465. {
  38466. mouseMoveSelects = b;
  38467. if (b)
  38468. addMouseListener (this, true);
  38469. }
  38470. void ListBox::paint (Graphics& g)
  38471. {
  38472. if (! hasDoneInitialUpdate)
  38473. updateContent();
  38474. g.fillAll (findColour (backgroundColourId));
  38475. }
  38476. void ListBox::paintOverChildren (Graphics& g)
  38477. {
  38478. if (outlineThickness > 0)
  38479. {
  38480. g.setColour (findColour (outlineColourId));
  38481. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38482. }
  38483. }
  38484. void ListBox::resized()
  38485. {
  38486. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38487. outlineThickness,
  38488. outlineThickness,
  38489. outlineThickness));
  38490. viewport->setSingleStepSizes (20, getRowHeight());
  38491. viewport->updateVisibleArea (false);
  38492. }
  38493. void ListBox::visibilityChanged()
  38494. {
  38495. viewport->updateVisibleArea (true);
  38496. }
  38497. Viewport* ListBox::getViewport() const throw()
  38498. {
  38499. return viewport;
  38500. }
  38501. void ListBox::updateContent()
  38502. {
  38503. hasDoneInitialUpdate = true;
  38504. totalItems = (model != 0) ? model->getNumRows() : 0;
  38505. bool selectionChanged = false;
  38506. if (selected [selected.size() - 1] >= totalItems)
  38507. {
  38508. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38509. lastRowSelected = getSelectedRow (0);
  38510. selectionChanged = true;
  38511. }
  38512. viewport->updateVisibleArea (isVisible());
  38513. viewport->resized();
  38514. if (selectionChanged && model != 0)
  38515. model->selectedRowsChanged (lastRowSelected);
  38516. }
  38517. void ListBox::selectRow (const int row,
  38518. bool dontScroll,
  38519. bool deselectOthersFirst)
  38520. {
  38521. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38522. }
  38523. void ListBox::selectRowInternal (const int row,
  38524. bool dontScroll,
  38525. bool deselectOthersFirst,
  38526. bool isMouseClick)
  38527. {
  38528. if (! multipleSelection)
  38529. deselectOthersFirst = true;
  38530. if ((! isRowSelected (row))
  38531. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38532. {
  38533. if (((unsigned int) row) < (unsigned int) totalItems)
  38534. {
  38535. if (deselectOthersFirst)
  38536. selected.clear();
  38537. selected.addRange (Range<int> (row, row + 1));
  38538. if (getHeight() == 0 || getWidth() == 0)
  38539. dontScroll = true;
  38540. viewport->hasUpdated = false;
  38541. if (row < viewport->firstWholeIndex && ! dontScroll)
  38542. {
  38543. viewport->setViewPosition (viewport->getViewPositionX(),
  38544. row * getRowHeight());
  38545. }
  38546. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38547. {
  38548. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38549. if (row >= lastRowSelected + rowsOnScreen
  38550. && rowsOnScreen < totalItems - 1
  38551. && ! isMouseClick)
  38552. {
  38553. viewport->setViewPosition (viewport->getViewPositionX(),
  38554. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38555. * getRowHeight());
  38556. }
  38557. else
  38558. {
  38559. viewport->setViewPosition (viewport->getViewPositionX(),
  38560. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38561. }
  38562. }
  38563. if (! viewport->hasUpdated)
  38564. viewport->updateContents();
  38565. lastRowSelected = row;
  38566. model->selectedRowsChanged (row);
  38567. }
  38568. else
  38569. {
  38570. if (deselectOthersFirst)
  38571. deselectAllRows();
  38572. }
  38573. }
  38574. }
  38575. void ListBox::deselectRow (const int row)
  38576. {
  38577. if (selected.contains (row))
  38578. {
  38579. selected.removeRange (Range <int> (row, row + 1));
  38580. if (row == lastRowSelected)
  38581. lastRowSelected = getSelectedRow (0);
  38582. viewport->updateContents();
  38583. model->selectedRowsChanged (lastRowSelected);
  38584. }
  38585. }
  38586. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38587. const bool sendNotificationEventToModel)
  38588. {
  38589. selected = setOfRowsToBeSelected;
  38590. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38591. if (! isRowSelected (lastRowSelected))
  38592. lastRowSelected = getSelectedRow (0);
  38593. viewport->updateContents();
  38594. if ((model != 0) && sendNotificationEventToModel)
  38595. model->selectedRowsChanged (lastRowSelected);
  38596. }
  38597. const SparseSet<int> ListBox::getSelectedRows() const
  38598. {
  38599. return selected;
  38600. }
  38601. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38602. {
  38603. if (multipleSelection && (firstRow != lastRow))
  38604. {
  38605. const int numRows = totalItems - 1;
  38606. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38607. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38608. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38609. jmax (firstRow, lastRow) + 1));
  38610. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38611. }
  38612. selectRowInternal (lastRow, false, false, true);
  38613. }
  38614. void ListBox::flipRowSelection (const int row)
  38615. {
  38616. if (isRowSelected (row))
  38617. deselectRow (row);
  38618. else
  38619. selectRowInternal (row, false, false, true);
  38620. }
  38621. void ListBox::deselectAllRows()
  38622. {
  38623. if (! selected.isEmpty())
  38624. {
  38625. selected.clear();
  38626. lastRowSelected = -1;
  38627. viewport->updateContents();
  38628. if (model != 0)
  38629. model->selectedRowsChanged (lastRowSelected);
  38630. }
  38631. }
  38632. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38633. const ModifierKeys& mods)
  38634. {
  38635. if (multipleSelection && mods.isCommandDown())
  38636. {
  38637. flipRowSelection (row);
  38638. }
  38639. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38640. {
  38641. selectRangeOfRows (lastRowSelected, row);
  38642. }
  38643. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38644. {
  38645. selectRowInternal (row, false, true, true);
  38646. }
  38647. }
  38648. int ListBox::getNumSelectedRows() const
  38649. {
  38650. return selected.size();
  38651. }
  38652. int ListBox::getSelectedRow (const int index) const
  38653. {
  38654. return (((unsigned int) index) < (unsigned int) selected.size())
  38655. ? selected [index] : -1;
  38656. }
  38657. bool ListBox::isRowSelected (const int row) const
  38658. {
  38659. return selected.contains (row);
  38660. }
  38661. int ListBox::getLastRowSelected() const
  38662. {
  38663. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38664. }
  38665. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38666. {
  38667. if (((unsigned int) x) < (unsigned int) getWidth())
  38668. {
  38669. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38670. if (((unsigned int) row) < (unsigned int) totalItems)
  38671. return row;
  38672. }
  38673. return -1;
  38674. }
  38675. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38676. {
  38677. if (((unsigned int) x) < (unsigned int) getWidth())
  38678. {
  38679. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38680. return jlimit (0, totalItems, row);
  38681. }
  38682. return -1;
  38683. }
  38684. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38685. {
  38686. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38687. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38688. }
  38689. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38690. {
  38691. return viewport->getRowNumberOfComponent (rowComponent);
  38692. }
  38693. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38694. const bool relativeToComponentTopLeft) const throw()
  38695. {
  38696. int y = viewport->getY() + rowHeight * rowNumber;
  38697. if (relativeToComponentTopLeft)
  38698. y -= viewport->getViewPositionY();
  38699. return Rectangle<int> (viewport->getX(), y,
  38700. viewport->getViewedComponent()->getWidth(), rowHeight);
  38701. }
  38702. void ListBox::setVerticalPosition (const double proportion)
  38703. {
  38704. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38705. viewport->setViewPosition (viewport->getViewPositionX(),
  38706. jmax (0, roundToInt (proportion * offscreen)));
  38707. }
  38708. double ListBox::getVerticalPosition() const
  38709. {
  38710. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38711. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38712. : 0;
  38713. }
  38714. int ListBox::getVisibleRowWidth() const throw()
  38715. {
  38716. return viewport->getViewWidth();
  38717. }
  38718. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38719. {
  38720. if (row < viewport->firstWholeIndex)
  38721. {
  38722. viewport->setViewPosition (viewport->getViewPositionX(),
  38723. row * getRowHeight());
  38724. }
  38725. else if (row >= viewport->lastWholeIndex)
  38726. {
  38727. viewport->setViewPosition (viewport->getViewPositionX(),
  38728. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38729. }
  38730. }
  38731. bool ListBox::keyPressed (const KeyPress& key)
  38732. {
  38733. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38734. const bool multiple = multipleSelection
  38735. && (lastRowSelected >= 0)
  38736. && (key.getModifiers().isShiftDown()
  38737. || key.getModifiers().isCtrlDown()
  38738. || key.getModifiers().isCommandDown());
  38739. if (key.isKeyCode (KeyPress::upKey))
  38740. {
  38741. if (multiple)
  38742. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38743. else
  38744. selectRow (jmax (0, lastRowSelected - 1));
  38745. }
  38746. else if (key.isKeyCode (KeyPress::returnKey)
  38747. && isRowSelected (lastRowSelected))
  38748. {
  38749. if (model != 0)
  38750. model->returnKeyPressed (lastRowSelected);
  38751. }
  38752. else if (key.isKeyCode (KeyPress::pageUpKey))
  38753. {
  38754. if (multiple)
  38755. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38756. else
  38757. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38758. }
  38759. else if (key.isKeyCode (KeyPress::pageDownKey))
  38760. {
  38761. if (multiple)
  38762. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38763. else
  38764. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38765. }
  38766. else if (key.isKeyCode (KeyPress::homeKey))
  38767. {
  38768. if (multiple && key.getModifiers().isShiftDown())
  38769. selectRangeOfRows (lastRowSelected, 0);
  38770. else
  38771. selectRow (0);
  38772. }
  38773. else if (key.isKeyCode (KeyPress::endKey))
  38774. {
  38775. if (multiple && key.getModifiers().isShiftDown())
  38776. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38777. else
  38778. selectRow (totalItems - 1);
  38779. }
  38780. else if (key.isKeyCode (KeyPress::downKey))
  38781. {
  38782. if (multiple)
  38783. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38784. else
  38785. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38786. }
  38787. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38788. && isRowSelected (lastRowSelected))
  38789. {
  38790. if (model != 0)
  38791. model->deleteKeyPressed (lastRowSelected);
  38792. }
  38793. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38794. {
  38795. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38796. }
  38797. else
  38798. {
  38799. return false;
  38800. }
  38801. return true;
  38802. }
  38803. bool ListBox::keyStateChanged (const bool isKeyDown)
  38804. {
  38805. return isKeyDown
  38806. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38807. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38808. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38809. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38810. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38811. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38812. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38813. }
  38814. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38815. {
  38816. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38817. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38818. }
  38819. void ListBox::mouseMove (const MouseEvent& e)
  38820. {
  38821. if (mouseMoveSelects)
  38822. {
  38823. const MouseEvent e2 (e.getEventRelativeTo (this));
  38824. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38825. }
  38826. }
  38827. void ListBox::mouseExit (const MouseEvent& e)
  38828. {
  38829. mouseMove (e);
  38830. }
  38831. void ListBox::mouseUp (const MouseEvent& e)
  38832. {
  38833. if (e.mouseWasClicked() && model != 0)
  38834. model->backgroundClicked();
  38835. }
  38836. void ListBox::setRowHeight (const int newHeight)
  38837. {
  38838. rowHeight = jmax (1, newHeight);
  38839. viewport->setSingleStepSizes (20, rowHeight);
  38840. updateContent();
  38841. }
  38842. int ListBox::getNumRowsOnScreen() const throw()
  38843. {
  38844. return viewport->getMaximumVisibleHeight() / rowHeight;
  38845. }
  38846. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38847. {
  38848. minimumRowWidth = newMinimumWidth;
  38849. updateContent();
  38850. }
  38851. int ListBox::getVisibleContentWidth() const throw()
  38852. {
  38853. return viewport->getMaximumVisibleWidth();
  38854. }
  38855. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38856. {
  38857. return viewport->getVerticalScrollBar();
  38858. }
  38859. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38860. {
  38861. return viewport->getHorizontalScrollBar();
  38862. }
  38863. void ListBox::colourChanged()
  38864. {
  38865. setOpaque (findColour (backgroundColourId).isOpaque());
  38866. viewport->setOpaque (isOpaque());
  38867. repaint();
  38868. }
  38869. void ListBox::setOutlineThickness (const int outlineThickness_)
  38870. {
  38871. outlineThickness = outlineThickness_;
  38872. resized();
  38873. }
  38874. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38875. {
  38876. if (newHeaderComponent != headerComponent)
  38877. {
  38878. headerComponent = newHeaderComponent;
  38879. addAndMakeVisible (newHeaderComponent);
  38880. ListBox::resized();
  38881. }
  38882. }
  38883. void ListBox::repaintRow (const int rowNumber) throw()
  38884. {
  38885. repaint (getRowPosition (rowNumber, true));
  38886. }
  38887. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38888. {
  38889. Rectangle<int> imageArea;
  38890. const int firstRow = getRowContainingPosition (0, 0);
  38891. int i;
  38892. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38893. {
  38894. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38895. if (rowComp != 0 && isRowSelected (firstRow + i))
  38896. {
  38897. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38898. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38899. imageArea = imageArea.getUnion (rowRect);
  38900. }
  38901. }
  38902. imageArea = imageArea.getIntersection (getLocalBounds());
  38903. imageX = imageArea.getX();
  38904. imageY = imageArea.getY();
  38905. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  38906. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38907. {
  38908. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38909. if (rowComp != 0 && isRowSelected (firstRow + i))
  38910. {
  38911. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38912. Graphics g (snapshot);
  38913. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38914. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38915. rowComp->paintEntireComponent (g);
  38916. }
  38917. }
  38918. return snapshot;
  38919. }
  38920. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38921. {
  38922. DragAndDropContainer* const dragContainer
  38923. = DragAndDropContainer::findParentDragContainerFor (this);
  38924. if (dragContainer != 0)
  38925. {
  38926. int x, y;
  38927. Image dragImage (createSnapshotOfSelectedRows (x, y));
  38928. dragImage.multiplyAllAlphas (0.6f);
  38929. MouseEvent e2 (e.getEventRelativeTo (this));
  38930. const Point<int> p (x - e2.x, y - e2.y);
  38931. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38932. }
  38933. else
  38934. {
  38935. // to be able to do a drag-and-drop operation, the listbox needs to
  38936. // be inside a component which is also a DragAndDropContainer.
  38937. jassertfalse;
  38938. }
  38939. }
  38940. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38941. {
  38942. (void) existingComponentToUpdate;
  38943. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38944. return 0;
  38945. }
  38946. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38947. {
  38948. }
  38949. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38950. {
  38951. }
  38952. void ListBoxModel::backgroundClicked()
  38953. {
  38954. }
  38955. void ListBoxModel::selectedRowsChanged (int)
  38956. {
  38957. }
  38958. void ListBoxModel::deleteKeyPressed (int)
  38959. {
  38960. }
  38961. void ListBoxModel::returnKeyPressed (int)
  38962. {
  38963. }
  38964. void ListBoxModel::listWasScrolled()
  38965. {
  38966. }
  38967. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38968. {
  38969. return String::empty;
  38970. }
  38971. const String ListBoxModel::getTooltipForRow (int)
  38972. {
  38973. return String::empty;
  38974. }
  38975. END_JUCE_NAMESPACE
  38976. /*** End of inlined file: juce_ListBox.cpp ***/
  38977. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38978. BEGIN_JUCE_NAMESPACE
  38979. ProgressBar::ProgressBar (double& progress_)
  38980. : progress (progress_),
  38981. displayPercentage (true),
  38982. lastCallbackTime (0)
  38983. {
  38984. currentValue = jlimit (0.0, 1.0, progress);
  38985. }
  38986. ProgressBar::~ProgressBar()
  38987. {
  38988. }
  38989. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38990. {
  38991. displayPercentage = shouldDisplayPercentage;
  38992. repaint();
  38993. }
  38994. void ProgressBar::setTextToDisplay (const String& text)
  38995. {
  38996. displayPercentage = false;
  38997. displayedMessage = text;
  38998. }
  38999. void ProgressBar::lookAndFeelChanged()
  39000. {
  39001. setOpaque (findColour (backgroundColourId).isOpaque());
  39002. }
  39003. void ProgressBar::colourChanged()
  39004. {
  39005. lookAndFeelChanged();
  39006. }
  39007. void ProgressBar::paint (Graphics& g)
  39008. {
  39009. String text;
  39010. if (displayPercentage)
  39011. {
  39012. if (currentValue >= 0 && currentValue <= 1.0)
  39013. text << roundToInt (currentValue * 100.0) << '%';
  39014. }
  39015. else
  39016. {
  39017. text = displayedMessage;
  39018. }
  39019. getLookAndFeel().drawProgressBar (g, *this,
  39020. getWidth(), getHeight(),
  39021. currentValue, text);
  39022. }
  39023. void ProgressBar::visibilityChanged()
  39024. {
  39025. if (isVisible())
  39026. startTimer (30);
  39027. else
  39028. stopTimer();
  39029. }
  39030. void ProgressBar::timerCallback()
  39031. {
  39032. double newProgress = progress;
  39033. const uint32 now = Time::getMillisecondCounter();
  39034. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39035. lastCallbackTime = now;
  39036. if (currentValue != newProgress
  39037. || newProgress < 0 || newProgress >= 1.0
  39038. || currentMessage != displayedMessage)
  39039. {
  39040. if (currentValue < newProgress
  39041. && newProgress >= 0 && newProgress < 1.0
  39042. && currentValue >= 0 && currentValue < 1.0)
  39043. {
  39044. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39045. newProgress);
  39046. }
  39047. currentValue = newProgress;
  39048. currentMessage = displayedMessage;
  39049. repaint();
  39050. }
  39051. }
  39052. END_JUCE_NAMESPACE
  39053. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39054. /*** Start of inlined file: juce_Slider.cpp ***/
  39055. BEGIN_JUCE_NAMESPACE
  39056. class SliderPopupDisplayComponent : public BubbleComponent
  39057. {
  39058. public:
  39059. SliderPopupDisplayComponent (Slider* const owner_)
  39060. : owner (owner_),
  39061. font (15.0f, Font::bold)
  39062. {
  39063. setAlwaysOnTop (true);
  39064. }
  39065. ~SliderPopupDisplayComponent()
  39066. {
  39067. }
  39068. void paintContent (Graphics& g, int w, int h)
  39069. {
  39070. g.setFont (font);
  39071. g.setColour (Colours::black);
  39072. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39073. }
  39074. void getContentSize (int& w, int& h)
  39075. {
  39076. w = font.getStringWidth (text) + 18;
  39077. h = (int) (font.getHeight() * 1.6f);
  39078. }
  39079. void updatePosition (const String& newText)
  39080. {
  39081. if (text != newText)
  39082. {
  39083. text = newText;
  39084. repaint();
  39085. }
  39086. BubbleComponent::setPosition (owner);
  39087. }
  39088. juce_UseDebuggingNewOperator
  39089. private:
  39090. Slider* owner;
  39091. Font font;
  39092. String text;
  39093. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39094. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39095. };
  39096. Slider::Slider (const String& name)
  39097. : Component (name),
  39098. lastCurrentValue (0),
  39099. lastValueMin (0),
  39100. lastValueMax (0),
  39101. minimum (0),
  39102. maximum (10),
  39103. interval (0),
  39104. skewFactor (1.0),
  39105. velocityModeSensitivity (1.0),
  39106. velocityModeOffset (0.0),
  39107. velocityModeThreshold (1),
  39108. rotaryStart (float_Pi * 1.2f),
  39109. rotaryEnd (float_Pi * 2.8f),
  39110. numDecimalPlaces (7),
  39111. sliderRegionStart (0),
  39112. sliderRegionSize (1),
  39113. sliderBeingDragged (-1),
  39114. pixelsForFullDragExtent (250),
  39115. style (LinearHorizontal),
  39116. textBoxPos (TextBoxLeft),
  39117. textBoxWidth (80),
  39118. textBoxHeight (20),
  39119. incDecButtonMode (incDecButtonsNotDraggable),
  39120. editableText (true),
  39121. doubleClickToValue (false),
  39122. isVelocityBased (false),
  39123. userKeyOverridesVelocity (true),
  39124. rotaryStop (true),
  39125. incDecButtonsSideBySide (false),
  39126. sendChangeOnlyOnRelease (false),
  39127. popupDisplayEnabled (false),
  39128. menuEnabled (false),
  39129. menuShown (false),
  39130. scrollWheelEnabled (true),
  39131. snapsToMousePos (true),
  39132. valueBox (0),
  39133. incButton (0),
  39134. decButton (0),
  39135. popupDisplay (0),
  39136. parentForPopupDisplay (0)
  39137. {
  39138. setWantsKeyboardFocus (false);
  39139. setRepaintsOnMouseActivity (true);
  39140. lookAndFeelChanged();
  39141. updateText();
  39142. currentValue.addListener (this);
  39143. valueMin.addListener (this);
  39144. valueMax.addListener (this);
  39145. }
  39146. Slider::~Slider()
  39147. {
  39148. currentValue.removeListener (this);
  39149. valueMin.removeListener (this);
  39150. valueMax.removeListener (this);
  39151. popupDisplay = 0;
  39152. deleteAllChildren();
  39153. }
  39154. void Slider::handleAsyncUpdate()
  39155. {
  39156. cancelPendingUpdate();
  39157. Component::BailOutChecker checker (this);
  39158. listeners.callChecked (checker, &Listener::sliderValueChanged, this);
  39159. }
  39160. void Slider::sendDragStart()
  39161. {
  39162. startedDragging();
  39163. Component::BailOutChecker checker (this);
  39164. listeners.callChecked (checker, &Listener::sliderDragStarted, this);
  39165. }
  39166. void Slider::sendDragEnd()
  39167. {
  39168. stoppedDragging();
  39169. sliderBeingDragged = -1;
  39170. Component::BailOutChecker checker (this);
  39171. listeners.callChecked (checker, &Listener::sliderDragEnded, this);
  39172. }
  39173. void Slider::addListener (Listener* const listener)
  39174. {
  39175. listeners.add (listener);
  39176. }
  39177. void Slider::removeListener (Listener* const listener)
  39178. {
  39179. listeners.remove (listener);
  39180. }
  39181. void Slider::setSliderStyle (const SliderStyle newStyle)
  39182. {
  39183. if (style != newStyle)
  39184. {
  39185. style = newStyle;
  39186. repaint();
  39187. lookAndFeelChanged();
  39188. }
  39189. }
  39190. void Slider::setRotaryParameters (const float startAngleRadians,
  39191. const float endAngleRadians,
  39192. const bool stopAtEnd)
  39193. {
  39194. // make sure the values are sensible..
  39195. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39196. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39197. jassert (rotaryStart < rotaryEnd);
  39198. rotaryStart = startAngleRadians;
  39199. rotaryEnd = endAngleRadians;
  39200. rotaryStop = stopAtEnd;
  39201. }
  39202. void Slider::setVelocityBasedMode (const bool velBased)
  39203. {
  39204. isVelocityBased = velBased;
  39205. }
  39206. void Slider::setVelocityModeParameters (const double sensitivity,
  39207. const int threshold,
  39208. const double offset,
  39209. const bool userCanPressKeyToSwapMode)
  39210. {
  39211. jassert (threshold >= 0);
  39212. jassert (sensitivity > 0);
  39213. jassert (offset >= 0);
  39214. velocityModeSensitivity = sensitivity;
  39215. velocityModeOffset = offset;
  39216. velocityModeThreshold = threshold;
  39217. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39218. }
  39219. void Slider::setSkewFactor (const double factor)
  39220. {
  39221. skewFactor = factor;
  39222. }
  39223. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39224. {
  39225. if (maximum > minimum)
  39226. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39227. / (maximum - minimum));
  39228. }
  39229. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39230. {
  39231. jassert (distanceForFullScaleDrag > 0);
  39232. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39233. }
  39234. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39235. {
  39236. if (incDecButtonMode != mode)
  39237. {
  39238. incDecButtonMode = mode;
  39239. lookAndFeelChanged();
  39240. }
  39241. }
  39242. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39243. const bool isReadOnly,
  39244. const int textEntryBoxWidth,
  39245. const int textEntryBoxHeight)
  39246. {
  39247. if (textBoxPos != newPosition
  39248. || editableText != (! isReadOnly)
  39249. || textBoxWidth != textEntryBoxWidth
  39250. || textBoxHeight != textEntryBoxHeight)
  39251. {
  39252. textBoxPos = newPosition;
  39253. editableText = ! isReadOnly;
  39254. textBoxWidth = textEntryBoxWidth;
  39255. textBoxHeight = textEntryBoxHeight;
  39256. repaint();
  39257. lookAndFeelChanged();
  39258. }
  39259. }
  39260. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39261. {
  39262. editableText = shouldBeEditable;
  39263. if (valueBox != 0)
  39264. valueBox->setEditable (shouldBeEditable && isEnabled());
  39265. }
  39266. void Slider::showTextBox()
  39267. {
  39268. jassert (editableText); // this should probably be avoided in read-only sliders.
  39269. if (valueBox != 0)
  39270. valueBox->showEditor();
  39271. }
  39272. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39273. {
  39274. if (valueBox != 0)
  39275. {
  39276. valueBox->hideEditor (discardCurrentEditorContents);
  39277. if (discardCurrentEditorContents)
  39278. updateText();
  39279. }
  39280. }
  39281. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39282. {
  39283. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39284. }
  39285. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39286. {
  39287. snapsToMousePos = shouldSnapToMouse;
  39288. }
  39289. void Slider::setPopupDisplayEnabled (const bool enabled,
  39290. Component* const parentComponentToUse)
  39291. {
  39292. popupDisplayEnabled = enabled;
  39293. parentForPopupDisplay = parentComponentToUse;
  39294. }
  39295. void Slider::colourChanged()
  39296. {
  39297. lookAndFeelChanged();
  39298. }
  39299. void Slider::lookAndFeelChanged()
  39300. {
  39301. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39302. : getTextFromValue (currentValue.getValue()));
  39303. deleteAllChildren();
  39304. valueBox = 0;
  39305. LookAndFeel& lf = getLookAndFeel();
  39306. if (textBoxPos != NoTextBox)
  39307. {
  39308. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39309. valueBox->setWantsKeyboardFocus (false);
  39310. valueBox->setText (previousTextBoxContent, false);
  39311. valueBox->setEditable (editableText && isEnabled());
  39312. valueBox->addListener (this);
  39313. if (style == LinearBar)
  39314. valueBox->addMouseListener (this, false);
  39315. valueBox->setTooltip (getTooltip());
  39316. }
  39317. if (style == IncDecButtons)
  39318. {
  39319. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39320. incButton->addButtonListener (this);
  39321. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39322. decButton->addButtonListener (this);
  39323. if (incDecButtonMode != incDecButtonsNotDraggable)
  39324. {
  39325. incButton->addMouseListener (this, false);
  39326. decButton->addMouseListener (this, false);
  39327. }
  39328. else
  39329. {
  39330. incButton->setRepeatSpeed (300, 100, 20);
  39331. incButton->addMouseListener (decButton, false);
  39332. decButton->setRepeatSpeed (300, 100, 20);
  39333. decButton->addMouseListener (incButton, false);
  39334. }
  39335. incButton->setTooltip (getTooltip());
  39336. decButton->setTooltip (getTooltip());
  39337. }
  39338. setComponentEffect (lf.getSliderEffect());
  39339. resized();
  39340. repaint();
  39341. }
  39342. void Slider::setRange (const double newMin,
  39343. const double newMax,
  39344. const double newInt)
  39345. {
  39346. if (minimum != newMin
  39347. || maximum != newMax
  39348. || interval != newInt)
  39349. {
  39350. minimum = newMin;
  39351. maximum = newMax;
  39352. interval = newInt;
  39353. // figure out the number of DPs needed to display all values at this
  39354. // interval setting.
  39355. numDecimalPlaces = 7;
  39356. if (newInt != 0)
  39357. {
  39358. int v = abs ((int) (newInt * 10000000));
  39359. while ((v % 10) == 0)
  39360. {
  39361. --numDecimalPlaces;
  39362. v /= 10;
  39363. }
  39364. }
  39365. // keep the current values inside the new range..
  39366. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39367. {
  39368. setValue (getValue(), false, false);
  39369. }
  39370. else
  39371. {
  39372. setMinValue (getMinValue(), false, false);
  39373. setMaxValue (getMaxValue(), false, false);
  39374. }
  39375. updateText();
  39376. }
  39377. }
  39378. void Slider::triggerChangeMessage (const bool synchronous)
  39379. {
  39380. if (synchronous)
  39381. handleAsyncUpdate();
  39382. else
  39383. triggerAsyncUpdate();
  39384. valueChanged();
  39385. }
  39386. void Slider::valueChanged (Value& value)
  39387. {
  39388. if (value.refersToSameSourceAs (currentValue))
  39389. {
  39390. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39391. setValue (currentValue.getValue(), false, false);
  39392. }
  39393. else if (value.refersToSameSourceAs (valueMin))
  39394. setMinValue (valueMin.getValue(), false, false, true);
  39395. else if (value.refersToSameSourceAs (valueMax))
  39396. setMaxValue (valueMax.getValue(), false, false, true);
  39397. }
  39398. double Slider::getValue() const
  39399. {
  39400. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39401. // methods to get the two values.
  39402. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39403. return currentValue.getValue();
  39404. }
  39405. void Slider::setValue (double newValue,
  39406. const bool sendUpdateMessage,
  39407. const bool sendMessageSynchronously)
  39408. {
  39409. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39410. // methods to set the two values.
  39411. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39412. newValue = constrainedValue (newValue);
  39413. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39414. {
  39415. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39416. newValue = jlimit ((double) valueMin.getValue(),
  39417. (double) valueMax.getValue(),
  39418. newValue);
  39419. }
  39420. if (newValue != lastCurrentValue)
  39421. {
  39422. if (valueBox != 0)
  39423. valueBox->hideEditor (true);
  39424. lastCurrentValue = newValue;
  39425. currentValue = newValue;
  39426. updateText();
  39427. repaint();
  39428. if (popupDisplay != 0)
  39429. {
  39430. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39431. ->updatePosition (getTextFromValue (newValue));
  39432. popupDisplay->repaint();
  39433. }
  39434. if (sendUpdateMessage)
  39435. triggerChangeMessage (sendMessageSynchronously);
  39436. }
  39437. }
  39438. double Slider::getMinValue() const
  39439. {
  39440. // The minimum value only applies to sliders that are in two- or three-value mode.
  39441. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39442. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39443. return valueMin.getValue();
  39444. }
  39445. double Slider::getMaxValue() const
  39446. {
  39447. // The maximum value only applies to sliders that are in two- or three-value mode.
  39448. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39449. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39450. return valueMax.getValue();
  39451. }
  39452. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39453. {
  39454. // The minimum value only applies to sliders that are in two- or three-value mode.
  39455. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39456. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39457. newValue = constrainedValue (newValue);
  39458. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39459. {
  39460. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39461. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39462. newValue = jmin ((double) valueMax.getValue(), newValue);
  39463. }
  39464. else
  39465. {
  39466. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39467. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39468. newValue = jmin (lastCurrentValue, newValue);
  39469. }
  39470. if (lastValueMin != newValue)
  39471. {
  39472. lastValueMin = newValue;
  39473. valueMin = newValue;
  39474. repaint();
  39475. if (popupDisplay != 0)
  39476. {
  39477. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39478. ->updatePosition (getTextFromValue (newValue));
  39479. popupDisplay->repaint();
  39480. }
  39481. if (sendUpdateMessage)
  39482. triggerChangeMessage (sendMessageSynchronously);
  39483. }
  39484. }
  39485. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39486. {
  39487. // The maximum value only applies to sliders that are in two- or three-value mode.
  39488. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39489. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39490. newValue = constrainedValue (newValue);
  39491. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39492. {
  39493. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39494. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39495. newValue = jmax ((double) valueMin.getValue(), newValue);
  39496. }
  39497. else
  39498. {
  39499. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39500. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39501. newValue = jmax (lastCurrentValue, newValue);
  39502. }
  39503. if (lastValueMax != newValue)
  39504. {
  39505. lastValueMax = newValue;
  39506. valueMax = newValue;
  39507. repaint();
  39508. if (popupDisplay != 0)
  39509. {
  39510. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39511. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39512. popupDisplay->repaint();
  39513. }
  39514. if (sendUpdateMessage)
  39515. triggerChangeMessage (sendMessageSynchronously);
  39516. }
  39517. }
  39518. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39519. const double valueToSetOnDoubleClick)
  39520. {
  39521. doubleClickToValue = isDoubleClickEnabled;
  39522. doubleClickReturnValue = valueToSetOnDoubleClick;
  39523. }
  39524. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39525. {
  39526. isEnabled_ = doubleClickToValue;
  39527. return doubleClickReturnValue;
  39528. }
  39529. void Slider::updateText()
  39530. {
  39531. if (valueBox != 0)
  39532. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39533. }
  39534. void Slider::setTextValueSuffix (const String& suffix)
  39535. {
  39536. if (textSuffix != suffix)
  39537. {
  39538. textSuffix = suffix;
  39539. updateText();
  39540. }
  39541. }
  39542. const String Slider::getTextValueSuffix() const
  39543. {
  39544. return textSuffix;
  39545. }
  39546. const String Slider::getTextFromValue (double v)
  39547. {
  39548. if (getNumDecimalPlacesToDisplay() > 0)
  39549. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39550. else
  39551. return String (roundToInt (v)) + getTextValueSuffix();
  39552. }
  39553. double Slider::getValueFromText (const String& text)
  39554. {
  39555. String t (text.trimStart());
  39556. if (t.endsWith (textSuffix))
  39557. t = t.substring (0, t.length() - textSuffix.length());
  39558. while (t.startsWithChar ('+'))
  39559. t = t.substring (1).trimStart();
  39560. return t.initialSectionContainingOnly ("0123456789.,-")
  39561. .getDoubleValue();
  39562. }
  39563. double Slider::proportionOfLengthToValue (double proportion)
  39564. {
  39565. if (skewFactor != 1.0 && proportion > 0.0)
  39566. proportion = exp (log (proportion) / skewFactor);
  39567. return minimum + (maximum - minimum) * proportion;
  39568. }
  39569. double Slider::valueToProportionOfLength (double value)
  39570. {
  39571. const double n = (value - minimum) / (maximum - minimum);
  39572. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39573. }
  39574. double Slider::snapValue (double attemptedValue, const bool)
  39575. {
  39576. return attemptedValue;
  39577. }
  39578. void Slider::startedDragging()
  39579. {
  39580. }
  39581. void Slider::stoppedDragging()
  39582. {
  39583. }
  39584. void Slider::valueChanged()
  39585. {
  39586. }
  39587. void Slider::enablementChanged()
  39588. {
  39589. repaint();
  39590. }
  39591. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39592. {
  39593. menuEnabled = menuEnabled_;
  39594. }
  39595. void Slider::setScrollWheelEnabled (const bool enabled)
  39596. {
  39597. scrollWheelEnabled = enabled;
  39598. }
  39599. void Slider::labelTextChanged (Label* label)
  39600. {
  39601. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39602. if (newValue != (double) currentValue.getValue())
  39603. {
  39604. sendDragStart();
  39605. setValue (newValue, true, true);
  39606. sendDragEnd();
  39607. }
  39608. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39609. }
  39610. void Slider::buttonClicked (Button* button)
  39611. {
  39612. if (style == IncDecButtons)
  39613. {
  39614. sendDragStart();
  39615. if (button == incButton)
  39616. setValue (snapValue (getValue() + interval, false), true, true);
  39617. else if (button == decButton)
  39618. setValue (snapValue (getValue() - interval, false), true, true);
  39619. sendDragEnd();
  39620. }
  39621. }
  39622. double Slider::constrainedValue (double value) const
  39623. {
  39624. if (interval > 0)
  39625. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39626. if (value <= minimum || maximum <= minimum)
  39627. value = minimum;
  39628. else if (value >= maximum)
  39629. value = maximum;
  39630. return value;
  39631. }
  39632. float Slider::getLinearSliderPos (const double value)
  39633. {
  39634. double sliderPosProportional;
  39635. if (maximum > minimum)
  39636. {
  39637. if (value < minimum)
  39638. {
  39639. sliderPosProportional = 0.0;
  39640. }
  39641. else if (value > maximum)
  39642. {
  39643. sliderPosProportional = 1.0;
  39644. }
  39645. else
  39646. {
  39647. sliderPosProportional = valueToProportionOfLength (value);
  39648. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39649. }
  39650. }
  39651. else
  39652. {
  39653. sliderPosProportional = 0.5;
  39654. }
  39655. if (isVertical() || style == IncDecButtons)
  39656. sliderPosProportional = 1.0 - sliderPosProportional;
  39657. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39658. }
  39659. bool Slider::isHorizontal() const
  39660. {
  39661. return style == LinearHorizontal
  39662. || style == LinearBar
  39663. || style == TwoValueHorizontal
  39664. || style == ThreeValueHorizontal;
  39665. }
  39666. bool Slider::isVertical() const
  39667. {
  39668. return style == LinearVertical
  39669. || style == TwoValueVertical
  39670. || style == ThreeValueVertical;
  39671. }
  39672. bool Slider::incDecDragDirectionIsHorizontal() const
  39673. {
  39674. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39675. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39676. }
  39677. float Slider::getPositionOfValue (const double value)
  39678. {
  39679. if (isHorizontal() || isVertical())
  39680. {
  39681. return getLinearSliderPos (value);
  39682. }
  39683. else
  39684. {
  39685. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  39686. return 0.0f;
  39687. }
  39688. }
  39689. void Slider::paint (Graphics& g)
  39690. {
  39691. if (style != IncDecButtons)
  39692. {
  39693. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39694. {
  39695. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39696. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39697. getLookAndFeel().drawRotarySlider (g,
  39698. sliderRect.getX(),
  39699. sliderRect.getY(),
  39700. sliderRect.getWidth(),
  39701. sliderRect.getHeight(),
  39702. sliderPos,
  39703. rotaryStart, rotaryEnd,
  39704. *this);
  39705. }
  39706. else
  39707. {
  39708. getLookAndFeel().drawLinearSlider (g,
  39709. sliderRect.getX(),
  39710. sliderRect.getY(),
  39711. sliderRect.getWidth(),
  39712. sliderRect.getHeight(),
  39713. getLinearSliderPos (lastCurrentValue),
  39714. getLinearSliderPos (lastValueMin),
  39715. getLinearSliderPos (lastValueMax),
  39716. style,
  39717. *this);
  39718. }
  39719. if (style == LinearBar && valueBox == 0)
  39720. {
  39721. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39722. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39723. }
  39724. }
  39725. }
  39726. void Slider::resized()
  39727. {
  39728. int minXSpace = 0;
  39729. int minYSpace = 0;
  39730. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39731. minXSpace = 30;
  39732. else
  39733. minYSpace = 15;
  39734. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39735. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39736. if (style == LinearBar)
  39737. {
  39738. if (valueBox != 0)
  39739. valueBox->setBounds (getLocalBounds());
  39740. }
  39741. else
  39742. {
  39743. if (textBoxPos == NoTextBox)
  39744. {
  39745. sliderRect = getLocalBounds();
  39746. }
  39747. else if (textBoxPos == TextBoxLeft)
  39748. {
  39749. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39750. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39751. }
  39752. else if (textBoxPos == TextBoxRight)
  39753. {
  39754. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39755. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39756. }
  39757. else if (textBoxPos == TextBoxAbove)
  39758. {
  39759. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39760. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39761. }
  39762. else if (textBoxPos == TextBoxBelow)
  39763. {
  39764. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39765. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39766. }
  39767. }
  39768. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39769. if (style == LinearBar)
  39770. {
  39771. const int barIndent = 1;
  39772. sliderRegionStart = barIndent;
  39773. sliderRegionSize = getWidth() - barIndent * 2;
  39774. sliderRect.setBounds (sliderRegionStart, barIndent,
  39775. sliderRegionSize, getHeight() - barIndent * 2);
  39776. }
  39777. else if (isHorizontal())
  39778. {
  39779. sliderRegionStart = sliderRect.getX() + indent;
  39780. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39781. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39782. sliderRegionSize, sliderRect.getHeight());
  39783. }
  39784. else if (isVertical())
  39785. {
  39786. sliderRegionStart = sliderRect.getY() + indent;
  39787. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39788. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39789. sliderRect.getWidth(), sliderRegionSize);
  39790. }
  39791. else
  39792. {
  39793. sliderRegionStart = 0;
  39794. sliderRegionSize = 100;
  39795. }
  39796. if (style == IncDecButtons)
  39797. {
  39798. Rectangle<int> buttonRect (sliderRect);
  39799. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39800. buttonRect.expand (-2, 0);
  39801. else
  39802. buttonRect.expand (0, -2);
  39803. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39804. if (incDecButtonsSideBySide)
  39805. {
  39806. decButton->setBounds (buttonRect.getX(),
  39807. buttonRect.getY(),
  39808. buttonRect.getWidth() / 2,
  39809. buttonRect.getHeight());
  39810. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39811. incButton->setBounds (buttonRect.getCentreX(),
  39812. buttonRect.getY(),
  39813. buttonRect.getWidth() / 2,
  39814. buttonRect.getHeight());
  39815. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39816. }
  39817. else
  39818. {
  39819. incButton->setBounds (buttonRect.getX(),
  39820. buttonRect.getY(),
  39821. buttonRect.getWidth(),
  39822. buttonRect.getHeight() / 2);
  39823. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39824. decButton->setBounds (buttonRect.getX(),
  39825. buttonRect.getCentreY(),
  39826. buttonRect.getWidth(),
  39827. buttonRect.getHeight() / 2);
  39828. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39829. }
  39830. }
  39831. }
  39832. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39833. {
  39834. repaint();
  39835. }
  39836. void Slider::mouseDown (const MouseEvent& e)
  39837. {
  39838. mouseWasHidden = false;
  39839. incDecDragged = false;
  39840. mouseXWhenLastDragged = e.x;
  39841. mouseYWhenLastDragged = e.y;
  39842. mouseDragStartX = e.getMouseDownX();
  39843. mouseDragStartY = e.getMouseDownY();
  39844. if (isEnabled())
  39845. {
  39846. if (e.mods.isPopupMenu() && menuEnabled)
  39847. {
  39848. menuShown = true;
  39849. PopupMenu m;
  39850. m.setLookAndFeel (&getLookAndFeel());
  39851. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39852. m.addSeparator();
  39853. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39854. {
  39855. PopupMenu rotaryMenu;
  39856. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39857. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39858. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39859. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39860. }
  39861. const int r = m.show();
  39862. if (r == 1)
  39863. {
  39864. setVelocityBasedMode (! isVelocityBased);
  39865. }
  39866. else if (r == 2)
  39867. {
  39868. setSliderStyle (Rotary);
  39869. }
  39870. else if (r == 3)
  39871. {
  39872. setSliderStyle (RotaryHorizontalDrag);
  39873. }
  39874. else if (r == 4)
  39875. {
  39876. setSliderStyle (RotaryVerticalDrag);
  39877. }
  39878. }
  39879. else if (maximum > minimum)
  39880. {
  39881. menuShown = false;
  39882. if (valueBox != 0)
  39883. valueBox->hideEditor (true);
  39884. sliderBeingDragged = 0;
  39885. if (style == TwoValueHorizontal
  39886. || style == TwoValueVertical
  39887. || style == ThreeValueHorizontal
  39888. || style == ThreeValueVertical)
  39889. {
  39890. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39891. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39892. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39893. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39894. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39895. {
  39896. if (maxPosDistance <= minPosDistance)
  39897. sliderBeingDragged = 2;
  39898. else
  39899. sliderBeingDragged = 1;
  39900. }
  39901. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39902. {
  39903. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39904. sliderBeingDragged = 1;
  39905. else if (normalPosDistance >= maxPosDistance)
  39906. sliderBeingDragged = 2;
  39907. }
  39908. }
  39909. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39910. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39911. * valueToProportionOfLength (currentValue.getValue());
  39912. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39913. : ((sliderBeingDragged == 1) ? valueMin
  39914. : currentValue)).getValue();
  39915. valueOnMouseDown = valueWhenLastDragged;
  39916. if (popupDisplayEnabled)
  39917. {
  39918. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39919. popupDisplay = popup;
  39920. if (parentForPopupDisplay != 0)
  39921. {
  39922. parentForPopupDisplay->addChildComponent (popup);
  39923. }
  39924. else
  39925. {
  39926. popup->addToDesktop (0);
  39927. }
  39928. popup->setVisible (true);
  39929. }
  39930. sendDragStart();
  39931. mouseDrag (e);
  39932. }
  39933. }
  39934. }
  39935. void Slider::mouseUp (const MouseEvent&)
  39936. {
  39937. if (isEnabled()
  39938. && (! menuShown)
  39939. && (maximum > minimum)
  39940. && (style != IncDecButtons || incDecDragged))
  39941. {
  39942. restoreMouseIfHidden();
  39943. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39944. triggerChangeMessage (false);
  39945. sendDragEnd();
  39946. popupDisplay = 0;
  39947. if (style == IncDecButtons)
  39948. {
  39949. incButton->setState (Button::buttonNormal);
  39950. decButton->setState (Button::buttonNormal);
  39951. }
  39952. }
  39953. }
  39954. void Slider::restoreMouseIfHidden()
  39955. {
  39956. if (mouseWasHidden)
  39957. {
  39958. mouseWasHidden = false;
  39959. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39960. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39961. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39962. : ((sliderBeingDragged == 1) ? getMinValue()
  39963. : (double) currentValue.getValue());
  39964. Point<int> mousePos;
  39965. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39966. {
  39967. mousePos = Desktop::getLastMouseDownPosition();
  39968. if (style == RotaryHorizontalDrag)
  39969. {
  39970. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39971. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39972. }
  39973. else
  39974. {
  39975. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39976. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39977. }
  39978. }
  39979. else
  39980. {
  39981. const int pixelPos = (int) getLinearSliderPos (pos);
  39982. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39983. isVertical() ? pixelPos : (getHeight() / 2)));
  39984. }
  39985. Desktop::setMousePosition (mousePos);
  39986. }
  39987. }
  39988. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39989. {
  39990. if (isEnabled()
  39991. && style != IncDecButtons
  39992. && style != Rotary
  39993. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39994. {
  39995. restoreMouseIfHidden();
  39996. }
  39997. }
  39998. static double smallestAngleBetween (double a1, double a2)
  39999. {
  40000. return jmin (std::abs (a1 - a2),
  40001. std::abs (a1 + double_Pi * 2.0 - a2),
  40002. std::abs (a2 + double_Pi * 2.0 - a1));
  40003. }
  40004. void Slider::mouseDrag (const MouseEvent& e)
  40005. {
  40006. if (isEnabled()
  40007. && (! menuShown)
  40008. && (maximum > minimum))
  40009. {
  40010. if (style == Rotary)
  40011. {
  40012. int dx = e.x - sliderRect.getCentreX();
  40013. int dy = e.y - sliderRect.getCentreY();
  40014. if (dx * dx + dy * dy > 25)
  40015. {
  40016. double angle = std::atan2 ((double) dx, (double) -dy);
  40017. while (angle < 0.0)
  40018. angle += double_Pi * 2.0;
  40019. if (rotaryStop && ! e.mouseWasClicked())
  40020. {
  40021. if (std::abs (angle - lastAngle) > double_Pi)
  40022. {
  40023. if (angle >= lastAngle)
  40024. angle -= double_Pi * 2.0;
  40025. else
  40026. angle += double_Pi * 2.0;
  40027. }
  40028. if (angle >= lastAngle)
  40029. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40030. else
  40031. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40032. }
  40033. else
  40034. {
  40035. while (angle < rotaryStart)
  40036. angle += double_Pi * 2.0;
  40037. if (angle > rotaryEnd)
  40038. {
  40039. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40040. angle = rotaryStart;
  40041. else
  40042. angle = rotaryEnd;
  40043. }
  40044. }
  40045. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40046. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40047. lastAngle = angle;
  40048. }
  40049. }
  40050. else
  40051. {
  40052. if (style == LinearBar && e.mouseWasClicked()
  40053. && valueBox != 0 && valueBox->isEditable())
  40054. return;
  40055. if (style == IncDecButtons && ! incDecDragged)
  40056. {
  40057. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40058. return;
  40059. incDecDragged = true;
  40060. mouseDragStartX = e.x;
  40061. mouseDragStartY = e.y;
  40062. }
  40063. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40064. : false))
  40065. || ((maximum - minimum) / sliderRegionSize < interval))
  40066. {
  40067. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40068. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40069. if (style == RotaryHorizontalDrag
  40070. || style == RotaryVerticalDrag
  40071. || style == IncDecButtons
  40072. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40073. && ! snapsToMousePos))
  40074. {
  40075. const int mouseDiff = (style == RotaryHorizontalDrag
  40076. || style == LinearHorizontal
  40077. || style == LinearBar
  40078. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40079. ? e.x - mouseDragStartX
  40080. : mouseDragStartY - e.y;
  40081. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40082. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40083. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40084. if (style == IncDecButtons)
  40085. {
  40086. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40087. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40088. }
  40089. }
  40090. else
  40091. {
  40092. if (isVertical())
  40093. scaledMousePos = 1.0 - scaledMousePos;
  40094. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40095. }
  40096. }
  40097. else
  40098. {
  40099. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40100. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40101. ? e.x - mouseXWhenLastDragged
  40102. : e.y - mouseYWhenLastDragged;
  40103. const double maxSpeed = jmax (200, sliderRegionSize);
  40104. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40105. if (speed != 0)
  40106. {
  40107. speed = 0.2 * velocityModeSensitivity
  40108. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40109. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40110. / maxSpeed))));
  40111. if (mouseDiff < 0)
  40112. speed = -speed;
  40113. if (isVertical() || style == RotaryVerticalDrag
  40114. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40115. speed = -speed;
  40116. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40117. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40118. e.source.enableUnboundedMouseMovement (true, false);
  40119. mouseWasHidden = true;
  40120. }
  40121. }
  40122. }
  40123. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40124. if (sliderBeingDragged == 0)
  40125. {
  40126. setValue (snapValue (valueWhenLastDragged, true),
  40127. ! sendChangeOnlyOnRelease, true);
  40128. }
  40129. else if (sliderBeingDragged == 1)
  40130. {
  40131. setMinValue (snapValue (valueWhenLastDragged, true),
  40132. ! sendChangeOnlyOnRelease, false, true);
  40133. if (e.mods.isShiftDown())
  40134. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40135. else
  40136. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40137. }
  40138. else
  40139. {
  40140. jassert (sliderBeingDragged == 2);
  40141. setMaxValue (snapValue (valueWhenLastDragged, true),
  40142. ! sendChangeOnlyOnRelease, false, true);
  40143. if (e.mods.isShiftDown())
  40144. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40145. else
  40146. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40147. }
  40148. mouseXWhenLastDragged = e.x;
  40149. mouseYWhenLastDragged = e.y;
  40150. }
  40151. }
  40152. void Slider::mouseDoubleClick (const MouseEvent&)
  40153. {
  40154. if (doubleClickToValue
  40155. && isEnabled()
  40156. && style != IncDecButtons
  40157. && minimum <= doubleClickReturnValue
  40158. && maximum >= doubleClickReturnValue)
  40159. {
  40160. sendDragStart();
  40161. setValue (doubleClickReturnValue, true, true);
  40162. sendDragEnd();
  40163. }
  40164. }
  40165. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40166. {
  40167. if (scrollWheelEnabled && isEnabled()
  40168. && style != TwoValueHorizontal
  40169. && style != TwoValueVertical)
  40170. {
  40171. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40172. {
  40173. if (valueBox != 0)
  40174. valueBox->hideEditor (false);
  40175. const double value = (double) currentValue.getValue();
  40176. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40177. const double currentPos = valueToProportionOfLength (value);
  40178. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40179. double delta = (newValue != value)
  40180. ? jmax (std::abs (newValue - value), interval) : 0;
  40181. if (value > newValue)
  40182. delta = -delta;
  40183. sendDragStart();
  40184. setValue (snapValue (value + delta, false), true, true);
  40185. sendDragEnd();
  40186. }
  40187. }
  40188. else
  40189. {
  40190. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40191. }
  40192. }
  40193. void Slider::Listener::sliderDragStarted (Slider*)
  40194. {
  40195. }
  40196. void Slider::Listener::sliderDragEnded (Slider*)
  40197. {
  40198. }
  40199. END_JUCE_NAMESPACE
  40200. /*** End of inlined file: juce_Slider.cpp ***/
  40201. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40202. BEGIN_JUCE_NAMESPACE
  40203. class DragOverlayComp : public Component
  40204. {
  40205. public:
  40206. DragOverlayComp (const Image& image_)
  40207. : image (image_)
  40208. {
  40209. image.duplicateIfShared();
  40210. image.multiplyAllAlphas (0.8f);
  40211. setAlwaysOnTop (true);
  40212. }
  40213. ~DragOverlayComp()
  40214. {
  40215. }
  40216. void paint (Graphics& g)
  40217. {
  40218. g.drawImageAt (image, 0, 0);
  40219. }
  40220. private:
  40221. Image image;
  40222. DragOverlayComp (const DragOverlayComp&);
  40223. DragOverlayComp& operator= (const DragOverlayComp&);
  40224. };
  40225. TableHeaderComponent::TableHeaderComponent()
  40226. : columnsChanged (false),
  40227. columnsResized (false),
  40228. sortChanged (false),
  40229. menuActive (true),
  40230. stretchToFit (false),
  40231. columnIdBeingResized (0),
  40232. columnIdBeingDragged (0),
  40233. columnIdUnderMouse (0),
  40234. lastDeliberateWidth (0)
  40235. {
  40236. }
  40237. TableHeaderComponent::~TableHeaderComponent()
  40238. {
  40239. dragOverlayComp = 0;
  40240. }
  40241. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40242. {
  40243. menuActive = hasMenu;
  40244. }
  40245. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40246. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40247. {
  40248. if (onlyCountVisibleColumns)
  40249. {
  40250. int num = 0;
  40251. for (int i = columns.size(); --i >= 0;)
  40252. if (columns.getUnchecked(i)->isVisible())
  40253. ++num;
  40254. return num;
  40255. }
  40256. else
  40257. {
  40258. return columns.size();
  40259. }
  40260. }
  40261. const String TableHeaderComponent::getColumnName (const int columnId) const
  40262. {
  40263. const ColumnInfo* const ci = getInfoForId (columnId);
  40264. return ci != 0 ? ci->name : String::empty;
  40265. }
  40266. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40267. {
  40268. ColumnInfo* const ci = getInfoForId (columnId);
  40269. if (ci != 0 && ci->name != newName)
  40270. {
  40271. ci->name = newName;
  40272. sendColumnsChanged();
  40273. }
  40274. }
  40275. void TableHeaderComponent::addColumn (const String& columnName,
  40276. const int columnId,
  40277. const int width,
  40278. const int minimumWidth,
  40279. const int maximumWidth,
  40280. const int propertyFlags,
  40281. const int insertIndex)
  40282. {
  40283. // can't have a duplicate or null ID!
  40284. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40285. jassert (width > 0);
  40286. ColumnInfo* const ci = new ColumnInfo();
  40287. ci->name = columnName;
  40288. ci->id = columnId;
  40289. ci->width = width;
  40290. ci->lastDeliberateWidth = width;
  40291. ci->minimumWidth = minimumWidth;
  40292. ci->maximumWidth = maximumWidth;
  40293. if (ci->maximumWidth < 0)
  40294. ci->maximumWidth = std::numeric_limits<int>::max();
  40295. jassert (ci->maximumWidth >= ci->minimumWidth);
  40296. ci->propertyFlags = propertyFlags;
  40297. columns.insert (insertIndex, ci);
  40298. sendColumnsChanged();
  40299. }
  40300. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40301. {
  40302. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40303. if (index >= 0)
  40304. {
  40305. columns.remove (index);
  40306. sortChanged = true;
  40307. sendColumnsChanged();
  40308. }
  40309. }
  40310. void TableHeaderComponent::removeAllColumns()
  40311. {
  40312. if (columns.size() > 0)
  40313. {
  40314. columns.clear();
  40315. sendColumnsChanged();
  40316. }
  40317. }
  40318. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40319. {
  40320. const int currentIndex = getIndexOfColumnId (columnId, false);
  40321. newIndex = visibleIndexToTotalIndex (newIndex);
  40322. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40323. {
  40324. columns.move (currentIndex, newIndex);
  40325. sendColumnsChanged();
  40326. }
  40327. }
  40328. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40329. {
  40330. const ColumnInfo* const ci = getInfoForId (columnId);
  40331. return ci != 0 ? ci->width : 0;
  40332. }
  40333. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40334. {
  40335. ColumnInfo* const ci = getInfoForId (columnId);
  40336. if (ci != 0 && ci->width != newWidth)
  40337. {
  40338. const int numColumns = getNumColumns (true);
  40339. ci->lastDeliberateWidth = ci->width
  40340. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40341. if (stretchToFit)
  40342. {
  40343. const int index = getIndexOfColumnId (columnId, true) + 1;
  40344. if (((unsigned int) index) < (unsigned int) numColumns)
  40345. {
  40346. const int x = getColumnPosition (index).getX();
  40347. if (lastDeliberateWidth == 0)
  40348. lastDeliberateWidth = getTotalWidth();
  40349. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40350. }
  40351. }
  40352. repaint();
  40353. columnsResized = true;
  40354. triggerAsyncUpdate();
  40355. }
  40356. }
  40357. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40358. {
  40359. int n = 0;
  40360. for (int i = 0; i < columns.size(); ++i)
  40361. {
  40362. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40363. {
  40364. if (columns.getUnchecked(i)->id == columnId)
  40365. return n;
  40366. ++n;
  40367. }
  40368. }
  40369. return -1;
  40370. }
  40371. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40372. {
  40373. if (onlyCountVisibleColumns)
  40374. index = visibleIndexToTotalIndex (index);
  40375. const ColumnInfo* const ci = columns [index];
  40376. return (ci != 0) ? ci->id : 0;
  40377. }
  40378. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40379. {
  40380. int x = 0, width = 0, n = 0;
  40381. for (int i = 0; i < columns.size(); ++i)
  40382. {
  40383. x += width;
  40384. if (columns.getUnchecked(i)->isVisible())
  40385. {
  40386. width = columns.getUnchecked(i)->width;
  40387. if (n++ == index)
  40388. break;
  40389. }
  40390. else
  40391. {
  40392. width = 0;
  40393. }
  40394. }
  40395. return Rectangle<int> (x, 0, width, getHeight());
  40396. }
  40397. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40398. {
  40399. if (xToFind >= 0)
  40400. {
  40401. int x = 0;
  40402. for (int i = 0; i < columns.size(); ++i)
  40403. {
  40404. const ColumnInfo* const ci = columns.getUnchecked(i);
  40405. if (ci->isVisible())
  40406. {
  40407. x += ci->width;
  40408. if (xToFind < x)
  40409. return ci->id;
  40410. }
  40411. }
  40412. }
  40413. return 0;
  40414. }
  40415. int TableHeaderComponent::getTotalWidth() const
  40416. {
  40417. int w = 0;
  40418. for (int i = columns.size(); --i >= 0;)
  40419. if (columns.getUnchecked(i)->isVisible())
  40420. w += columns.getUnchecked(i)->width;
  40421. return w;
  40422. }
  40423. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40424. {
  40425. stretchToFit = shouldStretchToFit;
  40426. lastDeliberateWidth = getTotalWidth();
  40427. resized();
  40428. }
  40429. bool TableHeaderComponent::isStretchToFitActive() const
  40430. {
  40431. return stretchToFit;
  40432. }
  40433. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40434. {
  40435. if (stretchToFit && getWidth() > 0
  40436. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40437. {
  40438. lastDeliberateWidth = targetTotalWidth;
  40439. resizeColumnsToFit (0, targetTotalWidth);
  40440. }
  40441. }
  40442. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40443. {
  40444. targetTotalWidth = jmax (targetTotalWidth, 0);
  40445. StretchableObjectResizer sor;
  40446. int i;
  40447. for (i = firstColumnIndex; i < columns.size(); ++i)
  40448. {
  40449. ColumnInfo* const ci = columns.getUnchecked(i);
  40450. if (ci->isVisible())
  40451. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40452. }
  40453. sor.resizeToFit (targetTotalWidth);
  40454. int visIndex = 0;
  40455. for (i = firstColumnIndex; i < columns.size(); ++i)
  40456. {
  40457. ColumnInfo* const ci = columns.getUnchecked(i);
  40458. if (ci->isVisible())
  40459. {
  40460. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40461. (int) std::floor (sor.getItemSize (visIndex++)));
  40462. if (newWidth != ci->width)
  40463. {
  40464. ci->width = newWidth;
  40465. repaint();
  40466. columnsResized = true;
  40467. triggerAsyncUpdate();
  40468. }
  40469. }
  40470. }
  40471. }
  40472. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40473. {
  40474. ColumnInfo* const ci = getInfoForId (columnId);
  40475. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40476. {
  40477. if (shouldBeVisible)
  40478. ci->propertyFlags |= visible;
  40479. else
  40480. ci->propertyFlags &= ~visible;
  40481. sendColumnsChanged();
  40482. resized();
  40483. }
  40484. }
  40485. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40486. {
  40487. const ColumnInfo* const ci = getInfoForId (columnId);
  40488. return ci != 0 && ci->isVisible();
  40489. }
  40490. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40491. {
  40492. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40493. {
  40494. for (int i = columns.size(); --i >= 0;)
  40495. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40496. ColumnInfo* const ci = getInfoForId (columnId);
  40497. if (ci != 0)
  40498. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40499. reSortTable();
  40500. }
  40501. }
  40502. int TableHeaderComponent::getSortColumnId() const
  40503. {
  40504. for (int i = columns.size(); --i >= 0;)
  40505. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40506. return columns.getUnchecked(i)->id;
  40507. return 0;
  40508. }
  40509. bool TableHeaderComponent::isSortedForwards() const
  40510. {
  40511. for (int i = columns.size(); --i >= 0;)
  40512. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40513. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40514. return true;
  40515. }
  40516. void TableHeaderComponent::reSortTable()
  40517. {
  40518. sortChanged = true;
  40519. repaint();
  40520. triggerAsyncUpdate();
  40521. }
  40522. const String TableHeaderComponent::toString() const
  40523. {
  40524. String s;
  40525. XmlElement doc ("TABLELAYOUT");
  40526. doc.setAttribute ("sortedCol", getSortColumnId());
  40527. doc.setAttribute ("sortForwards", isSortedForwards());
  40528. for (int i = 0; i < columns.size(); ++i)
  40529. {
  40530. const ColumnInfo* const ci = columns.getUnchecked (i);
  40531. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40532. e->setAttribute ("id", ci->id);
  40533. e->setAttribute ("visible", ci->isVisible());
  40534. e->setAttribute ("width", ci->width);
  40535. }
  40536. return doc.createDocument (String::empty, true, false);
  40537. }
  40538. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40539. {
  40540. XmlDocument doc (storedVersion);
  40541. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40542. int index = 0;
  40543. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40544. {
  40545. forEachXmlChildElement (*storedXml, col)
  40546. {
  40547. const int tabId = col->getIntAttribute ("id");
  40548. ColumnInfo* const ci = getInfoForId (tabId);
  40549. if (ci != 0)
  40550. {
  40551. columns.move (columns.indexOf (ci), index);
  40552. ci->width = col->getIntAttribute ("width");
  40553. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40554. }
  40555. ++index;
  40556. }
  40557. columnsResized = true;
  40558. sendColumnsChanged();
  40559. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40560. storedXml->getBoolAttribute ("sortForwards", true));
  40561. }
  40562. }
  40563. void TableHeaderComponent::addListener (Listener* const newListener)
  40564. {
  40565. listeners.addIfNotAlreadyThere (newListener);
  40566. }
  40567. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  40568. {
  40569. listeners.removeValue (listenerToRemove);
  40570. }
  40571. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40572. {
  40573. const ColumnInfo* const ci = getInfoForId (columnId);
  40574. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40575. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40576. }
  40577. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40578. {
  40579. for (int i = 0; i < columns.size(); ++i)
  40580. {
  40581. const ColumnInfo* const ci = columns.getUnchecked(i);
  40582. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40583. menu.addItem (ci->id, ci->name,
  40584. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40585. isColumnVisible (ci->id));
  40586. }
  40587. }
  40588. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40589. {
  40590. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40591. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40592. }
  40593. void TableHeaderComponent::paint (Graphics& g)
  40594. {
  40595. LookAndFeel& lf = getLookAndFeel();
  40596. lf.drawTableHeaderBackground (g, *this);
  40597. const Rectangle<int> clip (g.getClipBounds());
  40598. int x = 0;
  40599. for (int i = 0; i < columns.size(); ++i)
  40600. {
  40601. const ColumnInfo* const ci = columns.getUnchecked(i);
  40602. if (ci->isVisible())
  40603. {
  40604. if (x + ci->width > clip.getX()
  40605. && (ci->id != columnIdBeingDragged
  40606. || dragOverlayComp == 0
  40607. || ! dragOverlayComp->isVisible()))
  40608. {
  40609. g.saveState();
  40610. g.setOrigin (x, 0);
  40611. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40612. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40613. ci->id == columnIdUnderMouse,
  40614. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40615. ci->propertyFlags);
  40616. g.restoreState();
  40617. }
  40618. x += ci->width;
  40619. if (x >= clip.getRight())
  40620. break;
  40621. }
  40622. }
  40623. }
  40624. void TableHeaderComponent::resized()
  40625. {
  40626. }
  40627. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40628. {
  40629. updateColumnUnderMouse (e.x, e.y);
  40630. }
  40631. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40632. {
  40633. updateColumnUnderMouse (e.x, e.y);
  40634. }
  40635. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40636. {
  40637. updateColumnUnderMouse (e.x, e.y);
  40638. }
  40639. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40640. {
  40641. repaint();
  40642. columnIdBeingResized = 0;
  40643. columnIdBeingDragged = 0;
  40644. if (columnIdUnderMouse != 0)
  40645. {
  40646. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40647. if (e.mods.isPopupMenu())
  40648. columnClicked (columnIdUnderMouse, e.mods);
  40649. }
  40650. if (menuActive && e.mods.isPopupMenu())
  40651. showColumnChooserMenu (columnIdUnderMouse);
  40652. }
  40653. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40654. {
  40655. if (columnIdBeingResized == 0
  40656. && columnIdBeingDragged == 0
  40657. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40658. {
  40659. dragOverlayComp = 0;
  40660. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40661. if (columnIdBeingResized != 0)
  40662. {
  40663. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40664. initialColumnWidth = ci->width;
  40665. }
  40666. else
  40667. {
  40668. beginDrag (e);
  40669. }
  40670. }
  40671. if (columnIdBeingResized != 0)
  40672. {
  40673. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40674. if (ci != 0)
  40675. {
  40676. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40677. initialColumnWidth + e.getDistanceFromDragStartX());
  40678. if (stretchToFit)
  40679. {
  40680. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40681. int minWidthOnRight = 0;
  40682. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40683. if (columns.getUnchecked (i)->isVisible())
  40684. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40685. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40686. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40687. }
  40688. setColumnWidth (columnIdBeingResized, w);
  40689. }
  40690. }
  40691. else if (columnIdBeingDragged != 0)
  40692. {
  40693. if (e.y >= -50 && e.y < getHeight() + 50)
  40694. {
  40695. if (dragOverlayComp != 0)
  40696. {
  40697. dragOverlayComp->setVisible (true);
  40698. dragOverlayComp->setBounds (jlimit (0,
  40699. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40700. e.x - draggingColumnOffset),
  40701. 0,
  40702. dragOverlayComp->getWidth(),
  40703. getHeight());
  40704. for (int i = columns.size(); --i >= 0;)
  40705. {
  40706. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40707. int newIndex = currentIndex;
  40708. if (newIndex > 0)
  40709. {
  40710. // if the previous column isn't draggable, we can't move our column
  40711. // past it, because that'd change the undraggable column's position..
  40712. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40713. if ((previous->propertyFlags & draggable) != 0)
  40714. {
  40715. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40716. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40717. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40718. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40719. {
  40720. --newIndex;
  40721. }
  40722. }
  40723. }
  40724. if (newIndex < columns.size() - 1)
  40725. {
  40726. // if the next column isn't draggable, we can't move our column
  40727. // past it, because that'd change the undraggable column's position..
  40728. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40729. if ((nextCol->propertyFlags & draggable) != 0)
  40730. {
  40731. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40732. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40733. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40734. > abs (dragOverlayComp->getRight() - rightOfNext))
  40735. {
  40736. ++newIndex;
  40737. }
  40738. }
  40739. }
  40740. if (newIndex != currentIndex)
  40741. moveColumn (columnIdBeingDragged, newIndex);
  40742. else
  40743. break;
  40744. }
  40745. }
  40746. }
  40747. else
  40748. {
  40749. endDrag (draggingColumnOriginalIndex);
  40750. }
  40751. }
  40752. }
  40753. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40754. {
  40755. if (columnIdBeingDragged == 0)
  40756. {
  40757. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40758. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40759. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40760. {
  40761. columnIdBeingDragged = 0;
  40762. }
  40763. else
  40764. {
  40765. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40766. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40767. const int temp = columnIdBeingDragged;
  40768. columnIdBeingDragged = 0;
  40769. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40770. columnIdBeingDragged = temp;
  40771. dragOverlayComp->setBounds (columnRect);
  40772. for (int i = listeners.size(); --i >= 0;)
  40773. {
  40774. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40775. i = jmin (i, listeners.size() - 1);
  40776. }
  40777. }
  40778. }
  40779. }
  40780. void TableHeaderComponent::endDrag (const int finalIndex)
  40781. {
  40782. if (columnIdBeingDragged != 0)
  40783. {
  40784. moveColumn (columnIdBeingDragged, finalIndex);
  40785. columnIdBeingDragged = 0;
  40786. repaint();
  40787. for (int i = listeners.size(); --i >= 0;)
  40788. {
  40789. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40790. i = jmin (i, listeners.size() - 1);
  40791. }
  40792. }
  40793. }
  40794. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40795. {
  40796. mouseDrag (e);
  40797. for (int i = columns.size(); --i >= 0;)
  40798. if (columns.getUnchecked (i)->isVisible())
  40799. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40800. columnIdBeingResized = 0;
  40801. repaint();
  40802. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40803. updateColumnUnderMouse (e.x, e.y);
  40804. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40805. columnClicked (columnIdUnderMouse, e.mods);
  40806. dragOverlayComp = 0;
  40807. }
  40808. const MouseCursor TableHeaderComponent::getMouseCursor()
  40809. {
  40810. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40811. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40812. return Component::getMouseCursor();
  40813. }
  40814. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40815. {
  40816. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40817. }
  40818. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40819. {
  40820. for (int i = columns.size(); --i >= 0;)
  40821. if (columns.getUnchecked(i)->id == id)
  40822. return columns.getUnchecked(i);
  40823. return 0;
  40824. }
  40825. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40826. {
  40827. int n = 0;
  40828. for (int i = 0; i < columns.size(); ++i)
  40829. {
  40830. if (columns.getUnchecked(i)->isVisible())
  40831. {
  40832. if (n == visibleIndex)
  40833. return i;
  40834. ++n;
  40835. }
  40836. }
  40837. return -1;
  40838. }
  40839. void TableHeaderComponent::sendColumnsChanged()
  40840. {
  40841. if (stretchToFit && lastDeliberateWidth > 0)
  40842. resizeAllColumnsToFit (lastDeliberateWidth);
  40843. repaint();
  40844. columnsChanged = true;
  40845. triggerAsyncUpdate();
  40846. }
  40847. void TableHeaderComponent::handleAsyncUpdate()
  40848. {
  40849. const bool changed = columnsChanged || sortChanged;
  40850. const bool sized = columnsResized || changed;
  40851. const bool sorted = sortChanged;
  40852. columnsChanged = false;
  40853. columnsResized = false;
  40854. sortChanged = false;
  40855. if (sorted)
  40856. {
  40857. for (int i = listeners.size(); --i >= 0;)
  40858. {
  40859. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40860. i = jmin (i, listeners.size() - 1);
  40861. }
  40862. }
  40863. if (changed)
  40864. {
  40865. for (int i = listeners.size(); --i >= 0;)
  40866. {
  40867. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40868. i = jmin (i, listeners.size() - 1);
  40869. }
  40870. }
  40871. if (sized)
  40872. {
  40873. for (int i = listeners.size(); --i >= 0;)
  40874. {
  40875. listeners.getUnchecked(i)->tableColumnsResized (this);
  40876. i = jmin (i, listeners.size() - 1);
  40877. }
  40878. }
  40879. }
  40880. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40881. {
  40882. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40883. {
  40884. const int draggableDistance = 3;
  40885. int x = 0;
  40886. for (int i = 0; i < columns.size(); ++i)
  40887. {
  40888. const ColumnInfo* const ci = columns.getUnchecked(i);
  40889. if (ci->isVisible())
  40890. {
  40891. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40892. && (ci->propertyFlags & resizable) != 0)
  40893. return ci->id;
  40894. x += ci->width;
  40895. }
  40896. }
  40897. }
  40898. return 0;
  40899. }
  40900. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40901. {
  40902. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40903. ? getColumnIdAtX (x) : 0;
  40904. if (newCol != columnIdUnderMouse)
  40905. {
  40906. columnIdUnderMouse = newCol;
  40907. repaint();
  40908. }
  40909. }
  40910. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40911. {
  40912. PopupMenu m;
  40913. addMenuItems (m, columnIdClicked);
  40914. if (m.getNumItems() > 0)
  40915. {
  40916. m.setLookAndFeel (&getLookAndFeel());
  40917. const int result = m.show();
  40918. if (result != 0)
  40919. reactToMenuItem (result, columnIdClicked);
  40920. }
  40921. }
  40922. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40923. {
  40924. }
  40925. END_JUCE_NAMESPACE
  40926. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40927. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40928. BEGIN_JUCE_NAMESPACE
  40929. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40930. class TableListRowComp : public Component,
  40931. public TooltipClient
  40932. {
  40933. public:
  40934. TableListRowComp (TableListBox& owner_)
  40935. : owner (owner_),
  40936. row (-1),
  40937. isSelected (false)
  40938. {
  40939. }
  40940. ~TableListRowComp()
  40941. {
  40942. deleteAllChildren();
  40943. }
  40944. void paint (Graphics& g)
  40945. {
  40946. TableListBoxModel* const model = owner.getModel();
  40947. if (model != 0)
  40948. {
  40949. const TableHeaderComponent* const header = owner.getHeader();
  40950. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40951. const int numColumns = header->getNumColumns (true);
  40952. for (int i = 0; i < numColumns; ++i)
  40953. {
  40954. if (! columnsWithComponents [i])
  40955. {
  40956. const int columnId = header->getColumnIdOfIndex (i, true);
  40957. Rectangle<int> columnRect (header->getColumnPosition (i));
  40958. columnRect.setSize (columnRect.getWidth(), getHeight());
  40959. g.saveState();
  40960. g.reduceClipRegion (columnRect);
  40961. g.setOrigin (columnRect.getX(), 0);
  40962. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40963. g.restoreState();
  40964. }
  40965. }
  40966. }
  40967. }
  40968. void update (const int newRow, const bool isNowSelected)
  40969. {
  40970. if (newRow != row || isNowSelected != isSelected)
  40971. {
  40972. row = newRow;
  40973. isSelected = isNowSelected;
  40974. repaint();
  40975. }
  40976. if (row < owner.getNumRows())
  40977. {
  40978. jassert (row >= 0);
  40979. const Identifier tagPropertyName ("_tableLastUseNum");
  40980. const int newTag = Random::getSystemRandom().nextInt();
  40981. const TableHeaderComponent* const header = owner.getHeader();
  40982. const int numColumns = header->getNumColumns (true);
  40983. int i;
  40984. columnsWithComponents.clear();
  40985. if (owner.getModel() != 0)
  40986. {
  40987. for (i = 0; i < numColumns; ++i)
  40988. {
  40989. const int columnId = header->getColumnIdOfIndex (i, true);
  40990. Component* const newComp
  40991. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40992. findChildComponentForColumn (columnId));
  40993. if (newComp != 0)
  40994. {
  40995. addAndMakeVisible (newComp);
  40996. newComp->getProperties().set (tagPropertyName, newTag);
  40997. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40998. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40999. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41000. columnsWithComponents.setBit (i);
  41001. }
  41002. }
  41003. }
  41004. for (i = getNumChildComponents(); --i >= 0;)
  41005. {
  41006. Component* const c = getChildComponent (i);
  41007. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41008. delete c;
  41009. }
  41010. }
  41011. else
  41012. {
  41013. columnsWithComponents.clear();
  41014. deleteAllChildren();
  41015. }
  41016. }
  41017. void resized()
  41018. {
  41019. for (int i = getNumChildComponents(); --i >= 0;)
  41020. {
  41021. Component* const c = getChildComponent (i);
  41022. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41023. if (columnId != 0)
  41024. {
  41025. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41026. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41027. }
  41028. }
  41029. }
  41030. void mouseDown (const MouseEvent& e)
  41031. {
  41032. isDragging = false;
  41033. selectRowOnMouseUp = false;
  41034. if (isEnabled())
  41035. {
  41036. if (! isSelected)
  41037. {
  41038. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41039. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41040. if (columnId != 0 && owner.getModel() != 0)
  41041. owner.getModel()->cellClicked (row, columnId, e);
  41042. }
  41043. else
  41044. {
  41045. selectRowOnMouseUp = true;
  41046. }
  41047. }
  41048. }
  41049. void mouseDrag (const MouseEvent& e)
  41050. {
  41051. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41052. {
  41053. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41054. if (selectedRows.size() > 0)
  41055. {
  41056. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41057. if (dragDescription.isNotEmpty())
  41058. {
  41059. isDragging = true;
  41060. owner.startDragAndDrop (e, dragDescription);
  41061. }
  41062. }
  41063. }
  41064. }
  41065. void mouseUp (const MouseEvent& e)
  41066. {
  41067. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41068. {
  41069. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41070. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41071. if (columnId != 0 && owner.getModel() != 0)
  41072. owner.getModel()->cellClicked (row, columnId, e);
  41073. }
  41074. }
  41075. void mouseDoubleClick (const MouseEvent& e)
  41076. {
  41077. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41078. if (columnId != 0 && owner.getModel() != 0)
  41079. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41080. }
  41081. const String getTooltip()
  41082. {
  41083. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41084. if (columnId != 0 && owner.getModel() != 0)
  41085. return owner.getModel()->getCellTooltip (row, columnId);
  41086. return String::empty;
  41087. }
  41088. Component* findChildComponentForColumn (const int columnId) const
  41089. {
  41090. for (int i = getNumChildComponents(); --i >= 0;)
  41091. {
  41092. Component* const c = getChildComponent (i);
  41093. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41094. return c;
  41095. }
  41096. return 0;
  41097. }
  41098. juce_UseDebuggingNewOperator
  41099. private:
  41100. TableListBox& owner;
  41101. int row;
  41102. bool isSelected, isDragging, selectRowOnMouseUp;
  41103. BigInteger columnsWithComponents;
  41104. TableListRowComp (const TableListRowComp&);
  41105. TableListRowComp& operator= (const TableListRowComp&);
  41106. };
  41107. class TableListBoxHeader : public TableHeaderComponent
  41108. {
  41109. public:
  41110. TableListBoxHeader (TableListBox& owner_)
  41111. : owner (owner_)
  41112. {
  41113. }
  41114. ~TableListBoxHeader()
  41115. {
  41116. }
  41117. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41118. {
  41119. if (owner.isAutoSizeMenuOptionShown())
  41120. {
  41121. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41122. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41123. menu.addSeparator();
  41124. }
  41125. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41126. }
  41127. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41128. {
  41129. if (menuReturnId == 0xf836743)
  41130. {
  41131. owner.autoSizeColumn (columnIdClicked);
  41132. }
  41133. else if (menuReturnId == 0xf836744)
  41134. {
  41135. owner.autoSizeAllColumns();
  41136. }
  41137. else
  41138. {
  41139. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41140. }
  41141. }
  41142. juce_UseDebuggingNewOperator
  41143. private:
  41144. TableListBox& owner;
  41145. TableListBoxHeader (const TableListBoxHeader&);
  41146. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41147. };
  41148. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41149. : ListBox (name, 0),
  41150. model (model_),
  41151. autoSizeOptionsShown (true)
  41152. {
  41153. ListBox::model = this;
  41154. header = new TableListBoxHeader (*this);
  41155. header->setSize (100, 28);
  41156. header->addListener (this);
  41157. setHeaderComponent (header);
  41158. }
  41159. TableListBox::~TableListBox()
  41160. {
  41161. header = 0;
  41162. }
  41163. void TableListBox::setModel (TableListBoxModel* const newModel)
  41164. {
  41165. if (model != newModel)
  41166. {
  41167. model = newModel;
  41168. updateContent();
  41169. }
  41170. }
  41171. int TableListBox::getHeaderHeight() const
  41172. {
  41173. return header->getHeight();
  41174. }
  41175. void TableListBox::setHeaderHeight (const int newHeight)
  41176. {
  41177. header->setSize (header->getWidth(), newHeight);
  41178. resized();
  41179. }
  41180. void TableListBox::autoSizeColumn (const int columnId)
  41181. {
  41182. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41183. if (width > 0)
  41184. header->setColumnWidth (columnId, width);
  41185. }
  41186. void TableListBox::autoSizeAllColumns()
  41187. {
  41188. for (int i = 0; i < header->getNumColumns (true); ++i)
  41189. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41190. }
  41191. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41192. {
  41193. autoSizeOptionsShown = shouldBeShown;
  41194. }
  41195. bool TableListBox::isAutoSizeMenuOptionShown() const
  41196. {
  41197. return autoSizeOptionsShown;
  41198. }
  41199. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41200. const int rowNumber,
  41201. const bool relativeToComponentTopLeft) const
  41202. {
  41203. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41204. if (relativeToComponentTopLeft)
  41205. headerCell.translate (header->getX(), 0);
  41206. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41207. return Rectangle<int> (headerCell.getX(), row.getY(),
  41208. headerCell.getWidth(), row.getHeight());
  41209. }
  41210. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41211. {
  41212. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41213. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41214. }
  41215. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41216. {
  41217. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41218. if (scrollbar != 0)
  41219. {
  41220. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41221. double x = scrollbar->getCurrentRangeStart();
  41222. const double w = scrollbar->getCurrentRangeSize();
  41223. if (pos.getX() < x)
  41224. x = pos.getX();
  41225. else if (pos.getRight() > x + w)
  41226. x += jmax (0.0, pos.getRight() - (x + w));
  41227. scrollbar->setCurrentRangeStart (x);
  41228. }
  41229. }
  41230. int TableListBox::getNumRows()
  41231. {
  41232. return model != 0 ? model->getNumRows() : 0;
  41233. }
  41234. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41235. {
  41236. }
  41237. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41238. {
  41239. if (existingComponentToUpdate == 0)
  41240. existingComponentToUpdate = new TableListRowComp (*this);
  41241. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41242. return existingComponentToUpdate;
  41243. }
  41244. void TableListBox::selectedRowsChanged (int row)
  41245. {
  41246. if (model != 0)
  41247. model->selectedRowsChanged (row);
  41248. }
  41249. void TableListBox::deleteKeyPressed (int row)
  41250. {
  41251. if (model != 0)
  41252. model->deleteKeyPressed (row);
  41253. }
  41254. void TableListBox::returnKeyPressed (int row)
  41255. {
  41256. if (model != 0)
  41257. model->returnKeyPressed (row);
  41258. }
  41259. void TableListBox::backgroundClicked()
  41260. {
  41261. if (model != 0)
  41262. model->backgroundClicked();
  41263. }
  41264. void TableListBox::listWasScrolled()
  41265. {
  41266. if (model != 0)
  41267. model->listWasScrolled();
  41268. }
  41269. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41270. {
  41271. setMinimumContentWidth (header->getTotalWidth());
  41272. repaint();
  41273. updateColumnComponents();
  41274. }
  41275. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41276. {
  41277. setMinimumContentWidth (header->getTotalWidth());
  41278. repaint();
  41279. updateColumnComponents();
  41280. }
  41281. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41282. {
  41283. if (model != 0)
  41284. model->sortOrderChanged (header->getSortColumnId(),
  41285. header->isSortedForwards());
  41286. }
  41287. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41288. {
  41289. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41290. repaint();
  41291. }
  41292. void TableListBox::resized()
  41293. {
  41294. ListBox::resized();
  41295. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41296. setMinimumContentWidth (header->getTotalWidth());
  41297. }
  41298. void TableListBox::updateColumnComponents() const
  41299. {
  41300. const int firstRow = getRowContainingPosition (0, 0);
  41301. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41302. {
  41303. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41304. if (rowComp != 0)
  41305. rowComp->resized();
  41306. }
  41307. }
  41308. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41309. {
  41310. }
  41311. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41312. {
  41313. }
  41314. void TableListBoxModel::backgroundClicked()
  41315. {
  41316. }
  41317. void TableListBoxModel::sortOrderChanged (int, const bool)
  41318. {
  41319. }
  41320. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41321. {
  41322. return 0;
  41323. }
  41324. void TableListBoxModel::selectedRowsChanged (int)
  41325. {
  41326. }
  41327. void TableListBoxModel::deleteKeyPressed (int)
  41328. {
  41329. }
  41330. void TableListBoxModel::returnKeyPressed (int)
  41331. {
  41332. }
  41333. void TableListBoxModel::listWasScrolled()
  41334. {
  41335. }
  41336. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41337. {
  41338. return String::empty;
  41339. }
  41340. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41341. {
  41342. return String::empty;
  41343. }
  41344. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41345. {
  41346. (void) existingComponentToUpdate;
  41347. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41348. return 0;
  41349. }
  41350. END_JUCE_NAMESPACE
  41351. /*** End of inlined file: juce_TableListBox.cpp ***/
  41352. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41353. BEGIN_JUCE_NAMESPACE
  41354. // a word or space that can't be broken down any further
  41355. struct TextAtom
  41356. {
  41357. String atomText;
  41358. float width;
  41359. uint16 numChars;
  41360. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41361. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41362. const String getText (const juce_wchar passwordCharacter) const
  41363. {
  41364. if (passwordCharacter == 0)
  41365. return atomText;
  41366. else
  41367. return String::repeatedString (String::charToString (passwordCharacter),
  41368. atomText.length());
  41369. }
  41370. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41371. {
  41372. if (passwordCharacter == 0)
  41373. return atomText.substring (0, numChars);
  41374. else if (isNewLine())
  41375. return String::empty;
  41376. else
  41377. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41378. }
  41379. };
  41380. // a run of text with a single font and colour
  41381. class TextEditor::UniformTextSection
  41382. {
  41383. public:
  41384. UniformTextSection (const String& text,
  41385. const Font& font_,
  41386. const Colour& colour_,
  41387. const juce_wchar passwordCharacter)
  41388. : font (font_),
  41389. colour (colour_)
  41390. {
  41391. initialiseAtoms (text, passwordCharacter);
  41392. }
  41393. UniformTextSection (const UniformTextSection& other)
  41394. : font (other.font),
  41395. colour (other.colour)
  41396. {
  41397. atoms.ensureStorageAllocated (other.atoms.size());
  41398. for (int i = 0; i < other.atoms.size(); ++i)
  41399. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41400. }
  41401. ~UniformTextSection()
  41402. {
  41403. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41404. }
  41405. void clear()
  41406. {
  41407. for (int i = atoms.size(); --i >= 0;)
  41408. delete getAtom(i);
  41409. atoms.clear();
  41410. }
  41411. int getNumAtoms() const
  41412. {
  41413. return atoms.size();
  41414. }
  41415. TextAtom* getAtom (const int index) const throw()
  41416. {
  41417. return atoms.getUnchecked (index);
  41418. }
  41419. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41420. {
  41421. if (other.atoms.size() > 0)
  41422. {
  41423. TextAtom* const lastAtom = atoms.getLast();
  41424. int i = 0;
  41425. if (lastAtom != 0)
  41426. {
  41427. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41428. {
  41429. TextAtom* const first = other.getAtom(0);
  41430. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41431. {
  41432. lastAtom->atomText += first->atomText;
  41433. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41434. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41435. delete first;
  41436. ++i;
  41437. }
  41438. }
  41439. }
  41440. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41441. while (i < other.atoms.size())
  41442. {
  41443. atoms.add (other.getAtom(i));
  41444. ++i;
  41445. }
  41446. }
  41447. }
  41448. UniformTextSection* split (const int indexToBreakAt,
  41449. const juce_wchar passwordCharacter)
  41450. {
  41451. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41452. font, colour,
  41453. passwordCharacter);
  41454. int index = 0;
  41455. for (int i = 0; i < atoms.size(); ++i)
  41456. {
  41457. TextAtom* const atom = getAtom(i);
  41458. const int nextIndex = index + atom->numChars;
  41459. if (index == indexToBreakAt)
  41460. {
  41461. int j;
  41462. for (j = i; j < atoms.size(); ++j)
  41463. section2->atoms.add (getAtom (j));
  41464. for (j = atoms.size(); --j >= i;)
  41465. atoms.remove (j);
  41466. break;
  41467. }
  41468. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41469. {
  41470. TextAtom* const secondAtom = new TextAtom();
  41471. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41472. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41473. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41474. section2->atoms.add (secondAtom);
  41475. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41476. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41477. atom->numChars = (uint16) (indexToBreakAt - index);
  41478. int j;
  41479. for (j = i + 1; j < atoms.size(); ++j)
  41480. section2->atoms.add (getAtom (j));
  41481. for (j = atoms.size(); --j > i;)
  41482. atoms.remove (j);
  41483. break;
  41484. }
  41485. index = nextIndex;
  41486. }
  41487. return section2;
  41488. }
  41489. void appendAllText (String::Concatenator& concatenator) const
  41490. {
  41491. for (int i = 0; i < atoms.size(); ++i)
  41492. concatenator.append (getAtom(i)->atomText);
  41493. }
  41494. void appendSubstring (String::Concatenator& concatenator,
  41495. const Range<int>& range) const
  41496. {
  41497. int index = 0;
  41498. for (int i = 0; i < atoms.size(); ++i)
  41499. {
  41500. const TextAtom* const atom = getAtom (i);
  41501. const int nextIndex = index + atom->numChars;
  41502. if (range.getStart() < nextIndex)
  41503. {
  41504. if (range.getEnd() <= index)
  41505. break;
  41506. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41507. if (! r.isEmpty())
  41508. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41509. }
  41510. index = nextIndex;
  41511. }
  41512. }
  41513. int getTotalLength() const
  41514. {
  41515. int total = 0;
  41516. for (int i = atoms.size(); --i >= 0;)
  41517. total += getAtom(i)->numChars;
  41518. return total;
  41519. }
  41520. void setFont (const Font& newFont,
  41521. const juce_wchar passwordCharacter)
  41522. {
  41523. if (font != newFont)
  41524. {
  41525. font = newFont;
  41526. for (int i = atoms.size(); --i >= 0;)
  41527. {
  41528. TextAtom* const atom = atoms.getUnchecked(i);
  41529. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41530. }
  41531. }
  41532. }
  41533. juce_UseDebuggingNewOperator
  41534. Font font;
  41535. Colour colour;
  41536. private:
  41537. Array <TextAtom*> atoms;
  41538. void initialiseAtoms (const String& textToParse,
  41539. const juce_wchar passwordCharacter)
  41540. {
  41541. int i = 0;
  41542. const int len = textToParse.length();
  41543. const juce_wchar* const text = textToParse;
  41544. while (i < len)
  41545. {
  41546. int start = i;
  41547. // create a whitespace atom unless it starts with non-ws
  41548. if (CharacterFunctions::isWhitespace (text[i])
  41549. && text[i] != '\r'
  41550. && text[i] != '\n')
  41551. {
  41552. while (i < len
  41553. && CharacterFunctions::isWhitespace (text[i])
  41554. && text[i] != '\r'
  41555. && text[i] != '\n')
  41556. {
  41557. ++i;
  41558. }
  41559. }
  41560. else
  41561. {
  41562. if (text[i] == '\r')
  41563. {
  41564. ++i;
  41565. if ((i < len) && (text[i] == '\n'))
  41566. {
  41567. ++start;
  41568. ++i;
  41569. }
  41570. }
  41571. else if (text[i] == '\n')
  41572. {
  41573. ++i;
  41574. }
  41575. else
  41576. {
  41577. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41578. ++i;
  41579. }
  41580. }
  41581. TextAtom* const atom = new TextAtom();
  41582. atom->atomText = String (text + start, i - start);
  41583. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41584. atom->numChars = (uint16) (i - start);
  41585. atoms.add (atom);
  41586. }
  41587. }
  41588. UniformTextSection& operator= (const UniformTextSection& other);
  41589. };
  41590. class TextEditor::Iterator
  41591. {
  41592. public:
  41593. Iterator (const Array <UniformTextSection*>& sections_,
  41594. const float wordWrapWidth_,
  41595. const juce_wchar passwordCharacter_)
  41596. : indexInText (0),
  41597. lineY (0),
  41598. lineHeight (0),
  41599. maxDescent (0),
  41600. atomX (0),
  41601. atomRight (0),
  41602. atom (0),
  41603. currentSection (0),
  41604. sections (sections_),
  41605. sectionIndex (0),
  41606. atomIndex (0),
  41607. wordWrapWidth (wordWrapWidth_),
  41608. passwordCharacter (passwordCharacter_)
  41609. {
  41610. jassert (wordWrapWidth_ > 0);
  41611. if (sections.size() > 0)
  41612. {
  41613. currentSection = sections.getUnchecked (sectionIndex);
  41614. if (currentSection != 0)
  41615. beginNewLine();
  41616. }
  41617. }
  41618. Iterator (const Iterator& other)
  41619. : indexInText (other.indexInText),
  41620. lineY (other.lineY),
  41621. lineHeight (other.lineHeight),
  41622. maxDescent (other.maxDescent),
  41623. atomX (other.atomX),
  41624. atomRight (other.atomRight),
  41625. atom (other.atom),
  41626. currentSection (other.currentSection),
  41627. sections (other.sections),
  41628. sectionIndex (other.sectionIndex),
  41629. atomIndex (other.atomIndex),
  41630. wordWrapWidth (other.wordWrapWidth),
  41631. passwordCharacter (other.passwordCharacter),
  41632. tempAtom (other.tempAtom)
  41633. {
  41634. }
  41635. ~Iterator()
  41636. {
  41637. }
  41638. bool next()
  41639. {
  41640. if (atom == &tempAtom)
  41641. {
  41642. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41643. if (numRemaining > 0)
  41644. {
  41645. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41646. atomX = 0;
  41647. if (tempAtom.numChars > 0)
  41648. lineY += lineHeight;
  41649. indexInText += tempAtom.numChars;
  41650. GlyphArrangement g;
  41651. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41652. int split;
  41653. for (split = 0; split < g.getNumGlyphs(); ++split)
  41654. if (shouldWrap (g.getGlyph (split).getRight()))
  41655. break;
  41656. if (split > 0 && split <= numRemaining)
  41657. {
  41658. tempAtom.numChars = (uint16) split;
  41659. tempAtom.width = g.getGlyph (split - 1).getRight();
  41660. atomRight = atomX + tempAtom.width;
  41661. return true;
  41662. }
  41663. }
  41664. }
  41665. bool forceNewLine = false;
  41666. if (sectionIndex >= sections.size())
  41667. {
  41668. moveToEndOfLastAtom();
  41669. return false;
  41670. }
  41671. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41672. {
  41673. if (atomIndex >= currentSection->getNumAtoms())
  41674. {
  41675. if (++sectionIndex >= sections.size())
  41676. {
  41677. moveToEndOfLastAtom();
  41678. return false;
  41679. }
  41680. atomIndex = 0;
  41681. currentSection = sections.getUnchecked (sectionIndex);
  41682. }
  41683. else
  41684. {
  41685. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41686. if (! lastAtom->isWhitespace())
  41687. {
  41688. // handle the case where the last atom in a section is actually part of the same
  41689. // word as the first atom of the next section...
  41690. float right = atomRight + lastAtom->width;
  41691. float lineHeight2 = lineHeight;
  41692. float maxDescent2 = maxDescent;
  41693. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41694. {
  41695. const UniformTextSection* const s = sections.getUnchecked (section);
  41696. if (s->getNumAtoms() == 0)
  41697. break;
  41698. const TextAtom* const nextAtom = s->getAtom (0);
  41699. if (nextAtom->isWhitespace())
  41700. break;
  41701. right += nextAtom->width;
  41702. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41703. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41704. if (shouldWrap (right))
  41705. {
  41706. lineHeight = lineHeight2;
  41707. maxDescent = maxDescent2;
  41708. forceNewLine = true;
  41709. break;
  41710. }
  41711. if (s->getNumAtoms() > 1)
  41712. break;
  41713. }
  41714. }
  41715. }
  41716. }
  41717. if (atom != 0)
  41718. {
  41719. atomX = atomRight;
  41720. indexInText += atom->numChars;
  41721. if (atom->isNewLine())
  41722. beginNewLine();
  41723. }
  41724. atom = currentSection->getAtom (atomIndex);
  41725. atomRight = atomX + atom->width;
  41726. ++atomIndex;
  41727. if (shouldWrap (atomRight) || forceNewLine)
  41728. {
  41729. if (atom->isWhitespace())
  41730. {
  41731. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41732. atomRight = jmin (atomRight, wordWrapWidth);
  41733. }
  41734. else
  41735. {
  41736. atomRight = atom->width;
  41737. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41738. {
  41739. tempAtom = *atom;
  41740. tempAtom.width = 0;
  41741. tempAtom.numChars = 0;
  41742. atom = &tempAtom;
  41743. if (atomX > 0)
  41744. beginNewLine();
  41745. return next();
  41746. }
  41747. beginNewLine();
  41748. return true;
  41749. }
  41750. }
  41751. return true;
  41752. }
  41753. void beginNewLine()
  41754. {
  41755. atomX = 0;
  41756. lineY += lineHeight;
  41757. int tempSectionIndex = sectionIndex;
  41758. int tempAtomIndex = atomIndex;
  41759. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41760. lineHeight = section->font.getHeight();
  41761. maxDescent = section->font.getDescent();
  41762. float x = (atom != 0) ? atom->width : 0;
  41763. while (! shouldWrap (x))
  41764. {
  41765. if (tempSectionIndex >= sections.size())
  41766. break;
  41767. bool checkSize = false;
  41768. if (tempAtomIndex >= section->getNumAtoms())
  41769. {
  41770. if (++tempSectionIndex >= sections.size())
  41771. break;
  41772. tempAtomIndex = 0;
  41773. section = sections.getUnchecked (tempSectionIndex);
  41774. checkSize = true;
  41775. }
  41776. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41777. if (nextAtom == 0)
  41778. break;
  41779. x += nextAtom->width;
  41780. if (shouldWrap (x) || nextAtom->isNewLine())
  41781. break;
  41782. if (checkSize)
  41783. {
  41784. lineHeight = jmax (lineHeight, section->font.getHeight());
  41785. maxDescent = jmax (maxDescent, section->font.getDescent());
  41786. }
  41787. ++tempAtomIndex;
  41788. }
  41789. }
  41790. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41791. {
  41792. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41793. {
  41794. if (lastSection != currentSection)
  41795. {
  41796. lastSection = currentSection;
  41797. g.setColour (currentSection->colour);
  41798. g.setFont (currentSection->font);
  41799. }
  41800. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41801. GlyphArrangement ga;
  41802. ga.addLineOfText (currentSection->font,
  41803. atom->getTrimmedText (passwordCharacter),
  41804. atomX,
  41805. (float) roundToInt (lineY + lineHeight - maxDescent));
  41806. ga.draw (g);
  41807. }
  41808. }
  41809. void drawSelection (Graphics& g,
  41810. const Range<int>& selection) const
  41811. {
  41812. const int startX = roundToInt (indexToX (selection.getStart()));
  41813. const int endX = roundToInt (indexToX (selection.getEnd()));
  41814. const int y = roundToInt (lineY);
  41815. const int nextY = roundToInt (lineY + lineHeight);
  41816. g.fillRect (startX, y, endX - startX, nextY - y);
  41817. }
  41818. void drawSelectedText (Graphics& g,
  41819. const Range<int>& selection,
  41820. const Colour& selectedTextColour) const
  41821. {
  41822. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41823. {
  41824. GlyphArrangement ga;
  41825. ga.addLineOfText (currentSection->font,
  41826. atom->getTrimmedText (passwordCharacter),
  41827. atomX,
  41828. (float) roundToInt (lineY + lineHeight - maxDescent));
  41829. if (selection.getEnd() < indexInText + atom->numChars)
  41830. {
  41831. GlyphArrangement ga2 (ga);
  41832. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41833. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41834. g.setColour (currentSection->colour);
  41835. ga2.draw (g);
  41836. }
  41837. if (selection.getStart() > indexInText)
  41838. {
  41839. GlyphArrangement ga2 (ga);
  41840. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41841. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41842. g.setColour (currentSection->colour);
  41843. ga2.draw (g);
  41844. }
  41845. g.setColour (selectedTextColour);
  41846. ga.draw (g);
  41847. }
  41848. }
  41849. float indexToX (const int indexToFind) const
  41850. {
  41851. if (indexToFind <= indexInText)
  41852. return atomX;
  41853. if (indexToFind >= indexInText + atom->numChars)
  41854. return atomRight;
  41855. GlyphArrangement g;
  41856. g.addLineOfText (currentSection->font,
  41857. atom->getText (passwordCharacter),
  41858. atomX, 0.0f);
  41859. if (indexToFind - indexInText >= g.getNumGlyphs())
  41860. return atomRight;
  41861. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41862. }
  41863. int xToIndex (const float xToFind) const
  41864. {
  41865. if (xToFind <= atomX || atom->isNewLine())
  41866. return indexInText;
  41867. if (xToFind >= atomRight)
  41868. return indexInText + atom->numChars;
  41869. GlyphArrangement g;
  41870. g.addLineOfText (currentSection->font,
  41871. atom->getText (passwordCharacter),
  41872. atomX, 0.0f);
  41873. int j;
  41874. for (j = 0; j < g.getNumGlyphs(); ++j)
  41875. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41876. break;
  41877. return indexInText + j;
  41878. }
  41879. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41880. {
  41881. while (next())
  41882. {
  41883. if (indexInText + atom->numChars > index)
  41884. {
  41885. cx = indexToX (index);
  41886. cy = lineY;
  41887. lineHeight_ = lineHeight;
  41888. return true;
  41889. }
  41890. }
  41891. cx = atomX;
  41892. cy = lineY;
  41893. lineHeight_ = lineHeight;
  41894. return false;
  41895. }
  41896. juce_UseDebuggingNewOperator
  41897. int indexInText;
  41898. float lineY, lineHeight, maxDescent;
  41899. float atomX, atomRight;
  41900. const TextAtom* atom;
  41901. const UniformTextSection* currentSection;
  41902. private:
  41903. const Array <UniformTextSection*>& sections;
  41904. int sectionIndex, atomIndex;
  41905. const float wordWrapWidth;
  41906. const juce_wchar passwordCharacter;
  41907. TextAtom tempAtom;
  41908. Iterator& operator= (const Iterator&);
  41909. void moveToEndOfLastAtom()
  41910. {
  41911. if (atom != 0)
  41912. {
  41913. atomX = atomRight;
  41914. if (atom->isNewLine())
  41915. {
  41916. atomX = 0.0f;
  41917. lineY += lineHeight;
  41918. }
  41919. }
  41920. }
  41921. bool shouldWrap (const float x) const
  41922. {
  41923. return (x - 0.0001f) >= wordWrapWidth;
  41924. }
  41925. };
  41926. class TextEditor::InsertAction : public UndoableAction
  41927. {
  41928. TextEditor& owner;
  41929. const String text;
  41930. const int insertIndex, oldCaretPos, newCaretPos;
  41931. const Font font;
  41932. const Colour colour;
  41933. InsertAction (const InsertAction&);
  41934. InsertAction& operator= (const InsertAction&);
  41935. public:
  41936. InsertAction (TextEditor& owner_,
  41937. const String& text_,
  41938. const int insertIndex_,
  41939. const Font& font_,
  41940. const Colour& colour_,
  41941. const int oldCaretPos_,
  41942. const int newCaretPos_)
  41943. : owner (owner_),
  41944. text (text_),
  41945. insertIndex (insertIndex_),
  41946. oldCaretPos (oldCaretPos_),
  41947. newCaretPos (newCaretPos_),
  41948. font (font_),
  41949. colour (colour_)
  41950. {
  41951. }
  41952. ~InsertAction()
  41953. {
  41954. }
  41955. bool perform()
  41956. {
  41957. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41958. return true;
  41959. }
  41960. bool undo()
  41961. {
  41962. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41963. return true;
  41964. }
  41965. int getSizeInUnits()
  41966. {
  41967. return text.length() + 16;
  41968. }
  41969. };
  41970. class TextEditor::RemoveAction : public UndoableAction
  41971. {
  41972. TextEditor& owner;
  41973. const Range<int> range;
  41974. const int oldCaretPos, newCaretPos;
  41975. Array <UniformTextSection*> removedSections;
  41976. RemoveAction (const RemoveAction&);
  41977. RemoveAction& operator= (const RemoveAction&);
  41978. public:
  41979. RemoveAction (TextEditor& owner_,
  41980. const Range<int> range_,
  41981. const int oldCaretPos_,
  41982. const int newCaretPos_,
  41983. const Array <UniformTextSection*>& removedSections_)
  41984. : owner (owner_),
  41985. range (range_),
  41986. oldCaretPos (oldCaretPos_),
  41987. newCaretPos (newCaretPos_),
  41988. removedSections (removedSections_)
  41989. {
  41990. }
  41991. ~RemoveAction()
  41992. {
  41993. for (int i = removedSections.size(); --i >= 0;)
  41994. {
  41995. UniformTextSection* const section = removedSections.getUnchecked (i);
  41996. section->clear();
  41997. delete section;
  41998. }
  41999. }
  42000. bool perform()
  42001. {
  42002. owner.remove (range, 0, newCaretPos);
  42003. return true;
  42004. }
  42005. bool undo()
  42006. {
  42007. owner.reinsert (range.getStart(), removedSections);
  42008. owner.moveCursorTo (oldCaretPos, false);
  42009. return true;
  42010. }
  42011. int getSizeInUnits()
  42012. {
  42013. int n = 0;
  42014. for (int i = removedSections.size(); --i >= 0;)
  42015. n += removedSections.getUnchecked (i)->getTotalLength();
  42016. return n + 16;
  42017. }
  42018. };
  42019. class TextEditor::TextHolderComponent : public Component,
  42020. public Timer,
  42021. public Value::Listener
  42022. {
  42023. public:
  42024. TextHolderComponent (TextEditor& owner_)
  42025. : owner (owner_)
  42026. {
  42027. setWantsKeyboardFocus (false);
  42028. setInterceptsMouseClicks (false, true);
  42029. owner.getTextValue().addListener (this);
  42030. }
  42031. ~TextHolderComponent()
  42032. {
  42033. owner.getTextValue().removeListener (this);
  42034. }
  42035. void paint (Graphics& g)
  42036. {
  42037. owner.drawContent (g);
  42038. }
  42039. void timerCallback()
  42040. {
  42041. owner.timerCallbackInt();
  42042. }
  42043. const MouseCursor getMouseCursor()
  42044. {
  42045. return owner.getMouseCursor();
  42046. }
  42047. void valueChanged (Value&)
  42048. {
  42049. owner.textWasChangedByValue();
  42050. }
  42051. private:
  42052. TextEditor& owner;
  42053. TextHolderComponent (const TextHolderComponent&);
  42054. TextHolderComponent& operator= (const TextHolderComponent&);
  42055. };
  42056. class TextEditorViewport : public Viewport
  42057. {
  42058. public:
  42059. TextEditorViewport (TextEditor* const owner_)
  42060. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42061. {
  42062. }
  42063. ~TextEditorViewport()
  42064. {
  42065. }
  42066. void visibleAreaChanged (int, int, int, int)
  42067. {
  42068. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42069. // appear and disappear, causing the wrap width to change.
  42070. {
  42071. const float wordWrapWidth = owner->getWordWrapWidth();
  42072. if (wordWrapWidth != lastWordWrapWidth)
  42073. {
  42074. lastWordWrapWidth = wordWrapWidth;
  42075. rentrant = true;
  42076. owner->updateTextHolderSize();
  42077. rentrant = false;
  42078. }
  42079. }
  42080. }
  42081. private:
  42082. TextEditor* const owner;
  42083. float lastWordWrapWidth;
  42084. bool rentrant;
  42085. TextEditorViewport (const TextEditorViewport&);
  42086. TextEditorViewport& operator= (const TextEditorViewport&);
  42087. };
  42088. namespace TextEditorDefs
  42089. {
  42090. const int flashSpeedIntervalMs = 380;
  42091. const int textChangeMessageId = 0x10003001;
  42092. const int returnKeyMessageId = 0x10003002;
  42093. const int escapeKeyMessageId = 0x10003003;
  42094. const int focusLossMessageId = 0x10003004;
  42095. const int maxActionsPerTransaction = 100;
  42096. }
  42097. TextEditor::TextEditor (const String& name,
  42098. const juce_wchar passwordCharacter_)
  42099. : Component (name),
  42100. borderSize (1, 1, 1, 3),
  42101. readOnly (false),
  42102. multiline (false),
  42103. wordWrap (false),
  42104. returnKeyStartsNewLine (false),
  42105. caretVisible (true),
  42106. popupMenuEnabled (true),
  42107. selectAllTextWhenFocused (false),
  42108. scrollbarVisible (true),
  42109. wasFocused (false),
  42110. caretFlashState (true),
  42111. keepCursorOnScreen (true),
  42112. tabKeyUsed (false),
  42113. menuActive (false),
  42114. valueTextNeedsUpdating (false),
  42115. cursorX (0),
  42116. cursorY (0),
  42117. cursorHeight (0),
  42118. maxTextLength (0),
  42119. leftIndent (4),
  42120. topIndent (4),
  42121. lastTransactionTime (0),
  42122. currentFont (14.0f),
  42123. totalNumChars (0),
  42124. caretPosition (0),
  42125. passwordCharacter (passwordCharacter_),
  42126. dragType (notDragging)
  42127. {
  42128. setOpaque (true);
  42129. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42130. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42131. viewport->setWantsKeyboardFocus (false);
  42132. viewport->setScrollBarsShown (false, false);
  42133. setMouseCursor (MouseCursor::IBeamCursor);
  42134. setWantsKeyboardFocus (true);
  42135. }
  42136. TextEditor::~TextEditor()
  42137. {
  42138. textValue.referTo (Value());
  42139. clearInternal (0);
  42140. viewport = 0;
  42141. textHolder = 0;
  42142. }
  42143. void TextEditor::newTransaction()
  42144. {
  42145. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42146. undoManager.beginNewTransaction();
  42147. }
  42148. void TextEditor::doUndoRedo (const bool isRedo)
  42149. {
  42150. if (! isReadOnly())
  42151. {
  42152. if (isRedo ? undoManager.redo()
  42153. : undoManager.undo())
  42154. {
  42155. scrollToMakeSureCursorIsVisible();
  42156. repaint();
  42157. textChanged();
  42158. }
  42159. }
  42160. }
  42161. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42162. const bool shouldWordWrap)
  42163. {
  42164. if (multiline != shouldBeMultiLine
  42165. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42166. {
  42167. multiline = shouldBeMultiLine;
  42168. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42169. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42170. scrollbarVisible && multiline);
  42171. viewport->setViewPosition (0, 0);
  42172. resized();
  42173. scrollToMakeSureCursorIsVisible();
  42174. }
  42175. }
  42176. bool TextEditor::isMultiLine() const
  42177. {
  42178. return multiline;
  42179. }
  42180. void TextEditor::setScrollbarsShown (bool shown)
  42181. {
  42182. if (scrollbarVisible != shown)
  42183. {
  42184. scrollbarVisible = shown;
  42185. shown = shown && isMultiLine();
  42186. viewport->setScrollBarsShown (shown, shown);
  42187. }
  42188. }
  42189. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42190. {
  42191. if (readOnly != shouldBeReadOnly)
  42192. {
  42193. readOnly = shouldBeReadOnly;
  42194. enablementChanged();
  42195. }
  42196. }
  42197. bool TextEditor::isReadOnly() const
  42198. {
  42199. return readOnly || ! isEnabled();
  42200. }
  42201. bool TextEditor::isTextInputActive() const
  42202. {
  42203. return ! isReadOnly();
  42204. }
  42205. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42206. {
  42207. returnKeyStartsNewLine = shouldStartNewLine;
  42208. }
  42209. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42210. {
  42211. tabKeyUsed = shouldTabKeyBeUsed;
  42212. }
  42213. void TextEditor::setPopupMenuEnabled (const bool b)
  42214. {
  42215. popupMenuEnabled = b;
  42216. }
  42217. void TextEditor::setSelectAllWhenFocused (const bool b)
  42218. {
  42219. selectAllTextWhenFocused = b;
  42220. }
  42221. const Font TextEditor::getFont() const
  42222. {
  42223. return currentFont;
  42224. }
  42225. void TextEditor::setFont (const Font& newFont)
  42226. {
  42227. currentFont = newFont;
  42228. scrollToMakeSureCursorIsVisible();
  42229. }
  42230. void TextEditor::applyFontToAllText (const Font& newFont)
  42231. {
  42232. currentFont = newFont;
  42233. const Colour overallColour (findColour (textColourId));
  42234. for (int i = sections.size(); --i >= 0;)
  42235. {
  42236. UniformTextSection* const uts = sections.getUnchecked (i);
  42237. uts->setFont (newFont, passwordCharacter);
  42238. uts->colour = overallColour;
  42239. }
  42240. coalesceSimilarSections();
  42241. updateTextHolderSize();
  42242. scrollToMakeSureCursorIsVisible();
  42243. repaint();
  42244. }
  42245. void TextEditor::colourChanged()
  42246. {
  42247. setOpaque (findColour (backgroundColourId).isOpaque());
  42248. repaint();
  42249. }
  42250. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42251. {
  42252. caretVisible = shouldCaretBeVisible;
  42253. if (shouldCaretBeVisible)
  42254. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42255. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42256. : MouseCursor::NormalCursor);
  42257. }
  42258. void TextEditor::setInputRestrictions (const int maxLen,
  42259. const String& chars)
  42260. {
  42261. maxTextLength = jmax (0, maxLen);
  42262. allowedCharacters = chars;
  42263. }
  42264. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42265. {
  42266. textToShowWhenEmpty = text;
  42267. colourForTextWhenEmpty = colourToUse;
  42268. }
  42269. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42270. {
  42271. if (passwordCharacter != newPasswordCharacter)
  42272. {
  42273. passwordCharacter = newPasswordCharacter;
  42274. resized();
  42275. repaint();
  42276. }
  42277. }
  42278. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42279. {
  42280. viewport->setScrollBarThickness (newThicknessPixels);
  42281. }
  42282. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42283. {
  42284. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42285. }
  42286. void TextEditor::clear()
  42287. {
  42288. clearInternal (0);
  42289. updateTextHolderSize();
  42290. undoManager.clearUndoHistory();
  42291. }
  42292. void TextEditor::setText (const String& newText,
  42293. const bool sendTextChangeMessage)
  42294. {
  42295. const int newLength = newText.length();
  42296. if (newLength != getTotalNumChars() || getText() != newText)
  42297. {
  42298. const int oldCursorPos = caretPosition;
  42299. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42300. clearInternal (0);
  42301. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42302. // if you're adding text with line-feeds to a single-line text editor, it
  42303. // ain't gonna look right!
  42304. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42305. if (cursorWasAtEnd && ! isMultiLine())
  42306. moveCursorTo (getTotalNumChars(), false);
  42307. else
  42308. moveCursorTo (oldCursorPos, false);
  42309. if (sendTextChangeMessage)
  42310. textChanged();
  42311. updateTextHolderSize();
  42312. scrollToMakeSureCursorIsVisible();
  42313. undoManager.clearUndoHistory();
  42314. repaint();
  42315. }
  42316. }
  42317. Value& TextEditor::getTextValue()
  42318. {
  42319. if (valueTextNeedsUpdating)
  42320. {
  42321. valueTextNeedsUpdating = false;
  42322. textValue = getText();
  42323. }
  42324. return textValue;
  42325. }
  42326. void TextEditor::textWasChangedByValue()
  42327. {
  42328. if (textValue.getValueSource().getReferenceCount() > 1)
  42329. setText (textValue.getValue());
  42330. }
  42331. void TextEditor::textChanged()
  42332. {
  42333. updateTextHolderSize();
  42334. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42335. if (textValue.getValueSource().getReferenceCount() > 1)
  42336. {
  42337. valueTextNeedsUpdating = false;
  42338. textValue = getText();
  42339. }
  42340. }
  42341. void TextEditor::returnPressed()
  42342. {
  42343. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42344. }
  42345. void TextEditor::escapePressed()
  42346. {
  42347. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42348. }
  42349. void TextEditor::addListener (Listener* const newListener)
  42350. {
  42351. listeners.add (newListener);
  42352. }
  42353. void TextEditor::removeListener (Listener* const listenerToRemove)
  42354. {
  42355. listeners.remove (listenerToRemove);
  42356. }
  42357. void TextEditor::timerCallbackInt()
  42358. {
  42359. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42360. if (caretFlashState != newState)
  42361. {
  42362. caretFlashState = newState;
  42363. if (caretFlashState)
  42364. wasFocused = true;
  42365. if (caretVisible
  42366. && hasKeyboardFocus (false)
  42367. && ! isReadOnly())
  42368. {
  42369. repaintCaret();
  42370. }
  42371. }
  42372. const unsigned int now = Time::getApproximateMillisecondCounter();
  42373. if (now > lastTransactionTime + 200)
  42374. newTransaction();
  42375. }
  42376. void TextEditor::repaintCaret()
  42377. {
  42378. if (! findColour (caretColourId).isTransparent())
  42379. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42380. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42381. 4,
  42382. roundToInt (cursorHeight) + 2);
  42383. }
  42384. void TextEditor::repaintText (const Range<int>& range)
  42385. {
  42386. if (! range.isEmpty())
  42387. {
  42388. float x = 0, y = 0, lh = currentFont.getHeight();
  42389. const float wordWrapWidth = getWordWrapWidth();
  42390. if (wordWrapWidth > 0)
  42391. {
  42392. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42393. i.getCharPosition (range.getStart(), x, y, lh);
  42394. const int y1 = (int) y;
  42395. int y2;
  42396. if (range.getEnd() >= getTotalNumChars())
  42397. {
  42398. y2 = textHolder->getHeight();
  42399. }
  42400. else
  42401. {
  42402. i.getCharPosition (range.getEnd(), x, y, lh);
  42403. y2 = (int) (y + lh * 2.0f);
  42404. }
  42405. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42406. }
  42407. }
  42408. }
  42409. void TextEditor::moveCaret (int newCaretPos)
  42410. {
  42411. if (newCaretPos < 0)
  42412. newCaretPos = 0;
  42413. else if (newCaretPos > getTotalNumChars())
  42414. newCaretPos = getTotalNumChars();
  42415. if (newCaretPos != getCaretPosition())
  42416. {
  42417. repaintCaret();
  42418. caretFlashState = true;
  42419. caretPosition = newCaretPos;
  42420. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42421. scrollToMakeSureCursorIsVisible();
  42422. repaintCaret();
  42423. }
  42424. }
  42425. void TextEditor::setCaretPosition (const int newIndex)
  42426. {
  42427. moveCursorTo (newIndex, false);
  42428. }
  42429. int TextEditor::getCaretPosition() const
  42430. {
  42431. return caretPosition;
  42432. }
  42433. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42434. const int desiredCaretY)
  42435. {
  42436. updateCaretPosition();
  42437. int vx = roundToInt (cursorX) - desiredCaretX;
  42438. int vy = roundToInt (cursorY) - desiredCaretY;
  42439. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42440. {
  42441. vx += desiredCaretX - proportionOfWidth (0.2f);
  42442. }
  42443. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42444. {
  42445. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42446. }
  42447. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42448. if (! isMultiLine())
  42449. {
  42450. vy = viewport->getViewPositionY();
  42451. }
  42452. else
  42453. {
  42454. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42455. const int curH = roundToInt (cursorHeight);
  42456. if (desiredCaretY < 0)
  42457. {
  42458. vy = jmax (0, desiredCaretY + vy);
  42459. }
  42460. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42461. {
  42462. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42463. }
  42464. }
  42465. viewport->setViewPosition (vx, vy);
  42466. }
  42467. const Rectangle<int> TextEditor::getCaretRectangle()
  42468. {
  42469. updateCaretPosition();
  42470. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42471. roundToInt (cursorY) - viewport->getY(),
  42472. 1, roundToInt (cursorHeight));
  42473. }
  42474. float TextEditor::getWordWrapWidth() const
  42475. {
  42476. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42477. : 1.0e10f;
  42478. }
  42479. void TextEditor::updateTextHolderSize()
  42480. {
  42481. const float wordWrapWidth = getWordWrapWidth();
  42482. if (wordWrapWidth > 0)
  42483. {
  42484. float maxWidth = 0.0f;
  42485. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42486. while (i.next())
  42487. maxWidth = jmax (maxWidth, i.atomRight);
  42488. const int w = leftIndent + roundToInt (maxWidth);
  42489. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42490. currentFont.getHeight()));
  42491. textHolder->setSize (w + 1, h + 1);
  42492. }
  42493. }
  42494. int TextEditor::getTextWidth() const
  42495. {
  42496. return textHolder->getWidth();
  42497. }
  42498. int TextEditor::getTextHeight() const
  42499. {
  42500. return textHolder->getHeight();
  42501. }
  42502. void TextEditor::setIndents (const int newLeftIndent,
  42503. const int newTopIndent)
  42504. {
  42505. leftIndent = newLeftIndent;
  42506. topIndent = newTopIndent;
  42507. }
  42508. void TextEditor::setBorder (const BorderSize& border)
  42509. {
  42510. borderSize = border;
  42511. resized();
  42512. }
  42513. const BorderSize TextEditor::getBorder() const
  42514. {
  42515. return borderSize;
  42516. }
  42517. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42518. {
  42519. keepCursorOnScreen = shouldScrollToShowCursor;
  42520. }
  42521. void TextEditor::updateCaretPosition()
  42522. {
  42523. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42524. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42525. }
  42526. void TextEditor::scrollToMakeSureCursorIsVisible()
  42527. {
  42528. updateCaretPosition();
  42529. if (keepCursorOnScreen)
  42530. {
  42531. int x = viewport->getViewPositionX();
  42532. int y = viewport->getViewPositionY();
  42533. const int relativeCursorX = roundToInt (cursorX) - x;
  42534. const int relativeCursorY = roundToInt (cursorY) - y;
  42535. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42536. {
  42537. x += relativeCursorX - proportionOfWidth (0.2f);
  42538. }
  42539. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42540. {
  42541. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42542. }
  42543. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42544. if (! isMultiLine())
  42545. {
  42546. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42547. }
  42548. else
  42549. {
  42550. const int curH = roundToInt (cursorHeight);
  42551. if (relativeCursorY < 0)
  42552. {
  42553. y = jmax (0, relativeCursorY + y);
  42554. }
  42555. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42556. {
  42557. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42558. }
  42559. }
  42560. viewport->setViewPosition (x, y);
  42561. }
  42562. }
  42563. void TextEditor::moveCursorTo (const int newPosition,
  42564. const bool isSelecting)
  42565. {
  42566. if (isSelecting)
  42567. {
  42568. moveCaret (newPosition);
  42569. const Range<int> oldSelection (selection);
  42570. if (dragType == notDragging)
  42571. {
  42572. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42573. dragType = draggingSelectionStart;
  42574. else
  42575. dragType = draggingSelectionEnd;
  42576. }
  42577. if (dragType == draggingSelectionStart)
  42578. {
  42579. if (getCaretPosition() >= selection.getEnd())
  42580. dragType = draggingSelectionEnd;
  42581. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42582. }
  42583. else
  42584. {
  42585. if (getCaretPosition() < selection.getStart())
  42586. dragType = draggingSelectionStart;
  42587. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42588. }
  42589. repaintText (selection.getUnionWith (oldSelection));
  42590. }
  42591. else
  42592. {
  42593. dragType = notDragging;
  42594. repaintText (selection);
  42595. moveCaret (newPosition);
  42596. selection = Range<int>::emptyRange (getCaretPosition());
  42597. }
  42598. }
  42599. int TextEditor::getTextIndexAt (const int x,
  42600. const int y)
  42601. {
  42602. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42603. (float) (y + viewport->getViewPositionY() - topIndent));
  42604. }
  42605. void TextEditor::insertTextAtCaret (const String& newText_)
  42606. {
  42607. String newText (newText_);
  42608. if (allowedCharacters.isNotEmpty())
  42609. newText = newText.retainCharacters (allowedCharacters);
  42610. if ((! returnKeyStartsNewLine) && newText == "\n")
  42611. {
  42612. returnPressed();
  42613. return;
  42614. }
  42615. if (! isMultiLine())
  42616. newText = newText.replaceCharacters ("\r\n", " ");
  42617. else
  42618. newText = newText.replace ("\r\n", "\n");
  42619. const int newCaretPos = selection.getStart() + newText.length();
  42620. const int insertIndex = selection.getStart();
  42621. remove (selection, getUndoManager(),
  42622. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42623. if (maxTextLength > 0)
  42624. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42625. if (newText.isNotEmpty())
  42626. insert (newText,
  42627. insertIndex,
  42628. currentFont,
  42629. findColour (textColourId),
  42630. getUndoManager(),
  42631. newCaretPos);
  42632. textChanged();
  42633. }
  42634. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42635. {
  42636. moveCursorTo (newSelection.getStart(), false);
  42637. moveCursorTo (newSelection.getEnd(), true);
  42638. }
  42639. void TextEditor::copy()
  42640. {
  42641. if (passwordCharacter == 0)
  42642. {
  42643. const String selectedText (getHighlightedText());
  42644. if (selectedText.isNotEmpty())
  42645. SystemClipboard::copyTextToClipboard (selectedText);
  42646. }
  42647. }
  42648. void TextEditor::paste()
  42649. {
  42650. if (! isReadOnly())
  42651. {
  42652. const String clip (SystemClipboard::getTextFromClipboard());
  42653. if (clip.isNotEmpty())
  42654. insertTextAtCaret (clip);
  42655. }
  42656. }
  42657. void TextEditor::cut()
  42658. {
  42659. if (! isReadOnly())
  42660. {
  42661. moveCaret (selection.getEnd());
  42662. insertTextAtCaret (String::empty);
  42663. }
  42664. }
  42665. void TextEditor::drawContent (Graphics& g)
  42666. {
  42667. const float wordWrapWidth = getWordWrapWidth();
  42668. if (wordWrapWidth > 0)
  42669. {
  42670. g.setOrigin (leftIndent, topIndent);
  42671. const Rectangle<int> clip (g.getClipBounds());
  42672. Colour selectedTextColour;
  42673. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42674. while (i.lineY + 200.0 < clip.getY() && i.next())
  42675. {}
  42676. if (! selection.isEmpty())
  42677. {
  42678. g.setColour (findColour (highlightColourId)
  42679. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42680. selectedTextColour = findColour (highlightedTextColourId);
  42681. Iterator i2 (i);
  42682. while (i2.next() && i2.lineY < clip.getBottom())
  42683. {
  42684. if (i2.lineY + i2.lineHeight >= clip.getY()
  42685. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42686. {
  42687. i2.drawSelection (g, selection);
  42688. }
  42689. }
  42690. }
  42691. const UniformTextSection* lastSection = 0;
  42692. while (i.next() && i.lineY < clip.getBottom())
  42693. {
  42694. if (i.lineY + i.lineHeight >= clip.getY())
  42695. {
  42696. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42697. {
  42698. i.drawSelectedText (g, selection, selectedTextColour);
  42699. lastSection = 0;
  42700. }
  42701. else
  42702. {
  42703. i.draw (g, lastSection);
  42704. }
  42705. }
  42706. }
  42707. }
  42708. }
  42709. void TextEditor::paint (Graphics& g)
  42710. {
  42711. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42712. }
  42713. void TextEditor::paintOverChildren (Graphics& g)
  42714. {
  42715. if (caretFlashState
  42716. && hasKeyboardFocus (false)
  42717. && caretVisible
  42718. && ! isReadOnly())
  42719. {
  42720. g.setColour (findColour (caretColourId));
  42721. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42722. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42723. 2.0f, cursorHeight);
  42724. }
  42725. if (textToShowWhenEmpty.isNotEmpty()
  42726. && (! hasKeyboardFocus (false))
  42727. && getTotalNumChars() == 0)
  42728. {
  42729. g.setColour (colourForTextWhenEmpty);
  42730. g.setFont (getFont());
  42731. if (isMultiLine())
  42732. {
  42733. g.drawText (textToShowWhenEmpty,
  42734. 0, 0, getWidth(), getHeight(),
  42735. Justification::centred, true);
  42736. }
  42737. else
  42738. {
  42739. g.drawText (textToShowWhenEmpty,
  42740. leftIndent, topIndent,
  42741. viewport->getWidth() - leftIndent,
  42742. viewport->getHeight() - topIndent,
  42743. Justification::centredLeft, true);
  42744. }
  42745. }
  42746. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42747. }
  42748. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  42749. {
  42750. public:
  42751. TextEditorMenuPerformer (TextEditor* const editor_)
  42752. : editor (editor_)
  42753. {
  42754. }
  42755. void modalStateFinished (int returnValue)
  42756. {
  42757. if (editor != 0 && returnValue != 0)
  42758. editor->performPopupMenuAction (returnValue);
  42759. }
  42760. private:
  42761. Component::SafePointer<TextEditor> editor;
  42762. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  42763. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  42764. };
  42765. void TextEditor::mouseDown (const MouseEvent& e)
  42766. {
  42767. beginDragAutoRepeat (100);
  42768. newTransaction();
  42769. if (wasFocused || ! selectAllTextWhenFocused)
  42770. {
  42771. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42772. {
  42773. moveCursorTo (getTextIndexAt (e.x, e.y),
  42774. e.mods.isShiftDown());
  42775. }
  42776. else
  42777. {
  42778. PopupMenu m;
  42779. m.setLookAndFeel (&getLookAndFeel());
  42780. addPopupMenuItems (m, &e);
  42781. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  42782. }
  42783. }
  42784. }
  42785. void TextEditor::mouseDrag (const MouseEvent& e)
  42786. {
  42787. if (wasFocused || ! selectAllTextWhenFocused)
  42788. {
  42789. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42790. {
  42791. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42792. }
  42793. }
  42794. }
  42795. void TextEditor::mouseUp (const MouseEvent& e)
  42796. {
  42797. newTransaction();
  42798. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42799. if (wasFocused || ! selectAllTextWhenFocused)
  42800. {
  42801. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42802. {
  42803. moveCaret (getTextIndexAt (e.x, e.y));
  42804. }
  42805. }
  42806. wasFocused = true;
  42807. }
  42808. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42809. {
  42810. int tokenEnd = getTextIndexAt (e.x, e.y);
  42811. int tokenStart = tokenEnd;
  42812. if (e.getNumberOfClicks() > 3)
  42813. {
  42814. tokenStart = 0;
  42815. tokenEnd = getTotalNumChars();
  42816. }
  42817. else
  42818. {
  42819. const String t (getText());
  42820. const int totalLength = getTotalNumChars();
  42821. while (tokenEnd < totalLength)
  42822. {
  42823. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42824. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  42825. ++tokenEnd;
  42826. else
  42827. break;
  42828. }
  42829. tokenStart = tokenEnd;
  42830. while (tokenStart > 0)
  42831. {
  42832. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42833. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  42834. --tokenStart;
  42835. else
  42836. break;
  42837. }
  42838. if (e.getNumberOfClicks() > 2)
  42839. {
  42840. while (tokenEnd < totalLength)
  42841. {
  42842. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42843. ++tokenEnd;
  42844. else
  42845. break;
  42846. }
  42847. while (tokenStart > 0)
  42848. {
  42849. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42850. --tokenStart;
  42851. else
  42852. break;
  42853. }
  42854. }
  42855. }
  42856. moveCursorTo (tokenEnd, false);
  42857. moveCursorTo (tokenStart, true);
  42858. }
  42859. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42860. {
  42861. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42862. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42863. }
  42864. bool TextEditor::keyPressed (const KeyPress& key)
  42865. {
  42866. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42867. return false;
  42868. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42869. if (key.isKeyCode (KeyPress::leftKey)
  42870. || key.isKeyCode (KeyPress::upKey))
  42871. {
  42872. newTransaction();
  42873. int newPos;
  42874. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42875. newPos = indexAtPosition (cursorX, cursorY - 1);
  42876. else if (moveInWholeWordSteps)
  42877. newPos = findWordBreakBefore (getCaretPosition());
  42878. else
  42879. newPos = getCaretPosition() - 1;
  42880. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42881. }
  42882. else if (key.isKeyCode (KeyPress::rightKey)
  42883. || key.isKeyCode (KeyPress::downKey))
  42884. {
  42885. newTransaction();
  42886. int newPos;
  42887. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42888. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42889. else if (moveInWholeWordSteps)
  42890. newPos = findWordBreakAfter (getCaretPosition());
  42891. else
  42892. newPos = getCaretPosition() + 1;
  42893. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42894. }
  42895. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42896. {
  42897. newTransaction();
  42898. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42899. key.getModifiers().isShiftDown());
  42900. }
  42901. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42902. {
  42903. newTransaction();
  42904. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42905. key.getModifiers().isShiftDown());
  42906. }
  42907. else if (key.isKeyCode (KeyPress::homeKey))
  42908. {
  42909. newTransaction();
  42910. if (isMultiLine() && ! moveInWholeWordSteps)
  42911. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42912. key.getModifiers().isShiftDown());
  42913. else
  42914. moveCursorTo (0, key.getModifiers().isShiftDown());
  42915. }
  42916. else if (key.isKeyCode (KeyPress::endKey))
  42917. {
  42918. newTransaction();
  42919. if (isMultiLine() && ! moveInWholeWordSteps)
  42920. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42921. key.getModifiers().isShiftDown());
  42922. else
  42923. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42924. }
  42925. else if (key.isKeyCode (KeyPress::backspaceKey))
  42926. {
  42927. if (moveInWholeWordSteps)
  42928. {
  42929. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42930. }
  42931. else
  42932. {
  42933. if (selection.isEmpty() && selection.getStart() > 0)
  42934. selection.setStart (selection.getEnd() - 1);
  42935. }
  42936. cut();
  42937. }
  42938. else if (key.isKeyCode (KeyPress::deleteKey))
  42939. {
  42940. if (key.getModifiers().isShiftDown())
  42941. copy();
  42942. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42943. selection.setEnd (selection.getStart() + 1);
  42944. cut();
  42945. }
  42946. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42947. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42948. {
  42949. newTransaction();
  42950. copy();
  42951. }
  42952. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42953. {
  42954. newTransaction();
  42955. copy();
  42956. cut();
  42957. }
  42958. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42959. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42960. {
  42961. newTransaction();
  42962. paste();
  42963. }
  42964. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42965. {
  42966. newTransaction();
  42967. doUndoRedo (false);
  42968. }
  42969. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42970. {
  42971. newTransaction();
  42972. doUndoRedo (true);
  42973. }
  42974. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42975. {
  42976. newTransaction();
  42977. moveCursorTo (getTotalNumChars(), false);
  42978. moveCursorTo (0, true);
  42979. }
  42980. else if (key == KeyPress::returnKey)
  42981. {
  42982. newTransaction();
  42983. insertTextAtCaret ("\n");
  42984. }
  42985. else if (key.isKeyCode (KeyPress::escapeKey))
  42986. {
  42987. newTransaction();
  42988. moveCursorTo (getCaretPosition(), false);
  42989. escapePressed();
  42990. }
  42991. else if (key.getTextCharacter() >= ' '
  42992. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42993. {
  42994. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42995. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42996. }
  42997. else
  42998. {
  42999. return false;
  43000. }
  43001. return true;
  43002. }
  43003. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43004. {
  43005. if (! isKeyDown)
  43006. return false;
  43007. #if JUCE_WINDOWS
  43008. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43009. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43010. #endif
  43011. // (overridden to avoid forwarding key events to the parent)
  43012. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43013. }
  43014. const int baseMenuItemID = 0x7fff0000;
  43015. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43016. {
  43017. const bool writable = ! isReadOnly();
  43018. if (passwordCharacter == 0)
  43019. {
  43020. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43021. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43022. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43023. }
  43024. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43025. m.addSeparator();
  43026. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43027. m.addSeparator();
  43028. if (getUndoManager() != 0)
  43029. {
  43030. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43031. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43032. }
  43033. }
  43034. void TextEditor::performPopupMenuAction (const int menuItemID)
  43035. {
  43036. switch (menuItemID)
  43037. {
  43038. case baseMenuItemID + 1:
  43039. copy();
  43040. cut();
  43041. break;
  43042. case baseMenuItemID + 2:
  43043. copy();
  43044. break;
  43045. case baseMenuItemID + 3:
  43046. paste();
  43047. break;
  43048. case baseMenuItemID + 4:
  43049. cut();
  43050. break;
  43051. case baseMenuItemID + 5:
  43052. moveCursorTo (getTotalNumChars(), false);
  43053. moveCursorTo (0, true);
  43054. break;
  43055. case baseMenuItemID + 6:
  43056. doUndoRedo (false);
  43057. break;
  43058. case baseMenuItemID + 7:
  43059. doUndoRedo (true);
  43060. break;
  43061. default:
  43062. break;
  43063. }
  43064. }
  43065. void TextEditor::focusGained (FocusChangeType)
  43066. {
  43067. newTransaction();
  43068. caretFlashState = true;
  43069. if (selectAllTextWhenFocused)
  43070. {
  43071. moveCursorTo (0, false);
  43072. moveCursorTo (getTotalNumChars(), true);
  43073. }
  43074. repaint();
  43075. if (caretVisible)
  43076. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43077. ComponentPeer* const peer = getPeer();
  43078. if (peer != 0 && ! isReadOnly())
  43079. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43080. }
  43081. void TextEditor::focusLost (FocusChangeType)
  43082. {
  43083. newTransaction();
  43084. wasFocused = false;
  43085. textHolder->stopTimer();
  43086. caretFlashState = false;
  43087. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43088. repaint();
  43089. }
  43090. void TextEditor::resized()
  43091. {
  43092. viewport->setBoundsInset (borderSize);
  43093. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43094. updateTextHolderSize();
  43095. if (! isMultiLine())
  43096. {
  43097. scrollToMakeSureCursorIsVisible();
  43098. }
  43099. else
  43100. {
  43101. updateCaretPosition();
  43102. }
  43103. }
  43104. void TextEditor::handleCommandMessage (const int commandId)
  43105. {
  43106. Component::BailOutChecker checker (this);
  43107. switch (commandId)
  43108. {
  43109. case TextEditorDefs::textChangeMessageId:
  43110. listeners.callChecked (checker, &Listener::textEditorTextChanged, (TextEditor&) *this);
  43111. break;
  43112. case TextEditorDefs::returnKeyMessageId:
  43113. listeners.callChecked (checker, &Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43114. break;
  43115. case TextEditorDefs::escapeKeyMessageId:
  43116. listeners.callChecked (checker, &Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43117. break;
  43118. case TextEditorDefs::focusLossMessageId:
  43119. listeners.callChecked (checker, &Listener::textEditorFocusLost, (TextEditor&) *this);
  43120. break;
  43121. default:
  43122. jassertfalse;
  43123. break;
  43124. }
  43125. }
  43126. void TextEditor::enablementChanged()
  43127. {
  43128. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43129. : MouseCursor::IBeamCursor);
  43130. repaint();
  43131. }
  43132. UndoManager* TextEditor::getUndoManager() throw()
  43133. {
  43134. return isReadOnly() ? 0 : &undoManager;
  43135. }
  43136. void TextEditor::clearInternal (UndoManager* const um)
  43137. {
  43138. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43139. }
  43140. void TextEditor::insert (const String& text,
  43141. const int insertIndex,
  43142. const Font& font,
  43143. const Colour& colour,
  43144. UndoManager* const um,
  43145. const int caretPositionToMoveTo)
  43146. {
  43147. if (text.isNotEmpty())
  43148. {
  43149. if (um != 0)
  43150. {
  43151. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43152. newTransaction();
  43153. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43154. caretPosition, caretPositionToMoveTo));
  43155. }
  43156. else
  43157. {
  43158. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43159. // a line gets moved due to word wrap
  43160. int index = 0;
  43161. int nextIndex = 0;
  43162. for (int i = 0; i < sections.size(); ++i)
  43163. {
  43164. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43165. if (insertIndex == index)
  43166. {
  43167. sections.insert (i, new UniformTextSection (text,
  43168. font, colour,
  43169. passwordCharacter));
  43170. break;
  43171. }
  43172. else if (insertIndex > index && insertIndex < nextIndex)
  43173. {
  43174. splitSection (i, insertIndex - index);
  43175. sections.insert (i + 1, new UniformTextSection (text,
  43176. font, colour,
  43177. passwordCharacter));
  43178. break;
  43179. }
  43180. index = nextIndex;
  43181. }
  43182. if (nextIndex == insertIndex)
  43183. sections.add (new UniformTextSection (text,
  43184. font, colour,
  43185. passwordCharacter));
  43186. coalesceSimilarSections();
  43187. totalNumChars = -1;
  43188. valueTextNeedsUpdating = true;
  43189. moveCursorTo (caretPositionToMoveTo, false);
  43190. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43191. }
  43192. }
  43193. }
  43194. void TextEditor::reinsert (const int insertIndex,
  43195. const Array <UniformTextSection*>& sectionsToInsert)
  43196. {
  43197. int index = 0;
  43198. int nextIndex = 0;
  43199. for (int i = 0; i < sections.size(); ++i)
  43200. {
  43201. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43202. if (insertIndex == index)
  43203. {
  43204. for (int j = sectionsToInsert.size(); --j >= 0;)
  43205. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43206. break;
  43207. }
  43208. else if (insertIndex > index && insertIndex < nextIndex)
  43209. {
  43210. splitSection (i, insertIndex - index);
  43211. for (int j = sectionsToInsert.size(); --j >= 0;)
  43212. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43213. break;
  43214. }
  43215. index = nextIndex;
  43216. }
  43217. if (nextIndex == insertIndex)
  43218. {
  43219. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43220. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43221. }
  43222. coalesceSimilarSections();
  43223. totalNumChars = -1;
  43224. valueTextNeedsUpdating = true;
  43225. }
  43226. void TextEditor::remove (const Range<int>& range,
  43227. UndoManager* const um,
  43228. const int caretPositionToMoveTo)
  43229. {
  43230. if (! range.isEmpty())
  43231. {
  43232. int index = 0;
  43233. for (int i = 0; i < sections.size(); ++i)
  43234. {
  43235. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43236. if (range.getStart() > index && range.getStart() < nextIndex)
  43237. {
  43238. splitSection (i, range.getStart() - index);
  43239. --i;
  43240. }
  43241. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43242. {
  43243. splitSection (i, range.getEnd() - index);
  43244. --i;
  43245. }
  43246. else
  43247. {
  43248. index = nextIndex;
  43249. if (index > range.getEnd())
  43250. break;
  43251. }
  43252. }
  43253. index = 0;
  43254. if (um != 0)
  43255. {
  43256. Array <UniformTextSection*> removedSections;
  43257. for (int i = 0; i < sections.size(); ++i)
  43258. {
  43259. if (range.getEnd() <= range.getStart())
  43260. break;
  43261. UniformTextSection* const section = sections.getUnchecked (i);
  43262. const int nextIndex = index + section->getTotalLength();
  43263. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43264. removedSections.add (new UniformTextSection (*section));
  43265. index = nextIndex;
  43266. }
  43267. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43268. newTransaction();
  43269. um->perform (new RemoveAction (*this, range, caretPosition,
  43270. caretPositionToMoveTo, removedSections));
  43271. }
  43272. else
  43273. {
  43274. Range<int> remainingRange (range);
  43275. for (int i = 0; i < sections.size(); ++i)
  43276. {
  43277. UniformTextSection* const section = sections.getUnchecked (i);
  43278. const int nextIndex = index + section->getTotalLength();
  43279. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43280. {
  43281. sections.remove(i);
  43282. section->clear();
  43283. delete section;
  43284. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43285. if (remainingRange.isEmpty())
  43286. break;
  43287. --i;
  43288. }
  43289. else
  43290. {
  43291. index = nextIndex;
  43292. }
  43293. }
  43294. coalesceSimilarSections();
  43295. totalNumChars = -1;
  43296. valueTextNeedsUpdating = true;
  43297. moveCursorTo (caretPositionToMoveTo, false);
  43298. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43299. }
  43300. }
  43301. }
  43302. const String TextEditor::getText() const
  43303. {
  43304. String t;
  43305. t.preallocateStorage (getTotalNumChars());
  43306. String::Concatenator concatenator (t);
  43307. for (int i = 0; i < sections.size(); ++i)
  43308. sections.getUnchecked (i)->appendAllText (concatenator);
  43309. return t;
  43310. }
  43311. const String TextEditor::getTextInRange (const Range<int>& range) const
  43312. {
  43313. String t;
  43314. if (! range.isEmpty())
  43315. {
  43316. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43317. String::Concatenator concatenator (t);
  43318. int index = 0;
  43319. for (int i = 0; i < sections.size(); ++i)
  43320. {
  43321. const UniformTextSection* const s = sections.getUnchecked (i);
  43322. const int nextIndex = index + s->getTotalLength();
  43323. if (range.getStart() < nextIndex)
  43324. {
  43325. if (range.getEnd() <= index)
  43326. break;
  43327. s->appendSubstring (concatenator, range - index);
  43328. }
  43329. index = nextIndex;
  43330. }
  43331. }
  43332. return t;
  43333. }
  43334. const String TextEditor::getHighlightedText() const
  43335. {
  43336. return getTextInRange (selection);
  43337. }
  43338. int TextEditor::getTotalNumChars() const
  43339. {
  43340. if (totalNumChars < 0)
  43341. {
  43342. totalNumChars = 0;
  43343. for (int i = sections.size(); --i >= 0;)
  43344. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43345. }
  43346. return totalNumChars;
  43347. }
  43348. bool TextEditor::isEmpty() const
  43349. {
  43350. return getTotalNumChars() == 0;
  43351. }
  43352. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43353. {
  43354. const float wordWrapWidth = getWordWrapWidth();
  43355. if (wordWrapWidth > 0 && sections.size() > 0)
  43356. {
  43357. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43358. i.getCharPosition (index, cx, cy, lineHeight);
  43359. }
  43360. else
  43361. {
  43362. cx = cy = 0;
  43363. lineHeight = currentFont.getHeight();
  43364. }
  43365. }
  43366. int TextEditor::indexAtPosition (const float x, const float y)
  43367. {
  43368. const float wordWrapWidth = getWordWrapWidth();
  43369. if (wordWrapWidth > 0)
  43370. {
  43371. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43372. while (i.next())
  43373. {
  43374. if (i.lineY + i.lineHeight > y)
  43375. {
  43376. if (i.lineY > y)
  43377. return jmax (0, i.indexInText - 1);
  43378. if (i.atomX >= x)
  43379. return i.indexInText;
  43380. if (x < i.atomRight)
  43381. return i.xToIndex (x);
  43382. }
  43383. }
  43384. }
  43385. return getTotalNumChars();
  43386. }
  43387. static int getCharacterCategory (const juce_wchar character)
  43388. {
  43389. return CharacterFunctions::isLetterOrDigit (character)
  43390. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43391. }
  43392. int TextEditor::findWordBreakAfter (const int position) const
  43393. {
  43394. const String t (getTextInRange (Range<int> (position, position + 512)));
  43395. const int totalLength = t.length();
  43396. int i = 0;
  43397. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43398. ++i;
  43399. const int type = getCharacterCategory (t[i]);
  43400. while (i < totalLength && type == getCharacterCategory (t[i]))
  43401. ++i;
  43402. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43403. ++i;
  43404. return position + i;
  43405. }
  43406. int TextEditor::findWordBreakBefore (const int position) const
  43407. {
  43408. if (position <= 0)
  43409. return 0;
  43410. const int startOfBuffer = jmax (0, position - 512);
  43411. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43412. int i = position - startOfBuffer;
  43413. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43414. --i;
  43415. if (i > 0)
  43416. {
  43417. const int type = getCharacterCategory (t [i - 1]);
  43418. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43419. --i;
  43420. }
  43421. jassert (startOfBuffer + i >= 0);
  43422. return startOfBuffer + i;
  43423. }
  43424. void TextEditor::splitSection (const int sectionIndex,
  43425. const int charToSplitAt)
  43426. {
  43427. jassert (sections[sectionIndex] != 0);
  43428. sections.insert (sectionIndex + 1,
  43429. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43430. }
  43431. void TextEditor::coalesceSimilarSections()
  43432. {
  43433. for (int i = 0; i < sections.size() - 1; ++i)
  43434. {
  43435. UniformTextSection* const s1 = sections.getUnchecked (i);
  43436. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43437. if (s1->font == s2->font
  43438. && s1->colour == s2->colour)
  43439. {
  43440. s1->append (*s2, passwordCharacter);
  43441. sections.remove (i + 1);
  43442. delete s2;
  43443. --i;
  43444. }
  43445. }
  43446. }
  43447. END_JUCE_NAMESPACE
  43448. /*** End of inlined file: juce_TextEditor.cpp ***/
  43449. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43450. BEGIN_JUCE_NAMESPACE
  43451. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43452. class ToolbarSpacerComp : public ToolbarItemComponent
  43453. {
  43454. public:
  43455. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43456. : ToolbarItemComponent (itemId_, String::empty, false),
  43457. fixedSize (fixedSize_),
  43458. drawBar (drawBar_)
  43459. {
  43460. }
  43461. ~ToolbarSpacerComp()
  43462. {
  43463. }
  43464. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43465. int& preferredSize, int& minSize, int& maxSize)
  43466. {
  43467. if (fixedSize <= 0)
  43468. {
  43469. preferredSize = toolbarThickness * 2;
  43470. minSize = 4;
  43471. maxSize = 32768;
  43472. }
  43473. else
  43474. {
  43475. maxSize = roundToInt (toolbarThickness * fixedSize);
  43476. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43477. preferredSize = maxSize;
  43478. if (getEditingMode() == editableOnPalette)
  43479. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43480. }
  43481. return true;
  43482. }
  43483. void paintButtonArea (Graphics&, int, int, bool, bool)
  43484. {
  43485. }
  43486. void contentAreaChanged (const Rectangle<int>&)
  43487. {
  43488. }
  43489. int getResizeOrder() const throw()
  43490. {
  43491. return fixedSize <= 0 ? 0 : 1;
  43492. }
  43493. void paint (Graphics& g)
  43494. {
  43495. const int w = getWidth();
  43496. const int h = getHeight();
  43497. if (drawBar)
  43498. {
  43499. g.setColour (findColour (Toolbar::separatorColourId, true));
  43500. const float thickness = 0.2f;
  43501. if (isToolbarVertical())
  43502. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43503. else
  43504. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43505. }
  43506. if (getEditingMode() != normalMode && ! drawBar)
  43507. {
  43508. g.setColour (findColour (Toolbar::separatorColourId, true));
  43509. const int indentX = jmin (2, (w - 3) / 2);
  43510. const int indentY = jmin (2, (h - 3) / 2);
  43511. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43512. if (fixedSize <= 0)
  43513. {
  43514. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43515. if (isToolbarVertical())
  43516. {
  43517. x1 = w * 0.5f;
  43518. y1 = h * 0.4f;
  43519. x2 = x1;
  43520. y2 = indentX * 2.0f;
  43521. x3 = x1;
  43522. y3 = h * 0.6f;
  43523. x4 = x1;
  43524. y4 = h - y2;
  43525. hw = w * 0.15f;
  43526. hl = w * 0.2f;
  43527. }
  43528. else
  43529. {
  43530. x1 = w * 0.4f;
  43531. y1 = h * 0.5f;
  43532. x2 = indentX * 2.0f;
  43533. y2 = y1;
  43534. x3 = w * 0.6f;
  43535. y3 = y1;
  43536. x4 = w - x2;
  43537. y4 = y1;
  43538. hw = h * 0.15f;
  43539. hl = h * 0.2f;
  43540. }
  43541. Path p;
  43542. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43543. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43544. g.fillPath (p);
  43545. }
  43546. }
  43547. }
  43548. juce_UseDebuggingNewOperator
  43549. private:
  43550. const float fixedSize;
  43551. const bool drawBar;
  43552. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43553. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43554. };
  43555. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  43556. {
  43557. public:
  43558. MissingItemsComponent (Toolbar& owner_, const int height_)
  43559. : PopupMenuCustomComponent (true),
  43560. owner (owner_),
  43561. height (height_)
  43562. {
  43563. for (int i = owner_.items.size(); --i >= 0;)
  43564. {
  43565. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43566. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43567. {
  43568. oldIndexes.insert (0, i);
  43569. addAndMakeVisible (tc, 0);
  43570. }
  43571. }
  43572. layout (400);
  43573. }
  43574. ~MissingItemsComponent()
  43575. {
  43576. // deleting the toolbar while its menu it open??
  43577. jassert (owner.isValidComponent());
  43578. for (int i = 0; i < getNumChildComponents(); ++i)
  43579. {
  43580. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43581. if (tc != 0)
  43582. {
  43583. tc->setVisible (false);
  43584. const int index = oldIndexes.remove (i);
  43585. owner.addChildComponent (tc, index);
  43586. --i;
  43587. }
  43588. }
  43589. owner.resized();
  43590. }
  43591. void layout (const int preferredWidth)
  43592. {
  43593. const int indent = 8;
  43594. int x = indent;
  43595. int y = indent;
  43596. int maxX = 0;
  43597. for (int i = 0; i < getNumChildComponents(); ++i)
  43598. {
  43599. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43600. if (tc != 0)
  43601. {
  43602. int preferredSize = 1, minSize = 1, maxSize = 1;
  43603. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43604. {
  43605. if (x + preferredSize > preferredWidth && x > indent)
  43606. {
  43607. x = indent;
  43608. y += height;
  43609. }
  43610. tc->setBounds (x, y, preferredSize, height);
  43611. x += preferredSize;
  43612. maxX = jmax (maxX, x);
  43613. }
  43614. }
  43615. }
  43616. setSize (maxX + 8, y + height + 8);
  43617. }
  43618. void getIdealSize (int& idealWidth, int& idealHeight)
  43619. {
  43620. idealWidth = getWidth();
  43621. idealHeight = getHeight();
  43622. }
  43623. juce_UseDebuggingNewOperator
  43624. private:
  43625. Toolbar& owner;
  43626. const int height;
  43627. Array <int> oldIndexes;
  43628. MissingItemsComponent (const MissingItemsComponent&);
  43629. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43630. };
  43631. Toolbar::Toolbar()
  43632. : vertical (false),
  43633. isEditingActive (false),
  43634. toolbarStyle (Toolbar::iconsOnly)
  43635. {
  43636. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43637. missingItemsButton->setAlwaysOnTop (true);
  43638. missingItemsButton->addButtonListener (this);
  43639. }
  43640. Toolbar::~Toolbar()
  43641. {
  43642. animator.cancelAllAnimations (true);
  43643. deleteAllChildren();
  43644. }
  43645. void Toolbar::setVertical (const bool shouldBeVertical)
  43646. {
  43647. if (vertical != shouldBeVertical)
  43648. {
  43649. vertical = shouldBeVertical;
  43650. resized();
  43651. }
  43652. }
  43653. void Toolbar::clear()
  43654. {
  43655. for (int i = items.size(); --i >= 0;)
  43656. {
  43657. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43658. items.remove (i);
  43659. delete tc;
  43660. }
  43661. resized();
  43662. }
  43663. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43664. {
  43665. if (itemId == ToolbarItemFactory::separatorBarId)
  43666. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43667. else if (itemId == ToolbarItemFactory::spacerId)
  43668. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43669. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43670. return new ToolbarSpacerComp (itemId, 0, false);
  43671. return factory.createItem (itemId);
  43672. }
  43673. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43674. const int itemId,
  43675. const int insertIndex)
  43676. {
  43677. // An ID can't be zero - this might indicate a mistake somewhere?
  43678. jassert (itemId != 0);
  43679. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43680. if (tc != 0)
  43681. {
  43682. #if JUCE_DEBUG
  43683. Array <int> allowedIds;
  43684. factory.getAllToolbarItemIds (allowedIds);
  43685. // If your factory can create an item for a given ID, it must also return
  43686. // that ID from its getAllToolbarItemIds() method!
  43687. jassert (allowedIds.contains (itemId));
  43688. #endif
  43689. items.insert (insertIndex, tc);
  43690. addAndMakeVisible (tc, insertIndex);
  43691. }
  43692. }
  43693. void Toolbar::addItem (ToolbarItemFactory& factory,
  43694. const int itemId,
  43695. const int insertIndex)
  43696. {
  43697. addItemInternal (factory, itemId, insertIndex);
  43698. resized();
  43699. }
  43700. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43701. {
  43702. Array <int> ids;
  43703. factoryToUse.getDefaultItemSet (ids);
  43704. clear();
  43705. for (int i = 0; i < ids.size(); ++i)
  43706. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43707. resized();
  43708. }
  43709. void Toolbar::removeToolbarItem (const int itemIndex)
  43710. {
  43711. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43712. if (tc != 0)
  43713. {
  43714. items.removeValue (tc);
  43715. delete tc;
  43716. resized();
  43717. }
  43718. }
  43719. int Toolbar::getNumItems() const throw()
  43720. {
  43721. return items.size();
  43722. }
  43723. int Toolbar::getItemId (const int itemIndex) const throw()
  43724. {
  43725. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43726. return tc != 0 ? tc->getItemId() : 0;
  43727. }
  43728. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43729. {
  43730. return items [itemIndex];
  43731. }
  43732. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43733. {
  43734. for (;;)
  43735. {
  43736. index += delta;
  43737. ToolbarItemComponent* const tc = getItemComponent (index);
  43738. if (tc == 0)
  43739. break;
  43740. if (tc->isActive)
  43741. return tc;
  43742. }
  43743. return 0;
  43744. }
  43745. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43746. {
  43747. if (toolbarStyle != newStyle)
  43748. {
  43749. toolbarStyle = newStyle;
  43750. updateAllItemPositions (false);
  43751. }
  43752. }
  43753. const String Toolbar::toString() const
  43754. {
  43755. String s ("TB:");
  43756. for (int i = 0; i < getNumItems(); ++i)
  43757. s << getItemId(i) << ' ';
  43758. return s.trimEnd();
  43759. }
  43760. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43761. const String& savedVersion)
  43762. {
  43763. if (! savedVersion.startsWith ("TB:"))
  43764. return false;
  43765. StringArray tokens;
  43766. tokens.addTokens (savedVersion.substring (3), false);
  43767. clear();
  43768. for (int i = 0; i < tokens.size(); ++i)
  43769. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43770. resized();
  43771. return true;
  43772. }
  43773. void Toolbar::paint (Graphics& g)
  43774. {
  43775. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43776. }
  43777. int Toolbar::getThickness() const throw()
  43778. {
  43779. return vertical ? getWidth() : getHeight();
  43780. }
  43781. int Toolbar::getLength() const throw()
  43782. {
  43783. return vertical ? getHeight() : getWidth();
  43784. }
  43785. void Toolbar::setEditingActive (const bool active)
  43786. {
  43787. if (isEditingActive != active)
  43788. {
  43789. isEditingActive = active;
  43790. updateAllItemPositions (false);
  43791. }
  43792. }
  43793. void Toolbar::resized()
  43794. {
  43795. updateAllItemPositions (false);
  43796. }
  43797. void Toolbar::updateAllItemPositions (const bool animate)
  43798. {
  43799. if (getWidth() > 0 && getHeight() > 0)
  43800. {
  43801. StretchableObjectResizer resizer;
  43802. int i;
  43803. for (i = 0; i < items.size(); ++i)
  43804. {
  43805. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43806. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43807. : ToolbarItemComponent::normalMode);
  43808. tc->setStyle (toolbarStyle);
  43809. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43810. int preferredSize = 1, minSize = 1, maxSize = 1;
  43811. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43812. preferredSize, minSize, maxSize))
  43813. {
  43814. tc->isActive = true;
  43815. resizer.addItem (preferredSize, minSize, maxSize,
  43816. spacer != 0 ? spacer->getResizeOrder() : 2);
  43817. }
  43818. else
  43819. {
  43820. tc->isActive = false;
  43821. tc->setVisible (false);
  43822. }
  43823. }
  43824. resizer.resizeToFit (getLength());
  43825. int totalLength = 0;
  43826. for (i = 0; i < resizer.getNumItems(); ++i)
  43827. totalLength += (int) resizer.getItemSize (i);
  43828. const bool itemsOffTheEnd = totalLength > getLength();
  43829. const int extrasButtonSize = getThickness() / 2;
  43830. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43831. missingItemsButton->setVisible (itemsOffTheEnd);
  43832. missingItemsButton->setEnabled (! isEditingActive);
  43833. if (vertical)
  43834. missingItemsButton->setCentrePosition (getWidth() / 2,
  43835. getHeight() - 4 - extrasButtonSize / 2);
  43836. else
  43837. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43838. getHeight() / 2);
  43839. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43840. : missingItemsButton->getX()) - 4
  43841. : getLength();
  43842. int pos = 0, activeIndex = 0;
  43843. for (i = 0; i < items.size(); ++i)
  43844. {
  43845. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43846. if (tc->isActive)
  43847. {
  43848. const int size = (int) resizer.getItemSize (activeIndex++);
  43849. Rectangle<int> newBounds;
  43850. if (vertical)
  43851. newBounds.setBounds (0, pos, getWidth(), size);
  43852. else
  43853. newBounds.setBounds (pos, 0, size, getHeight());
  43854. if (animate)
  43855. {
  43856. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43857. }
  43858. else
  43859. {
  43860. animator.cancelAnimation (tc, false);
  43861. tc->setBounds (newBounds);
  43862. }
  43863. pos += size;
  43864. tc->setVisible (pos <= maxLength
  43865. && ((! tc->isBeingDragged)
  43866. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43867. }
  43868. }
  43869. }
  43870. }
  43871. void Toolbar::buttonClicked (Button*)
  43872. {
  43873. jassert (missingItemsButton->isShowing());
  43874. if (missingItemsButton->isShowing())
  43875. {
  43876. PopupMenu m;
  43877. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43878. m.showAt (missingItemsButton);
  43879. }
  43880. }
  43881. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43882. Component* /*sourceComponent*/)
  43883. {
  43884. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43885. }
  43886. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43887. {
  43888. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43889. if (tc != 0)
  43890. {
  43891. if (getNumItems() == 0)
  43892. {
  43893. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43894. {
  43895. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43896. if (palette != 0)
  43897. palette->replaceComponent (tc);
  43898. }
  43899. else
  43900. {
  43901. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43902. }
  43903. items.add (tc);
  43904. addChildComponent (tc);
  43905. updateAllItemPositions (false);
  43906. }
  43907. else
  43908. {
  43909. for (int i = getNumItems(); --i >= 0;)
  43910. {
  43911. int currentIndex = getIndexOfChildComponent (tc);
  43912. if (currentIndex < 0)
  43913. {
  43914. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43915. {
  43916. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43917. if (palette != 0)
  43918. palette->replaceComponent (tc);
  43919. }
  43920. else
  43921. {
  43922. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43923. }
  43924. items.add (tc);
  43925. addChildComponent (tc);
  43926. currentIndex = getIndexOfChildComponent (tc);
  43927. updateAllItemPositions (true);
  43928. }
  43929. int newIndex = currentIndex;
  43930. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43931. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43932. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43933. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43934. if (prev != 0)
  43935. {
  43936. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43937. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43938. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43939. {
  43940. newIndex = getIndexOfChildComponent (prev);
  43941. }
  43942. }
  43943. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43944. if (next != 0)
  43945. {
  43946. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43947. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43948. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43949. {
  43950. newIndex = getIndexOfChildComponent (next) + 1;
  43951. }
  43952. }
  43953. if (newIndex != currentIndex)
  43954. {
  43955. items.removeValue (tc);
  43956. removeChildComponent (tc);
  43957. addChildComponent (tc, newIndex);
  43958. items.insert (newIndex, tc);
  43959. updateAllItemPositions (true);
  43960. }
  43961. else
  43962. {
  43963. break;
  43964. }
  43965. }
  43966. }
  43967. }
  43968. }
  43969. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43970. {
  43971. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43972. if (tc != 0)
  43973. {
  43974. if (isParentOf (tc))
  43975. {
  43976. items.removeValue (tc);
  43977. removeChildComponent (tc);
  43978. updateAllItemPositions (true);
  43979. }
  43980. }
  43981. }
  43982. void Toolbar::itemDropped (const String&, Component*, int, int)
  43983. {
  43984. }
  43985. void Toolbar::mouseDown (const MouseEvent& e)
  43986. {
  43987. if (e.mods.isPopupMenu())
  43988. {
  43989. }
  43990. }
  43991. class ToolbarCustomisationDialog : public DialogWindow
  43992. {
  43993. public:
  43994. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43995. Toolbar* const toolbar_,
  43996. const int optionFlags)
  43997. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43998. toolbar (toolbar_)
  43999. {
  44000. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44001. setResizable (true, true);
  44002. setResizeLimits (400, 300, 1500, 1000);
  44003. positionNearBar();
  44004. }
  44005. ~ToolbarCustomisationDialog()
  44006. {
  44007. setContentComponent (0, true);
  44008. }
  44009. void closeButtonPressed()
  44010. {
  44011. setVisible (false);
  44012. }
  44013. bool canModalEventBeSentToComponent (const Component* comp)
  44014. {
  44015. return toolbar->isParentOf (comp);
  44016. }
  44017. void positionNearBar()
  44018. {
  44019. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44020. const int tbx = toolbar->getScreenX();
  44021. const int tby = toolbar->getScreenY();
  44022. const int gap = 8;
  44023. int x, y;
  44024. if (toolbar->isVertical())
  44025. {
  44026. y = tby;
  44027. if (tbx > screenSize.getCentreX())
  44028. x = tbx - getWidth() - gap;
  44029. else
  44030. x = tbx + toolbar->getWidth() + gap;
  44031. }
  44032. else
  44033. {
  44034. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44035. if (tby > screenSize.getCentreY())
  44036. y = tby - getHeight() - gap;
  44037. else
  44038. y = tby + toolbar->getHeight() + gap;
  44039. }
  44040. setTopLeftPosition (x, y);
  44041. }
  44042. private:
  44043. Toolbar* const toolbar;
  44044. class CustomiserPanel : public Component,
  44045. private ComboBox::Listener,
  44046. private Button::Listener
  44047. {
  44048. public:
  44049. CustomiserPanel (ToolbarItemFactory& factory_,
  44050. Toolbar* const toolbar_,
  44051. const int optionFlags)
  44052. : factory (factory_),
  44053. toolbar (toolbar_),
  44054. styleBox (0),
  44055. defaultButton (0)
  44056. {
  44057. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44058. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44059. | Toolbar::allowIconsWithTextChoice
  44060. | Toolbar::allowTextOnlyChoice)) != 0)
  44061. {
  44062. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44063. styleBox->setEditableText (false);
  44064. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44065. styleBox->addItem (TRANS("Show icons only"), 1);
  44066. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44067. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44068. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44069. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44070. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44071. styleBox->setSelectedId (1);
  44072. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44073. styleBox->setSelectedId (2);
  44074. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44075. styleBox->setSelectedId (3);
  44076. styleBox->addListener (this);
  44077. }
  44078. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44079. {
  44080. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44081. defaultButton->addButtonListener (this);
  44082. }
  44083. addAndMakeVisible (instructions = new Label (String::empty,
  44084. 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.")));
  44085. instructions->setFont (Font (13.0f));
  44086. setSize (500, 300);
  44087. }
  44088. ~CustomiserPanel()
  44089. {
  44090. deleteAllChildren();
  44091. }
  44092. void comboBoxChanged (ComboBox*)
  44093. {
  44094. if (styleBox->getSelectedId() == 1)
  44095. toolbar->setStyle (Toolbar::iconsOnly);
  44096. else if (styleBox->getSelectedId() == 2)
  44097. toolbar->setStyle (Toolbar::iconsWithText);
  44098. else if (styleBox->getSelectedId() == 3)
  44099. toolbar->setStyle (Toolbar::textOnly);
  44100. palette->resized(); // to make it update the styles
  44101. }
  44102. void buttonClicked (Button*)
  44103. {
  44104. toolbar->addDefaultItems (factory);
  44105. }
  44106. void paint (Graphics& g)
  44107. {
  44108. Colour background;
  44109. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44110. if (dw != 0)
  44111. background = dw->getBackgroundColour();
  44112. g.setColour (background.contrasting().withAlpha (0.3f));
  44113. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44114. }
  44115. void resized()
  44116. {
  44117. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44118. if (styleBox != 0)
  44119. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44120. if (defaultButton != 0)
  44121. {
  44122. defaultButton->changeWidthToFitText (22);
  44123. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44124. }
  44125. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44126. }
  44127. private:
  44128. ToolbarItemFactory& factory;
  44129. Toolbar* const toolbar;
  44130. Label* instructions;
  44131. ToolbarItemPalette* palette;
  44132. ComboBox* styleBox;
  44133. TextButton* defaultButton;
  44134. };
  44135. };
  44136. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44137. {
  44138. setEditingActive (true);
  44139. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44140. dw.runModalLoop();
  44141. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44142. setEditingActive (false);
  44143. }
  44144. END_JUCE_NAMESPACE
  44145. /*** End of inlined file: juce_Toolbar.cpp ***/
  44146. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44147. BEGIN_JUCE_NAMESPACE
  44148. ToolbarItemFactory::ToolbarItemFactory()
  44149. {
  44150. }
  44151. ToolbarItemFactory::~ToolbarItemFactory()
  44152. {
  44153. }
  44154. class ItemDragAndDropOverlayComponent : public Component
  44155. {
  44156. public:
  44157. ItemDragAndDropOverlayComponent()
  44158. : isDragging (false)
  44159. {
  44160. setAlwaysOnTop (true);
  44161. setRepaintsOnMouseActivity (true);
  44162. setMouseCursor (MouseCursor::DraggingHandCursor);
  44163. }
  44164. ~ItemDragAndDropOverlayComponent()
  44165. {
  44166. }
  44167. void paint (Graphics& g)
  44168. {
  44169. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44170. if (isMouseOverOrDragging()
  44171. && tc != 0
  44172. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44173. {
  44174. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44175. g.drawRect (0, 0, getWidth(), getHeight(),
  44176. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44177. }
  44178. }
  44179. void mouseDown (const MouseEvent& e)
  44180. {
  44181. isDragging = false;
  44182. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44183. if (tc != 0)
  44184. {
  44185. tc->dragOffsetX = e.x;
  44186. tc->dragOffsetY = e.y;
  44187. }
  44188. }
  44189. void mouseDrag (const MouseEvent& e)
  44190. {
  44191. if (! (isDragging || e.mouseWasClicked()))
  44192. {
  44193. isDragging = true;
  44194. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44195. if (dnd != 0)
  44196. {
  44197. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44198. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44199. if (tc != 0)
  44200. {
  44201. tc->isBeingDragged = true;
  44202. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44203. tc->setVisible (false);
  44204. }
  44205. }
  44206. }
  44207. }
  44208. void mouseUp (const MouseEvent&)
  44209. {
  44210. isDragging = false;
  44211. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44212. if (tc != 0)
  44213. {
  44214. tc->isBeingDragged = false;
  44215. Toolbar* const tb = tc->getToolbar();
  44216. if (tb != 0)
  44217. tb->updateAllItemPositions (true);
  44218. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44219. delete tc;
  44220. }
  44221. }
  44222. void parentSizeChanged()
  44223. {
  44224. setBounds (0, 0, getParentWidth(), getParentHeight());
  44225. }
  44226. juce_UseDebuggingNewOperator
  44227. private:
  44228. bool isDragging;
  44229. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44230. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44231. };
  44232. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44233. const String& labelText,
  44234. const bool isBeingUsedAsAButton_)
  44235. : Button (labelText),
  44236. itemId (itemId_),
  44237. mode (normalMode),
  44238. toolbarStyle (Toolbar::iconsOnly),
  44239. dragOffsetX (0),
  44240. dragOffsetY (0),
  44241. isActive (true),
  44242. isBeingDragged (false),
  44243. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44244. {
  44245. // Your item ID can't be 0!
  44246. jassert (itemId_ != 0);
  44247. }
  44248. ToolbarItemComponent::~ToolbarItemComponent()
  44249. {
  44250. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44251. overlayComp = 0;
  44252. }
  44253. Toolbar* ToolbarItemComponent::getToolbar() const
  44254. {
  44255. return dynamic_cast <Toolbar*> (getParentComponent());
  44256. }
  44257. bool ToolbarItemComponent::isToolbarVertical() const
  44258. {
  44259. const Toolbar* const t = getToolbar();
  44260. return t != 0 && t->isVertical();
  44261. }
  44262. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44263. {
  44264. if (toolbarStyle != newStyle)
  44265. {
  44266. toolbarStyle = newStyle;
  44267. repaint();
  44268. resized();
  44269. }
  44270. }
  44271. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44272. {
  44273. if (isBeingUsedAsAButton)
  44274. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44275. over, down, *this);
  44276. if (toolbarStyle != Toolbar::iconsOnly)
  44277. {
  44278. const int indent = contentArea.getX();
  44279. int y = indent;
  44280. int h = getHeight() - indent * 2;
  44281. if (toolbarStyle == Toolbar::iconsWithText)
  44282. {
  44283. y = contentArea.getBottom() + indent / 2;
  44284. h -= contentArea.getHeight();
  44285. }
  44286. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44287. getButtonText(), *this);
  44288. }
  44289. if (! contentArea.isEmpty())
  44290. {
  44291. g.saveState();
  44292. g.setOrigin (contentArea.getX(), contentArea.getY());
  44293. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44294. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44295. g.restoreState();
  44296. }
  44297. }
  44298. void ToolbarItemComponent::resized()
  44299. {
  44300. if (toolbarStyle != Toolbar::textOnly)
  44301. {
  44302. const int indent = jmin (proportionOfWidth (0.08f),
  44303. proportionOfHeight (0.08f));
  44304. contentArea = Rectangle<int> (indent, indent,
  44305. getWidth() - indent * 2,
  44306. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44307. : (getHeight() - indent * 2));
  44308. }
  44309. else
  44310. {
  44311. contentArea = Rectangle<int>();
  44312. }
  44313. contentAreaChanged (contentArea);
  44314. }
  44315. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44316. {
  44317. if (mode != newMode)
  44318. {
  44319. mode = newMode;
  44320. repaint();
  44321. if (mode == normalMode)
  44322. {
  44323. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44324. overlayComp = 0;
  44325. }
  44326. else if (overlayComp == 0)
  44327. {
  44328. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44329. overlayComp->parentSizeChanged();
  44330. }
  44331. resized();
  44332. }
  44333. }
  44334. END_JUCE_NAMESPACE
  44335. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44336. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44337. BEGIN_JUCE_NAMESPACE
  44338. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44339. Toolbar* const toolbar_)
  44340. : factory (factory_),
  44341. toolbar (toolbar_)
  44342. {
  44343. Component* const itemHolder = new Component();
  44344. Array <int> allIds;
  44345. factory_.getAllToolbarItemIds (allIds);
  44346. for (int i = 0; i < allIds.size(); ++i)
  44347. {
  44348. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44349. jassert (tc != 0);
  44350. if (tc != 0)
  44351. {
  44352. itemHolder->addAndMakeVisible (tc);
  44353. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44354. }
  44355. }
  44356. viewport = new Viewport();
  44357. viewport->setViewedComponent (itemHolder);
  44358. addAndMakeVisible (viewport);
  44359. }
  44360. ToolbarItemPalette::~ToolbarItemPalette()
  44361. {
  44362. viewport->getViewedComponent()->deleteAllChildren();
  44363. deleteAllChildren();
  44364. }
  44365. void ToolbarItemPalette::resized()
  44366. {
  44367. viewport->setBoundsInset (BorderSize (1));
  44368. Component* const itemHolder = viewport->getViewedComponent();
  44369. const int indent = 8;
  44370. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44371. const int height = toolbar->getThickness();
  44372. int x = indent;
  44373. int y = indent;
  44374. int maxX = 0;
  44375. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44376. {
  44377. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44378. if (tc != 0)
  44379. {
  44380. tc->setStyle (toolbar->getStyle());
  44381. int preferredSize = 1, minSize = 1, maxSize = 1;
  44382. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44383. {
  44384. if (x + preferredSize > preferredWidth && x > indent)
  44385. {
  44386. x = indent;
  44387. y += height;
  44388. }
  44389. tc->setBounds (x, y, preferredSize, height);
  44390. x += preferredSize + 8;
  44391. maxX = jmax (maxX, x);
  44392. }
  44393. }
  44394. }
  44395. itemHolder->setSize (maxX, y + height + 8);
  44396. }
  44397. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44398. {
  44399. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44400. jassert (tc != 0);
  44401. if (tc != 0)
  44402. {
  44403. tc->setBounds (comp->getBounds());
  44404. tc->setStyle (toolbar->getStyle());
  44405. tc->setEditingMode (comp->getEditingMode());
  44406. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44407. }
  44408. }
  44409. END_JUCE_NAMESPACE
  44410. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44411. /*** Start of inlined file: juce_TreeView.cpp ***/
  44412. BEGIN_JUCE_NAMESPACE
  44413. class TreeViewContentComponent : public Component,
  44414. public TooltipClient
  44415. {
  44416. public:
  44417. TreeViewContentComponent (TreeView& owner_)
  44418. : owner (owner_),
  44419. buttonUnderMouse (0),
  44420. isDragging (false)
  44421. {
  44422. }
  44423. ~TreeViewContentComponent()
  44424. {
  44425. deleteAllChildren();
  44426. }
  44427. void mouseDown (const MouseEvent& e)
  44428. {
  44429. updateButtonUnderMouse (e);
  44430. isDragging = false;
  44431. needSelectionOnMouseUp = false;
  44432. Rectangle<int> pos;
  44433. TreeViewItem* const item = findItemAt (e.y, pos);
  44434. if (item == 0)
  44435. return;
  44436. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44437. // as selection clicks)
  44438. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44439. {
  44440. if (e.x >= pos.getX() - owner.getIndentSize())
  44441. item->setOpen (! item->isOpen());
  44442. // (clicks to the left of an open/close button are ignored)
  44443. }
  44444. else
  44445. {
  44446. // mouse-down inside the body of the item..
  44447. if (! owner.isMultiSelectEnabled())
  44448. item->setSelected (true, true);
  44449. else if (item->isSelected())
  44450. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44451. else
  44452. selectBasedOnModifiers (item, e.mods);
  44453. if (e.x >= pos.getX())
  44454. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44455. }
  44456. }
  44457. void mouseUp (const MouseEvent& e)
  44458. {
  44459. updateButtonUnderMouse (e);
  44460. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44461. {
  44462. Rectangle<int> pos;
  44463. TreeViewItem* const item = findItemAt (e.y, pos);
  44464. if (item != 0)
  44465. selectBasedOnModifiers (item, e.mods);
  44466. }
  44467. }
  44468. void mouseDoubleClick (const MouseEvent& e)
  44469. {
  44470. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44471. {
  44472. Rectangle<int> pos;
  44473. TreeViewItem* const item = findItemAt (e.y, pos);
  44474. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44475. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44476. }
  44477. }
  44478. void mouseDrag (const MouseEvent& e)
  44479. {
  44480. if (isEnabled()
  44481. && ! (isDragging || e.mouseWasClicked()
  44482. || e.getDistanceFromDragStart() < 5
  44483. || e.mods.isPopupMenu()))
  44484. {
  44485. isDragging = true;
  44486. Rectangle<int> pos;
  44487. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44488. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44489. {
  44490. const String dragDescription (item->getDragSourceDescription());
  44491. if (dragDescription.isNotEmpty())
  44492. {
  44493. DragAndDropContainer* const dragContainer
  44494. = DragAndDropContainer::findParentDragContainerFor (this);
  44495. if (dragContainer != 0)
  44496. {
  44497. pos.setSize (pos.getWidth(), item->itemHeight);
  44498. Image dragImage (Component::createComponentSnapshot (pos, true));
  44499. dragImage.multiplyAllAlphas (0.6f);
  44500. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44501. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44502. }
  44503. else
  44504. {
  44505. // to be able to do a drag-and-drop operation, the treeview needs to
  44506. // be inside a component which is also a DragAndDropContainer.
  44507. jassertfalse;
  44508. }
  44509. }
  44510. }
  44511. }
  44512. }
  44513. void mouseMove (const MouseEvent& e)
  44514. {
  44515. updateButtonUnderMouse (e);
  44516. }
  44517. void mouseExit (const MouseEvent& e)
  44518. {
  44519. updateButtonUnderMouse (e);
  44520. }
  44521. void paint (Graphics& g)
  44522. {
  44523. if (owner.rootItem != 0)
  44524. {
  44525. owner.handleAsyncUpdate();
  44526. if (! owner.rootItemVisible)
  44527. g.setOrigin (0, -owner.rootItem->itemHeight);
  44528. owner.rootItem->paintRecursively (g, getWidth());
  44529. }
  44530. }
  44531. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44532. {
  44533. if (owner.rootItem != 0)
  44534. {
  44535. owner.handleAsyncUpdate();
  44536. if (! owner.rootItemVisible)
  44537. y += owner.rootItem->itemHeight;
  44538. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44539. if (ti != 0)
  44540. itemPosition = ti->getItemPosition (false);
  44541. return ti;
  44542. }
  44543. return 0;
  44544. }
  44545. void updateComponents()
  44546. {
  44547. const int visibleTop = -getY();
  44548. const int visibleBottom = visibleTop + getParentHeight();
  44549. BigInteger itemsToKeep;
  44550. {
  44551. TreeViewItem* item = owner.rootItem;
  44552. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44553. while (item != 0 && y < visibleBottom)
  44554. {
  44555. y += item->itemHeight;
  44556. if (y >= visibleTop)
  44557. {
  44558. const int index = rowComponentIds.indexOf (item->uid);
  44559. if (index < 0)
  44560. {
  44561. Component* const comp = item->createItemComponent();
  44562. if (comp != 0)
  44563. {
  44564. addAndMakeVisible (comp);
  44565. itemsToKeep.setBit (rowComponentItems.size());
  44566. rowComponentItems.add (item);
  44567. rowComponentIds.add (item->uid);
  44568. rowComponents.add (comp);
  44569. }
  44570. }
  44571. else
  44572. {
  44573. itemsToKeep.setBit (index);
  44574. }
  44575. }
  44576. item = item->getNextVisibleItem (true);
  44577. }
  44578. }
  44579. for (int i = rowComponentItems.size(); --i >= 0;)
  44580. {
  44581. Component* const comp = rowComponents.getUnchecked(i);
  44582. bool keep = false;
  44583. if (isParentOf (comp))
  44584. {
  44585. if (itemsToKeep[i])
  44586. {
  44587. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44588. Rectangle<int> pos (item->getItemPosition (false));
  44589. pos.setSize (pos.getWidth(), item->itemHeight);
  44590. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44591. {
  44592. keep = true;
  44593. comp->setBounds (pos);
  44594. }
  44595. }
  44596. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44597. {
  44598. keep = true;
  44599. comp->setSize (0, 0);
  44600. }
  44601. }
  44602. if (! keep)
  44603. {
  44604. delete comp;
  44605. rowComponents.remove (i);
  44606. rowComponentIds.remove (i);
  44607. rowComponentItems.remove (i);
  44608. }
  44609. }
  44610. }
  44611. void updateButtonUnderMouse (const MouseEvent& e)
  44612. {
  44613. TreeViewItem* newItem = 0;
  44614. if (owner.openCloseButtonsVisible)
  44615. {
  44616. Rectangle<int> pos;
  44617. TreeViewItem* item = findItemAt (e.y, pos);
  44618. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44619. {
  44620. newItem = item;
  44621. if (! newItem->mightContainSubItems())
  44622. newItem = 0;
  44623. }
  44624. }
  44625. if (buttonUnderMouse != newItem)
  44626. {
  44627. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44628. {
  44629. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44630. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44631. }
  44632. buttonUnderMouse = newItem;
  44633. if (buttonUnderMouse != 0)
  44634. {
  44635. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44636. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44637. }
  44638. }
  44639. }
  44640. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44641. {
  44642. return item == buttonUnderMouse;
  44643. }
  44644. void resized()
  44645. {
  44646. owner.itemsChanged();
  44647. }
  44648. const String getTooltip()
  44649. {
  44650. Rectangle<int> pos;
  44651. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44652. if (item != 0)
  44653. return item->getTooltip();
  44654. return owner.getTooltip();
  44655. }
  44656. juce_UseDebuggingNewOperator
  44657. private:
  44658. TreeView& owner;
  44659. Array <TreeViewItem*> rowComponentItems;
  44660. Array <int> rowComponentIds;
  44661. Array <Component*> rowComponents;
  44662. TreeViewItem* buttonUnderMouse;
  44663. bool isDragging, needSelectionOnMouseUp;
  44664. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44665. {
  44666. TreeViewItem* firstSelected = 0;
  44667. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44668. {
  44669. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44670. jassert (lastSelected != 0);
  44671. int rowStart = firstSelected->getRowNumberInTree();
  44672. int rowEnd = lastSelected->getRowNumberInTree();
  44673. if (rowStart > rowEnd)
  44674. swapVariables (rowStart, rowEnd);
  44675. int ourRow = item->getRowNumberInTree();
  44676. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44677. if (ourRow > otherEnd)
  44678. swapVariables (ourRow, otherEnd);
  44679. for (int i = ourRow; i <= otherEnd; ++i)
  44680. owner.getItemOnRow (i)->setSelected (true, false);
  44681. }
  44682. else
  44683. {
  44684. const bool cmd = modifiers.isCommandDown();
  44685. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44686. }
  44687. }
  44688. bool containsItem (TreeViewItem* const item) const
  44689. {
  44690. for (int i = rowComponentItems.size(); --i >= 0;)
  44691. if (rowComponentItems.getUnchecked(i) == item)
  44692. return true;
  44693. return false;
  44694. }
  44695. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44696. {
  44697. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44698. {
  44699. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44700. if (source->isDragging())
  44701. {
  44702. Component* const underMouse = source->getComponentUnderMouse();
  44703. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44704. return true;
  44705. }
  44706. }
  44707. return false;
  44708. }
  44709. TreeViewContentComponent (const TreeViewContentComponent&);
  44710. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44711. };
  44712. class TreeView::TreeViewport : public Viewport
  44713. {
  44714. public:
  44715. TreeViewport() throw() : lastX (-1) {}
  44716. ~TreeViewport() throw() {}
  44717. void updateComponents (const bool triggerResize = false)
  44718. {
  44719. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44720. if (tvc != 0)
  44721. {
  44722. if (triggerResize)
  44723. tvc->resized();
  44724. else
  44725. tvc->updateComponents();
  44726. }
  44727. repaint();
  44728. }
  44729. void visibleAreaChanged (int x, int, int, int)
  44730. {
  44731. const bool hasScrolledSideways = (x != lastX);
  44732. lastX = x;
  44733. updateComponents (hasScrolledSideways);
  44734. }
  44735. juce_UseDebuggingNewOperator
  44736. private:
  44737. int lastX;
  44738. TreeViewport (const TreeViewport&);
  44739. TreeViewport& operator= (const TreeViewport&);
  44740. };
  44741. TreeView::TreeView (const String& componentName)
  44742. : Component (componentName),
  44743. rootItem (0),
  44744. indentSize (24),
  44745. defaultOpenness (false),
  44746. needsRecalculating (true),
  44747. rootItemVisible (true),
  44748. multiSelectEnabled (false),
  44749. openCloseButtonsVisible (true)
  44750. {
  44751. addAndMakeVisible (viewport = new TreeViewport());
  44752. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44753. viewport->setWantsKeyboardFocus (false);
  44754. setWantsKeyboardFocus (true);
  44755. }
  44756. TreeView::~TreeView()
  44757. {
  44758. if (rootItem != 0)
  44759. rootItem->setOwnerView (0);
  44760. }
  44761. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44762. {
  44763. if (rootItem != newRootItem)
  44764. {
  44765. if (newRootItem != 0)
  44766. {
  44767. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44768. if (newRootItem->ownerView != 0)
  44769. newRootItem->ownerView->setRootItem (0);
  44770. }
  44771. if (rootItem != 0)
  44772. rootItem->setOwnerView (0);
  44773. rootItem = newRootItem;
  44774. if (newRootItem != 0)
  44775. newRootItem->setOwnerView (this);
  44776. needsRecalculating = true;
  44777. handleAsyncUpdate();
  44778. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44779. {
  44780. rootItem->setOpen (false); // force a re-open
  44781. rootItem->setOpen (true);
  44782. }
  44783. }
  44784. }
  44785. void TreeView::deleteRootItem()
  44786. {
  44787. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44788. setRootItem (0);
  44789. }
  44790. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44791. {
  44792. rootItemVisible = shouldBeVisible;
  44793. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44794. {
  44795. rootItem->setOpen (false); // force a re-open
  44796. rootItem->setOpen (true);
  44797. }
  44798. itemsChanged();
  44799. }
  44800. void TreeView::colourChanged()
  44801. {
  44802. setOpaque (findColour (backgroundColourId).isOpaque());
  44803. repaint();
  44804. }
  44805. void TreeView::setIndentSize (const int newIndentSize)
  44806. {
  44807. if (indentSize != newIndentSize)
  44808. {
  44809. indentSize = newIndentSize;
  44810. resized();
  44811. }
  44812. }
  44813. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44814. {
  44815. if (defaultOpenness != isOpenByDefault)
  44816. {
  44817. defaultOpenness = isOpenByDefault;
  44818. itemsChanged();
  44819. }
  44820. }
  44821. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44822. {
  44823. multiSelectEnabled = canMultiSelect;
  44824. }
  44825. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44826. {
  44827. if (openCloseButtonsVisible != shouldBeVisible)
  44828. {
  44829. openCloseButtonsVisible = shouldBeVisible;
  44830. itemsChanged();
  44831. }
  44832. }
  44833. Viewport* TreeView::getViewport() const throw()
  44834. {
  44835. return viewport;
  44836. }
  44837. void TreeView::clearSelectedItems()
  44838. {
  44839. if (rootItem != 0)
  44840. rootItem->deselectAllRecursively();
  44841. }
  44842. int TreeView::getNumSelectedItems() const throw()
  44843. {
  44844. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44845. }
  44846. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44847. {
  44848. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44849. }
  44850. int TreeView::getNumRowsInTree() const
  44851. {
  44852. if (rootItem != 0)
  44853. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44854. return 0;
  44855. }
  44856. TreeViewItem* TreeView::getItemOnRow (int index) const
  44857. {
  44858. if (! rootItemVisible)
  44859. ++index;
  44860. if (rootItem != 0 && index >= 0)
  44861. return rootItem->getItemOnRow (index);
  44862. return 0;
  44863. }
  44864. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44865. {
  44866. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44867. Rectangle<int> pos;
  44868. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44869. }
  44870. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44871. {
  44872. if (rootItem == 0)
  44873. return 0;
  44874. return rootItem->findItemFromIdentifierString (identifierString);
  44875. }
  44876. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44877. {
  44878. XmlElement* e = 0;
  44879. if (rootItem != 0)
  44880. {
  44881. e = rootItem->getOpennessState();
  44882. if (e != 0 && alsoIncludeScrollPosition)
  44883. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44884. }
  44885. return e;
  44886. }
  44887. void TreeView::restoreOpennessState (const XmlElement& newState)
  44888. {
  44889. if (rootItem != 0)
  44890. {
  44891. rootItem->restoreOpennessState (newState);
  44892. if (newState.hasAttribute ("scrollPos"))
  44893. viewport->setViewPosition (viewport->getViewPositionX(),
  44894. newState.getIntAttribute ("scrollPos"));
  44895. }
  44896. }
  44897. void TreeView::paint (Graphics& g)
  44898. {
  44899. g.fillAll (findColour (backgroundColourId));
  44900. }
  44901. void TreeView::resized()
  44902. {
  44903. viewport->setBounds (getLocalBounds());
  44904. itemsChanged();
  44905. handleAsyncUpdate();
  44906. }
  44907. void TreeView::enablementChanged()
  44908. {
  44909. repaint();
  44910. }
  44911. void TreeView::moveSelectedRow (int delta)
  44912. {
  44913. if (delta == 0)
  44914. return;
  44915. int rowSelected = 0;
  44916. TreeViewItem* const firstSelected = getSelectedItem (0);
  44917. if (firstSelected != 0)
  44918. rowSelected = firstSelected->getRowNumberInTree();
  44919. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44920. for (;;)
  44921. {
  44922. TreeViewItem* item = getItemOnRow (rowSelected);
  44923. if (item != 0)
  44924. {
  44925. if (! item->canBeSelected())
  44926. {
  44927. // if the row we want to highlight doesn't allow it, try skipping
  44928. // to the next item..
  44929. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44930. rowSelected + (delta < 0 ? -1 : 1));
  44931. if (rowSelected != nextRowToTry)
  44932. {
  44933. rowSelected = nextRowToTry;
  44934. continue;
  44935. }
  44936. else
  44937. {
  44938. break;
  44939. }
  44940. }
  44941. item->setSelected (true, true);
  44942. scrollToKeepItemVisible (item);
  44943. }
  44944. break;
  44945. }
  44946. }
  44947. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44948. {
  44949. if (item != 0 && item->ownerView == this)
  44950. {
  44951. handleAsyncUpdate();
  44952. item = item->getDeepestOpenParentItem();
  44953. int y = item->y;
  44954. int viewTop = viewport->getViewPositionY();
  44955. if (y < viewTop)
  44956. {
  44957. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44958. }
  44959. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44960. {
  44961. viewport->setViewPosition (viewport->getViewPositionX(),
  44962. (y + item->itemHeight) - viewport->getViewHeight());
  44963. }
  44964. }
  44965. }
  44966. bool TreeView::keyPressed (const KeyPress& key)
  44967. {
  44968. if (key.isKeyCode (KeyPress::upKey))
  44969. {
  44970. moveSelectedRow (-1);
  44971. }
  44972. else if (key.isKeyCode (KeyPress::downKey))
  44973. {
  44974. moveSelectedRow (1);
  44975. }
  44976. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44977. {
  44978. if (rootItem != 0)
  44979. {
  44980. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44981. if (key.isKeyCode (KeyPress::pageUpKey))
  44982. rowsOnScreen = -rowsOnScreen;
  44983. moveSelectedRow (rowsOnScreen);
  44984. }
  44985. }
  44986. else if (key.isKeyCode (KeyPress::homeKey))
  44987. {
  44988. moveSelectedRow (-0x3fffffff);
  44989. }
  44990. else if (key.isKeyCode (KeyPress::endKey))
  44991. {
  44992. moveSelectedRow (0x3fffffff);
  44993. }
  44994. else if (key.isKeyCode (KeyPress::returnKey))
  44995. {
  44996. TreeViewItem* const firstSelected = getSelectedItem (0);
  44997. if (firstSelected != 0)
  44998. firstSelected->setOpen (! firstSelected->isOpen());
  44999. }
  45000. else if (key.isKeyCode (KeyPress::leftKey))
  45001. {
  45002. TreeViewItem* const firstSelected = getSelectedItem (0);
  45003. if (firstSelected != 0)
  45004. {
  45005. if (firstSelected->isOpen())
  45006. {
  45007. firstSelected->setOpen (false);
  45008. }
  45009. else
  45010. {
  45011. TreeViewItem* parent = firstSelected->parentItem;
  45012. if ((! rootItemVisible) && parent == rootItem)
  45013. parent = 0;
  45014. if (parent != 0)
  45015. {
  45016. parent->setSelected (true, true);
  45017. scrollToKeepItemVisible (parent);
  45018. }
  45019. }
  45020. }
  45021. }
  45022. else if (key.isKeyCode (KeyPress::rightKey))
  45023. {
  45024. TreeViewItem* const firstSelected = getSelectedItem (0);
  45025. if (firstSelected != 0)
  45026. {
  45027. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45028. moveSelectedRow (1);
  45029. else
  45030. firstSelected->setOpen (true);
  45031. }
  45032. }
  45033. else
  45034. {
  45035. return false;
  45036. }
  45037. return true;
  45038. }
  45039. void TreeView::itemsChanged() throw()
  45040. {
  45041. needsRecalculating = true;
  45042. repaint();
  45043. triggerAsyncUpdate();
  45044. }
  45045. void TreeView::handleAsyncUpdate()
  45046. {
  45047. if (needsRecalculating)
  45048. {
  45049. needsRecalculating = false;
  45050. const ScopedLock sl (nodeAlterationLock);
  45051. if (rootItem != 0)
  45052. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45053. viewport->updateComponents();
  45054. if (rootItem != 0)
  45055. {
  45056. viewport->getViewedComponent()
  45057. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45058. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45059. }
  45060. else
  45061. {
  45062. viewport->getViewedComponent()->setSize (0, 0);
  45063. }
  45064. }
  45065. }
  45066. class TreeView::InsertPointHighlight : public Component
  45067. {
  45068. public:
  45069. InsertPointHighlight()
  45070. : lastItem (0)
  45071. {
  45072. setSize (100, 12);
  45073. setAlwaysOnTop (true);
  45074. setInterceptsMouseClicks (false, false);
  45075. }
  45076. ~InsertPointHighlight() {}
  45077. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45078. {
  45079. lastItem = item;
  45080. lastIndex = insertIndex;
  45081. const int offset = getHeight() / 2;
  45082. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45083. }
  45084. void paint (Graphics& g)
  45085. {
  45086. Path p;
  45087. const float h = (float) getHeight();
  45088. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45089. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45090. p.lineTo ((float) getWidth(), h / 2.0f);
  45091. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45092. g.strokePath (p, PathStrokeType (2.0f));
  45093. }
  45094. TreeViewItem* lastItem;
  45095. int lastIndex;
  45096. private:
  45097. InsertPointHighlight (const InsertPointHighlight&);
  45098. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45099. };
  45100. class TreeView::TargetGroupHighlight : public Component
  45101. {
  45102. public:
  45103. TargetGroupHighlight()
  45104. {
  45105. setAlwaysOnTop (true);
  45106. setInterceptsMouseClicks (false, false);
  45107. }
  45108. ~TargetGroupHighlight() {}
  45109. void setTargetPosition (TreeViewItem* const item) throw()
  45110. {
  45111. Rectangle<int> r (item->getItemPosition (true));
  45112. r.setHeight (item->getItemHeight());
  45113. setBounds (r);
  45114. }
  45115. void paint (Graphics& g)
  45116. {
  45117. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45118. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45119. }
  45120. private:
  45121. TargetGroupHighlight (const TargetGroupHighlight&);
  45122. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45123. };
  45124. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45125. {
  45126. beginDragAutoRepeat (1000 / 30);
  45127. if (dragInsertPointHighlight == 0)
  45128. {
  45129. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45130. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45131. }
  45132. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45133. dragTargetGroupHighlight->setTargetPosition (item);
  45134. }
  45135. void TreeView::hideDragHighlight() throw()
  45136. {
  45137. dragInsertPointHighlight = 0;
  45138. dragTargetGroupHighlight = 0;
  45139. }
  45140. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45141. const StringArray& files, const String& sourceDescription,
  45142. Component* sourceComponent) const throw()
  45143. {
  45144. insertIndex = 0;
  45145. TreeViewItem* item = getItemAt (y);
  45146. if (item == 0)
  45147. return 0;
  45148. Rectangle<int> itemPos (item->getItemPosition (true));
  45149. insertIndex = item->getIndexInParent();
  45150. const int oldY = y;
  45151. y = itemPos.getY();
  45152. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45153. {
  45154. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45155. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45156. {
  45157. // Check if we're trying to drag into an empty group item..
  45158. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45159. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45160. {
  45161. insertIndex = 0;
  45162. x = itemPos.getX() + getIndentSize();
  45163. y = itemPos.getBottom();
  45164. return item;
  45165. }
  45166. }
  45167. }
  45168. if (oldY > itemPos.getCentreY())
  45169. {
  45170. y += item->getItemHeight();
  45171. while (item->isLastOfSiblings() && item->parentItem != 0
  45172. && item->parentItem->parentItem != 0)
  45173. {
  45174. if (x > itemPos.getX())
  45175. break;
  45176. item = item->parentItem;
  45177. itemPos = item->getItemPosition (true);
  45178. insertIndex = item->getIndexInParent();
  45179. }
  45180. ++insertIndex;
  45181. }
  45182. x = itemPos.getX();
  45183. return item->parentItem;
  45184. }
  45185. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45186. {
  45187. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45188. int insertIndex;
  45189. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45190. if (item != 0)
  45191. {
  45192. if (scrolled || dragInsertPointHighlight == 0
  45193. || dragInsertPointHighlight->lastItem != item
  45194. || dragInsertPointHighlight->lastIndex != insertIndex)
  45195. {
  45196. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45197. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45198. showDragHighlight (item, insertIndex, x, y);
  45199. else
  45200. hideDragHighlight();
  45201. }
  45202. }
  45203. else
  45204. {
  45205. hideDragHighlight();
  45206. }
  45207. }
  45208. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45209. {
  45210. hideDragHighlight();
  45211. int insertIndex;
  45212. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45213. if (item != 0)
  45214. {
  45215. if (files.size() > 0)
  45216. {
  45217. if (item->isInterestedInFileDrag (files))
  45218. item->filesDropped (files, insertIndex);
  45219. }
  45220. else
  45221. {
  45222. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45223. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45224. }
  45225. }
  45226. }
  45227. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45228. {
  45229. return true;
  45230. }
  45231. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45232. {
  45233. fileDragMove (files, x, y);
  45234. }
  45235. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45236. {
  45237. handleDrag (files, String::empty, 0, x, y);
  45238. }
  45239. void TreeView::fileDragExit (const StringArray&)
  45240. {
  45241. hideDragHighlight();
  45242. }
  45243. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45244. {
  45245. handleDrop (files, String::empty, 0, x, y);
  45246. }
  45247. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45248. {
  45249. return true;
  45250. }
  45251. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45252. {
  45253. itemDragMove (sourceDescription, sourceComponent, x, y);
  45254. }
  45255. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45256. {
  45257. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45258. }
  45259. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45260. {
  45261. hideDragHighlight();
  45262. }
  45263. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45264. {
  45265. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45266. }
  45267. enum TreeViewOpenness
  45268. {
  45269. opennessDefault = 0,
  45270. opennessClosed = 1,
  45271. opennessOpen = 2
  45272. };
  45273. TreeViewItem::TreeViewItem()
  45274. : ownerView (0),
  45275. parentItem (0),
  45276. y (0),
  45277. itemHeight (0),
  45278. totalHeight (0),
  45279. selected (false),
  45280. redrawNeeded (true),
  45281. drawLinesInside (true),
  45282. drawsInLeftMargin (false),
  45283. openness (opennessDefault)
  45284. {
  45285. static int nextUID = 0;
  45286. uid = nextUID++;
  45287. }
  45288. TreeViewItem::~TreeViewItem()
  45289. {
  45290. }
  45291. const String TreeViewItem::getUniqueName() const
  45292. {
  45293. return String::empty;
  45294. }
  45295. void TreeViewItem::itemOpennessChanged (bool)
  45296. {
  45297. }
  45298. int TreeViewItem::getNumSubItems() const throw()
  45299. {
  45300. return subItems.size();
  45301. }
  45302. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45303. {
  45304. return subItems [index];
  45305. }
  45306. void TreeViewItem::clearSubItems()
  45307. {
  45308. if (subItems.size() > 0)
  45309. {
  45310. if (ownerView != 0)
  45311. {
  45312. const ScopedLock sl (ownerView->nodeAlterationLock);
  45313. subItems.clear();
  45314. treeHasChanged();
  45315. }
  45316. else
  45317. {
  45318. subItems.clear();
  45319. }
  45320. }
  45321. }
  45322. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45323. {
  45324. if (newItem != 0)
  45325. {
  45326. newItem->parentItem = this;
  45327. newItem->setOwnerView (ownerView);
  45328. newItem->y = 0;
  45329. newItem->itemHeight = newItem->getItemHeight();
  45330. newItem->totalHeight = 0;
  45331. newItem->itemWidth = newItem->getItemWidth();
  45332. newItem->totalWidth = 0;
  45333. if (ownerView != 0)
  45334. {
  45335. const ScopedLock sl (ownerView->nodeAlterationLock);
  45336. subItems.insert (insertPosition, newItem);
  45337. treeHasChanged();
  45338. if (newItem->isOpen())
  45339. newItem->itemOpennessChanged (true);
  45340. }
  45341. else
  45342. {
  45343. subItems.insert (insertPosition, newItem);
  45344. if (newItem->isOpen())
  45345. newItem->itemOpennessChanged (true);
  45346. }
  45347. }
  45348. }
  45349. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45350. {
  45351. if (ownerView != 0)
  45352. {
  45353. const ScopedLock sl (ownerView->nodeAlterationLock);
  45354. if (((unsigned int) index) < (unsigned int) subItems.size())
  45355. {
  45356. subItems.remove (index, deleteItem);
  45357. treeHasChanged();
  45358. }
  45359. }
  45360. else
  45361. {
  45362. subItems.remove (index, deleteItem);
  45363. }
  45364. }
  45365. bool TreeViewItem::isOpen() const throw()
  45366. {
  45367. if (openness == opennessDefault)
  45368. return ownerView != 0 && ownerView->defaultOpenness;
  45369. else
  45370. return openness == opennessOpen;
  45371. }
  45372. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45373. {
  45374. if (isOpen() != shouldBeOpen)
  45375. {
  45376. openness = shouldBeOpen ? opennessOpen
  45377. : opennessClosed;
  45378. treeHasChanged();
  45379. itemOpennessChanged (isOpen());
  45380. }
  45381. }
  45382. bool TreeViewItem::isSelected() const throw()
  45383. {
  45384. return selected;
  45385. }
  45386. void TreeViewItem::deselectAllRecursively()
  45387. {
  45388. setSelected (false, false);
  45389. for (int i = 0; i < subItems.size(); ++i)
  45390. subItems.getUnchecked(i)->deselectAllRecursively();
  45391. }
  45392. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45393. const bool deselectOtherItemsFirst)
  45394. {
  45395. if (shouldBeSelected && ! canBeSelected())
  45396. return;
  45397. if (deselectOtherItemsFirst)
  45398. getTopLevelItem()->deselectAllRecursively();
  45399. if (shouldBeSelected != selected)
  45400. {
  45401. selected = shouldBeSelected;
  45402. if (ownerView != 0)
  45403. ownerView->repaint();
  45404. itemSelectionChanged (shouldBeSelected);
  45405. }
  45406. }
  45407. void TreeViewItem::paintItem (Graphics&, int, int)
  45408. {
  45409. }
  45410. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45411. {
  45412. ownerView->getLookAndFeel()
  45413. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45414. }
  45415. void TreeViewItem::itemClicked (const MouseEvent&)
  45416. {
  45417. }
  45418. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45419. {
  45420. if (mightContainSubItems())
  45421. setOpen (! isOpen());
  45422. }
  45423. void TreeViewItem::itemSelectionChanged (bool)
  45424. {
  45425. }
  45426. const String TreeViewItem::getTooltip()
  45427. {
  45428. return String::empty;
  45429. }
  45430. const String TreeViewItem::getDragSourceDescription()
  45431. {
  45432. return String::empty;
  45433. }
  45434. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45435. {
  45436. return false;
  45437. }
  45438. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45439. {
  45440. }
  45441. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45442. {
  45443. return false;
  45444. }
  45445. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45446. {
  45447. }
  45448. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45449. {
  45450. const int indentX = getIndentX();
  45451. int width = itemWidth;
  45452. if (ownerView != 0 && width < 0)
  45453. width = ownerView->viewport->getViewWidth() - indentX;
  45454. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45455. if (relativeToTreeViewTopLeft)
  45456. r -= ownerView->viewport->getViewPosition();
  45457. return r;
  45458. }
  45459. void TreeViewItem::treeHasChanged() const throw()
  45460. {
  45461. if (ownerView != 0)
  45462. ownerView->itemsChanged();
  45463. }
  45464. void TreeViewItem::repaintItem() const
  45465. {
  45466. if (ownerView != 0 && areAllParentsOpen())
  45467. {
  45468. Rectangle<int> r (getItemPosition (true));
  45469. r.setLeft (0);
  45470. ownerView->viewport->repaint (r);
  45471. }
  45472. }
  45473. bool TreeViewItem::areAllParentsOpen() const throw()
  45474. {
  45475. return parentItem == 0
  45476. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45477. }
  45478. void TreeViewItem::updatePositions (int newY)
  45479. {
  45480. y = newY;
  45481. itemHeight = getItemHeight();
  45482. totalHeight = itemHeight;
  45483. itemWidth = getItemWidth();
  45484. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45485. if (isOpen())
  45486. {
  45487. newY += totalHeight;
  45488. for (int i = 0; i < subItems.size(); ++i)
  45489. {
  45490. TreeViewItem* const ti = subItems.getUnchecked(i);
  45491. ti->updatePositions (newY);
  45492. newY += ti->totalHeight;
  45493. totalHeight += ti->totalHeight;
  45494. totalWidth = jmax (totalWidth, ti->totalWidth);
  45495. }
  45496. }
  45497. }
  45498. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45499. {
  45500. TreeViewItem* result = this;
  45501. TreeViewItem* item = this;
  45502. while (item->parentItem != 0)
  45503. {
  45504. item = item->parentItem;
  45505. if (! item->isOpen())
  45506. result = item;
  45507. }
  45508. return result;
  45509. }
  45510. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45511. {
  45512. ownerView = newOwner;
  45513. for (int i = subItems.size(); --i >= 0;)
  45514. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45515. }
  45516. int TreeViewItem::getIndentX() const throw()
  45517. {
  45518. const int indentWidth = ownerView->getIndentSize();
  45519. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45520. if (! ownerView->openCloseButtonsVisible)
  45521. x -= indentWidth;
  45522. TreeViewItem* p = parentItem;
  45523. while (p != 0)
  45524. {
  45525. x += indentWidth;
  45526. p = p->parentItem;
  45527. }
  45528. return x;
  45529. }
  45530. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45531. {
  45532. drawsInLeftMargin = canDrawInLeftMargin;
  45533. }
  45534. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45535. {
  45536. jassert (ownerView != 0);
  45537. if (ownerView == 0)
  45538. return;
  45539. const int indent = getIndentX();
  45540. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45541. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45542. const float halfH = itemHeight * 0.5f;
  45543. int depth = 0;
  45544. TreeViewItem* p = parentItem;
  45545. while (p != 0)
  45546. {
  45547. ++depth;
  45548. p = p->parentItem;
  45549. }
  45550. if (! ownerView->rootItemVisible)
  45551. --depth;
  45552. const int indentWidth = ownerView->getIndentSize();
  45553. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45554. {
  45555. float x = (depth + 0.5f) * indentWidth;
  45556. if (depth >= 0)
  45557. {
  45558. if (parentItem != 0 && parentItem->drawLinesInside)
  45559. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45560. if ((parentItem != 0 && parentItem->drawLinesInside)
  45561. || (parentItem == 0 && drawLinesInside))
  45562. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45563. }
  45564. p = parentItem;
  45565. int d = depth;
  45566. while (p != 0 && --d >= 0)
  45567. {
  45568. x -= (float) indentWidth;
  45569. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45570. && ! p->isLastOfSiblings())
  45571. {
  45572. g.drawLine (x, 0, x, (float) itemHeight);
  45573. }
  45574. p = p->parentItem;
  45575. }
  45576. if (mightContainSubItems())
  45577. {
  45578. g.saveState();
  45579. g.setOrigin (depth * indentWidth, 0);
  45580. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45581. paintOpenCloseButton (g, indentWidth, itemHeight,
  45582. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45583. ->isMouseOverButton (this));
  45584. g.restoreState();
  45585. }
  45586. }
  45587. {
  45588. g.saveState();
  45589. g.setOrigin (indent, 0);
  45590. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45591. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45592. paintItem (g, itemW, itemHeight);
  45593. g.restoreState();
  45594. }
  45595. if (isOpen())
  45596. {
  45597. const Rectangle<int> clip (g.getClipBounds());
  45598. for (int i = 0; i < subItems.size(); ++i)
  45599. {
  45600. TreeViewItem* const ti = subItems.getUnchecked(i);
  45601. const int relY = ti->y - y;
  45602. if (relY >= clip.getBottom())
  45603. break;
  45604. if (relY + ti->totalHeight >= clip.getY())
  45605. {
  45606. g.saveState();
  45607. g.setOrigin (0, relY);
  45608. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45609. ti->paintRecursively (g, width);
  45610. g.restoreState();
  45611. }
  45612. }
  45613. }
  45614. }
  45615. bool TreeViewItem::isLastOfSiblings() const throw()
  45616. {
  45617. return parentItem == 0
  45618. || parentItem->subItems.getLast() == this;
  45619. }
  45620. int TreeViewItem::getIndexInParent() const throw()
  45621. {
  45622. if (parentItem == 0)
  45623. return 0;
  45624. return parentItem->subItems.indexOf (this);
  45625. }
  45626. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45627. {
  45628. return (parentItem == 0) ? this
  45629. : parentItem->getTopLevelItem();
  45630. }
  45631. int TreeViewItem::getNumRows() const throw()
  45632. {
  45633. int num = 1;
  45634. if (isOpen())
  45635. {
  45636. for (int i = subItems.size(); --i >= 0;)
  45637. num += subItems.getUnchecked(i)->getNumRows();
  45638. }
  45639. return num;
  45640. }
  45641. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45642. {
  45643. if (index == 0)
  45644. return this;
  45645. if (index > 0 && isOpen())
  45646. {
  45647. --index;
  45648. for (int i = 0; i < subItems.size(); ++i)
  45649. {
  45650. TreeViewItem* const item = subItems.getUnchecked(i);
  45651. if (index == 0)
  45652. return item;
  45653. const int numRows = item->getNumRows();
  45654. if (numRows > index)
  45655. return item->getItemOnRow (index);
  45656. index -= numRows;
  45657. }
  45658. }
  45659. return 0;
  45660. }
  45661. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45662. {
  45663. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45664. {
  45665. const int h = itemHeight;
  45666. if (targetY < h)
  45667. return this;
  45668. if (isOpen())
  45669. {
  45670. targetY -= h;
  45671. for (int i = 0; i < subItems.size(); ++i)
  45672. {
  45673. TreeViewItem* const ti = subItems.getUnchecked(i);
  45674. if (targetY < ti->totalHeight)
  45675. return ti->findItemRecursively (targetY);
  45676. targetY -= ti->totalHeight;
  45677. }
  45678. }
  45679. }
  45680. return 0;
  45681. }
  45682. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45683. {
  45684. int total = 0;
  45685. if (isSelected())
  45686. ++total;
  45687. for (int i = subItems.size(); --i >= 0;)
  45688. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45689. return total;
  45690. }
  45691. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45692. {
  45693. if (isSelected())
  45694. {
  45695. if (index == 0)
  45696. return this;
  45697. --index;
  45698. }
  45699. if (index >= 0)
  45700. {
  45701. for (int i = 0; i < subItems.size(); ++i)
  45702. {
  45703. TreeViewItem* const item = subItems.getUnchecked(i);
  45704. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45705. if (found != 0)
  45706. return found;
  45707. index -= item->countSelectedItemsRecursively();
  45708. }
  45709. }
  45710. return 0;
  45711. }
  45712. int TreeViewItem::getRowNumberInTree() const throw()
  45713. {
  45714. if (parentItem != 0 && ownerView != 0)
  45715. {
  45716. int n = 1 + parentItem->getRowNumberInTree();
  45717. int ourIndex = parentItem->subItems.indexOf (this);
  45718. jassert (ourIndex >= 0);
  45719. while (--ourIndex >= 0)
  45720. n += parentItem->subItems [ourIndex]->getNumRows();
  45721. if (parentItem->parentItem == 0
  45722. && ! ownerView->rootItemVisible)
  45723. --n;
  45724. return n;
  45725. }
  45726. else
  45727. {
  45728. return 0;
  45729. }
  45730. }
  45731. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45732. {
  45733. drawLinesInside = drawLines;
  45734. }
  45735. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45736. {
  45737. if (recurse && isOpen() && subItems.size() > 0)
  45738. return subItems [0];
  45739. if (parentItem != 0)
  45740. {
  45741. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45742. if (nextIndex >= parentItem->subItems.size())
  45743. return parentItem->getNextVisibleItem (false);
  45744. return parentItem->subItems [nextIndex];
  45745. }
  45746. return 0;
  45747. }
  45748. const String TreeViewItem::getItemIdentifierString() const
  45749. {
  45750. String s;
  45751. if (parentItem != 0)
  45752. s = parentItem->getItemIdentifierString();
  45753. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45754. }
  45755. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45756. {
  45757. const String thisId (getUniqueName());
  45758. if (thisId == identifierString)
  45759. return this;
  45760. if (identifierString.startsWith (thisId + "/"))
  45761. {
  45762. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45763. bool wasOpen = isOpen();
  45764. setOpen (true);
  45765. for (int i = subItems.size(); --i >= 0;)
  45766. {
  45767. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45768. if (item != 0)
  45769. return item;
  45770. }
  45771. setOpen (wasOpen);
  45772. }
  45773. return 0;
  45774. }
  45775. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45776. {
  45777. if (e.hasTagName ("CLOSED"))
  45778. {
  45779. setOpen (false);
  45780. }
  45781. else if (e.hasTagName ("OPEN"))
  45782. {
  45783. setOpen (true);
  45784. forEachXmlChildElement (e, n)
  45785. {
  45786. const String id (n->getStringAttribute ("id"));
  45787. for (int i = 0; i < subItems.size(); ++i)
  45788. {
  45789. TreeViewItem* const ti = subItems.getUnchecked(i);
  45790. if (ti->getUniqueName() == id)
  45791. {
  45792. ti->restoreOpennessState (*n);
  45793. break;
  45794. }
  45795. }
  45796. }
  45797. }
  45798. }
  45799. XmlElement* TreeViewItem::getOpennessState() const throw()
  45800. {
  45801. const String name (getUniqueName());
  45802. if (name.isNotEmpty())
  45803. {
  45804. XmlElement* e;
  45805. if (isOpen())
  45806. {
  45807. e = new XmlElement ("OPEN");
  45808. for (int i = 0; i < subItems.size(); ++i)
  45809. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45810. }
  45811. else
  45812. {
  45813. e = new XmlElement ("CLOSED");
  45814. }
  45815. e->setAttribute ("id", name);
  45816. return e;
  45817. }
  45818. else
  45819. {
  45820. // trying to save the openness for an element that has no name - this won't
  45821. // work because it needs the names to identify what to open.
  45822. jassertfalse;
  45823. }
  45824. return 0;
  45825. }
  45826. END_JUCE_NAMESPACE
  45827. /*** End of inlined file: juce_TreeView.cpp ***/
  45828. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45829. BEGIN_JUCE_NAMESPACE
  45830. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45831. : fileList (listToShow)
  45832. {
  45833. }
  45834. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45835. {
  45836. }
  45837. FileBrowserListener::~FileBrowserListener()
  45838. {
  45839. }
  45840. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45841. {
  45842. listeners.add (listener);
  45843. }
  45844. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45845. {
  45846. listeners.remove (listener);
  45847. }
  45848. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45849. {
  45850. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45851. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45852. }
  45853. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45854. {
  45855. if (fileList.getDirectory().exists())
  45856. {
  45857. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45858. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45859. }
  45860. }
  45861. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45862. {
  45863. if (fileList.getDirectory().exists())
  45864. {
  45865. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45866. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45867. }
  45868. }
  45869. END_JUCE_NAMESPACE
  45870. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45871. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45872. BEGIN_JUCE_NAMESPACE
  45873. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45874. TimeSliceThread& thread_)
  45875. : fileFilter (fileFilter_),
  45876. thread (thread_),
  45877. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45878. fileFindHandle (0),
  45879. shouldStop (true)
  45880. {
  45881. }
  45882. DirectoryContentsList::~DirectoryContentsList()
  45883. {
  45884. clear();
  45885. }
  45886. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45887. {
  45888. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45889. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45890. }
  45891. bool DirectoryContentsList::ignoresHiddenFiles() const
  45892. {
  45893. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45894. }
  45895. const File& DirectoryContentsList::getDirectory() const
  45896. {
  45897. return root;
  45898. }
  45899. void DirectoryContentsList::setDirectory (const File& directory,
  45900. const bool includeDirectories,
  45901. const bool includeFiles)
  45902. {
  45903. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45904. if (directory != root)
  45905. {
  45906. clear();
  45907. root = directory;
  45908. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45909. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45910. }
  45911. int newFlags = fileTypeFlags;
  45912. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45913. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45914. setTypeFlags (newFlags);
  45915. }
  45916. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45917. {
  45918. if (fileTypeFlags != newFlags)
  45919. {
  45920. fileTypeFlags = newFlags;
  45921. refresh();
  45922. }
  45923. }
  45924. void DirectoryContentsList::clear()
  45925. {
  45926. shouldStop = true;
  45927. thread.removeTimeSliceClient (this);
  45928. fileFindHandle = 0;
  45929. if (files.size() > 0)
  45930. {
  45931. files.clear();
  45932. changed();
  45933. }
  45934. }
  45935. void DirectoryContentsList::refresh()
  45936. {
  45937. clear();
  45938. if (root.isDirectory())
  45939. {
  45940. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45941. shouldStop = false;
  45942. thread.addTimeSliceClient (this);
  45943. }
  45944. }
  45945. int DirectoryContentsList::getNumFiles() const
  45946. {
  45947. return files.size();
  45948. }
  45949. bool DirectoryContentsList::getFileInfo (const int index,
  45950. FileInfo& result) const
  45951. {
  45952. const ScopedLock sl (fileListLock);
  45953. const FileInfo* const info = files [index];
  45954. if (info != 0)
  45955. {
  45956. result = *info;
  45957. return true;
  45958. }
  45959. return false;
  45960. }
  45961. const File DirectoryContentsList::getFile (const int index) const
  45962. {
  45963. const ScopedLock sl (fileListLock);
  45964. const FileInfo* const info = files [index];
  45965. if (info != 0)
  45966. return root.getChildFile (info->filename);
  45967. return File::nonexistent;
  45968. }
  45969. bool DirectoryContentsList::isStillLoading() const
  45970. {
  45971. return fileFindHandle != 0;
  45972. }
  45973. void DirectoryContentsList::changed()
  45974. {
  45975. sendChangeMessage (this);
  45976. }
  45977. bool DirectoryContentsList::useTimeSlice()
  45978. {
  45979. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45980. bool hasChanged = false;
  45981. for (int i = 100; --i >= 0;)
  45982. {
  45983. if (! checkNextFile (hasChanged))
  45984. {
  45985. if (hasChanged)
  45986. changed();
  45987. return false;
  45988. }
  45989. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45990. break;
  45991. }
  45992. if (hasChanged)
  45993. changed();
  45994. return true;
  45995. }
  45996. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45997. {
  45998. if (fileFindHandle != 0)
  45999. {
  46000. bool fileFoundIsDir, isHidden, isReadOnly;
  46001. int64 fileSize;
  46002. Time modTime, creationTime;
  46003. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46004. &modTime, &creationTime, &isReadOnly))
  46005. {
  46006. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46007. fileSize, modTime, creationTime, isReadOnly))
  46008. {
  46009. hasChanged = true;
  46010. }
  46011. return true;
  46012. }
  46013. else
  46014. {
  46015. fileFindHandle = 0;
  46016. }
  46017. }
  46018. return false;
  46019. }
  46020. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46021. const DirectoryContentsList::FileInfo* const second)
  46022. {
  46023. #if JUCE_WINDOWS
  46024. if (first->isDirectory != second->isDirectory)
  46025. return first->isDirectory ? -1 : 1;
  46026. #endif
  46027. return first->filename.compareIgnoreCase (second->filename);
  46028. }
  46029. bool DirectoryContentsList::addFile (const File& file,
  46030. const bool isDir,
  46031. const int64 fileSize,
  46032. const Time& modTime,
  46033. const Time& creationTime,
  46034. const bool isReadOnly)
  46035. {
  46036. if (fileFilter == 0
  46037. || ((! isDir) && fileFilter->isFileSuitable (file))
  46038. || (isDir && fileFilter->isDirectorySuitable (file)))
  46039. {
  46040. ScopedPointer <FileInfo> info (new FileInfo());
  46041. info->filename = file.getFileName();
  46042. info->fileSize = fileSize;
  46043. info->modificationTime = modTime;
  46044. info->creationTime = creationTime;
  46045. info->isDirectory = isDir;
  46046. info->isReadOnly = isReadOnly;
  46047. const ScopedLock sl (fileListLock);
  46048. for (int i = files.size(); --i >= 0;)
  46049. if (files.getUnchecked(i)->filename == info->filename)
  46050. return false;
  46051. files.addSorted (*this, info.release());
  46052. return true;
  46053. }
  46054. return false;
  46055. }
  46056. END_JUCE_NAMESPACE
  46057. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46058. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46059. BEGIN_JUCE_NAMESPACE
  46060. FileBrowserComponent::FileBrowserComponent (int flags_,
  46061. const File& initialFileOrDirectory,
  46062. const FileFilter* fileFilter_,
  46063. FilePreviewComponent* previewComp_)
  46064. : FileFilter (String::empty),
  46065. fileFilter (fileFilter_),
  46066. flags (flags_),
  46067. previewComp (previewComp_),
  46068. thread ("Juce FileBrowser")
  46069. {
  46070. // You need to specify one or other of the open/save flags..
  46071. jassert ((flags & (saveMode | openMode)) != 0);
  46072. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46073. // You need to specify at least one of these flags..
  46074. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46075. String filename;
  46076. if (initialFileOrDirectory == File::nonexistent)
  46077. {
  46078. currentRoot = File::getCurrentWorkingDirectory();
  46079. }
  46080. else if (initialFileOrDirectory.isDirectory())
  46081. {
  46082. currentRoot = initialFileOrDirectory;
  46083. }
  46084. else
  46085. {
  46086. chosenFiles.add (initialFileOrDirectory);
  46087. currentRoot = initialFileOrDirectory.getParentDirectory();
  46088. filename = initialFileOrDirectory.getFileName();
  46089. }
  46090. fileList = new DirectoryContentsList (this, thread);
  46091. if ((flags & useTreeView) != 0)
  46092. {
  46093. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46094. if ((flags & canSelectMultipleItems) != 0)
  46095. tree->setMultiSelectEnabled (true);
  46096. addAndMakeVisible (tree);
  46097. fileListComponent = tree;
  46098. }
  46099. else
  46100. {
  46101. FileListComponent* const list = new FileListComponent (*fileList);
  46102. list->setOutlineThickness (1);
  46103. if ((flags & canSelectMultipleItems) != 0)
  46104. list->setMultipleSelectionEnabled (true);
  46105. addAndMakeVisible (list);
  46106. fileListComponent = list;
  46107. }
  46108. fileListComponent->addListener (this);
  46109. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46110. currentPathBox->setEditableText (true);
  46111. StringArray rootNames, rootPaths;
  46112. const BigInteger separators (getRoots (rootNames, rootPaths));
  46113. for (int i = 0; i < rootNames.size(); ++i)
  46114. {
  46115. if (separators [i])
  46116. currentPathBox->addSeparator();
  46117. currentPathBox->addItem (rootNames[i], i + 1);
  46118. }
  46119. currentPathBox->addSeparator();
  46120. currentPathBox->addListener (this);
  46121. addAndMakeVisible (filenameBox = new TextEditor());
  46122. filenameBox->setMultiLine (false);
  46123. filenameBox->setSelectAllWhenFocused (true);
  46124. filenameBox->setText (filename, false);
  46125. filenameBox->addListener (this);
  46126. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46127. Label* label = new Label ("f", TRANS("file:"));
  46128. addAndMakeVisible (label);
  46129. label->attachToComponent (filenameBox, true);
  46130. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46131. goUpButton->addButtonListener (this);
  46132. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46133. if (previewComp != 0)
  46134. addAndMakeVisible (previewComp);
  46135. setRoot (currentRoot);
  46136. thread.startThread (4);
  46137. }
  46138. FileBrowserComponent::~FileBrowserComponent()
  46139. {
  46140. if (previewComp != 0)
  46141. removeChildComponent (previewComp);
  46142. deleteAllChildren();
  46143. fileList = 0;
  46144. thread.stopThread (10000);
  46145. }
  46146. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46147. {
  46148. listeners.add (newListener);
  46149. }
  46150. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46151. {
  46152. listeners.remove (listener);
  46153. }
  46154. bool FileBrowserComponent::isSaveMode() const throw()
  46155. {
  46156. return (flags & saveMode) != 0;
  46157. }
  46158. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46159. {
  46160. if (chosenFiles.size() == 0 && currentFileIsValid())
  46161. return 1;
  46162. return chosenFiles.size();
  46163. }
  46164. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46165. {
  46166. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46167. return currentRoot;
  46168. if (! filenameBox->isReadOnly())
  46169. return currentRoot.getChildFile (filenameBox->getText());
  46170. return chosenFiles[index];
  46171. }
  46172. bool FileBrowserComponent::currentFileIsValid() const
  46173. {
  46174. if (isSaveMode())
  46175. return ! getSelectedFile (0).isDirectory();
  46176. else
  46177. return getSelectedFile (0).exists();
  46178. }
  46179. const File FileBrowserComponent::getHighlightedFile() const throw()
  46180. {
  46181. return fileListComponent->getSelectedFile (0);
  46182. }
  46183. void FileBrowserComponent::deselectAllFiles()
  46184. {
  46185. fileListComponent->deselectAllFiles();
  46186. }
  46187. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46188. {
  46189. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46190. : false;
  46191. }
  46192. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46193. {
  46194. return true;
  46195. }
  46196. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46197. {
  46198. if (f.isDirectory())
  46199. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46200. return (flags & canSelectFiles) != 0 && f.exists()
  46201. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46202. }
  46203. const File FileBrowserComponent::getRoot() const
  46204. {
  46205. return currentRoot;
  46206. }
  46207. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46208. {
  46209. if (currentRoot != newRootDirectory)
  46210. {
  46211. fileListComponent->scrollToTop();
  46212. String path (newRootDirectory.getFullPathName());
  46213. if (path.isEmpty())
  46214. path = File::separatorString;
  46215. StringArray rootNames, rootPaths;
  46216. getRoots (rootNames, rootPaths);
  46217. if (! rootPaths.contains (path, true))
  46218. {
  46219. bool alreadyListed = false;
  46220. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46221. {
  46222. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46223. {
  46224. alreadyListed = true;
  46225. break;
  46226. }
  46227. }
  46228. if (! alreadyListed)
  46229. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46230. }
  46231. }
  46232. currentRoot = newRootDirectory;
  46233. fileList->setDirectory (currentRoot, true, true);
  46234. String currentRootName (currentRoot.getFullPathName());
  46235. if (currentRootName.isEmpty())
  46236. currentRootName = File::separatorString;
  46237. currentPathBox->setText (currentRootName, true);
  46238. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46239. && currentRoot.getParentDirectory() != currentRoot);
  46240. }
  46241. void FileBrowserComponent::goUp()
  46242. {
  46243. setRoot (getRoot().getParentDirectory());
  46244. }
  46245. void FileBrowserComponent::refresh()
  46246. {
  46247. fileList->refresh();
  46248. }
  46249. const String FileBrowserComponent::getActionVerb() const
  46250. {
  46251. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46252. }
  46253. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46254. {
  46255. return previewComp;
  46256. }
  46257. void FileBrowserComponent::resized()
  46258. {
  46259. getLookAndFeel()
  46260. .layoutFileBrowserComponent (*this, fileListComponent,
  46261. previewComp, currentPathBox,
  46262. filenameBox, goUpButton);
  46263. }
  46264. void FileBrowserComponent::sendListenerChangeMessage()
  46265. {
  46266. Component::BailOutChecker checker (this);
  46267. if (previewComp != 0)
  46268. previewComp->selectedFileChanged (getSelectedFile (0));
  46269. // You shouldn't delete the browser when the file gets changed!
  46270. jassert (! checker.shouldBailOut());
  46271. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46272. }
  46273. void FileBrowserComponent::selectionChanged()
  46274. {
  46275. StringArray newFilenames;
  46276. bool resetChosenFiles = true;
  46277. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46278. {
  46279. const File f (fileListComponent->getSelectedFile (i));
  46280. if (isFileOrDirSuitable (f))
  46281. {
  46282. if (resetChosenFiles)
  46283. {
  46284. chosenFiles.clear();
  46285. resetChosenFiles = false;
  46286. }
  46287. chosenFiles.add (f);
  46288. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46289. }
  46290. }
  46291. if (newFilenames.size() > 0)
  46292. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46293. sendListenerChangeMessage();
  46294. }
  46295. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46296. {
  46297. Component::BailOutChecker checker (this);
  46298. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46299. }
  46300. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46301. {
  46302. if (f.isDirectory())
  46303. {
  46304. setRoot (f);
  46305. if ((flags & canSelectDirectories) != 0)
  46306. filenameBox->setText (String::empty);
  46307. }
  46308. else
  46309. {
  46310. Component::BailOutChecker checker (this);
  46311. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46312. }
  46313. }
  46314. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46315. {
  46316. (void) key;
  46317. #if JUCE_LINUX || JUCE_WINDOWS
  46318. if (key.getModifiers().isCommandDown()
  46319. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46320. {
  46321. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46322. fileList->refresh();
  46323. return true;
  46324. }
  46325. #endif
  46326. return false;
  46327. }
  46328. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46329. {
  46330. sendListenerChangeMessage();
  46331. }
  46332. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46333. {
  46334. if (filenameBox->getText().containsChar (File::separator))
  46335. {
  46336. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46337. if (f.isDirectory())
  46338. {
  46339. setRoot (f);
  46340. chosenFiles.clear();
  46341. filenameBox->setText (String::empty);
  46342. }
  46343. else
  46344. {
  46345. setRoot (f.getParentDirectory());
  46346. chosenFiles.clear();
  46347. chosenFiles.add (f);
  46348. filenameBox->setText (f.getFileName());
  46349. }
  46350. }
  46351. else
  46352. {
  46353. fileDoubleClicked (getSelectedFile (0));
  46354. }
  46355. }
  46356. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46357. {
  46358. }
  46359. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46360. {
  46361. if (! isSaveMode())
  46362. selectionChanged();
  46363. }
  46364. void FileBrowserComponent::buttonClicked (Button*)
  46365. {
  46366. goUp();
  46367. }
  46368. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46369. {
  46370. const String newText (currentPathBox->getText().trim().unquoted());
  46371. if (newText.isNotEmpty())
  46372. {
  46373. const int index = currentPathBox->getSelectedId() - 1;
  46374. StringArray rootNames, rootPaths;
  46375. getRoots (rootNames, rootPaths);
  46376. if (rootPaths [index].isNotEmpty())
  46377. {
  46378. setRoot (File (rootPaths [index]));
  46379. }
  46380. else
  46381. {
  46382. File f (newText);
  46383. for (;;)
  46384. {
  46385. if (f.isDirectory())
  46386. {
  46387. setRoot (f);
  46388. break;
  46389. }
  46390. if (f.getParentDirectory() == f)
  46391. break;
  46392. f = f.getParentDirectory();
  46393. }
  46394. }
  46395. }
  46396. }
  46397. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46398. {
  46399. BigInteger separators;
  46400. #if JUCE_WINDOWS
  46401. Array<File> roots;
  46402. File::findFileSystemRoots (roots);
  46403. rootPaths.clear();
  46404. for (int i = 0; i < roots.size(); ++i)
  46405. {
  46406. const File& drive = roots.getReference(i);
  46407. String name (drive.getFullPathName());
  46408. rootPaths.add (name);
  46409. if (drive.isOnHardDisk())
  46410. {
  46411. String volume (drive.getVolumeLabel());
  46412. if (volume.isEmpty())
  46413. volume = TRANS("Hard Drive");
  46414. name << " [" << drive.getVolumeLabel() << ']';
  46415. }
  46416. else if (drive.isOnCDRomDrive())
  46417. {
  46418. name << TRANS(" [CD/DVD drive]");
  46419. }
  46420. rootNames.add (name);
  46421. }
  46422. separators.setBit (rootPaths.size());
  46423. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46424. rootNames.add ("Documents");
  46425. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46426. rootNames.add ("Desktop");
  46427. #endif
  46428. #if JUCE_MAC
  46429. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46430. rootNames.add ("Home folder");
  46431. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46432. rootNames.add ("Documents");
  46433. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46434. rootNames.add ("Desktop");
  46435. separators.setBit (rootPaths.size());
  46436. Array <File> volumes;
  46437. File vol ("/Volumes");
  46438. vol.findChildFiles (volumes, File::findDirectories, false);
  46439. for (int i = 0; i < volumes.size(); ++i)
  46440. {
  46441. const File& volume = volumes.getReference(i);
  46442. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46443. {
  46444. rootPaths.add (volume.getFullPathName());
  46445. rootNames.add (volume.getFileName());
  46446. }
  46447. }
  46448. #endif
  46449. #if JUCE_LINUX
  46450. rootPaths.add ("/");
  46451. rootNames.add ("/");
  46452. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46453. rootNames.add ("Home folder");
  46454. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46455. rootNames.add ("Desktop");
  46456. #endif
  46457. return separators;
  46458. }
  46459. END_JUCE_NAMESPACE
  46460. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46461. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46462. BEGIN_JUCE_NAMESPACE
  46463. FileChooser::FileChooser (const String& chooserBoxTitle,
  46464. const File& currentFileOrDirectory,
  46465. const String& fileFilters,
  46466. const bool useNativeDialogBox_)
  46467. : title (chooserBoxTitle),
  46468. filters (fileFilters),
  46469. startingFile (currentFileOrDirectory),
  46470. useNativeDialogBox (useNativeDialogBox_)
  46471. {
  46472. #if JUCE_LINUX
  46473. useNativeDialogBox = false;
  46474. #endif
  46475. if (! fileFilters.containsNonWhitespaceChars())
  46476. filters = "*";
  46477. }
  46478. FileChooser::~FileChooser()
  46479. {
  46480. }
  46481. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46482. {
  46483. return showDialog (false, true, false, false, false, previewComponent);
  46484. }
  46485. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46486. {
  46487. return showDialog (false, true, false, false, true, previewComponent);
  46488. }
  46489. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46490. {
  46491. return showDialog (true, true, false, false, true, previewComponent);
  46492. }
  46493. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46494. {
  46495. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46496. }
  46497. bool FileChooser::browseForDirectory()
  46498. {
  46499. return showDialog (true, false, false, false, false, 0);
  46500. }
  46501. const File FileChooser::getResult() const
  46502. {
  46503. // if you've used a multiple-file select, you should use the getResults() method
  46504. // to retrieve all the files that were chosen.
  46505. jassert (results.size() <= 1);
  46506. return results.getFirst();
  46507. }
  46508. const Array<File>& FileChooser::getResults() const
  46509. {
  46510. return results;
  46511. }
  46512. bool FileChooser::showDialog (const bool selectsDirectories,
  46513. const bool selectsFiles,
  46514. const bool isSave,
  46515. const bool warnAboutOverwritingExistingFiles,
  46516. const bool selectMultipleFiles,
  46517. FilePreviewComponent* const previewComponent)
  46518. {
  46519. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46520. results.clear();
  46521. // the preview component needs to be the right size before you pass it in here..
  46522. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46523. && previewComponent->getHeight() > 10));
  46524. #if JUCE_WINDOWS
  46525. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46526. #elif JUCE_MAC
  46527. if (useNativeDialogBox && (previewComponent == 0))
  46528. #else
  46529. if (false)
  46530. #endif
  46531. {
  46532. showPlatformDialog (results, title, startingFile, filters,
  46533. selectsDirectories, selectsFiles, isSave,
  46534. warnAboutOverwritingExistingFiles,
  46535. selectMultipleFiles,
  46536. previewComponent);
  46537. }
  46538. else
  46539. {
  46540. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46541. selectsDirectories ? "*" : String::empty,
  46542. String::empty);
  46543. int flags = isSave ? FileBrowserComponent::saveMode
  46544. : FileBrowserComponent::openMode;
  46545. if (selectsFiles)
  46546. flags |= FileBrowserComponent::canSelectFiles;
  46547. if (selectsDirectories)
  46548. {
  46549. flags |= FileBrowserComponent::canSelectDirectories;
  46550. if (! isSave)
  46551. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46552. }
  46553. if (selectMultipleFiles)
  46554. flags |= FileBrowserComponent::canSelectMultipleItems;
  46555. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46556. FileChooserDialogBox box (title, String::empty,
  46557. browserComponent,
  46558. warnAboutOverwritingExistingFiles,
  46559. browserComponent.findColour (AlertWindow::backgroundColourId));
  46560. if (box.show())
  46561. {
  46562. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46563. results.add (browserComponent.getSelectedFile (i));
  46564. }
  46565. }
  46566. if (previouslyFocused != 0)
  46567. previouslyFocused->grabKeyboardFocus();
  46568. return results.size() > 0;
  46569. }
  46570. FilePreviewComponent::FilePreviewComponent()
  46571. {
  46572. }
  46573. FilePreviewComponent::~FilePreviewComponent()
  46574. {
  46575. }
  46576. END_JUCE_NAMESPACE
  46577. /*** End of inlined file: juce_FileChooser.cpp ***/
  46578. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46579. BEGIN_JUCE_NAMESPACE
  46580. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46581. const String& instructions,
  46582. FileBrowserComponent& chooserComponent,
  46583. const bool warnAboutOverwritingExistingFiles_,
  46584. const Colour& backgroundColour)
  46585. : ResizableWindow (name, backgroundColour, true),
  46586. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46587. {
  46588. content = new ContentComponent();
  46589. content->setName (name);
  46590. content->instructions = instructions;
  46591. content->chooserComponent = &chooserComponent;
  46592. content->addAndMakeVisible (&chooserComponent);
  46593. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46594. content->addAndMakeVisible (content->okButton);
  46595. content->okButton->addButtonListener (this);
  46596. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46597. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46598. content->cancelButton = new TextButton (TRANS("Cancel"));
  46599. content->addAndMakeVisible (content->cancelButton);
  46600. content->cancelButton->addButtonListener (this);
  46601. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46602. setContentComponent (content);
  46603. setResizable (true, true);
  46604. setResizeLimits (300, 300, 1200, 1000);
  46605. content->chooserComponent->addListener (this);
  46606. }
  46607. FileChooserDialogBox::~FileChooserDialogBox()
  46608. {
  46609. content->chooserComponent->removeListener (this);
  46610. }
  46611. bool FileChooserDialogBox::show (int w, int h)
  46612. {
  46613. return showAt (-1, -1, w, h);
  46614. }
  46615. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46616. {
  46617. if (w <= 0)
  46618. {
  46619. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46620. if (previewComp != 0)
  46621. w = 400 + previewComp->getWidth();
  46622. else
  46623. w = 600;
  46624. }
  46625. if (h <= 0)
  46626. h = 500;
  46627. if (x < 0 || y < 0)
  46628. centreWithSize (w, h);
  46629. else
  46630. setBounds (x, y, w, h);
  46631. const bool ok = (runModalLoop() != 0);
  46632. setVisible (false);
  46633. return ok;
  46634. }
  46635. void FileChooserDialogBox::buttonClicked (Button* button)
  46636. {
  46637. if (button == content->okButton)
  46638. {
  46639. if (warnAboutOverwritingExistingFiles
  46640. && content->chooserComponent->isSaveMode()
  46641. && content->chooserComponent->getSelectedFile(0).exists())
  46642. {
  46643. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46644. TRANS("File already exists"),
  46645. TRANS("There's already a file called:")
  46646. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46647. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46648. TRANS("overwrite"),
  46649. TRANS("cancel")))
  46650. {
  46651. return;
  46652. }
  46653. }
  46654. exitModalState (1);
  46655. }
  46656. else if (button == content->cancelButton)
  46657. closeButtonPressed();
  46658. }
  46659. void FileChooserDialogBox::closeButtonPressed()
  46660. {
  46661. setVisible (false);
  46662. }
  46663. void FileChooserDialogBox::selectionChanged()
  46664. {
  46665. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46666. }
  46667. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46668. {
  46669. }
  46670. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46671. {
  46672. selectionChanged();
  46673. content->okButton->triggerClick();
  46674. }
  46675. FileChooserDialogBox::ContentComponent::ContentComponent()
  46676. {
  46677. setInterceptsMouseClicks (false, true);
  46678. }
  46679. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46680. {
  46681. delete okButton;
  46682. delete cancelButton;
  46683. }
  46684. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46685. {
  46686. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46687. text.draw (g);
  46688. }
  46689. void FileChooserDialogBox::ContentComponent::resized()
  46690. {
  46691. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46692. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46693. const int y = roundToInt (bb.getBottom()) + 10;
  46694. const int buttonHeight = 26;
  46695. const int buttonY = getHeight() - buttonHeight - 8;
  46696. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46697. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46698. proportionOfWidth (0.2f), buttonHeight);
  46699. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46700. proportionOfWidth (0.2f), buttonHeight);
  46701. }
  46702. END_JUCE_NAMESPACE
  46703. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46704. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46705. BEGIN_JUCE_NAMESPACE
  46706. FileFilter::FileFilter (const String& filterDescription)
  46707. : description (filterDescription)
  46708. {
  46709. }
  46710. FileFilter::~FileFilter()
  46711. {
  46712. }
  46713. const String& FileFilter::getDescription() const throw()
  46714. {
  46715. return description;
  46716. }
  46717. END_JUCE_NAMESPACE
  46718. /*** End of inlined file: juce_FileFilter.cpp ***/
  46719. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46720. BEGIN_JUCE_NAMESPACE
  46721. const Image juce_createIconForFile (const File& file);
  46722. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46723. : ListBox (String::empty, 0),
  46724. DirectoryContentsDisplayComponent (listToShow)
  46725. {
  46726. setModel (this);
  46727. fileList.addChangeListener (this);
  46728. }
  46729. FileListComponent::~FileListComponent()
  46730. {
  46731. fileList.removeChangeListener (this);
  46732. }
  46733. int FileListComponent::getNumSelectedFiles() const
  46734. {
  46735. return getNumSelectedRows();
  46736. }
  46737. const File FileListComponent::getSelectedFile (int index) const
  46738. {
  46739. return fileList.getFile (getSelectedRow (index));
  46740. }
  46741. void FileListComponent::deselectAllFiles()
  46742. {
  46743. deselectAllRows();
  46744. }
  46745. void FileListComponent::scrollToTop()
  46746. {
  46747. getVerticalScrollBar()->setCurrentRangeStart (0);
  46748. }
  46749. void FileListComponent::changeListenerCallback (void*)
  46750. {
  46751. updateContent();
  46752. if (lastDirectory != fileList.getDirectory())
  46753. {
  46754. lastDirectory = fileList.getDirectory();
  46755. deselectAllRows();
  46756. }
  46757. }
  46758. class FileListItemComponent : public Component,
  46759. public TimeSliceClient,
  46760. public AsyncUpdater
  46761. {
  46762. public:
  46763. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46764. : owner (owner_), thread (thread_),
  46765. highlighted (false), index (0), icon (0)
  46766. {
  46767. }
  46768. ~FileListItemComponent()
  46769. {
  46770. thread.removeTimeSliceClient (this);
  46771. clearIcon();
  46772. }
  46773. void paint (Graphics& g)
  46774. {
  46775. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46776. file.getFileName(),
  46777. &icon,
  46778. fileSize, modTime,
  46779. isDirectory, highlighted,
  46780. index);
  46781. }
  46782. void mouseDown (const MouseEvent& e)
  46783. {
  46784. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46785. owner.sendMouseClickMessage (file, e);
  46786. }
  46787. void mouseDoubleClick (const MouseEvent&)
  46788. {
  46789. owner.sendDoubleClickMessage (file);
  46790. }
  46791. void update (const File& root,
  46792. const DirectoryContentsList::FileInfo* const fileInfo,
  46793. const int index_,
  46794. const bool highlighted_)
  46795. {
  46796. thread.removeTimeSliceClient (this);
  46797. if (highlighted_ != highlighted
  46798. || index_ != index)
  46799. {
  46800. index = index_;
  46801. highlighted = highlighted_;
  46802. repaint();
  46803. }
  46804. File newFile;
  46805. String newFileSize;
  46806. String newModTime;
  46807. if (fileInfo != 0)
  46808. {
  46809. newFile = root.getChildFile (fileInfo->filename);
  46810. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46811. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46812. }
  46813. if (newFile != file
  46814. || fileSize != newFileSize
  46815. || modTime != newModTime)
  46816. {
  46817. file = newFile;
  46818. fileSize = newFileSize;
  46819. modTime = newModTime;
  46820. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46821. repaint();
  46822. clearIcon();
  46823. }
  46824. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  46825. {
  46826. updateIcon (true);
  46827. if (! icon.isValid())
  46828. thread.addTimeSliceClient (this);
  46829. }
  46830. }
  46831. bool useTimeSlice()
  46832. {
  46833. updateIcon (false);
  46834. return false;
  46835. }
  46836. void handleAsyncUpdate()
  46837. {
  46838. repaint();
  46839. }
  46840. juce_UseDebuggingNewOperator
  46841. private:
  46842. FileListComponent& owner;
  46843. TimeSliceThread& thread;
  46844. bool highlighted;
  46845. int index;
  46846. File file;
  46847. String fileSize;
  46848. String modTime;
  46849. Image icon;
  46850. bool isDirectory;
  46851. void clearIcon()
  46852. {
  46853. icon = Image::null;
  46854. }
  46855. void updateIcon (const bool onlyUpdateIfCached)
  46856. {
  46857. if (icon.isNull())
  46858. {
  46859. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46860. Image im (ImageCache::getFromHashCode (hashCode));
  46861. if (im.isNull() && ! onlyUpdateIfCached)
  46862. {
  46863. im = juce_createIconForFile (file);
  46864. if (im.isValid())
  46865. ImageCache::addImageToCache (im, hashCode);
  46866. }
  46867. if (im.isValid())
  46868. {
  46869. icon = im;
  46870. triggerAsyncUpdate();
  46871. }
  46872. }
  46873. }
  46874. };
  46875. int FileListComponent::getNumRows()
  46876. {
  46877. return fileList.getNumFiles();
  46878. }
  46879. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46880. {
  46881. }
  46882. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46883. {
  46884. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46885. if (comp == 0)
  46886. {
  46887. delete existingComponentToUpdate;
  46888. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46889. }
  46890. DirectoryContentsList::FileInfo fileInfo;
  46891. if (fileList.getFileInfo (row, fileInfo))
  46892. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46893. else
  46894. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46895. return comp;
  46896. }
  46897. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46898. {
  46899. sendSelectionChangeMessage();
  46900. }
  46901. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46902. {
  46903. }
  46904. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46905. {
  46906. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46907. }
  46908. END_JUCE_NAMESPACE
  46909. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46910. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46911. BEGIN_JUCE_NAMESPACE
  46912. FilenameComponent::FilenameComponent (const String& name,
  46913. const File& currentFile,
  46914. const bool canEditFilename,
  46915. const bool isDirectory,
  46916. const bool isForSaving,
  46917. const String& fileBrowserWildcard,
  46918. const String& enforcedSuffix_,
  46919. const String& textWhenNothingSelected)
  46920. : Component (name),
  46921. maxRecentFiles (30),
  46922. isDir (isDirectory),
  46923. isSaving (isForSaving),
  46924. isFileDragOver (false),
  46925. wildcard (fileBrowserWildcard),
  46926. enforcedSuffix (enforcedSuffix_)
  46927. {
  46928. addAndMakeVisible (&filenameBox);
  46929. filenameBox.setEditableText (canEditFilename);
  46930. filenameBox.addListener (this);
  46931. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  46932. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46933. setBrowseButtonText ("...");
  46934. setCurrentFile (currentFile, true);
  46935. }
  46936. FilenameComponent::~FilenameComponent()
  46937. {
  46938. }
  46939. void FilenameComponent::paintOverChildren (Graphics& g)
  46940. {
  46941. if (isFileDragOver)
  46942. {
  46943. g.setColour (Colours::red.withAlpha (0.2f));
  46944. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46945. }
  46946. }
  46947. void FilenameComponent::resized()
  46948. {
  46949. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  46950. }
  46951. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46952. {
  46953. browseButtonText = newBrowseButtonText;
  46954. lookAndFeelChanged();
  46955. }
  46956. void FilenameComponent::lookAndFeelChanged()
  46957. {
  46958. browseButton = 0;
  46959. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46960. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46961. resized();
  46962. browseButton->addButtonListener (this);
  46963. }
  46964. void FilenameComponent::setTooltip (const String& newTooltip)
  46965. {
  46966. SettableTooltipClient::setTooltip (newTooltip);
  46967. filenameBox.setTooltip (newTooltip);
  46968. }
  46969. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46970. {
  46971. defaultBrowseFile = newDefaultDirectory;
  46972. }
  46973. void FilenameComponent::buttonClicked (Button*)
  46974. {
  46975. FileChooser fc (TRANS("Choose a new file"),
  46976. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46977. : getCurrentFile(),
  46978. wildcard);
  46979. if (isDir ? fc.browseForDirectory()
  46980. : (isSaving ? fc.browseForFileToSave (false)
  46981. : fc.browseForFileToOpen()))
  46982. {
  46983. setCurrentFile (fc.getResult(), true);
  46984. }
  46985. }
  46986. void FilenameComponent::comboBoxChanged (ComboBox*)
  46987. {
  46988. setCurrentFile (getCurrentFile(), true);
  46989. }
  46990. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46991. {
  46992. return true;
  46993. }
  46994. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46995. {
  46996. isFileDragOver = false;
  46997. repaint();
  46998. const File f (filenames[0]);
  46999. if (f.exists() && (f.isDirectory() == isDir))
  47000. setCurrentFile (f, true);
  47001. }
  47002. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47003. {
  47004. isFileDragOver = true;
  47005. repaint();
  47006. }
  47007. void FilenameComponent::fileDragExit (const StringArray&)
  47008. {
  47009. isFileDragOver = false;
  47010. repaint();
  47011. }
  47012. const File FilenameComponent::getCurrentFile() const
  47013. {
  47014. File f (filenameBox.getText());
  47015. if (enforcedSuffix.isNotEmpty())
  47016. f = f.withFileExtension (enforcedSuffix);
  47017. return f;
  47018. }
  47019. void FilenameComponent::setCurrentFile (File newFile,
  47020. const bool addToRecentlyUsedList,
  47021. const bool sendChangeNotification)
  47022. {
  47023. if (enforcedSuffix.isNotEmpty())
  47024. newFile = newFile.withFileExtension (enforcedSuffix);
  47025. if (newFile.getFullPathName() != lastFilename)
  47026. {
  47027. lastFilename = newFile.getFullPathName();
  47028. if (addToRecentlyUsedList)
  47029. addRecentlyUsedFile (newFile);
  47030. filenameBox.setText (lastFilename, true);
  47031. if (sendChangeNotification)
  47032. triggerAsyncUpdate();
  47033. }
  47034. }
  47035. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47036. {
  47037. filenameBox.setEditableText (shouldBeEditable);
  47038. }
  47039. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47040. {
  47041. StringArray names;
  47042. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47043. names.add (filenameBox.getItemText (i));
  47044. return names;
  47045. }
  47046. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47047. {
  47048. if (filenames != getRecentlyUsedFilenames())
  47049. {
  47050. filenameBox.clear();
  47051. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47052. filenameBox.addItem (filenames[i], i + 1);
  47053. }
  47054. }
  47055. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47056. {
  47057. maxRecentFiles = jmax (1, newMaximum);
  47058. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47059. }
  47060. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47061. {
  47062. StringArray files (getRecentlyUsedFilenames());
  47063. if (file.getFullPathName().isNotEmpty())
  47064. {
  47065. files.removeString (file.getFullPathName(), true);
  47066. files.insert (0, file.getFullPathName());
  47067. setRecentlyUsedFilenames (files);
  47068. }
  47069. }
  47070. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47071. {
  47072. listeners.add (listener);
  47073. }
  47074. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47075. {
  47076. listeners.remove (listener);
  47077. }
  47078. void FilenameComponent::handleAsyncUpdate()
  47079. {
  47080. Component::BailOutChecker checker (this);
  47081. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47082. }
  47083. END_JUCE_NAMESPACE
  47084. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47085. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47086. BEGIN_JUCE_NAMESPACE
  47087. FileSearchPathListComponent::FileSearchPathListComponent()
  47088. {
  47089. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47090. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47091. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47092. listBox->setOutlineThickness (1);
  47093. addAndMakeVisible (addButton = new TextButton ("+"));
  47094. addButton->addButtonListener (this);
  47095. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47096. addAndMakeVisible (removeButton = new TextButton ("-"));
  47097. removeButton->addButtonListener (this);
  47098. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47099. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47100. changeButton->addButtonListener (this);
  47101. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47102. upButton->addButtonListener (this);
  47103. {
  47104. Path arrowPath;
  47105. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47106. DrawablePath arrowImage;
  47107. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47108. arrowImage.setPath (arrowPath);
  47109. upButton->setImages (&arrowImage);
  47110. }
  47111. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47112. downButton->addButtonListener (this);
  47113. {
  47114. Path arrowPath;
  47115. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47116. DrawablePath arrowImage;
  47117. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47118. arrowImage.setPath (arrowPath);
  47119. downButton->setImages (&arrowImage);
  47120. }
  47121. updateButtons();
  47122. }
  47123. FileSearchPathListComponent::~FileSearchPathListComponent()
  47124. {
  47125. deleteAllChildren();
  47126. }
  47127. void FileSearchPathListComponent::updateButtons()
  47128. {
  47129. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47130. removeButton->setEnabled (anythingSelected);
  47131. changeButton->setEnabled (anythingSelected);
  47132. upButton->setEnabled (anythingSelected);
  47133. downButton->setEnabled (anythingSelected);
  47134. }
  47135. void FileSearchPathListComponent::changed()
  47136. {
  47137. listBox->updateContent();
  47138. listBox->repaint();
  47139. updateButtons();
  47140. }
  47141. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47142. {
  47143. if (newPath.toString() != path.toString())
  47144. {
  47145. path = newPath;
  47146. changed();
  47147. }
  47148. }
  47149. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47150. {
  47151. defaultBrowseTarget = newDefaultDirectory;
  47152. }
  47153. int FileSearchPathListComponent::getNumRows()
  47154. {
  47155. return path.getNumPaths();
  47156. }
  47157. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47158. {
  47159. if (rowIsSelected)
  47160. g.fillAll (findColour (TextEditor::highlightColourId));
  47161. g.setColour (findColour (ListBox::textColourId));
  47162. Font f (height * 0.7f);
  47163. f.setHorizontalScale (0.9f);
  47164. g.setFont (f);
  47165. g.drawText (path [rowNumber].getFullPathName(),
  47166. 4, 0, width - 6, height,
  47167. Justification::centredLeft, true);
  47168. }
  47169. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47170. {
  47171. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47172. {
  47173. path.remove (row);
  47174. changed();
  47175. }
  47176. }
  47177. void FileSearchPathListComponent::returnKeyPressed (int row)
  47178. {
  47179. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47180. if (chooser.browseForDirectory())
  47181. {
  47182. path.remove (row);
  47183. path.add (chooser.getResult(), row);
  47184. changed();
  47185. }
  47186. }
  47187. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47188. {
  47189. returnKeyPressed (row);
  47190. }
  47191. void FileSearchPathListComponent::selectedRowsChanged (int)
  47192. {
  47193. updateButtons();
  47194. }
  47195. void FileSearchPathListComponent::paint (Graphics& g)
  47196. {
  47197. g.fillAll (findColour (backgroundColourId));
  47198. }
  47199. void FileSearchPathListComponent::resized()
  47200. {
  47201. const int buttonH = 22;
  47202. const int buttonY = getHeight() - buttonH - 4;
  47203. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47204. addButton->setBounds (2, buttonY, buttonH, buttonH);
  47205. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47206. changeButton->changeWidthToFitText (buttonH);
  47207. downButton->setSize (buttonH * 2, buttonH);
  47208. upButton->setSize (buttonH * 2, buttonH);
  47209. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47210. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47211. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47212. }
  47213. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47214. {
  47215. return true;
  47216. }
  47217. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47218. {
  47219. for (int i = filenames.size(); --i >= 0;)
  47220. {
  47221. const File f (filenames[i]);
  47222. if (f.isDirectory())
  47223. {
  47224. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47225. path.add (f, row);
  47226. changed();
  47227. }
  47228. }
  47229. }
  47230. void FileSearchPathListComponent::buttonClicked (Button* button)
  47231. {
  47232. const int currentRow = listBox->getSelectedRow();
  47233. if (button == removeButton)
  47234. {
  47235. deleteKeyPressed (currentRow);
  47236. }
  47237. else if (button == addButton)
  47238. {
  47239. File start (defaultBrowseTarget);
  47240. if (start == File::nonexistent)
  47241. start = path [0];
  47242. if (start == File::nonexistent)
  47243. start = File::getCurrentWorkingDirectory();
  47244. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47245. if (chooser.browseForDirectory())
  47246. {
  47247. path.add (chooser.getResult(), currentRow);
  47248. }
  47249. }
  47250. else if (button == changeButton)
  47251. {
  47252. returnKeyPressed (currentRow);
  47253. }
  47254. else if (button == upButton)
  47255. {
  47256. if (currentRow > 0 && currentRow < path.getNumPaths())
  47257. {
  47258. const File f (path[currentRow]);
  47259. path.remove (currentRow);
  47260. path.add (f, currentRow - 1);
  47261. listBox->selectRow (currentRow - 1);
  47262. }
  47263. }
  47264. else if (button == downButton)
  47265. {
  47266. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47267. {
  47268. const File f (path[currentRow]);
  47269. path.remove (currentRow);
  47270. path.add (f, currentRow + 1);
  47271. listBox->selectRow (currentRow + 1);
  47272. }
  47273. }
  47274. changed();
  47275. }
  47276. END_JUCE_NAMESPACE
  47277. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47278. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47279. BEGIN_JUCE_NAMESPACE
  47280. const Image juce_createIconForFile (const File& file);
  47281. class FileListTreeItem : public TreeViewItem,
  47282. public TimeSliceClient,
  47283. public AsyncUpdater,
  47284. public ChangeListener
  47285. {
  47286. public:
  47287. FileListTreeItem (FileTreeComponent& owner_,
  47288. DirectoryContentsList* const parentContentsList_,
  47289. const int indexInContentsList_,
  47290. const File& file_,
  47291. TimeSliceThread& thread_)
  47292. : file (file_),
  47293. owner (owner_),
  47294. parentContentsList (parentContentsList_),
  47295. indexInContentsList (indexInContentsList_),
  47296. subContentsList (0),
  47297. canDeleteSubContentsList (false),
  47298. thread (thread_),
  47299. icon (0)
  47300. {
  47301. DirectoryContentsList::FileInfo fileInfo;
  47302. if (parentContentsList_ != 0
  47303. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47304. {
  47305. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47306. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47307. isDirectory = fileInfo.isDirectory;
  47308. }
  47309. else
  47310. {
  47311. isDirectory = true;
  47312. }
  47313. }
  47314. ~FileListTreeItem()
  47315. {
  47316. thread.removeTimeSliceClient (this);
  47317. clearSubItems();
  47318. if (canDeleteSubContentsList)
  47319. delete subContentsList;
  47320. }
  47321. bool mightContainSubItems() { return isDirectory; }
  47322. const String getUniqueName() const { return file.getFullPathName(); }
  47323. int getItemHeight() const { return 22; }
  47324. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47325. void itemOpennessChanged (bool isNowOpen)
  47326. {
  47327. if (isNowOpen)
  47328. {
  47329. clearSubItems();
  47330. isDirectory = file.isDirectory();
  47331. if (isDirectory)
  47332. {
  47333. if (subContentsList == 0)
  47334. {
  47335. jassert (parentContentsList != 0);
  47336. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47337. l->setDirectory (file, true, true);
  47338. setSubContentsList (l);
  47339. canDeleteSubContentsList = true;
  47340. }
  47341. changeListenerCallback (0);
  47342. }
  47343. }
  47344. }
  47345. void setSubContentsList (DirectoryContentsList* newList)
  47346. {
  47347. jassert (subContentsList == 0);
  47348. subContentsList = newList;
  47349. newList->addChangeListener (this);
  47350. }
  47351. void changeListenerCallback (void*)
  47352. {
  47353. clearSubItems();
  47354. if (isOpen() && subContentsList != 0)
  47355. {
  47356. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47357. {
  47358. FileListTreeItem* const item
  47359. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47360. addSubItem (item);
  47361. }
  47362. }
  47363. }
  47364. void paintItem (Graphics& g, int width, int height)
  47365. {
  47366. if (file != File::nonexistent)
  47367. {
  47368. updateIcon (true);
  47369. if (icon.isNull())
  47370. thread.addTimeSliceClient (this);
  47371. }
  47372. owner.getLookAndFeel()
  47373. .drawFileBrowserRow (g, width, height,
  47374. file.getFileName(),
  47375. &icon, fileSize, modTime,
  47376. isDirectory, isSelected(),
  47377. indexInContentsList);
  47378. }
  47379. void itemClicked (const MouseEvent& e)
  47380. {
  47381. owner.sendMouseClickMessage (file, e);
  47382. }
  47383. void itemDoubleClicked (const MouseEvent& e)
  47384. {
  47385. TreeViewItem::itemDoubleClicked (e);
  47386. owner.sendDoubleClickMessage (file);
  47387. }
  47388. void itemSelectionChanged (bool)
  47389. {
  47390. owner.sendSelectionChangeMessage();
  47391. }
  47392. bool useTimeSlice()
  47393. {
  47394. updateIcon (false);
  47395. thread.removeTimeSliceClient (this);
  47396. return false;
  47397. }
  47398. void handleAsyncUpdate()
  47399. {
  47400. owner.repaint();
  47401. }
  47402. const File file;
  47403. juce_UseDebuggingNewOperator
  47404. private:
  47405. FileTreeComponent& owner;
  47406. DirectoryContentsList* parentContentsList;
  47407. int indexInContentsList;
  47408. DirectoryContentsList* subContentsList;
  47409. bool isDirectory, canDeleteSubContentsList;
  47410. TimeSliceThread& thread;
  47411. Image icon;
  47412. String fileSize;
  47413. String modTime;
  47414. void updateIcon (const bool onlyUpdateIfCached)
  47415. {
  47416. if (icon.isNull())
  47417. {
  47418. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47419. Image im (ImageCache::getFromHashCode (hashCode));
  47420. if (im.isNull() && ! onlyUpdateIfCached)
  47421. {
  47422. im = juce_createIconForFile (file);
  47423. if (im.isValid())
  47424. ImageCache::addImageToCache (im, hashCode);
  47425. }
  47426. if (im.isValid())
  47427. {
  47428. icon = im;
  47429. triggerAsyncUpdate();
  47430. }
  47431. }
  47432. }
  47433. };
  47434. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47435. : DirectoryContentsDisplayComponent (listToShow)
  47436. {
  47437. FileListTreeItem* const root
  47438. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47439. listToShow.getTimeSliceThread());
  47440. root->setSubContentsList (&listToShow);
  47441. setRootItemVisible (false);
  47442. setRootItem (root);
  47443. }
  47444. FileTreeComponent::~FileTreeComponent()
  47445. {
  47446. deleteRootItem();
  47447. }
  47448. const File FileTreeComponent::getSelectedFile (const int index) const
  47449. {
  47450. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47451. return item != 0 ? item->file
  47452. : File::nonexistent;
  47453. }
  47454. void FileTreeComponent::deselectAllFiles()
  47455. {
  47456. clearSelectedItems();
  47457. }
  47458. void FileTreeComponent::scrollToTop()
  47459. {
  47460. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47461. }
  47462. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47463. {
  47464. dragAndDropDescription = description;
  47465. }
  47466. END_JUCE_NAMESPACE
  47467. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47468. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47469. BEGIN_JUCE_NAMESPACE
  47470. ImagePreviewComponent::ImagePreviewComponent()
  47471. {
  47472. }
  47473. ImagePreviewComponent::~ImagePreviewComponent()
  47474. {
  47475. }
  47476. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47477. {
  47478. const int availableW = proportionOfWidth (0.97f);
  47479. const int availableH = getHeight() - 13 * 4;
  47480. const double scale = jmin (1.0,
  47481. availableW / (double) w,
  47482. availableH / (double) h);
  47483. w = roundToInt (scale * w);
  47484. h = roundToInt (scale * h);
  47485. }
  47486. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47487. {
  47488. if (fileToLoad != file)
  47489. {
  47490. fileToLoad = file;
  47491. startTimer (100);
  47492. }
  47493. }
  47494. void ImagePreviewComponent::timerCallback()
  47495. {
  47496. stopTimer();
  47497. currentThumbnail = Image::null;
  47498. currentDetails = String::empty;
  47499. repaint();
  47500. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47501. if (in != 0)
  47502. {
  47503. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47504. if (format != 0)
  47505. {
  47506. currentThumbnail = format->decodeImage (*in);
  47507. if (currentThumbnail.isValid())
  47508. {
  47509. int w = currentThumbnail.getWidth();
  47510. int h = currentThumbnail.getHeight();
  47511. currentDetails
  47512. << fileToLoad.getFileName() << "\n"
  47513. << format->getFormatName() << "\n"
  47514. << w << " x " << h << " pixels\n"
  47515. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47516. getThumbSize (w, h);
  47517. currentThumbnail = currentThumbnail.rescaled (w, h);
  47518. }
  47519. }
  47520. }
  47521. }
  47522. void ImagePreviewComponent::paint (Graphics& g)
  47523. {
  47524. if (currentThumbnail.isValid())
  47525. {
  47526. g.setFont (13.0f);
  47527. int w = currentThumbnail.getWidth();
  47528. int h = currentThumbnail.getHeight();
  47529. getThumbSize (w, h);
  47530. const int numLines = 4;
  47531. const int totalH = 13 * numLines + h + 4;
  47532. const int y = (getHeight() - totalH) / 2;
  47533. g.drawImageWithin (currentThumbnail,
  47534. (getWidth() - w) / 2, y, w, h,
  47535. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47536. false);
  47537. g.drawFittedText (currentDetails,
  47538. 0, y + h + 4, getWidth(), 100,
  47539. Justification::centredTop, numLines);
  47540. }
  47541. }
  47542. END_JUCE_NAMESPACE
  47543. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47544. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47545. BEGIN_JUCE_NAMESPACE
  47546. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47547. const String& directoryWildcardPatterns,
  47548. const String& description_)
  47549. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47550. : (description_ + " (" + fileWildcardPatterns + ")"))
  47551. {
  47552. parse (fileWildcardPatterns, fileWildcards);
  47553. parse (directoryWildcardPatterns, directoryWildcards);
  47554. }
  47555. WildcardFileFilter::~WildcardFileFilter()
  47556. {
  47557. }
  47558. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47559. {
  47560. return match (file, fileWildcards);
  47561. }
  47562. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47563. {
  47564. return match (file, directoryWildcards);
  47565. }
  47566. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47567. {
  47568. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47569. result.trim();
  47570. result.removeEmptyStrings();
  47571. // special case for *.*, because people use it to mean "any file", but it
  47572. // would actually ignore files with no extension.
  47573. for (int i = result.size(); --i >= 0;)
  47574. if (result[i] == "*.*")
  47575. result.set (i, "*");
  47576. }
  47577. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47578. {
  47579. const String filename (file.getFileName());
  47580. for (int i = wildcards.size(); --i >= 0;)
  47581. if (filename.matchesWildcard (wildcards[i], true))
  47582. return true;
  47583. return false;
  47584. }
  47585. END_JUCE_NAMESPACE
  47586. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47587. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47588. BEGIN_JUCE_NAMESPACE
  47589. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47590. {
  47591. }
  47592. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47593. {
  47594. }
  47595. namespace KeyboardFocusHelpers
  47596. {
  47597. // This will sort a set of components, so that they are ordered in terms of
  47598. // left-to-right and then top-to-bottom.
  47599. class ScreenPositionComparator
  47600. {
  47601. public:
  47602. ScreenPositionComparator() {}
  47603. static int compareElements (const Component* const first, const Component* const second)
  47604. {
  47605. int explicitOrder1 = first->getExplicitFocusOrder();
  47606. if (explicitOrder1 <= 0)
  47607. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47608. int explicitOrder2 = second->getExplicitFocusOrder();
  47609. if (explicitOrder2 <= 0)
  47610. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47611. if (explicitOrder1 != explicitOrder2)
  47612. return explicitOrder1 - explicitOrder2;
  47613. const int diff = first->getY() - second->getY();
  47614. return (diff == 0) ? first->getX() - second->getX()
  47615. : diff;
  47616. }
  47617. };
  47618. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47619. {
  47620. if (parent->getNumChildComponents() > 0)
  47621. {
  47622. Array <Component*> localComps;
  47623. ScreenPositionComparator comparator;
  47624. int i;
  47625. for (i = parent->getNumChildComponents(); --i >= 0;)
  47626. {
  47627. Component* const c = parent->getChildComponent (i);
  47628. if (c->isVisible() && c->isEnabled())
  47629. localComps.addSorted (comparator, c);
  47630. }
  47631. for (i = 0; i < localComps.size(); ++i)
  47632. {
  47633. Component* const c = localComps.getUnchecked (i);
  47634. if (c->getWantsKeyboardFocus())
  47635. comps.add (c);
  47636. if (! c->isFocusContainer())
  47637. findAllFocusableComponents (c, comps);
  47638. }
  47639. }
  47640. }
  47641. }
  47642. static Component* getIncrementedComponent (Component* const current, const int delta)
  47643. {
  47644. Component* focusContainer = current->getParentComponent();
  47645. if (focusContainer != 0)
  47646. {
  47647. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47648. focusContainer = focusContainer->getParentComponent();
  47649. if (focusContainer != 0)
  47650. {
  47651. Array <Component*> comps;
  47652. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47653. if (comps.size() > 0)
  47654. {
  47655. const int index = comps.indexOf (current);
  47656. return comps [(index + comps.size() + delta) % comps.size()];
  47657. }
  47658. }
  47659. }
  47660. return 0;
  47661. }
  47662. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47663. {
  47664. return getIncrementedComponent (current, 1);
  47665. }
  47666. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47667. {
  47668. return getIncrementedComponent (current, -1);
  47669. }
  47670. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47671. {
  47672. Array <Component*> comps;
  47673. if (parentComponent != 0)
  47674. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47675. return comps.getFirst();
  47676. }
  47677. END_JUCE_NAMESPACE
  47678. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47679. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47680. BEGIN_JUCE_NAMESPACE
  47681. bool KeyListener::keyStateChanged (const bool, Component*)
  47682. {
  47683. return false;
  47684. }
  47685. END_JUCE_NAMESPACE
  47686. /*** End of inlined file: juce_KeyListener.cpp ***/
  47687. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47688. BEGIN_JUCE_NAMESPACE
  47689. // N.B. these two includes are put here deliberately to avoid problems with
  47690. // old GCCs failing on long include paths
  47691. const int maxKeys = 3;
  47692. class KeyMappingChangeButton : public Button
  47693. {
  47694. public:
  47695. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47696. const CommandID commandID_,
  47697. const String& keyName,
  47698. const int keyNum_)
  47699. : Button (keyName),
  47700. owner (owner_),
  47701. commandID (commandID_),
  47702. keyNum (keyNum_)
  47703. {
  47704. setWantsKeyboardFocus (false);
  47705. setTriggeredOnMouseDown (keyNum >= 0);
  47706. if (keyNum_ < 0)
  47707. setTooltip (TRANS("adds a new key-mapping"));
  47708. else
  47709. setTooltip (TRANS("click to change this key-mapping"));
  47710. }
  47711. ~KeyMappingChangeButton()
  47712. {
  47713. }
  47714. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47715. {
  47716. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47717. keyNum >= 0 ? getName() : String::empty);
  47718. }
  47719. void clicked()
  47720. {
  47721. if (keyNum >= 0)
  47722. {
  47723. // existing key clicked..
  47724. PopupMenu m;
  47725. m.addItem (1, TRANS("change this key-mapping"));
  47726. m.addSeparator();
  47727. m.addItem (2, TRANS("remove this key-mapping"));
  47728. const int res = m.show();
  47729. if (res == 1)
  47730. {
  47731. owner->assignNewKey (commandID, keyNum);
  47732. }
  47733. else if (res == 2)
  47734. {
  47735. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47736. }
  47737. }
  47738. else
  47739. {
  47740. // + button pressed..
  47741. owner->assignNewKey (commandID, -1);
  47742. }
  47743. }
  47744. void fitToContent (const int h) throw()
  47745. {
  47746. if (keyNum < 0)
  47747. {
  47748. setSize (h, h);
  47749. }
  47750. else
  47751. {
  47752. Font f (h * 0.6f);
  47753. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47754. }
  47755. }
  47756. juce_UseDebuggingNewOperator
  47757. private:
  47758. KeyMappingEditorComponent* const owner;
  47759. const CommandID commandID;
  47760. const int keyNum;
  47761. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47762. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47763. };
  47764. class KeyMappingItemComponent : public Component
  47765. {
  47766. public:
  47767. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47768. const CommandID commandID_)
  47769. : owner (owner_),
  47770. commandID (commandID_)
  47771. {
  47772. setInterceptsMouseClicks (false, true);
  47773. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47774. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47775. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47776. {
  47777. KeyMappingChangeButton* const kb
  47778. = new KeyMappingChangeButton (owner_, commandID,
  47779. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47780. kb->setEnabled (! isReadOnly);
  47781. addAndMakeVisible (kb);
  47782. }
  47783. KeyMappingChangeButton* const kb
  47784. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47785. addChildComponent (kb);
  47786. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47787. }
  47788. ~KeyMappingItemComponent()
  47789. {
  47790. deleteAllChildren();
  47791. }
  47792. void paint (Graphics& g)
  47793. {
  47794. g.setFont (getHeight() * 0.7f);
  47795. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47796. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47797. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47798. Justification::centredLeft, true);
  47799. }
  47800. void resized()
  47801. {
  47802. int x = getWidth() - 4;
  47803. for (int i = getNumChildComponents(); --i >= 0;)
  47804. {
  47805. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47806. kb->fitToContent (getHeight() - 2);
  47807. kb->setTopRightPosition (x, 1);
  47808. x -= kb->getWidth() + 5;
  47809. }
  47810. }
  47811. juce_UseDebuggingNewOperator
  47812. private:
  47813. KeyMappingEditorComponent* const owner;
  47814. const CommandID commandID;
  47815. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47816. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47817. };
  47818. class KeyMappingTreeViewItem : public TreeViewItem
  47819. {
  47820. public:
  47821. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47822. const CommandID commandID_)
  47823. : owner (owner_),
  47824. commandID (commandID_)
  47825. {
  47826. }
  47827. ~KeyMappingTreeViewItem()
  47828. {
  47829. }
  47830. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47831. bool mightContainSubItems() { return false; }
  47832. int getItemHeight() const { return 20; }
  47833. Component* createItemComponent()
  47834. {
  47835. return new KeyMappingItemComponent (owner, commandID);
  47836. }
  47837. juce_UseDebuggingNewOperator
  47838. private:
  47839. KeyMappingEditorComponent* const owner;
  47840. const CommandID commandID;
  47841. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47842. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47843. };
  47844. class KeyCategoryTreeViewItem : public TreeViewItem
  47845. {
  47846. public:
  47847. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47848. const String& name)
  47849. : owner (owner_),
  47850. categoryName (name)
  47851. {
  47852. }
  47853. ~KeyCategoryTreeViewItem()
  47854. {
  47855. }
  47856. const String getUniqueName() const { return categoryName + "_cat"; }
  47857. bool mightContainSubItems() { return true; }
  47858. int getItemHeight() const { return 28; }
  47859. void paintItem (Graphics& g, int width, int height)
  47860. {
  47861. g.setFont (height * 0.6f, Font::bold);
  47862. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47863. g.drawText (categoryName,
  47864. 2, 0, width - 2, height,
  47865. Justification::centredLeft, true);
  47866. }
  47867. void itemOpennessChanged (bool isNowOpen)
  47868. {
  47869. if (isNowOpen)
  47870. {
  47871. if (getNumSubItems() == 0)
  47872. {
  47873. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47874. for (int i = 0; i < commands.size(); ++i)
  47875. {
  47876. if (owner->shouldCommandBeIncluded (commands[i]))
  47877. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47878. }
  47879. }
  47880. }
  47881. else
  47882. {
  47883. clearSubItems();
  47884. }
  47885. }
  47886. juce_UseDebuggingNewOperator
  47887. private:
  47888. KeyMappingEditorComponent* owner;
  47889. String categoryName;
  47890. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47891. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47892. };
  47893. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47894. const bool showResetToDefaultButton)
  47895. : mappings (mappingManager)
  47896. {
  47897. jassert (mappingManager != 0); // can't be null!
  47898. mappingManager->addChangeListener (this);
  47899. setLinesDrawnForSubItems (false);
  47900. resetButton = 0;
  47901. if (showResetToDefaultButton)
  47902. {
  47903. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47904. resetButton->addButtonListener (this);
  47905. }
  47906. addAndMakeVisible (tree = new TreeView());
  47907. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47908. tree->setRootItemVisible (false);
  47909. tree->setDefaultOpenness (true);
  47910. tree->setRootItem (this);
  47911. }
  47912. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47913. {
  47914. mappings->removeChangeListener (this);
  47915. deleteAllChildren();
  47916. }
  47917. bool KeyMappingEditorComponent::mightContainSubItems()
  47918. {
  47919. return true;
  47920. }
  47921. const String KeyMappingEditorComponent::getUniqueName() const
  47922. {
  47923. return "keys";
  47924. }
  47925. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47926. const Colour& textColour)
  47927. {
  47928. setColour (backgroundColourId, mainBackground);
  47929. setColour (textColourId, textColour);
  47930. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47931. }
  47932. void KeyMappingEditorComponent::parentHierarchyChanged()
  47933. {
  47934. changeListenerCallback (0);
  47935. }
  47936. void KeyMappingEditorComponent::resized()
  47937. {
  47938. int h = getHeight();
  47939. if (resetButton != 0)
  47940. {
  47941. const int buttonHeight = 20;
  47942. h -= buttonHeight + 8;
  47943. int x = getWidth() - 8;
  47944. resetButton->changeWidthToFitText (buttonHeight);
  47945. resetButton->setTopRightPosition (x, h + 6);
  47946. }
  47947. tree->setBounds (0, 0, getWidth(), h);
  47948. }
  47949. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47950. {
  47951. if (button == resetButton)
  47952. {
  47953. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47954. TRANS("Reset to defaults"),
  47955. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47956. TRANS("Reset")))
  47957. {
  47958. mappings->resetToDefaultMappings();
  47959. }
  47960. }
  47961. }
  47962. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47963. {
  47964. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47965. clearSubItems();
  47966. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47967. for (int i = 0; i < categories.size(); ++i)
  47968. {
  47969. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47970. int count = 0;
  47971. for (int j = 0; j < commands.size(); ++j)
  47972. if (shouldCommandBeIncluded (commands[j]))
  47973. ++count;
  47974. if (count > 0)
  47975. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47976. }
  47977. if (oldOpenness != 0)
  47978. tree->restoreOpennessState (*oldOpenness);
  47979. }
  47980. class KeyEntryWindow : public AlertWindow
  47981. {
  47982. public:
  47983. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47984. : AlertWindow (TRANS("New key-mapping"),
  47985. TRANS("Please press a key combination now..."),
  47986. AlertWindow::NoIcon),
  47987. owner (owner_)
  47988. {
  47989. addButton (TRANS("ok"), 1);
  47990. addButton (TRANS("cancel"), 0);
  47991. // (avoid return + escape keys getting processed by the buttons..)
  47992. for (int i = getNumChildComponents(); --i >= 0;)
  47993. getChildComponent (i)->setWantsKeyboardFocus (false);
  47994. setWantsKeyboardFocus (true);
  47995. grabKeyboardFocus();
  47996. }
  47997. ~KeyEntryWindow()
  47998. {
  47999. }
  48000. bool keyPressed (const KeyPress& key)
  48001. {
  48002. lastPress = key;
  48003. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48004. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48005. if (previousCommand != 0)
  48006. {
  48007. message << "\n\n"
  48008. << TRANS("(Currently assigned to \"")
  48009. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48010. << "\")";
  48011. }
  48012. setMessage (message);
  48013. return true;
  48014. }
  48015. bool keyStateChanged (bool)
  48016. {
  48017. return true;
  48018. }
  48019. KeyPress lastPress;
  48020. juce_UseDebuggingNewOperator
  48021. private:
  48022. KeyMappingEditorComponent* owner;
  48023. KeyEntryWindow (const KeyEntryWindow&);
  48024. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48025. };
  48026. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48027. {
  48028. KeyEntryWindow entryWindow (this);
  48029. if (entryWindow.runModalLoop() != 0)
  48030. {
  48031. entryWindow.setVisible (false);
  48032. if (entryWindow.lastPress.isValid())
  48033. {
  48034. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48035. if (previousCommand != 0)
  48036. {
  48037. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48038. TRANS("Change key-mapping"),
  48039. TRANS("This key is already assigned to the command \"")
  48040. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48041. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48042. TRANS("re-assign"),
  48043. TRANS("cancel")))
  48044. {
  48045. return;
  48046. }
  48047. }
  48048. mappings->removeKeyPress (entryWindow.lastPress);
  48049. if (index >= 0)
  48050. mappings->removeKeyPress (commandID, index);
  48051. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48052. }
  48053. }
  48054. }
  48055. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48056. {
  48057. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48058. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48059. }
  48060. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48061. {
  48062. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48063. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48064. }
  48065. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48066. {
  48067. return key.getTextDescription();
  48068. }
  48069. END_JUCE_NAMESPACE
  48070. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48071. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48072. BEGIN_JUCE_NAMESPACE
  48073. KeyPress::KeyPress() throw()
  48074. : keyCode (0),
  48075. mods (0),
  48076. textCharacter (0)
  48077. {
  48078. }
  48079. KeyPress::KeyPress (const int keyCode_,
  48080. const ModifierKeys& mods_,
  48081. const juce_wchar textCharacter_) throw()
  48082. : keyCode (keyCode_),
  48083. mods (mods_),
  48084. textCharacter (textCharacter_)
  48085. {
  48086. }
  48087. KeyPress::KeyPress (const int keyCode_) throw()
  48088. : keyCode (keyCode_),
  48089. textCharacter (0)
  48090. {
  48091. }
  48092. KeyPress::KeyPress (const KeyPress& other) throw()
  48093. : keyCode (other.keyCode),
  48094. mods (other.mods),
  48095. textCharacter (other.textCharacter)
  48096. {
  48097. }
  48098. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48099. {
  48100. keyCode = other.keyCode;
  48101. mods = other.mods;
  48102. textCharacter = other.textCharacter;
  48103. return *this;
  48104. }
  48105. bool KeyPress::operator== (const KeyPress& other) const throw()
  48106. {
  48107. return mods.getRawFlags() == other.mods.getRawFlags()
  48108. && (textCharacter == other.textCharacter
  48109. || textCharacter == 0
  48110. || other.textCharacter == 0)
  48111. && (keyCode == other.keyCode
  48112. || (keyCode < 256
  48113. && other.keyCode < 256
  48114. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48115. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48116. }
  48117. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48118. {
  48119. return ! operator== (other);
  48120. }
  48121. bool KeyPress::isCurrentlyDown() const
  48122. {
  48123. return isKeyCurrentlyDown (keyCode)
  48124. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48125. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48126. }
  48127. namespace KeyPressHelpers
  48128. {
  48129. struct KeyNameAndCode
  48130. {
  48131. const char* name;
  48132. int code;
  48133. };
  48134. static const KeyNameAndCode translations[] =
  48135. {
  48136. { "spacebar", KeyPress::spaceKey },
  48137. { "return", KeyPress::returnKey },
  48138. { "escape", KeyPress::escapeKey },
  48139. { "backspace", KeyPress::backspaceKey },
  48140. { "cursor left", KeyPress::leftKey },
  48141. { "cursor right", KeyPress::rightKey },
  48142. { "cursor up", KeyPress::upKey },
  48143. { "cursor down", KeyPress::downKey },
  48144. { "page up", KeyPress::pageUpKey },
  48145. { "page down", KeyPress::pageDownKey },
  48146. { "home", KeyPress::homeKey },
  48147. { "end", KeyPress::endKey },
  48148. { "delete", KeyPress::deleteKey },
  48149. { "insert", KeyPress::insertKey },
  48150. { "tab", KeyPress::tabKey },
  48151. { "play", KeyPress::playKey },
  48152. { "stop", KeyPress::stopKey },
  48153. { "fast forward", KeyPress::fastForwardKey },
  48154. { "rewind", KeyPress::rewindKey }
  48155. };
  48156. static const String numberPadPrefix() { return "numpad "; }
  48157. }
  48158. const KeyPress KeyPress::createFromDescription (const String& desc)
  48159. {
  48160. int modifiers = 0;
  48161. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48162. || desc.containsWholeWordIgnoreCase ("control")
  48163. || desc.containsWholeWordIgnoreCase ("ctl"))
  48164. modifiers |= ModifierKeys::ctrlModifier;
  48165. if (desc.containsWholeWordIgnoreCase ("shift")
  48166. || desc.containsWholeWordIgnoreCase ("shft"))
  48167. modifiers |= ModifierKeys::shiftModifier;
  48168. if (desc.containsWholeWordIgnoreCase ("alt")
  48169. || desc.containsWholeWordIgnoreCase ("option"))
  48170. modifiers |= ModifierKeys::altModifier;
  48171. if (desc.containsWholeWordIgnoreCase ("command")
  48172. || desc.containsWholeWordIgnoreCase ("cmd"))
  48173. modifiers |= ModifierKeys::commandModifier;
  48174. int key = 0;
  48175. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48176. {
  48177. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48178. {
  48179. key = KeyPressHelpers::translations[i].code;
  48180. break;
  48181. }
  48182. }
  48183. if (key == 0)
  48184. {
  48185. // see if it's a numpad key..
  48186. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48187. {
  48188. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48189. if (lastChar >= '0' && lastChar <= '9')
  48190. key = numberPad0 + lastChar - '0';
  48191. else if (lastChar == '+')
  48192. key = numberPadAdd;
  48193. else if (lastChar == '-')
  48194. key = numberPadSubtract;
  48195. else if (lastChar == '*')
  48196. key = numberPadMultiply;
  48197. else if (lastChar == '/')
  48198. key = numberPadDivide;
  48199. else if (lastChar == '.')
  48200. key = numberPadDecimalPoint;
  48201. else if (lastChar == '=')
  48202. key = numberPadEquals;
  48203. else if (desc.endsWith ("separator"))
  48204. key = numberPadSeparator;
  48205. else if (desc.endsWith ("delete"))
  48206. key = numberPadDelete;
  48207. }
  48208. if (key == 0)
  48209. {
  48210. // see if it's a function key..
  48211. for (int i = 1; i <= 12; ++i)
  48212. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48213. key = F1Key + i - 1;
  48214. if (key == 0)
  48215. {
  48216. // give up and use the hex code..
  48217. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48218. .toLowerCase()
  48219. .retainCharacters ("0123456789abcdef")
  48220. .getHexValue32();
  48221. if (hexCode > 0)
  48222. key = hexCode;
  48223. else
  48224. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48225. }
  48226. }
  48227. }
  48228. return KeyPress (key, ModifierKeys (modifiers), 0);
  48229. }
  48230. const String KeyPress::getTextDescription() const
  48231. {
  48232. String desc;
  48233. if (keyCode > 0)
  48234. {
  48235. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48236. // want to store it as being a slash, not shift+whatever.
  48237. if (textCharacter == '/')
  48238. return "/";
  48239. if (mods.isCtrlDown())
  48240. desc << "ctrl + ";
  48241. if (mods.isShiftDown())
  48242. desc << "shift + ";
  48243. #if JUCE_MAC
  48244. // only do this on the mac, because on Windows ctrl and command are the same,
  48245. // and this would get confusing
  48246. if (mods.isCommandDown())
  48247. desc << "command + ";
  48248. if (mods.isAltDown())
  48249. desc << "option + ";
  48250. #else
  48251. if (mods.isAltDown())
  48252. desc << "alt + ";
  48253. #endif
  48254. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48255. if (keyCode == KeyPressHelpers::translations[i].code)
  48256. return desc + KeyPressHelpers::translations[i].name;
  48257. if (keyCode >= F1Key && keyCode <= F16Key)
  48258. desc << 'F' << (1 + keyCode - F1Key);
  48259. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48260. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48261. else if (keyCode >= 33 && keyCode < 176)
  48262. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48263. else if (keyCode == numberPadAdd)
  48264. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48265. else if (keyCode == numberPadSubtract)
  48266. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48267. else if (keyCode == numberPadMultiply)
  48268. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48269. else if (keyCode == numberPadDivide)
  48270. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48271. else if (keyCode == numberPadSeparator)
  48272. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48273. else if (keyCode == numberPadDecimalPoint)
  48274. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48275. else if (keyCode == numberPadDelete)
  48276. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48277. else
  48278. desc << '#' << String::toHexString (keyCode);
  48279. }
  48280. return desc;
  48281. }
  48282. END_JUCE_NAMESPACE
  48283. /*** End of inlined file: juce_KeyPress.cpp ***/
  48284. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48285. BEGIN_JUCE_NAMESPACE
  48286. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48287. : commandManager (commandManager_)
  48288. {
  48289. // A manager is needed to get the descriptions of commands, and will be called when
  48290. // a command is invoked. So you can't leave this null..
  48291. jassert (commandManager_ != 0);
  48292. Desktop::getInstance().addFocusChangeListener (this);
  48293. }
  48294. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48295. : commandManager (other.commandManager)
  48296. {
  48297. Desktop::getInstance().addFocusChangeListener (this);
  48298. }
  48299. KeyPressMappingSet::~KeyPressMappingSet()
  48300. {
  48301. Desktop::getInstance().removeFocusChangeListener (this);
  48302. }
  48303. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48304. {
  48305. for (int i = 0; i < mappings.size(); ++i)
  48306. if (mappings.getUnchecked(i)->commandID == commandID)
  48307. return mappings.getUnchecked (i)->keypresses;
  48308. return Array <KeyPress> ();
  48309. }
  48310. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48311. const KeyPress& newKeyPress,
  48312. int insertIndex)
  48313. {
  48314. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48315. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48316. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48317. && ! newKeyPress.getModifiers().isShiftDown()));
  48318. if (findCommandForKeyPress (newKeyPress) != commandID)
  48319. {
  48320. removeKeyPress (newKeyPress);
  48321. if (newKeyPress.isValid())
  48322. {
  48323. for (int i = mappings.size(); --i >= 0;)
  48324. {
  48325. if (mappings.getUnchecked(i)->commandID == commandID)
  48326. {
  48327. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48328. sendChangeMessage (this);
  48329. return;
  48330. }
  48331. }
  48332. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48333. if (ci != 0)
  48334. {
  48335. CommandMapping* const cm = new CommandMapping();
  48336. cm->commandID = commandID;
  48337. cm->keypresses.add (newKeyPress);
  48338. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48339. mappings.add (cm);
  48340. sendChangeMessage (this);
  48341. }
  48342. }
  48343. }
  48344. }
  48345. void KeyPressMappingSet::resetToDefaultMappings()
  48346. {
  48347. mappings.clear();
  48348. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48349. {
  48350. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48351. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48352. {
  48353. addKeyPress (ci->commandID,
  48354. ci->defaultKeypresses.getReference (j));
  48355. }
  48356. }
  48357. sendChangeMessage (this);
  48358. }
  48359. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48360. {
  48361. clearAllKeyPresses (commandID);
  48362. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48363. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48364. {
  48365. addKeyPress (ci->commandID,
  48366. ci->defaultKeypresses.getReference (j));
  48367. }
  48368. }
  48369. void KeyPressMappingSet::clearAllKeyPresses()
  48370. {
  48371. if (mappings.size() > 0)
  48372. {
  48373. sendChangeMessage (this);
  48374. mappings.clear();
  48375. }
  48376. }
  48377. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48378. {
  48379. for (int i = mappings.size(); --i >= 0;)
  48380. {
  48381. if (mappings.getUnchecked(i)->commandID == commandID)
  48382. {
  48383. mappings.remove (i);
  48384. sendChangeMessage (this);
  48385. }
  48386. }
  48387. }
  48388. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48389. {
  48390. if (keypress.isValid())
  48391. {
  48392. for (int i = mappings.size(); --i >= 0;)
  48393. {
  48394. CommandMapping* const cm = mappings.getUnchecked(i);
  48395. for (int j = cm->keypresses.size(); --j >= 0;)
  48396. {
  48397. if (keypress == cm->keypresses [j])
  48398. {
  48399. cm->keypresses.remove (j);
  48400. sendChangeMessage (this);
  48401. }
  48402. }
  48403. }
  48404. }
  48405. }
  48406. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48407. {
  48408. for (int i = mappings.size(); --i >= 0;)
  48409. {
  48410. if (mappings.getUnchecked(i)->commandID == commandID)
  48411. {
  48412. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48413. sendChangeMessage (this);
  48414. break;
  48415. }
  48416. }
  48417. }
  48418. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48419. {
  48420. for (int i = 0; i < mappings.size(); ++i)
  48421. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48422. return mappings.getUnchecked(i)->commandID;
  48423. return 0;
  48424. }
  48425. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48426. {
  48427. for (int i = mappings.size(); --i >= 0;)
  48428. if (mappings.getUnchecked(i)->commandID == commandID)
  48429. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48430. return false;
  48431. }
  48432. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48433. const KeyPress& key,
  48434. const bool isKeyDown,
  48435. const int millisecsSinceKeyPressed,
  48436. Component* const originatingComponent) const
  48437. {
  48438. ApplicationCommandTarget::InvocationInfo info (commandID);
  48439. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48440. info.isKeyDown = isKeyDown;
  48441. info.keyPress = key;
  48442. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48443. info.originatingComponent = originatingComponent;
  48444. commandManager->invoke (info, false);
  48445. }
  48446. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48447. {
  48448. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48449. {
  48450. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48451. {
  48452. // if the XML was created as a set of differences from the default mappings,
  48453. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48454. resetToDefaultMappings();
  48455. }
  48456. else
  48457. {
  48458. // if the XML was created calling createXml (false), then we need to clear all
  48459. // the keys and treat the xml as describing the entire set of mappings.
  48460. clearAllKeyPresses();
  48461. }
  48462. forEachXmlChildElement (xmlVersion, map)
  48463. {
  48464. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48465. if (commandId != 0)
  48466. {
  48467. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48468. if (map->hasTagName ("MAPPING"))
  48469. {
  48470. addKeyPress (commandId, key);
  48471. }
  48472. else if (map->hasTagName ("UNMAPPING"))
  48473. {
  48474. if (containsMapping (commandId, key))
  48475. removeKeyPress (key);
  48476. }
  48477. }
  48478. }
  48479. return true;
  48480. }
  48481. return false;
  48482. }
  48483. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48484. {
  48485. ScopedPointer <KeyPressMappingSet> defaultSet;
  48486. if (saveDifferencesFromDefaultSet)
  48487. {
  48488. defaultSet = new KeyPressMappingSet (commandManager);
  48489. defaultSet->resetToDefaultMappings();
  48490. }
  48491. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48492. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48493. int i;
  48494. for (i = 0; i < mappings.size(); ++i)
  48495. {
  48496. const CommandMapping* const cm = mappings.getUnchecked(i);
  48497. for (int j = 0; j < cm->keypresses.size(); ++j)
  48498. {
  48499. if (defaultSet == 0
  48500. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48501. {
  48502. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48503. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48504. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48505. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48506. }
  48507. }
  48508. }
  48509. if (defaultSet != 0)
  48510. {
  48511. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48512. {
  48513. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48514. for (int j = 0; j < cm->keypresses.size(); ++j)
  48515. {
  48516. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48517. {
  48518. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48519. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48520. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48521. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48522. }
  48523. }
  48524. }
  48525. }
  48526. return doc;
  48527. }
  48528. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48529. Component* originatingComponent)
  48530. {
  48531. bool used = false;
  48532. const CommandID commandID = findCommandForKeyPress (key);
  48533. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48534. if (ci != 0
  48535. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48536. {
  48537. ApplicationCommandInfo info (0);
  48538. if (commandManager->getTargetForCommand (commandID, info) != 0
  48539. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48540. {
  48541. invokeCommand (commandID, key, true, 0, originatingComponent);
  48542. used = true;
  48543. }
  48544. else
  48545. {
  48546. if (originatingComponent != 0)
  48547. originatingComponent->getLookAndFeel().playAlertSound();
  48548. }
  48549. }
  48550. return used;
  48551. }
  48552. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48553. {
  48554. bool used = false;
  48555. const uint32 now = Time::getMillisecondCounter();
  48556. for (int i = mappings.size(); --i >= 0;)
  48557. {
  48558. CommandMapping* const cm = mappings.getUnchecked(i);
  48559. if (cm->wantsKeyUpDownCallbacks)
  48560. {
  48561. for (int j = cm->keypresses.size(); --j >= 0;)
  48562. {
  48563. const KeyPress key (cm->keypresses.getReference (j));
  48564. const bool isDown = key.isCurrentlyDown();
  48565. int keyPressEntryIndex = 0;
  48566. bool wasDown = false;
  48567. for (int k = keysDown.size(); --k >= 0;)
  48568. {
  48569. if (key == keysDown.getUnchecked(k)->key)
  48570. {
  48571. keyPressEntryIndex = k;
  48572. wasDown = true;
  48573. used = true;
  48574. break;
  48575. }
  48576. }
  48577. if (isDown != wasDown)
  48578. {
  48579. int millisecs = 0;
  48580. if (isDown)
  48581. {
  48582. KeyPressTime* const k = new KeyPressTime();
  48583. k->key = key;
  48584. k->timeWhenPressed = now;
  48585. keysDown.add (k);
  48586. }
  48587. else
  48588. {
  48589. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48590. if (now > pressTime)
  48591. millisecs = now - pressTime;
  48592. keysDown.remove (keyPressEntryIndex);
  48593. }
  48594. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48595. used = true;
  48596. }
  48597. }
  48598. }
  48599. }
  48600. return used;
  48601. }
  48602. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48603. {
  48604. if (focusedComponent != 0)
  48605. focusedComponent->keyStateChanged (false);
  48606. }
  48607. END_JUCE_NAMESPACE
  48608. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48609. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48610. BEGIN_JUCE_NAMESPACE
  48611. ModifierKeys::ModifierKeys (const int flags_) throw()
  48612. : flags (flags_)
  48613. {
  48614. }
  48615. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48616. : flags (other.flags)
  48617. {
  48618. }
  48619. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48620. {
  48621. flags = other.flags;
  48622. return *this;
  48623. }
  48624. ModifierKeys ModifierKeys::currentModifiers;
  48625. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48626. {
  48627. return currentModifiers;
  48628. }
  48629. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48630. {
  48631. int num = 0;
  48632. if (isLeftButtonDown()) ++num;
  48633. if (isRightButtonDown()) ++num;
  48634. if (isMiddleButtonDown()) ++num;
  48635. return num;
  48636. }
  48637. END_JUCE_NAMESPACE
  48638. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48639. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48640. BEGIN_JUCE_NAMESPACE
  48641. class ComponentAnimator::AnimationTask
  48642. {
  48643. public:
  48644. AnimationTask (Component* const comp)
  48645. : component (comp)
  48646. {
  48647. }
  48648. Component::SafePointer<Component> component;
  48649. Rectangle<int> destination;
  48650. int msElapsed, msTotal;
  48651. double startSpeed, midSpeed, endSpeed, lastProgress;
  48652. double left, top, right, bottom;
  48653. bool useTimeslice (const int elapsed)
  48654. {
  48655. if (component == 0)
  48656. return false;
  48657. msElapsed += elapsed;
  48658. double newProgress = msElapsed / (double) msTotal;
  48659. if (newProgress >= 0 && newProgress < 1.0)
  48660. {
  48661. newProgress = timeToDistance (newProgress);
  48662. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48663. jassert (newProgress >= lastProgress);
  48664. lastProgress = newProgress;
  48665. left += (destination.getX() - left) * delta;
  48666. top += (destination.getY() - top) * delta;
  48667. right += (destination.getRight() - right) * delta;
  48668. bottom += (destination.getBottom() - bottom) * delta;
  48669. if (delta < 1.0)
  48670. {
  48671. const Rectangle<int> newBounds (roundToInt (left),
  48672. roundToInt (top),
  48673. roundToInt (right - left),
  48674. roundToInt (bottom - top));
  48675. if (newBounds != destination)
  48676. {
  48677. component->setBounds (newBounds);
  48678. return true;
  48679. }
  48680. }
  48681. }
  48682. component->setBounds (destination);
  48683. return false;
  48684. }
  48685. void moveToFinalDestination()
  48686. {
  48687. if (component != 0)
  48688. component->setBounds (destination);
  48689. }
  48690. private:
  48691. inline double timeToDistance (const double time) const
  48692. {
  48693. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48694. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48695. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48696. }
  48697. };
  48698. ComponentAnimator::ComponentAnimator()
  48699. : lastTime (0)
  48700. {
  48701. }
  48702. ComponentAnimator::~ComponentAnimator()
  48703. {
  48704. cancelAllAnimations (false);
  48705. jassert (tasks.size() == 0);
  48706. }
  48707. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48708. {
  48709. for (int i = tasks.size(); --i >= 0;)
  48710. if (component == tasks.getUnchecked(i)->component.getComponent())
  48711. return tasks.getUnchecked(i);
  48712. return 0;
  48713. }
  48714. void ComponentAnimator::animateComponent (Component* const component,
  48715. const Rectangle<int>& finalPosition,
  48716. const int millisecondsToSpendMoving,
  48717. const double startSpeed,
  48718. const double endSpeed)
  48719. {
  48720. if (component != 0)
  48721. {
  48722. AnimationTask* at = findTaskFor (component);
  48723. if (at == 0)
  48724. {
  48725. at = new AnimationTask (component);
  48726. tasks.add (at);
  48727. sendChangeMessage (this);
  48728. }
  48729. at->msElapsed = 0;
  48730. at->lastProgress = 0;
  48731. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48732. at->destination = finalPosition;
  48733. // the speeds must be 0 or greater!
  48734. jassert (startSpeed >= 0 && endSpeed >= 0)
  48735. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48736. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48737. at->midSpeed = invTotalDistance;
  48738. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48739. at->left = component->getX();
  48740. at->top = component->getY();
  48741. at->right = component->getRight();
  48742. at->bottom = component->getBottom();
  48743. if (! isTimerRunning())
  48744. {
  48745. lastTime = Time::getMillisecondCounter();
  48746. startTimer (1000 / 50);
  48747. }
  48748. }
  48749. }
  48750. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48751. {
  48752. for (int i = tasks.size(); --i >= 0;)
  48753. {
  48754. AnimationTask* const at = tasks.getUnchecked(i);
  48755. if (moveComponentsToTheirFinalPositions)
  48756. at->moveToFinalDestination();
  48757. delete at;
  48758. tasks.remove (i);
  48759. sendChangeMessage (this);
  48760. }
  48761. }
  48762. void ComponentAnimator::cancelAnimation (Component* const component,
  48763. const bool moveComponentToItsFinalPosition)
  48764. {
  48765. AnimationTask* const at = findTaskFor (component);
  48766. if (at != 0)
  48767. {
  48768. if (moveComponentToItsFinalPosition)
  48769. at->moveToFinalDestination();
  48770. tasks.removeValue (at);
  48771. delete at;
  48772. sendChangeMessage (this);
  48773. }
  48774. }
  48775. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48776. {
  48777. AnimationTask* const at = findTaskFor (component);
  48778. if (at != 0)
  48779. return at->destination;
  48780. else if (component != 0)
  48781. return component->getBounds();
  48782. return Rectangle<int>();
  48783. }
  48784. bool ComponentAnimator::isAnimating (Component* component) const
  48785. {
  48786. return findTaskFor (component) != 0;
  48787. }
  48788. void ComponentAnimator::timerCallback()
  48789. {
  48790. const uint32 timeNow = Time::getMillisecondCounter();
  48791. if (lastTime == 0 || lastTime == timeNow)
  48792. lastTime = timeNow;
  48793. const int elapsed = timeNow - lastTime;
  48794. for (int i = tasks.size(); --i >= 0;)
  48795. {
  48796. AnimationTask* const at = tasks.getUnchecked(i);
  48797. if (! at->useTimeslice (elapsed))
  48798. {
  48799. tasks.remove (i);
  48800. delete at;
  48801. sendChangeMessage (this);
  48802. }
  48803. }
  48804. lastTime = timeNow;
  48805. if (tasks.size() == 0)
  48806. stopTimer();
  48807. }
  48808. END_JUCE_NAMESPACE
  48809. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48810. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48811. BEGIN_JUCE_NAMESPACE
  48812. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48813. : minW (0),
  48814. maxW (0x3fffffff),
  48815. minH (0),
  48816. maxH (0x3fffffff),
  48817. minOffTop (0),
  48818. minOffLeft (0),
  48819. minOffBottom (0),
  48820. minOffRight (0),
  48821. aspectRatio (0.0)
  48822. {
  48823. }
  48824. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48825. {
  48826. }
  48827. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48828. {
  48829. minW = minimumWidth;
  48830. }
  48831. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48832. {
  48833. maxW = maximumWidth;
  48834. }
  48835. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48836. {
  48837. minH = minimumHeight;
  48838. }
  48839. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48840. {
  48841. maxH = maximumHeight;
  48842. }
  48843. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48844. {
  48845. jassert (maxW >= minimumWidth);
  48846. jassert (maxH >= minimumHeight);
  48847. jassert (minimumWidth > 0 && minimumHeight > 0);
  48848. minW = minimumWidth;
  48849. minH = minimumHeight;
  48850. if (minW > maxW)
  48851. maxW = minW;
  48852. if (minH > maxH)
  48853. maxH = minH;
  48854. }
  48855. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48856. {
  48857. jassert (maximumWidth >= minW);
  48858. jassert (maximumHeight >= minH);
  48859. jassert (maximumWidth > 0 && maximumHeight > 0);
  48860. maxW = jmax (minW, maximumWidth);
  48861. maxH = jmax (minH, maximumHeight);
  48862. }
  48863. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48864. const int minimumHeight,
  48865. const int maximumWidth,
  48866. const int maximumHeight) throw()
  48867. {
  48868. jassert (maximumWidth >= minimumWidth);
  48869. jassert (maximumHeight >= minimumHeight);
  48870. jassert (maximumWidth > 0 && maximumHeight > 0);
  48871. jassert (minimumWidth > 0 && minimumHeight > 0);
  48872. minW = jmax (0, minimumWidth);
  48873. minH = jmax (0, minimumHeight);
  48874. maxW = jmax (minW, maximumWidth);
  48875. maxH = jmax (minH, maximumHeight);
  48876. }
  48877. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48878. const int minimumWhenOffTheLeft,
  48879. const int minimumWhenOffTheBottom,
  48880. const int minimumWhenOffTheRight) throw()
  48881. {
  48882. minOffTop = minimumWhenOffTheTop;
  48883. minOffLeft = minimumWhenOffTheLeft;
  48884. minOffBottom = minimumWhenOffTheBottom;
  48885. minOffRight = minimumWhenOffTheRight;
  48886. }
  48887. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48888. {
  48889. aspectRatio = jmax (0.0, widthOverHeight);
  48890. }
  48891. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48892. {
  48893. return aspectRatio;
  48894. }
  48895. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48896. const Rectangle<int>& targetBounds,
  48897. const bool isStretchingTop,
  48898. const bool isStretchingLeft,
  48899. const bool isStretchingBottom,
  48900. const bool isStretchingRight)
  48901. {
  48902. jassert (component != 0);
  48903. Rectangle<int> limits, bounds (targetBounds);
  48904. BorderSize border;
  48905. Component* const parent = component->getParentComponent();
  48906. if (parent == 0)
  48907. {
  48908. ComponentPeer* peer = component->getPeer();
  48909. if (peer != 0)
  48910. border = peer->getFrameSize();
  48911. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48912. }
  48913. else
  48914. {
  48915. limits.setSize (parent->getWidth(), parent->getHeight());
  48916. }
  48917. border.addTo (bounds);
  48918. checkBounds (bounds,
  48919. border.addedTo (component->getBounds()), limits,
  48920. isStretchingTop, isStretchingLeft,
  48921. isStretchingBottom, isStretchingRight);
  48922. border.subtractFrom (bounds);
  48923. applyBoundsToComponent (component, bounds);
  48924. }
  48925. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48926. {
  48927. setBoundsForComponent (component, component->getBounds(),
  48928. false, false, false, false);
  48929. }
  48930. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48931. const Rectangle<int>& bounds)
  48932. {
  48933. component->setBounds (bounds);
  48934. }
  48935. void ComponentBoundsConstrainer::resizeStart()
  48936. {
  48937. }
  48938. void ComponentBoundsConstrainer::resizeEnd()
  48939. {
  48940. }
  48941. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48942. const Rectangle<int>& old,
  48943. const Rectangle<int>& limits,
  48944. const bool isStretchingTop,
  48945. const bool isStretchingLeft,
  48946. const bool isStretchingBottom,
  48947. const bool isStretchingRight)
  48948. {
  48949. int x = bounds.getX();
  48950. int y = bounds.getY();
  48951. int w = bounds.getWidth();
  48952. int h = bounds.getHeight();
  48953. // constrain the size if it's being stretched..
  48954. if (isStretchingLeft)
  48955. {
  48956. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48957. w = old.getRight() - x;
  48958. }
  48959. if (isStretchingRight)
  48960. {
  48961. w = jlimit (minW, maxW, w);
  48962. }
  48963. if (isStretchingTop)
  48964. {
  48965. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48966. h = old.getBottom() - y;
  48967. }
  48968. if (isStretchingBottom)
  48969. {
  48970. h = jlimit (minH, maxH, h);
  48971. }
  48972. // constrain the aspect ratio if one has been specified..
  48973. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48974. {
  48975. bool adjustWidth;
  48976. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48977. {
  48978. adjustWidth = true;
  48979. }
  48980. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48981. {
  48982. adjustWidth = false;
  48983. }
  48984. else
  48985. {
  48986. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48987. const double newRatio = std::abs (w / (double) h);
  48988. adjustWidth = (oldRatio > newRatio);
  48989. }
  48990. if (adjustWidth)
  48991. {
  48992. w = roundToInt (h * aspectRatio);
  48993. if (w > maxW || w < minW)
  48994. {
  48995. w = jlimit (minW, maxW, w);
  48996. h = roundToInt (w / aspectRatio);
  48997. }
  48998. }
  48999. else
  49000. {
  49001. h = roundToInt (w / aspectRatio);
  49002. if (h > maxH || h < minH)
  49003. {
  49004. h = jlimit (minH, maxH, h);
  49005. w = roundToInt (h * aspectRatio);
  49006. }
  49007. }
  49008. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49009. {
  49010. x = old.getX() + (old.getWidth() - w) / 2;
  49011. }
  49012. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49013. {
  49014. y = old.getY() + (old.getHeight() - h) / 2;
  49015. }
  49016. else
  49017. {
  49018. if (isStretchingLeft)
  49019. x = old.getRight() - w;
  49020. if (isStretchingTop)
  49021. y = old.getBottom() - h;
  49022. }
  49023. }
  49024. // ...and constrain the position if limits have been set for that.
  49025. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49026. {
  49027. if (minOffTop > 0)
  49028. {
  49029. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49030. if (y < limit)
  49031. {
  49032. if (isStretchingTop)
  49033. h -= (limit - y);
  49034. y = limit;
  49035. }
  49036. }
  49037. if (minOffLeft > 0)
  49038. {
  49039. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49040. if (x < limit)
  49041. {
  49042. if (isStretchingLeft)
  49043. w -= (limit - x);
  49044. x = limit;
  49045. }
  49046. }
  49047. if (minOffBottom > 0)
  49048. {
  49049. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49050. if (y > limit)
  49051. {
  49052. if (isStretchingBottom)
  49053. h += (limit - y);
  49054. else
  49055. y = limit;
  49056. }
  49057. }
  49058. if (minOffRight > 0)
  49059. {
  49060. const int limit = limits.getRight() - jmin (minOffRight, w);
  49061. if (x > limit)
  49062. {
  49063. if (isStretchingRight)
  49064. w += (limit - x);
  49065. else
  49066. x = limit;
  49067. }
  49068. }
  49069. }
  49070. jassert (w >= 0 && h >= 0);
  49071. bounds = Rectangle<int> (x, y, w, h);
  49072. }
  49073. END_JUCE_NAMESPACE
  49074. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49075. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49076. BEGIN_JUCE_NAMESPACE
  49077. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49078. : component (component_),
  49079. lastPeer (0),
  49080. reentrant (false)
  49081. {
  49082. jassert (component != 0); // can't use this with a null pointer..
  49083. component->addComponentListener (this);
  49084. registerWithParentComps();
  49085. }
  49086. ComponentMovementWatcher::~ComponentMovementWatcher()
  49087. {
  49088. component->removeComponentListener (this);
  49089. unregister();
  49090. }
  49091. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49092. {
  49093. // agh! don't delete the target component without deleting this object first!
  49094. jassert (component != 0);
  49095. if (! reentrant)
  49096. {
  49097. reentrant = true;
  49098. ComponentPeer* const peer = component->getPeer();
  49099. if (peer != lastPeer)
  49100. {
  49101. componentPeerChanged();
  49102. if (component == 0)
  49103. return;
  49104. lastPeer = peer;
  49105. }
  49106. unregister();
  49107. registerWithParentComps();
  49108. reentrant = false;
  49109. componentMovedOrResized (*component, true, true);
  49110. }
  49111. }
  49112. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49113. {
  49114. // agh! don't delete the target component without deleting this object first!
  49115. jassert (component != 0);
  49116. if (wasMoved)
  49117. {
  49118. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49119. wasMoved = lastBounds.getPosition() != pos;
  49120. lastBounds.setPosition (pos);
  49121. }
  49122. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49123. lastBounds.setSize (component->getWidth(), component->getHeight());
  49124. if (wasMoved || wasResized)
  49125. componentMovedOrResized (wasMoved, wasResized);
  49126. }
  49127. void ComponentMovementWatcher::registerWithParentComps()
  49128. {
  49129. Component* p = component->getParentComponent();
  49130. while (p != 0)
  49131. {
  49132. p->addComponentListener (this);
  49133. registeredParentComps.add (p);
  49134. p = p->getParentComponent();
  49135. }
  49136. }
  49137. void ComponentMovementWatcher::unregister()
  49138. {
  49139. for (int i = registeredParentComps.size(); --i >= 0;)
  49140. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49141. registeredParentComps.clear();
  49142. }
  49143. END_JUCE_NAMESPACE
  49144. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49145. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49146. BEGIN_JUCE_NAMESPACE
  49147. GroupComponent::GroupComponent (const String& componentName,
  49148. const String& labelText)
  49149. : Component (componentName),
  49150. text (labelText),
  49151. justification (Justification::left)
  49152. {
  49153. setInterceptsMouseClicks (false, true);
  49154. }
  49155. GroupComponent::~GroupComponent()
  49156. {
  49157. }
  49158. void GroupComponent::setText (const String& newText)
  49159. {
  49160. if (text != newText)
  49161. {
  49162. text = newText;
  49163. repaint();
  49164. }
  49165. }
  49166. const String GroupComponent::getText() const
  49167. {
  49168. return text;
  49169. }
  49170. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49171. {
  49172. if (justification != newJustification)
  49173. {
  49174. justification = newJustification;
  49175. repaint();
  49176. }
  49177. }
  49178. void GroupComponent::paint (Graphics& g)
  49179. {
  49180. getLookAndFeel()
  49181. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49182. text, justification,
  49183. *this);
  49184. }
  49185. void GroupComponent::enablementChanged()
  49186. {
  49187. repaint();
  49188. }
  49189. void GroupComponent::colourChanged()
  49190. {
  49191. repaint();
  49192. }
  49193. END_JUCE_NAMESPACE
  49194. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49195. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49196. BEGIN_JUCE_NAMESPACE
  49197. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49198. : DocumentWindow (String::empty, backgroundColour,
  49199. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49200. {
  49201. }
  49202. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49203. {
  49204. }
  49205. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49206. {
  49207. MultiDocumentPanel* const owner = getOwner();
  49208. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49209. if (owner != 0)
  49210. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49211. }
  49212. void MultiDocumentPanelWindow::closeButtonPressed()
  49213. {
  49214. MultiDocumentPanel* const owner = getOwner();
  49215. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49216. if (owner != 0)
  49217. owner->closeDocument (getContentComponent(), true);
  49218. }
  49219. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49220. {
  49221. DocumentWindow::activeWindowStatusChanged();
  49222. updateOrder();
  49223. }
  49224. void MultiDocumentPanelWindow::broughtToFront()
  49225. {
  49226. DocumentWindow::broughtToFront();
  49227. updateOrder();
  49228. }
  49229. void MultiDocumentPanelWindow::updateOrder()
  49230. {
  49231. MultiDocumentPanel* const owner = getOwner();
  49232. if (owner != 0)
  49233. owner->updateOrder();
  49234. }
  49235. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49236. {
  49237. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49238. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49239. }
  49240. class MDITabbedComponentInternal : public TabbedComponent
  49241. {
  49242. public:
  49243. MDITabbedComponentInternal()
  49244. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49245. {
  49246. }
  49247. ~MDITabbedComponentInternal()
  49248. {
  49249. }
  49250. void currentTabChanged (int, const String&)
  49251. {
  49252. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49253. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49254. if (owner != 0)
  49255. owner->updateOrder();
  49256. }
  49257. };
  49258. MultiDocumentPanel::MultiDocumentPanel()
  49259. : mode (MaximisedWindowsWithTabs),
  49260. tabComponent (0),
  49261. backgroundColour (Colours::lightblue),
  49262. maximumNumDocuments (0),
  49263. numDocsBeforeTabsUsed (0)
  49264. {
  49265. setOpaque (true);
  49266. }
  49267. MultiDocumentPanel::~MultiDocumentPanel()
  49268. {
  49269. closeAllDocuments (false);
  49270. }
  49271. static bool shouldDeleteComp (Component* const c)
  49272. {
  49273. return c->getProperties() ["mdiDocumentDelete_"];
  49274. }
  49275. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49276. {
  49277. while (components.size() > 0)
  49278. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49279. return false;
  49280. return true;
  49281. }
  49282. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49283. {
  49284. return new MultiDocumentPanelWindow (backgroundColour);
  49285. }
  49286. void MultiDocumentPanel::addWindow (Component* component)
  49287. {
  49288. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49289. dw->setResizable (true, false);
  49290. dw->setContentComponent (component, false, true);
  49291. dw->setName (component->getName());
  49292. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49293. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49294. int x = 4;
  49295. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49296. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49297. x += 16;
  49298. dw->setTopLeftPosition (x, x);
  49299. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49300. if (pos.toString().isNotEmpty())
  49301. dw->restoreWindowStateFromString (pos.toString());
  49302. addAndMakeVisible (dw);
  49303. dw->toFront (true);
  49304. }
  49305. bool MultiDocumentPanel::addDocument (Component* const component,
  49306. const Colour& docColour,
  49307. const bool deleteWhenRemoved)
  49308. {
  49309. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49310. // with a frame-within-a-frame! Just pass in the bare content component.
  49311. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49312. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49313. return false;
  49314. components.add (component);
  49315. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49316. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49317. component->addComponentListener (this);
  49318. if (mode == FloatingWindows)
  49319. {
  49320. if (isFullscreenWhenOneDocument())
  49321. {
  49322. if (components.size() == 1)
  49323. {
  49324. addAndMakeVisible (component);
  49325. }
  49326. else
  49327. {
  49328. if (components.size() == 2)
  49329. addWindow (components.getFirst());
  49330. addWindow (component);
  49331. }
  49332. }
  49333. else
  49334. {
  49335. addWindow (component);
  49336. }
  49337. }
  49338. else
  49339. {
  49340. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49341. {
  49342. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49343. Array <Component*> temp (components);
  49344. for (int i = 0; i < temp.size(); ++i)
  49345. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49346. resized();
  49347. }
  49348. else
  49349. {
  49350. if (tabComponent != 0)
  49351. tabComponent->addTab (component->getName(), docColour, component, false);
  49352. else
  49353. addAndMakeVisible (component);
  49354. }
  49355. setActiveDocument (component);
  49356. }
  49357. resized();
  49358. activeDocumentChanged();
  49359. return true;
  49360. }
  49361. bool MultiDocumentPanel::closeDocument (Component* component,
  49362. const bool checkItsOkToCloseFirst)
  49363. {
  49364. if (components.contains (component))
  49365. {
  49366. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49367. return false;
  49368. component->removeComponentListener (this);
  49369. const bool shouldDelete = shouldDeleteComp (component);
  49370. component->getProperties().remove ("mdiDocumentDelete_");
  49371. component->getProperties().remove ("mdiDocumentBkg_");
  49372. if (mode == FloatingWindows)
  49373. {
  49374. for (int i = getNumChildComponents(); --i >= 0;)
  49375. {
  49376. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49377. if (dw != 0 && dw->getContentComponent() == component)
  49378. {
  49379. dw->setContentComponent (0, false);
  49380. delete dw;
  49381. break;
  49382. }
  49383. }
  49384. if (shouldDelete)
  49385. delete component;
  49386. components.removeValue (component);
  49387. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49388. {
  49389. for (int i = getNumChildComponents(); --i >= 0;)
  49390. {
  49391. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49392. if (dw != 0)
  49393. {
  49394. dw->setContentComponent (0, false);
  49395. delete dw;
  49396. }
  49397. }
  49398. addAndMakeVisible (components.getFirst());
  49399. }
  49400. }
  49401. else
  49402. {
  49403. jassert (components.indexOf (component) >= 0);
  49404. if (tabComponent != 0)
  49405. {
  49406. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49407. if (tabComponent->getTabContentComponent (i) == component)
  49408. tabComponent->removeTab (i);
  49409. }
  49410. else
  49411. {
  49412. removeChildComponent (component);
  49413. }
  49414. if (shouldDelete)
  49415. delete component;
  49416. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49417. deleteAndZero (tabComponent);
  49418. components.removeValue (component);
  49419. if (components.size() > 0 && tabComponent == 0)
  49420. addAndMakeVisible (components.getFirst());
  49421. }
  49422. resized();
  49423. activeDocumentChanged();
  49424. }
  49425. else
  49426. {
  49427. jassertfalse;
  49428. }
  49429. return true;
  49430. }
  49431. int MultiDocumentPanel::getNumDocuments() const throw()
  49432. {
  49433. return components.size();
  49434. }
  49435. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49436. {
  49437. return components [index];
  49438. }
  49439. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49440. {
  49441. if (mode == FloatingWindows)
  49442. {
  49443. for (int i = getNumChildComponents(); --i >= 0;)
  49444. {
  49445. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49446. if (dw != 0 && dw->isActiveWindow())
  49447. return dw->getContentComponent();
  49448. }
  49449. }
  49450. return components.getLast();
  49451. }
  49452. void MultiDocumentPanel::setActiveDocument (Component* component)
  49453. {
  49454. if (mode == FloatingWindows)
  49455. {
  49456. component = getContainerComp (component);
  49457. if (component != 0)
  49458. component->toFront (true);
  49459. }
  49460. else if (tabComponent != 0)
  49461. {
  49462. jassert (components.indexOf (component) >= 0);
  49463. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49464. {
  49465. if (tabComponent->getTabContentComponent (i) == component)
  49466. {
  49467. tabComponent->setCurrentTabIndex (i);
  49468. break;
  49469. }
  49470. }
  49471. }
  49472. else
  49473. {
  49474. component->grabKeyboardFocus();
  49475. }
  49476. }
  49477. void MultiDocumentPanel::activeDocumentChanged()
  49478. {
  49479. }
  49480. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49481. {
  49482. maximumNumDocuments = newNumber;
  49483. }
  49484. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49485. {
  49486. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49487. }
  49488. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49489. {
  49490. return numDocsBeforeTabsUsed != 0;
  49491. }
  49492. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49493. {
  49494. if (mode != newLayoutMode)
  49495. {
  49496. mode = newLayoutMode;
  49497. if (mode == FloatingWindows)
  49498. {
  49499. deleteAndZero (tabComponent);
  49500. }
  49501. else
  49502. {
  49503. for (int i = getNumChildComponents(); --i >= 0;)
  49504. {
  49505. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49506. if (dw != 0)
  49507. {
  49508. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49509. dw->setContentComponent (0, false);
  49510. delete dw;
  49511. }
  49512. }
  49513. }
  49514. resized();
  49515. const Array <Component*> tempComps (components);
  49516. components.clear();
  49517. for (int i = 0; i < tempComps.size(); ++i)
  49518. {
  49519. Component* const c = tempComps.getUnchecked(i);
  49520. addDocument (c,
  49521. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49522. shouldDeleteComp (c));
  49523. }
  49524. }
  49525. }
  49526. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49527. {
  49528. if (backgroundColour != newBackgroundColour)
  49529. {
  49530. backgroundColour = newBackgroundColour;
  49531. setOpaque (newBackgroundColour.isOpaque());
  49532. repaint();
  49533. }
  49534. }
  49535. void MultiDocumentPanel::paint (Graphics& g)
  49536. {
  49537. g.fillAll (backgroundColour);
  49538. }
  49539. void MultiDocumentPanel::resized()
  49540. {
  49541. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49542. {
  49543. for (int i = getNumChildComponents(); --i >= 0;)
  49544. getChildComponent (i)->setBounds (getLocalBounds());
  49545. }
  49546. setWantsKeyboardFocus (components.size() == 0);
  49547. }
  49548. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49549. {
  49550. if (mode == FloatingWindows)
  49551. {
  49552. for (int i = 0; i < getNumChildComponents(); ++i)
  49553. {
  49554. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49555. if (dw != 0 && dw->getContentComponent() == c)
  49556. {
  49557. c = dw;
  49558. break;
  49559. }
  49560. }
  49561. }
  49562. return c;
  49563. }
  49564. void MultiDocumentPanel::componentNameChanged (Component&)
  49565. {
  49566. if (mode == FloatingWindows)
  49567. {
  49568. for (int i = 0; i < getNumChildComponents(); ++i)
  49569. {
  49570. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49571. if (dw != 0)
  49572. dw->setName (dw->getContentComponent()->getName());
  49573. }
  49574. }
  49575. else if (tabComponent != 0)
  49576. {
  49577. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49578. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49579. }
  49580. }
  49581. void MultiDocumentPanel::updateOrder()
  49582. {
  49583. const Array <Component*> oldList (components);
  49584. if (mode == FloatingWindows)
  49585. {
  49586. components.clear();
  49587. for (int i = 0; i < getNumChildComponents(); ++i)
  49588. {
  49589. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49590. if (dw != 0)
  49591. components.add (dw->getContentComponent());
  49592. }
  49593. }
  49594. else
  49595. {
  49596. if (tabComponent != 0)
  49597. {
  49598. Component* const current = tabComponent->getCurrentContentComponent();
  49599. if (current != 0)
  49600. {
  49601. components.removeValue (current);
  49602. components.add (current);
  49603. }
  49604. }
  49605. }
  49606. if (components != oldList)
  49607. activeDocumentChanged();
  49608. }
  49609. END_JUCE_NAMESPACE
  49610. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49611. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49612. BEGIN_JUCE_NAMESPACE
  49613. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49614. : zone (zoneFlags)
  49615. {
  49616. }
  49617. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49618. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49619. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49620. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49621. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49622. const BorderSize& border,
  49623. const Point<int>& position)
  49624. {
  49625. int z = 0;
  49626. if (totalSize.contains (position)
  49627. && ! border.subtractedFrom (totalSize).contains (position))
  49628. {
  49629. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49630. if (position.getX() < jmax (border.getLeft(), minW))
  49631. z |= left;
  49632. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49633. z |= right;
  49634. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49635. if (position.getY() < jmax (border.getTop(), minH))
  49636. z |= top;
  49637. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49638. z |= bottom;
  49639. }
  49640. return Zone (z);
  49641. }
  49642. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49643. {
  49644. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49645. switch (zone)
  49646. {
  49647. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49648. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49649. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49650. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49651. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49652. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49653. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49654. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49655. default: break;
  49656. }
  49657. return mc;
  49658. }
  49659. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49660. {
  49661. if (isDraggingWholeObject())
  49662. return b + offset;
  49663. if (isDraggingLeftEdge())
  49664. b.setLeft (b.getX() + offset.getX());
  49665. if (isDraggingRightEdge())
  49666. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49667. if (isDraggingTopEdge())
  49668. b.setTop (b.getY() + offset.getY());
  49669. if (isDraggingBottomEdge())
  49670. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49671. return b;
  49672. }
  49673. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49674. {
  49675. if (isDraggingWholeObject())
  49676. return b + offset;
  49677. if (isDraggingLeftEdge())
  49678. b.setLeft (b.getX() + offset.getX());
  49679. if (isDraggingRightEdge())
  49680. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49681. if (isDraggingTopEdge())
  49682. b.setTop (b.getY() + offset.getY());
  49683. if (isDraggingBottomEdge())
  49684. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49685. return b;
  49686. }
  49687. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49688. ComponentBoundsConstrainer* const constrainer_)
  49689. : component (componentToResize),
  49690. constrainer (constrainer_),
  49691. borderSize (5),
  49692. mouseZone (0)
  49693. {
  49694. }
  49695. ResizableBorderComponent::~ResizableBorderComponent()
  49696. {
  49697. }
  49698. void ResizableBorderComponent::paint (Graphics& g)
  49699. {
  49700. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49701. }
  49702. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49703. {
  49704. updateMouseZone (e);
  49705. }
  49706. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49707. {
  49708. updateMouseZone (e);
  49709. }
  49710. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49711. {
  49712. if (component == 0)
  49713. {
  49714. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49715. return;
  49716. }
  49717. updateMouseZone (e);
  49718. originalBounds = component->getBounds();
  49719. if (constrainer != 0)
  49720. constrainer->resizeStart();
  49721. }
  49722. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49723. {
  49724. if (component == 0)
  49725. {
  49726. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49727. return;
  49728. }
  49729. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49730. if (constrainer != 0)
  49731. constrainer->setBoundsForComponent (component, bounds,
  49732. mouseZone.isDraggingTopEdge(),
  49733. mouseZone.isDraggingLeftEdge(),
  49734. mouseZone.isDraggingBottomEdge(),
  49735. mouseZone.isDraggingRightEdge());
  49736. else
  49737. component->setBounds (bounds);
  49738. }
  49739. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49740. {
  49741. if (constrainer != 0)
  49742. constrainer->resizeEnd();
  49743. }
  49744. bool ResizableBorderComponent::hitTest (int x, int y)
  49745. {
  49746. return x < borderSize.getLeft()
  49747. || x >= getWidth() - borderSize.getRight()
  49748. || y < borderSize.getTop()
  49749. || y >= getHeight() - borderSize.getBottom();
  49750. }
  49751. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49752. {
  49753. if (borderSize != newBorderSize)
  49754. {
  49755. borderSize = newBorderSize;
  49756. repaint();
  49757. }
  49758. }
  49759. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49760. {
  49761. return borderSize;
  49762. }
  49763. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49764. {
  49765. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49766. if (mouseZone != newZone)
  49767. {
  49768. mouseZone = newZone;
  49769. setMouseCursor (newZone.getMouseCursor());
  49770. }
  49771. }
  49772. END_JUCE_NAMESPACE
  49773. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49774. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49775. BEGIN_JUCE_NAMESPACE
  49776. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49777. ComponentBoundsConstrainer* const constrainer_)
  49778. : component (componentToResize),
  49779. constrainer (constrainer_)
  49780. {
  49781. setRepaintsOnMouseActivity (true);
  49782. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49783. }
  49784. ResizableCornerComponent::~ResizableCornerComponent()
  49785. {
  49786. }
  49787. void ResizableCornerComponent::paint (Graphics& g)
  49788. {
  49789. getLookAndFeel()
  49790. .drawCornerResizer (g, getWidth(), getHeight(),
  49791. isMouseOverOrDragging(),
  49792. isMouseButtonDown());
  49793. }
  49794. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49795. {
  49796. if (component == 0)
  49797. {
  49798. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49799. return;
  49800. }
  49801. originalBounds = component->getBounds();
  49802. if (constrainer != 0)
  49803. constrainer->resizeStart();
  49804. }
  49805. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49806. {
  49807. if (component == 0)
  49808. {
  49809. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49810. return;
  49811. }
  49812. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49813. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49814. if (constrainer != 0)
  49815. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49816. else
  49817. component->setBounds (r);
  49818. }
  49819. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49820. {
  49821. if (constrainer != 0)
  49822. constrainer->resizeStart();
  49823. }
  49824. bool ResizableCornerComponent::hitTest (int x, int y)
  49825. {
  49826. if (getWidth() <= 0)
  49827. return false;
  49828. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49829. return y >= yAtX - getHeight() / 4;
  49830. }
  49831. END_JUCE_NAMESPACE
  49832. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49833. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49834. BEGIN_JUCE_NAMESPACE
  49835. class ScrollBar::ScrollbarButton : public Button
  49836. {
  49837. public:
  49838. int direction;
  49839. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49840. : Button (String::empty),
  49841. direction (direction_),
  49842. owner (owner_)
  49843. {
  49844. setWantsKeyboardFocus (false);
  49845. }
  49846. ~ScrollbarButton()
  49847. {
  49848. }
  49849. void paintButton (Graphics& g, bool over, bool down)
  49850. {
  49851. getLookAndFeel()
  49852. .drawScrollbarButton (g, owner,
  49853. getWidth(), getHeight(),
  49854. direction,
  49855. owner.isVertical(),
  49856. over, down);
  49857. }
  49858. void clicked()
  49859. {
  49860. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49861. }
  49862. juce_UseDebuggingNewOperator
  49863. private:
  49864. ScrollBar& owner;
  49865. ScrollbarButton (const ScrollbarButton&);
  49866. ScrollbarButton& operator= (const ScrollbarButton&);
  49867. };
  49868. ScrollBar::ScrollBar (const bool vertical_,
  49869. const bool buttonsAreVisible)
  49870. : totalRange (0.0, 1.0),
  49871. visibleRange (0.0, 0.1),
  49872. singleStepSize (0.1),
  49873. thumbAreaStart (0),
  49874. thumbAreaSize (0),
  49875. thumbStart (0),
  49876. thumbSize (0),
  49877. initialDelayInMillisecs (100),
  49878. repeatDelayInMillisecs (50),
  49879. minimumDelayInMillisecs (10),
  49880. vertical (vertical_),
  49881. isDraggingThumb (false),
  49882. autohides (true)
  49883. {
  49884. setButtonVisibility (buttonsAreVisible);
  49885. setRepaintsOnMouseActivity (true);
  49886. setFocusContainer (true);
  49887. }
  49888. ScrollBar::~ScrollBar()
  49889. {
  49890. upButton = 0;
  49891. downButton = 0;
  49892. }
  49893. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49894. {
  49895. if (totalRange != newRangeLimit)
  49896. {
  49897. totalRange = newRangeLimit;
  49898. setCurrentRange (visibleRange);
  49899. updateThumbPosition();
  49900. }
  49901. }
  49902. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49903. {
  49904. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49905. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49906. }
  49907. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49908. {
  49909. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49910. if (visibleRange != constrainedRange)
  49911. {
  49912. visibleRange = constrainedRange;
  49913. updateThumbPosition();
  49914. triggerAsyncUpdate();
  49915. }
  49916. }
  49917. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49918. {
  49919. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49920. }
  49921. void ScrollBar::setCurrentRangeStart (const double newStart)
  49922. {
  49923. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49924. }
  49925. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49926. {
  49927. singleStepSize = newSingleStepSize;
  49928. }
  49929. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49930. {
  49931. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49932. }
  49933. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49934. {
  49935. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49936. }
  49937. void ScrollBar::scrollToTop()
  49938. {
  49939. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49940. }
  49941. void ScrollBar::scrollToBottom()
  49942. {
  49943. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49944. }
  49945. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49946. const int repeatDelayInMillisecs_,
  49947. const int minimumDelayInMillisecs_)
  49948. {
  49949. initialDelayInMillisecs = initialDelayInMillisecs_;
  49950. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49951. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49952. if (upButton != 0)
  49953. {
  49954. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49955. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49956. }
  49957. }
  49958. void ScrollBar::addListener (Listener* const listener)
  49959. {
  49960. listeners.add (listener);
  49961. }
  49962. void ScrollBar::removeListener (Listener* const listener)
  49963. {
  49964. listeners.remove (listener);
  49965. }
  49966. void ScrollBar::handleAsyncUpdate()
  49967. {
  49968. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49969. listeners.call (&Listener::scrollBarMoved, this, start);
  49970. }
  49971. void ScrollBar::updateThumbPosition()
  49972. {
  49973. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49974. : thumbAreaSize);
  49975. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49976. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49977. if (newThumbSize > thumbAreaSize)
  49978. newThumbSize = thumbAreaSize;
  49979. int newThumbStart = thumbAreaStart;
  49980. if (totalRange.getLength() > visibleRange.getLength())
  49981. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49982. / (totalRange.getLength() - visibleRange.getLength()));
  49983. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49984. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49985. {
  49986. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49987. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49988. if (vertical)
  49989. repaint (0, repaintStart, getWidth(), repaintSize);
  49990. else
  49991. repaint (repaintStart, 0, repaintSize, getHeight());
  49992. thumbStart = newThumbStart;
  49993. thumbSize = newThumbSize;
  49994. }
  49995. }
  49996. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49997. {
  49998. if (vertical != shouldBeVertical)
  49999. {
  50000. vertical = shouldBeVertical;
  50001. if (upButton != 0)
  50002. {
  50003. upButton->direction = vertical ? 0 : 3;
  50004. downButton->direction = vertical ? 2 : 1;
  50005. }
  50006. updateThumbPosition();
  50007. }
  50008. }
  50009. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50010. {
  50011. upButton = 0;
  50012. downButton = 0;
  50013. if (buttonsAreVisible)
  50014. {
  50015. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50016. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50017. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50018. }
  50019. updateThumbPosition();
  50020. }
  50021. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50022. {
  50023. autohides = shouldHideWhenFullRange;
  50024. updateThumbPosition();
  50025. }
  50026. bool ScrollBar::autoHides() const throw()
  50027. {
  50028. return autohides;
  50029. }
  50030. void ScrollBar::paint (Graphics& g)
  50031. {
  50032. if (thumbAreaSize > 0)
  50033. {
  50034. LookAndFeel& lf = getLookAndFeel();
  50035. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50036. ? thumbSize : 0;
  50037. if (vertical)
  50038. {
  50039. lf.drawScrollbar (g, *this,
  50040. 0, thumbAreaStart,
  50041. getWidth(), thumbAreaSize,
  50042. vertical,
  50043. thumbStart, thumb,
  50044. isMouseOver(), isMouseButtonDown());
  50045. }
  50046. else
  50047. {
  50048. lf.drawScrollbar (g, *this,
  50049. thumbAreaStart, 0,
  50050. thumbAreaSize, getHeight(),
  50051. vertical,
  50052. thumbStart, thumb,
  50053. isMouseOver(), isMouseButtonDown());
  50054. }
  50055. }
  50056. }
  50057. void ScrollBar::lookAndFeelChanged()
  50058. {
  50059. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50060. }
  50061. void ScrollBar::resized()
  50062. {
  50063. const int length = ((vertical) ? getHeight() : getWidth());
  50064. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50065. : 0;
  50066. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50067. {
  50068. thumbAreaStart = length >> 1;
  50069. thumbAreaSize = 0;
  50070. }
  50071. else
  50072. {
  50073. thumbAreaStart = buttonSize;
  50074. thumbAreaSize = length - (buttonSize << 1);
  50075. }
  50076. if (upButton != 0)
  50077. {
  50078. if (vertical)
  50079. {
  50080. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50081. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50082. }
  50083. else
  50084. {
  50085. upButton->setBounds (0, 0, buttonSize, getHeight());
  50086. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50087. }
  50088. }
  50089. updateThumbPosition();
  50090. }
  50091. void ScrollBar::mouseDown (const MouseEvent& e)
  50092. {
  50093. isDraggingThumb = false;
  50094. lastMousePos = vertical ? e.y : e.x;
  50095. dragStartMousePos = lastMousePos;
  50096. dragStartRange = visibleRange.getStart();
  50097. if (dragStartMousePos < thumbStart)
  50098. {
  50099. moveScrollbarInPages (-1);
  50100. startTimer (400);
  50101. }
  50102. else if (dragStartMousePos >= thumbStart + thumbSize)
  50103. {
  50104. moveScrollbarInPages (1);
  50105. startTimer (400);
  50106. }
  50107. else
  50108. {
  50109. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50110. && (thumbAreaSize > thumbSize);
  50111. }
  50112. }
  50113. void ScrollBar::mouseDrag (const MouseEvent& e)
  50114. {
  50115. if (isDraggingThumb)
  50116. {
  50117. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50118. setCurrentRangeStart (dragStartRange
  50119. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50120. / (thumbAreaSize - thumbSize));
  50121. }
  50122. else
  50123. {
  50124. lastMousePos = (vertical) ? e.y : e.x;
  50125. }
  50126. }
  50127. void ScrollBar::mouseUp (const MouseEvent&)
  50128. {
  50129. isDraggingThumb = false;
  50130. stopTimer();
  50131. repaint();
  50132. }
  50133. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50134. float wheelIncrementX,
  50135. float wheelIncrementY)
  50136. {
  50137. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50138. if (increment < 0)
  50139. increment = jmin (increment * 10.0f, -1.0f);
  50140. else if (increment > 0)
  50141. increment = jmax (increment * 10.0f, 1.0f);
  50142. setCurrentRange (visibleRange - singleStepSize * increment);
  50143. }
  50144. void ScrollBar::timerCallback()
  50145. {
  50146. if (isMouseButtonDown())
  50147. {
  50148. startTimer (40);
  50149. if (lastMousePos < thumbStart)
  50150. setCurrentRange (visibleRange - visibleRange.getLength());
  50151. else if (lastMousePos > thumbStart + thumbSize)
  50152. setCurrentRangeStart (visibleRange.getEnd());
  50153. }
  50154. else
  50155. {
  50156. stopTimer();
  50157. }
  50158. }
  50159. bool ScrollBar::keyPressed (const KeyPress& key)
  50160. {
  50161. if (! isVisible())
  50162. return false;
  50163. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50164. moveScrollbarInSteps (-1);
  50165. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50166. moveScrollbarInSteps (1);
  50167. else if (key.isKeyCode (KeyPress::pageUpKey))
  50168. moveScrollbarInPages (-1);
  50169. else if (key.isKeyCode (KeyPress::pageDownKey))
  50170. moveScrollbarInPages (1);
  50171. else if (key.isKeyCode (KeyPress::homeKey))
  50172. scrollToTop();
  50173. else if (key.isKeyCode (KeyPress::endKey))
  50174. scrollToBottom();
  50175. else
  50176. return false;
  50177. return true;
  50178. }
  50179. END_JUCE_NAMESPACE
  50180. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50181. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50182. BEGIN_JUCE_NAMESPACE
  50183. StretchableLayoutManager::StretchableLayoutManager()
  50184. : totalSize (0)
  50185. {
  50186. }
  50187. StretchableLayoutManager::~StretchableLayoutManager()
  50188. {
  50189. }
  50190. void StretchableLayoutManager::clearAllItems()
  50191. {
  50192. items.clear();
  50193. totalSize = 0;
  50194. }
  50195. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50196. const double minimumSize,
  50197. const double maximumSize,
  50198. const double preferredSize)
  50199. {
  50200. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50201. if (layout == 0)
  50202. {
  50203. layout = new ItemLayoutProperties();
  50204. layout->itemIndex = itemIndex;
  50205. int i;
  50206. for (i = 0; i < items.size(); ++i)
  50207. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50208. break;
  50209. items.insert (i, layout);
  50210. }
  50211. layout->minSize = minimumSize;
  50212. layout->maxSize = maximumSize;
  50213. layout->preferredSize = preferredSize;
  50214. layout->currentSize = 0;
  50215. }
  50216. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50217. double& minimumSize,
  50218. double& maximumSize,
  50219. double& preferredSize) const
  50220. {
  50221. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50222. if (layout != 0)
  50223. {
  50224. minimumSize = layout->minSize;
  50225. maximumSize = layout->maxSize;
  50226. preferredSize = layout->preferredSize;
  50227. return true;
  50228. }
  50229. return false;
  50230. }
  50231. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50232. {
  50233. totalSize = newTotalSize;
  50234. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50235. }
  50236. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50237. {
  50238. int pos = 0;
  50239. for (int i = 0; i < itemIndex; ++i)
  50240. {
  50241. const ItemLayoutProperties* const layout = getInfoFor (i);
  50242. if (layout != 0)
  50243. pos += layout->currentSize;
  50244. }
  50245. return pos;
  50246. }
  50247. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50248. {
  50249. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50250. if (layout != 0)
  50251. return layout->currentSize;
  50252. return 0;
  50253. }
  50254. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50255. {
  50256. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50257. if (layout != 0)
  50258. return -layout->currentSize / (double) totalSize;
  50259. return 0;
  50260. }
  50261. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50262. int newPosition)
  50263. {
  50264. for (int i = items.size(); --i >= 0;)
  50265. {
  50266. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50267. if (layout->itemIndex == itemIndex)
  50268. {
  50269. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50270. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50271. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50272. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50273. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50274. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50275. endPos += layout->currentSize;
  50276. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50277. updatePrefSizesToMatchCurrentPositions();
  50278. break;
  50279. }
  50280. }
  50281. }
  50282. void StretchableLayoutManager::layOutComponents (Component** const components,
  50283. int numComponents,
  50284. int x, int y, int w, int h,
  50285. const bool vertically,
  50286. const bool resizeOtherDimension)
  50287. {
  50288. setTotalSize (vertically ? h : w);
  50289. int pos = vertically ? y : x;
  50290. for (int i = 0; i < numComponents; ++i)
  50291. {
  50292. const ItemLayoutProperties* const layout = getInfoFor (i);
  50293. if (layout != 0)
  50294. {
  50295. Component* const c = components[i];
  50296. if (c != 0)
  50297. {
  50298. if (i == numComponents - 1)
  50299. {
  50300. // if it's the last item, crop it to exactly fit the available space..
  50301. if (resizeOtherDimension)
  50302. {
  50303. if (vertically)
  50304. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50305. else
  50306. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50307. }
  50308. else
  50309. {
  50310. if (vertically)
  50311. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50312. else
  50313. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50314. }
  50315. }
  50316. else
  50317. {
  50318. if (resizeOtherDimension)
  50319. {
  50320. if (vertically)
  50321. c->setBounds (x, pos, w, layout->currentSize);
  50322. else
  50323. c->setBounds (pos, y, layout->currentSize, h);
  50324. }
  50325. else
  50326. {
  50327. if (vertically)
  50328. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50329. else
  50330. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50331. }
  50332. }
  50333. }
  50334. pos += layout->currentSize;
  50335. }
  50336. }
  50337. }
  50338. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50339. {
  50340. for (int i = items.size(); --i >= 0;)
  50341. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50342. return items.getUnchecked(i);
  50343. return 0;
  50344. }
  50345. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50346. const int endIndex,
  50347. const int availableSpace,
  50348. int startPos)
  50349. {
  50350. // calculate the total sizes
  50351. int i;
  50352. double totalIdealSize = 0.0;
  50353. int totalMinimums = 0;
  50354. for (i = startIndex; i < endIndex; ++i)
  50355. {
  50356. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50357. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50358. totalMinimums += layout->currentSize;
  50359. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  50360. }
  50361. if (totalIdealSize <= 0)
  50362. totalIdealSize = 1.0;
  50363. // now calc the best sizes..
  50364. int extraSpace = availableSpace - totalMinimums;
  50365. while (extraSpace > 0)
  50366. {
  50367. int numWantingMoreSpace = 0;
  50368. int numHavingTakenExtraSpace = 0;
  50369. // first figure out how many comps want a slice of the extra space..
  50370. for (i = startIndex; i < endIndex; ++i)
  50371. {
  50372. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50373. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50374. const int bestSize = jlimit (layout->currentSize,
  50375. jmax (layout->currentSize,
  50376. sizeToRealSize (layout->maxSize, totalSize)),
  50377. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50378. if (bestSize > layout->currentSize)
  50379. ++numWantingMoreSpace;
  50380. }
  50381. // ..share out the extra space..
  50382. for (i = startIndex; i < endIndex; ++i)
  50383. {
  50384. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50385. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50386. int bestSize = jlimit (layout->currentSize,
  50387. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50388. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50389. const int extraWanted = bestSize - layout->currentSize;
  50390. if (extraWanted > 0)
  50391. {
  50392. const int extraAllowed = jmin (extraWanted,
  50393. extraSpace / jmax (1, numWantingMoreSpace));
  50394. if (extraAllowed > 0)
  50395. {
  50396. ++numHavingTakenExtraSpace;
  50397. --numWantingMoreSpace;
  50398. layout->currentSize += extraAllowed;
  50399. extraSpace -= extraAllowed;
  50400. }
  50401. }
  50402. }
  50403. if (numHavingTakenExtraSpace <= 0)
  50404. break;
  50405. }
  50406. // ..and calculate the end position
  50407. for (i = startIndex; i < endIndex; ++i)
  50408. {
  50409. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50410. startPos += layout->currentSize;
  50411. }
  50412. return startPos;
  50413. }
  50414. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50415. const int endIndex) const
  50416. {
  50417. int totalMinimums = 0;
  50418. for (int i = startIndex; i < endIndex; ++i)
  50419. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50420. return totalMinimums;
  50421. }
  50422. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50423. {
  50424. int totalMaximums = 0;
  50425. for (int i = startIndex; i < endIndex; ++i)
  50426. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50427. return totalMaximums;
  50428. }
  50429. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50430. {
  50431. for (int i = 0; i < items.size(); ++i)
  50432. {
  50433. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50434. layout->preferredSize
  50435. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50436. : getItemCurrentAbsoluteSize (i);
  50437. }
  50438. }
  50439. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50440. {
  50441. if (size < 0)
  50442. size *= -totalSpace;
  50443. return roundToInt (size);
  50444. }
  50445. END_JUCE_NAMESPACE
  50446. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50447. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50448. BEGIN_JUCE_NAMESPACE
  50449. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50450. const int itemIndex_,
  50451. const bool isVertical_)
  50452. : layout (layout_),
  50453. itemIndex (itemIndex_),
  50454. isVertical (isVertical_)
  50455. {
  50456. setRepaintsOnMouseActivity (true);
  50457. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50458. : MouseCursor::UpDownResizeCursor));
  50459. }
  50460. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50461. {
  50462. }
  50463. void StretchableLayoutResizerBar::paint (Graphics& g)
  50464. {
  50465. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50466. getWidth(), getHeight(),
  50467. isVertical,
  50468. isMouseOver(),
  50469. isMouseButtonDown());
  50470. }
  50471. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50472. {
  50473. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50474. }
  50475. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50476. {
  50477. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50478. : e.getDistanceFromDragStartY());
  50479. layout->setItemPosition (itemIndex, desiredPos);
  50480. hasBeenMoved();
  50481. }
  50482. void StretchableLayoutResizerBar::hasBeenMoved()
  50483. {
  50484. if (getParentComponent() != 0)
  50485. getParentComponent()->resized();
  50486. }
  50487. END_JUCE_NAMESPACE
  50488. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50489. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50490. BEGIN_JUCE_NAMESPACE
  50491. StretchableObjectResizer::StretchableObjectResizer()
  50492. {
  50493. }
  50494. StretchableObjectResizer::~StretchableObjectResizer()
  50495. {
  50496. }
  50497. void StretchableObjectResizer::addItem (const double size,
  50498. const double minSize, const double maxSize,
  50499. const int order)
  50500. {
  50501. // the order must be >= 0 but less than the maximum integer value.
  50502. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50503. Item* const item = new Item();
  50504. item->size = size;
  50505. item->minSize = minSize;
  50506. item->maxSize = maxSize;
  50507. item->order = order;
  50508. items.add (item);
  50509. }
  50510. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50511. {
  50512. const Item* const it = items [index];
  50513. return it != 0 ? it->size : 0;
  50514. }
  50515. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50516. {
  50517. int order = 0;
  50518. for (;;)
  50519. {
  50520. double currentSize = 0;
  50521. double minSize = 0;
  50522. double maxSize = 0;
  50523. int nextHighestOrder = std::numeric_limits<int>::max();
  50524. for (int i = 0; i < items.size(); ++i)
  50525. {
  50526. const Item* const it = items.getUnchecked(i);
  50527. currentSize += it->size;
  50528. if (it->order <= order)
  50529. {
  50530. minSize += it->minSize;
  50531. maxSize += it->maxSize;
  50532. }
  50533. else
  50534. {
  50535. minSize += it->size;
  50536. maxSize += it->size;
  50537. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50538. }
  50539. }
  50540. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50541. if (thisIterationTarget >= currentSize)
  50542. {
  50543. const double availableExtraSpace = maxSize - currentSize;
  50544. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50545. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50546. for (int i = 0; i < items.size(); ++i)
  50547. {
  50548. Item* const it = items.getUnchecked(i);
  50549. if (it->order <= order)
  50550. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50551. }
  50552. }
  50553. else
  50554. {
  50555. const double amountOfSlack = currentSize - minSize;
  50556. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50557. const double scale = targetAmountOfSlack / amountOfSlack;
  50558. for (int i = 0; i < items.size(); ++i)
  50559. {
  50560. Item* const it = items.getUnchecked(i);
  50561. if (it->order <= order)
  50562. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50563. }
  50564. }
  50565. if (nextHighestOrder < std::numeric_limits<int>::max())
  50566. order = nextHighestOrder;
  50567. else
  50568. break;
  50569. }
  50570. }
  50571. END_JUCE_NAMESPACE
  50572. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50573. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50574. BEGIN_JUCE_NAMESPACE
  50575. TabBarButton::TabBarButton (const String& name,
  50576. TabbedButtonBar* const owner_,
  50577. const int index)
  50578. : Button (name),
  50579. owner (owner_),
  50580. tabIndex (index),
  50581. overlapPixels (0)
  50582. {
  50583. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50584. setComponentEffect (&shadow);
  50585. setWantsKeyboardFocus (false);
  50586. }
  50587. TabBarButton::~TabBarButton()
  50588. {
  50589. }
  50590. void TabBarButton::paintButton (Graphics& g,
  50591. bool isMouseOverButton,
  50592. bool isButtonDown)
  50593. {
  50594. int x, y, w, h;
  50595. getActiveArea (x, y, w, h);
  50596. g.setOrigin (x, y);
  50597. getLookAndFeel()
  50598. .drawTabButton (g, w, h,
  50599. owner->getTabBackgroundColour (tabIndex),
  50600. tabIndex, getButtonText(), *this,
  50601. owner->getOrientation(),
  50602. isMouseOverButton, isButtonDown,
  50603. getToggleState());
  50604. }
  50605. void TabBarButton::clicked (const ModifierKeys& mods)
  50606. {
  50607. if (mods.isPopupMenu())
  50608. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50609. else
  50610. owner->setCurrentTabIndex (tabIndex);
  50611. }
  50612. bool TabBarButton::hitTest (int mx, int my)
  50613. {
  50614. int x, y, w, h;
  50615. getActiveArea (x, y, w, h);
  50616. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50617. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50618. {
  50619. if (((unsigned int) mx) < (unsigned int) getWidth()
  50620. && my >= y + overlapPixels
  50621. && my < y + h - overlapPixels)
  50622. return true;
  50623. }
  50624. else
  50625. {
  50626. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50627. && ((unsigned int) my) < (unsigned int) getHeight())
  50628. return true;
  50629. }
  50630. Path p;
  50631. getLookAndFeel()
  50632. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50633. owner->getOrientation(),
  50634. false, false, getToggleState());
  50635. return p.contains ((float) (mx - x),
  50636. (float) (my - y));
  50637. }
  50638. int TabBarButton::getBestTabLength (const int depth)
  50639. {
  50640. return jlimit (depth * 2,
  50641. depth * 7,
  50642. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50643. }
  50644. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50645. {
  50646. x = 0;
  50647. y = 0;
  50648. int r = getWidth();
  50649. int b = getHeight();
  50650. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50651. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50652. r -= spaceAroundImage;
  50653. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50654. x += spaceAroundImage;
  50655. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50656. y += spaceAroundImage;
  50657. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50658. b -= spaceAroundImage;
  50659. w = r - x;
  50660. h = b - y;
  50661. }
  50662. class TabAreaBehindFrontButtonComponent : public Component
  50663. {
  50664. public:
  50665. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50666. : owner (owner_)
  50667. {
  50668. setInterceptsMouseClicks (false, false);
  50669. }
  50670. ~TabAreaBehindFrontButtonComponent()
  50671. {
  50672. }
  50673. void paint (Graphics& g)
  50674. {
  50675. getLookAndFeel()
  50676. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50677. *owner, owner->getOrientation());
  50678. }
  50679. void enablementChanged()
  50680. {
  50681. repaint();
  50682. }
  50683. private:
  50684. TabbedButtonBar* const owner;
  50685. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50686. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50687. };
  50688. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50689. : orientation (orientation_),
  50690. currentTabIndex (-1)
  50691. {
  50692. setInterceptsMouseClicks (false, true);
  50693. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50694. setFocusContainer (true);
  50695. }
  50696. TabbedButtonBar::~TabbedButtonBar()
  50697. {
  50698. extraTabsButton = 0;
  50699. deleteAllChildren();
  50700. }
  50701. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50702. {
  50703. orientation = newOrientation;
  50704. for (int i = getNumChildComponents(); --i >= 0;)
  50705. getChildComponent (i)->resized();
  50706. resized();
  50707. }
  50708. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50709. {
  50710. return new TabBarButton (name, this, index);
  50711. }
  50712. void TabbedButtonBar::clearTabs()
  50713. {
  50714. tabs.clear();
  50715. tabColours.clear();
  50716. currentTabIndex = -1;
  50717. extraTabsButton = 0;
  50718. removeChildComponent (behindFrontTab);
  50719. deleteAllChildren();
  50720. addChildComponent (behindFrontTab);
  50721. setCurrentTabIndex (-1);
  50722. }
  50723. void TabbedButtonBar::addTab (const String& tabName,
  50724. const Colour& tabBackgroundColour,
  50725. int insertIndex)
  50726. {
  50727. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50728. if (tabName.isNotEmpty())
  50729. {
  50730. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50731. insertIndex = tabs.size();
  50732. for (int i = tabs.size(); --i >= insertIndex;)
  50733. {
  50734. TabBarButton* const tb = getTabButton (i);
  50735. if (tb != 0)
  50736. tb->tabIndex++;
  50737. }
  50738. tabs.insert (insertIndex, tabName);
  50739. tabColours.insert (insertIndex, tabBackgroundColour);
  50740. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50741. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50742. addAndMakeVisible (tb, insertIndex);
  50743. resized();
  50744. if (currentTabIndex < 0)
  50745. setCurrentTabIndex (0);
  50746. }
  50747. }
  50748. void TabbedButtonBar::setTabName (const int tabIndex,
  50749. const String& newName)
  50750. {
  50751. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50752. && tabs[tabIndex] != newName)
  50753. {
  50754. tabs.set (tabIndex, newName);
  50755. TabBarButton* const tb = getTabButton (tabIndex);
  50756. if (tb != 0)
  50757. tb->setButtonText (newName);
  50758. resized();
  50759. }
  50760. }
  50761. void TabbedButtonBar::removeTab (const int tabIndex)
  50762. {
  50763. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50764. {
  50765. const int oldTabIndex = currentTabIndex;
  50766. if (currentTabIndex == tabIndex)
  50767. currentTabIndex = -1;
  50768. tabs.remove (tabIndex);
  50769. tabColours.remove (tabIndex);
  50770. delete getTabButton (tabIndex);
  50771. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50772. {
  50773. TabBarButton* const tb = getTabButton (i);
  50774. if (tb != 0)
  50775. tb->tabIndex--;
  50776. }
  50777. resized();
  50778. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50779. }
  50780. }
  50781. void TabbedButtonBar::moveTab (const int currentIndex,
  50782. const int newIndex)
  50783. {
  50784. tabs.move (currentIndex, newIndex);
  50785. tabColours.move (currentIndex, newIndex);
  50786. resized();
  50787. }
  50788. int TabbedButtonBar::getNumTabs() const
  50789. {
  50790. return tabs.size();
  50791. }
  50792. const StringArray TabbedButtonBar::getTabNames() const
  50793. {
  50794. return tabs;
  50795. }
  50796. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50797. {
  50798. if (currentTabIndex != newIndex)
  50799. {
  50800. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50801. newIndex = -1;
  50802. currentTabIndex = newIndex;
  50803. for (int i = 0; i < getNumChildComponents(); ++i)
  50804. {
  50805. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50806. if (tb != 0)
  50807. tb->setToggleState (tb->tabIndex == newIndex, false);
  50808. }
  50809. resized();
  50810. if (sendChangeMessage_)
  50811. sendChangeMessage (this);
  50812. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50813. }
  50814. }
  50815. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50816. {
  50817. for (int i = getNumChildComponents(); --i >= 0;)
  50818. {
  50819. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50820. if (tb != 0 && tb->tabIndex == index)
  50821. return tb;
  50822. }
  50823. return 0;
  50824. }
  50825. void TabbedButtonBar::lookAndFeelChanged()
  50826. {
  50827. extraTabsButton = 0;
  50828. resized();
  50829. }
  50830. void TabbedButtonBar::resized()
  50831. {
  50832. const double minimumScale = 0.7;
  50833. int depth = getWidth();
  50834. int length = getHeight();
  50835. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50836. swapVariables (depth, length);
  50837. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50838. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50839. int i, totalLength = overlap;
  50840. int numVisibleButtons = tabs.size();
  50841. for (i = 0; i < getNumChildComponents(); ++i)
  50842. {
  50843. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50844. if (tb != 0)
  50845. {
  50846. totalLength += tb->getBestTabLength (depth) - overlap;
  50847. tb->overlapPixels = overlap / 2;
  50848. }
  50849. }
  50850. double scale = 1.0;
  50851. if (totalLength > length)
  50852. scale = jmax (minimumScale, length / (double) totalLength);
  50853. const bool isTooBig = totalLength * scale > length;
  50854. int tabsButtonPos = 0;
  50855. if (isTooBig)
  50856. {
  50857. if (extraTabsButton == 0)
  50858. {
  50859. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50860. extraTabsButton->addButtonListener (this);
  50861. extraTabsButton->setAlwaysOnTop (true);
  50862. extraTabsButton->setTriggeredOnMouseDown (true);
  50863. }
  50864. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50865. extraTabsButton->setSize (buttonSize, buttonSize);
  50866. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50867. {
  50868. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50869. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50870. }
  50871. else
  50872. {
  50873. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50874. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50875. }
  50876. totalLength = 0;
  50877. for (i = 0; i < tabs.size(); ++i)
  50878. {
  50879. TabBarButton* const tb = getTabButton (i);
  50880. if (tb != 0)
  50881. {
  50882. const int newLength = totalLength + tb->getBestTabLength (depth);
  50883. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50884. {
  50885. totalLength += overlap;
  50886. break;
  50887. }
  50888. numVisibleButtons = i + 1;
  50889. totalLength = newLength - overlap;
  50890. }
  50891. }
  50892. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50893. }
  50894. else
  50895. {
  50896. extraTabsButton = 0;
  50897. }
  50898. int pos = 0;
  50899. TabBarButton* frontTab = 0;
  50900. for (i = 0; i < tabs.size(); ++i)
  50901. {
  50902. TabBarButton* const tb = getTabButton (i);
  50903. if (tb != 0)
  50904. {
  50905. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50906. if (i < numVisibleButtons)
  50907. {
  50908. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50909. tb->setBounds (pos, 0, bestLength, getHeight());
  50910. else
  50911. tb->setBounds (0, pos, getWidth(), bestLength);
  50912. tb->toBack();
  50913. if (tb->tabIndex == currentTabIndex)
  50914. frontTab = tb;
  50915. tb->setVisible (true);
  50916. }
  50917. else
  50918. {
  50919. tb->setVisible (false);
  50920. }
  50921. pos += bestLength - overlap;
  50922. }
  50923. }
  50924. behindFrontTab->setBounds (getLocalBounds());
  50925. if (frontTab != 0)
  50926. {
  50927. frontTab->toFront (false);
  50928. behindFrontTab->toBehind (frontTab);
  50929. }
  50930. }
  50931. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50932. {
  50933. return tabColours [tabIndex];
  50934. }
  50935. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50936. {
  50937. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50938. && tabColours [tabIndex] != newColour)
  50939. {
  50940. tabColours.set (tabIndex, newColour);
  50941. repaint();
  50942. }
  50943. }
  50944. void TabbedButtonBar::buttonClicked (Button* button)
  50945. {
  50946. if (button == extraTabsButton)
  50947. {
  50948. PopupMenu m;
  50949. for (int i = 0; i < tabs.size(); ++i)
  50950. {
  50951. TabBarButton* const tb = getTabButton (i);
  50952. if (tb != 0 && ! tb->isVisible())
  50953. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50954. }
  50955. const int res = m.showAt (extraTabsButton);
  50956. if (res != 0)
  50957. setCurrentTabIndex (res - 1);
  50958. }
  50959. }
  50960. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50961. {
  50962. }
  50963. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50964. {
  50965. }
  50966. END_JUCE_NAMESPACE
  50967. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50968. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50969. BEGIN_JUCE_NAMESPACE
  50970. class TabCompButtonBar : public TabbedButtonBar
  50971. {
  50972. public:
  50973. TabCompButtonBar (TabbedComponent* const owner_,
  50974. const TabbedButtonBar::Orientation orientation_)
  50975. : TabbedButtonBar (orientation_),
  50976. owner (owner_)
  50977. {
  50978. }
  50979. ~TabCompButtonBar()
  50980. {
  50981. }
  50982. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  50983. {
  50984. owner->changeCallback (newCurrentTabIndex, newTabName);
  50985. }
  50986. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  50987. {
  50988. owner->popupMenuClickOnTab (tabIndex, tabName);
  50989. }
  50990. const Colour getTabBackgroundColour (const int tabIndex)
  50991. {
  50992. return owner->tabs->getTabBackgroundColour (tabIndex);
  50993. }
  50994. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50995. {
  50996. return owner->createTabButton (tabName, tabIndex);
  50997. }
  50998. juce_UseDebuggingNewOperator
  50999. private:
  51000. TabbedComponent* const owner;
  51001. TabCompButtonBar (const TabCompButtonBar&);
  51002. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51003. };
  51004. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51005. : panelComponent (0),
  51006. tabDepth (30),
  51007. outlineThickness (1),
  51008. edgeIndent (0)
  51009. {
  51010. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51011. }
  51012. TabbedComponent::~TabbedComponent()
  51013. {
  51014. clearTabs();
  51015. delete tabs;
  51016. }
  51017. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51018. {
  51019. tabs->setOrientation (orientation);
  51020. resized();
  51021. }
  51022. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51023. {
  51024. return tabs->getOrientation();
  51025. }
  51026. void TabbedComponent::setTabBarDepth (const int newDepth)
  51027. {
  51028. if (tabDepth != newDepth)
  51029. {
  51030. tabDepth = newDepth;
  51031. resized();
  51032. }
  51033. }
  51034. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51035. {
  51036. return new TabBarButton (tabName, tabs, tabIndex);
  51037. }
  51038. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51039. void TabbedComponent::clearTabs()
  51040. {
  51041. if (panelComponent != 0)
  51042. {
  51043. panelComponent->setVisible (false);
  51044. removeChildComponent (panelComponent);
  51045. panelComponent = 0;
  51046. }
  51047. tabs->clearTabs();
  51048. for (int i = contentComponents.size(); --i >= 0;)
  51049. {
  51050. Component* const c = contentComponents.getUnchecked(i);
  51051. // be careful not to delete these components until they've been removed from the tab component
  51052. jassert (c == 0 || c->isValidComponent());
  51053. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51054. delete c;
  51055. }
  51056. contentComponents.clear();
  51057. }
  51058. void TabbedComponent::addTab (const String& tabName,
  51059. const Colour& tabBackgroundColour,
  51060. Component* const contentComponent,
  51061. const bool deleteComponentWhenNotNeeded,
  51062. const int insertIndex)
  51063. {
  51064. contentComponents.insert (insertIndex, contentComponent);
  51065. if (contentComponent != 0)
  51066. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51067. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51068. }
  51069. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51070. {
  51071. tabs->setTabName (tabIndex, newName);
  51072. }
  51073. void TabbedComponent::removeTab (const int tabIndex)
  51074. {
  51075. Component* const c = contentComponents [tabIndex];
  51076. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51077. {
  51078. if (c == panelComponent)
  51079. panelComponent = 0;
  51080. delete c;
  51081. }
  51082. contentComponents.remove (tabIndex);
  51083. tabs->removeTab (tabIndex);
  51084. }
  51085. int TabbedComponent::getNumTabs() const
  51086. {
  51087. return tabs->getNumTabs();
  51088. }
  51089. const StringArray TabbedComponent::getTabNames() const
  51090. {
  51091. return tabs->getTabNames();
  51092. }
  51093. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51094. {
  51095. return contentComponents [tabIndex];
  51096. }
  51097. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51098. {
  51099. return tabs->getTabBackgroundColour (tabIndex);
  51100. }
  51101. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51102. {
  51103. tabs->setTabBackgroundColour (tabIndex, newColour);
  51104. if (getCurrentTabIndex() == tabIndex)
  51105. repaint();
  51106. }
  51107. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51108. {
  51109. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51110. }
  51111. int TabbedComponent::getCurrentTabIndex() const
  51112. {
  51113. return tabs->getCurrentTabIndex();
  51114. }
  51115. const String& TabbedComponent::getCurrentTabName() const
  51116. {
  51117. return tabs->getCurrentTabName();
  51118. }
  51119. void TabbedComponent::setOutline (int thickness)
  51120. {
  51121. outlineThickness = thickness;
  51122. repaint();
  51123. }
  51124. void TabbedComponent::setIndent (const int indentThickness)
  51125. {
  51126. edgeIndent = indentThickness;
  51127. }
  51128. void TabbedComponent::paint (Graphics& g)
  51129. {
  51130. g.fillAll (findColour (backgroundColourId));
  51131. const TabbedButtonBar::Orientation o = getOrientation();
  51132. int x = 0;
  51133. int y = 0;
  51134. int r = getWidth();
  51135. int b = getHeight();
  51136. if (o == TabbedButtonBar::TabsAtTop)
  51137. y += tabDepth;
  51138. else if (o == TabbedButtonBar::TabsAtBottom)
  51139. b -= tabDepth;
  51140. else if (o == TabbedButtonBar::TabsAtLeft)
  51141. x += tabDepth;
  51142. else if (o == TabbedButtonBar::TabsAtRight)
  51143. r -= tabDepth;
  51144. g.reduceClipRegion (x, y, r - x, b - y);
  51145. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51146. if (outlineThickness > 0)
  51147. {
  51148. if (o == TabbedButtonBar::TabsAtTop)
  51149. --y;
  51150. else if (o == TabbedButtonBar::TabsAtBottom)
  51151. ++b;
  51152. else if (o == TabbedButtonBar::TabsAtLeft)
  51153. --x;
  51154. else if (o == TabbedButtonBar::TabsAtRight)
  51155. ++r;
  51156. g.setColour (findColour (outlineColourId));
  51157. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51158. }
  51159. }
  51160. void TabbedComponent::resized()
  51161. {
  51162. const TabbedButtonBar::Orientation o = getOrientation();
  51163. const int indent = edgeIndent + outlineThickness;
  51164. BorderSize indents (indent);
  51165. if (o == TabbedButtonBar::TabsAtTop)
  51166. {
  51167. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51168. indents.setTop (tabDepth + edgeIndent);
  51169. }
  51170. else if (o == TabbedButtonBar::TabsAtBottom)
  51171. {
  51172. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51173. indents.setBottom (tabDepth + edgeIndent);
  51174. }
  51175. else if (o == TabbedButtonBar::TabsAtLeft)
  51176. {
  51177. tabs->setBounds (0, 0, tabDepth, getHeight());
  51178. indents.setLeft (tabDepth + edgeIndent);
  51179. }
  51180. else if (o == TabbedButtonBar::TabsAtRight)
  51181. {
  51182. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51183. indents.setRight (tabDepth + edgeIndent);
  51184. }
  51185. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51186. for (int i = contentComponents.size(); --i >= 0;)
  51187. if (contentComponents.getUnchecked (i) != 0)
  51188. contentComponents.getUnchecked (i)->setBounds (bounds);
  51189. }
  51190. void TabbedComponent::lookAndFeelChanged()
  51191. {
  51192. for (int i = contentComponents.size(); --i >= 0;)
  51193. if (contentComponents.getUnchecked (i) != 0)
  51194. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51195. }
  51196. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51197. const String& newTabName)
  51198. {
  51199. if (panelComponent != 0)
  51200. {
  51201. panelComponent->setVisible (false);
  51202. removeChildComponent (panelComponent);
  51203. panelComponent = 0;
  51204. }
  51205. if (getCurrentTabIndex() >= 0)
  51206. {
  51207. panelComponent = contentComponents [getCurrentTabIndex()];
  51208. if (panelComponent != 0)
  51209. {
  51210. // do these ops as two stages instead of addAndMakeVisible() so that the
  51211. // component has always got a parent when it gets the visibilityChanged() callback
  51212. addChildComponent (panelComponent);
  51213. panelComponent->setVisible (true);
  51214. panelComponent->toFront (true);
  51215. }
  51216. repaint();
  51217. }
  51218. resized();
  51219. currentTabChanged (newCurrentTabIndex, newTabName);
  51220. }
  51221. void TabbedComponent::currentTabChanged (const int, const String&)
  51222. {
  51223. }
  51224. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51225. {
  51226. }
  51227. END_JUCE_NAMESPACE
  51228. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51229. /*** Start of inlined file: juce_Viewport.cpp ***/
  51230. BEGIN_JUCE_NAMESPACE
  51231. Viewport::Viewport (const String& componentName)
  51232. : Component (componentName),
  51233. scrollBarThickness (0),
  51234. singleStepX (16),
  51235. singleStepY (16),
  51236. showHScrollbar (true),
  51237. showVScrollbar (true),
  51238. verticalScrollBar (true),
  51239. horizontalScrollBar (false)
  51240. {
  51241. // content holder is used to clip the contents so they don't overlap the scrollbars
  51242. addAndMakeVisible (&contentHolder);
  51243. contentHolder.setInterceptsMouseClicks (false, true);
  51244. addChildComponent (&verticalScrollBar);
  51245. addChildComponent (&horizontalScrollBar);
  51246. verticalScrollBar.addListener (this);
  51247. horizontalScrollBar.addListener (this);
  51248. setInterceptsMouseClicks (false, true);
  51249. setWantsKeyboardFocus (true);
  51250. }
  51251. Viewport::~Viewport()
  51252. {
  51253. contentHolder.deleteAllChildren();
  51254. }
  51255. void Viewport::visibleAreaChanged (int, int, int, int)
  51256. {
  51257. }
  51258. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51259. {
  51260. if (contentComp.getComponent() != newViewedComponent)
  51261. {
  51262. {
  51263. ScopedPointer<Component> oldCompDeleter (contentComp);
  51264. contentComp = 0;
  51265. }
  51266. contentComp = newViewedComponent;
  51267. if (contentComp != 0)
  51268. {
  51269. contentComp->setTopLeftPosition (0, 0);
  51270. contentHolder.addAndMakeVisible (contentComp);
  51271. contentComp->addComponentListener (this);
  51272. }
  51273. updateVisibleArea();
  51274. }
  51275. }
  51276. int Viewport::getMaximumVisibleWidth() const
  51277. {
  51278. return contentHolder.getWidth();
  51279. }
  51280. int Viewport::getMaximumVisibleHeight() const
  51281. {
  51282. return contentHolder.getHeight();
  51283. }
  51284. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51285. {
  51286. if (contentComp != 0)
  51287. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51288. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51289. }
  51290. void Viewport::setViewPosition (const Point<int>& newPosition)
  51291. {
  51292. setViewPosition (newPosition.getX(), newPosition.getY());
  51293. }
  51294. void Viewport::setViewPositionProportionately (const double x, const double y)
  51295. {
  51296. if (contentComp != 0)
  51297. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51298. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51299. }
  51300. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51301. {
  51302. if (contentComp != 0)
  51303. {
  51304. int dx = 0, dy = 0;
  51305. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51306. {
  51307. if (mouseX < activeBorderThickness)
  51308. dx = activeBorderThickness - mouseX;
  51309. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51310. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51311. if (dx < 0)
  51312. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51313. else
  51314. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51315. }
  51316. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51317. {
  51318. if (mouseY < activeBorderThickness)
  51319. dy = activeBorderThickness - mouseY;
  51320. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51321. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51322. if (dy < 0)
  51323. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51324. else
  51325. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51326. }
  51327. if (dx != 0 || dy != 0)
  51328. {
  51329. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51330. contentComp->getY() + dy);
  51331. return true;
  51332. }
  51333. }
  51334. return false;
  51335. }
  51336. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51337. {
  51338. updateVisibleArea();
  51339. }
  51340. void Viewport::resized()
  51341. {
  51342. updateVisibleArea();
  51343. }
  51344. void Viewport::updateVisibleArea()
  51345. {
  51346. const int scrollbarWidth = getScrollBarThickness();
  51347. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51348. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51349. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51350. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51351. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51352. Rectangle<int> contentArea (getLocalBounds());
  51353. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51354. {
  51355. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51356. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51357. if (vBarVisible)
  51358. contentArea.setWidth (getWidth() - scrollbarWidth);
  51359. if (hBarVisible)
  51360. contentArea.setHeight (getHeight() - scrollbarWidth);
  51361. if (! contentArea.contains (contentComp->getBounds()))
  51362. {
  51363. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51364. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51365. }
  51366. }
  51367. if (vBarVisible)
  51368. contentArea.setWidth (getWidth() - scrollbarWidth);
  51369. if (hBarVisible)
  51370. contentArea.setHeight (getHeight() - scrollbarWidth);
  51371. contentHolder.setBounds (contentArea);
  51372. Rectangle<int> contentBounds;
  51373. if (contentComp != 0)
  51374. contentBounds = contentComp->getBounds();
  51375. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51376. if (hBarVisible)
  51377. {
  51378. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51379. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51380. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51381. horizontalScrollBar.setSingleStepSize (singleStepX);
  51382. horizontalScrollBar.cancelPendingUpdate();
  51383. }
  51384. if (vBarVisible)
  51385. {
  51386. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51387. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51388. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51389. verticalScrollBar.setSingleStepSize (singleStepY);
  51390. verticalScrollBar.cancelPendingUpdate();
  51391. }
  51392. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51393. horizontalScrollBar.setVisible (hBarVisible);
  51394. verticalScrollBar.setVisible (vBarVisible);
  51395. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51396. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51397. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51398. if (lastVisibleArea != visibleArea)
  51399. {
  51400. lastVisibleArea = visibleArea;
  51401. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51402. }
  51403. horizontalScrollBar.handleUpdateNowIfNeeded();
  51404. verticalScrollBar.handleUpdateNowIfNeeded();
  51405. }
  51406. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51407. {
  51408. if (singleStepX != stepX || singleStepY != stepY)
  51409. {
  51410. singleStepX = stepX;
  51411. singleStepY = stepY;
  51412. updateVisibleArea();
  51413. }
  51414. }
  51415. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51416. const bool showHorizontalScrollbarIfNeeded)
  51417. {
  51418. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51419. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51420. {
  51421. showVScrollbar = showVerticalScrollbarIfNeeded;
  51422. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51423. updateVisibleArea();
  51424. }
  51425. }
  51426. void Viewport::setScrollBarThickness (const int thickness)
  51427. {
  51428. if (scrollBarThickness != thickness)
  51429. {
  51430. scrollBarThickness = thickness;
  51431. updateVisibleArea();
  51432. }
  51433. }
  51434. int Viewport::getScrollBarThickness() const
  51435. {
  51436. return scrollBarThickness > 0 ? scrollBarThickness
  51437. : getLookAndFeel().getDefaultScrollbarWidth();
  51438. }
  51439. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51440. {
  51441. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51442. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51443. }
  51444. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51445. {
  51446. const int newRangeStartInt = roundToInt (newRangeStart);
  51447. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51448. {
  51449. setViewPosition (newRangeStartInt, getViewPositionY());
  51450. }
  51451. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51452. {
  51453. setViewPosition (getViewPositionX(), newRangeStartInt);
  51454. }
  51455. }
  51456. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51457. {
  51458. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51459. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51460. }
  51461. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51462. {
  51463. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51464. {
  51465. const bool hasVertBar = verticalScrollBar.isVisible();
  51466. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51467. if (hasHorzBar || hasVertBar)
  51468. {
  51469. if (wheelIncrementX != 0)
  51470. {
  51471. wheelIncrementX *= 14.0f * singleStepX;
  51472. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  51473. : jmax (wheelIncrementX, 1.0f);
  51474. }
  51475. if (wheelIncrementY != 0)
  51476. {
  51477. wheelIncrementY *= 14.0f * singleStepY;
  51478. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  51479. : jmax (wheelIncrementY, 1.0f);
  51480. }
  51481. Point<int> pos (getViewPosition());
  51482. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  51483. {
  51484. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51485. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51486. }
  51487. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51488. {
  51489. if (wheelIncrementX == 0 && ! hasVertBar)
  51490. wheelIncrementX = wheelIncrementY;
  51491. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51492. }
  51493. else if (hasVertBar && wheelIncrementY != 0)
  51494. {
  51495. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51496. }
  51497. if (pos != getViewPosition())
  51498. {
  51499. setViewPosition (pos);
  51500. return true;
  51501. }
  51502. }
  51503. }
  51504. return false;
  51505. }
  51506. bool Viewport::keyPressed (const KeyPress& key)
  51507. {
  51508. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51509. || key.isKeyCode (KeyPress::downKey)
  51510. || key.isKeyCode (KeyPress::pageUpKey)
  51511. || key.isKeyCode (KeyPress::pageDownKey)
  51512. || key.isKeyCode (KeyPress::homeKey)
  51513. || key.isKeyCode (KeyPress::endKey);
  51514. if (verticalScrollBar.isVisible() && isUpDownKey)
  51515. return verticalScrollBar.keyPressed (key);
  51516. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51517. || key.isKeyCode (KeyPress::rightKey);
  51518. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  51519. return horizontalScrollBar.keyPressed (key);
  51520. return false;
  51521. }
  51522. END_JUCE_NAMESPACE
  51523. /*** End of inlined file: juce_Viewport.cpp ***/
  51524. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51525. BEGIN_JUCE_NAMESPACE
  51526. static const Colour createBaseColour (const Colour& buttonColour,
  51527. const bool hasKeyboardFocus,
  51528. const bool isMouseOverButton,
  51529. const bool isButtonDown) throw()
  51530. {
  51531. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51532. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51533. if (isButtonDown)
  51534. return baseColour.contrasting (0.2f);
  51535. else if (isMouseOverButton)
  51536. return baseColour.contrasting (0.1f);
  51537. return baseColour;
  51538. }
  51539. LookAndFeel::LookAndFeel()
  51540. {
  51541. /* if this fails it means you're trying to create a LookAndFeel object before
  51542. the static Colours have been initialised. That ain't gonna work. It probably
  51543. means that you're using a static LookAndFeel object and that your compiler has
  51544. decided to intialise it before the Colours class.
  51545. */
  51546. jassert (Colours::white == Colour (0xffffffff));
  51547. // set up the standard set of colours..
  51548. const int textButtonColour = 0xffbbbbff;
  51549. const int textHighlightColour = 0x401111ee;
  51550. const int standardOutlineColour = 0xb2808080;
  51551. static const int standardColours[] =
  51552. {
  51553. TextButton::buttonColourId, textButtonColour,
  51554. TextButton::buttonOnColourId, 0xff4444ff,
  51555. TextButton::textColourOnId, 0xff000000,
  51556. TextButton::textColourOffId, 0xff000000,
  51557. ComboBox::buttonColourId, 0xffbbbbff,
  51558. ComboBox::outlineColourId, standardOutlineColour,
  51559. ToggleButton::textColourId, 0xff000000,
  51560. TextEditor::backgroundColourId, 0xffffffff,
  51561. TextEditor::textColourId, 0xff000000,
  51562. TextEditor::highlightColourId, textHighlightColour,
  51563. TextEditor::highlightedTextColourId, 0xff000000,
  51564. TextEditor::caretColourId, 0xff000000,
  51565. TextEditor::outlineColourId, 0x00000000,
  51566. TextEditor::focusedOutlineColourId, textButtonColour,
  51567. TextEditor::shadowColourId, 0x38000000,
  51568. Label::backgroundColourId, 0x00000000,
  51569. Label::textColourId, 0xff000000,
  51570. Label::outlineColourId, 0x00000000,
  51571. ScrollBar::backgroundColourId, 0x00000000,
  51572. ScrollBar::thumbColourId, 0xffffffff,
  51573. ScrollBar::trackColourId, 0xffffffff,
  51574. TreeView::linesColourId, 0x4c000000,
  51575. TreeView::backgroundColourId, 0x00000000,
  51576. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51577. PopupMenu::backgroundColourId, 0xffffffff,
  51578. PopupMenu::textColourId, 0xff000000,
  51579. PopupMenu::headerTextColourId, 0xff000000,
  51580. PopupMenu::highlightedTextColourId, 0xffffffff,
  51581. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51582. ComboBox::textColourId, 0xff000000,
  51583. ComboBox::backgroundColourId, 0xffffffff,
  51584. ComboBox::arrowColourId, 0x99000000,
  51585. ListBox::backgroundColourId, 0xffffffff,
  51586. ListBox::outlineColourId, standardOutlineColour,
  51587. ListBox::textColourId, 0xff000000,
  51588. Slider::backgroundColourId, 0x00000000,
  51589. Slider::thumbColourId, textButtonColour,
  51590. Slider::trackColourId, 0x7fffffff,
  51591. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51592. Slider::rotarySliderOutlineColourId, 0x66000000,
  51593. Slider::textBoxTextColourId, 0xff000000,
  51594. Slider::textBoxBackgroundColourId, 0xffffffff,
  51595. Slider::textBoxHighlightColourId, textHighlightColour,
  51596. Slider::textBoxOutlineColourId, standardOutlineColour,
  51597. ResizableWindow::backgroundColourId, 0xff777777,
  51598. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51599. AlertWindow::backgroundColourId, 0xffededed,
  51600. AlertWindow::textColourId, 0xff000000,
  51601. AlertWindow::outlineColourId, 0xff666666,
  51602. ProgressBar::backgroundColourId, 0xffeeeeee,
  51603. ProgressBar::foregroundColourId, 0xffaaaaee,
  51604. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51605. TooltipWindow::textColourId, 0xff000000,
  51606. TooltipWindow::outlineColourId, 0x4c000000,
  51607. TabbedComponent::backgroundColourId, 0x00000000,
  51608. TabbedComponent::outlineColourId, 0xff777777,
  51609. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51610. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51611. Toolbar::backgroundColourId, 0xfff6f8f9,
  51612. Toolbar::separatorColourId, 0x4c000000,
  51613. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51614. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51615. Toolbar::labelTextColourId, 0xff000000,
  51616. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51617. HyperlinkButton::textColourId, 0xcc1111ee,
  51618. GroupComponent::outlineColourId, 0x66000000,
  51619. GroupComponent::textColourId, 0xff000000,
  51620. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51621. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51622. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51623. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51624. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51625. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51626. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51627. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51628. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51629. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51630. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51631. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51632. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51633. CodeEditorComponent::caretColourId, 0xff000000,
  51634. CodeEditorComponent::highlightColourId, textHighlightColour,
  51635. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51636. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51637. ColourSelector::labelTextColourId, 0xff000000,
  51638. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51639. KeyMappingEditorComponent::textColourId, 0xff000000,
  51640. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51641. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51642. };
  51643. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51644. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51645. static String defaultSansName, defaultSerifName, defaultFixedName;
  51646. if (defaultSansName.isEmpty())
  51647. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51648. defaultSans = defaultSansName;
  51649. defaultSerif = defaultSerifName;
  51650. defaultFixed = defaultFixedName;
  51651. }
  51652. LookAndFeel::~LookAndFeel()
  51653. {
  51654. }
  51655. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51656. {
  51657. const int index = colourIds.indexOf (colourId);
  51658. if (index >= 0)
  51659. return colours [index];
  51660. jassertfalse;
  51661. return Colours::black;
  51662. }
  51663. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51664. {
  51665. const int index = colourIds.indexOf (colourId);
  51666. if (index >= 0)
  51667. {
  51668. colours.set (index, colour);
  51669. }
  51670. else
  51671. {
  51672. colourIds.add (colourId);
  51673. colours.add (colour);
  51674. }
  51675. }
  51676. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51677. {
  51678. return colourIds.contains (colourId);
  51679. }
  51680. static LookAndFeel* defaultLF = 0;
  51681. static LookAndFeel* currentDefaultLF = 0;
  51682. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51683. {
  51684. // if this happens, your app hasn't initialised itself properly.. if you're
  51685. // trying to hack your own main() function, have a look at
  51686. // JUCEApplication::initialiseForGUI()
  51687. jassert (currentDefaultLF != 0);
  51688. return *currentDefaultLF;
  51689. }
  51690. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51691. {
  51692. if (newDefaultLookAndFeel == 0)
  51693. {
  51694. if (defaultLF == 0)
  51695. defaultLF = new LookAndFeel();
  51696. newDefaultLookAndFeel = defaultLF;
  51697. }
  51698. currentDefaultLF = newDefaultLookAndFeel;
  51699. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51700. {
  51701. Component* const c = Desktop::getInstance().getComponent (i);
  51702. if (c != 0)
  51703. c->sendLookAndFeelChange();
  51704. }
  51705. }
  51706. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51707. {
  51708. if (currentDefaultLF == defaultLF)
  51709. currentDefaultLF = 0;
  51710. deleteAndZero (defaultLF);
  51711. }
  51712. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51713. {
  51714. String faceName (font.getTypefaceName());
  51715. if (faceName == Font::getDefaultSansSerifFontName())
  51716. faceName = defaultSans;
  51717. else if (faceName == Font::getDefaultSerifFontName())
  51718. faceName = defaultSerif;
  51719. else if (faceName == Font::getDefaultMonospacedFontName())
  51720. faceName = defaultFixed;
  51721. Font f (font);
  51722. f.setTypefaceName (faceName);
  51723. return Typeface::createSystemTypefaceFor (f);
  51724. }
  51725. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51726. {
  51727. defaultSans = newName;
  51728. }
  51729. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51730. {
  51731. return component.getMouseCursor();
  51732. }
  51733. void LookAndFeel::drawButtonBackground (Graphics& g,
  51734. Button& button,
  51735. const Colour& backgroundColour,
  51736. bool isMouseOverButton,
  51737. bool isButtonDown)
  51738. {
  51739. const int width = button.getWidth();
  51740. const int height = button.getHeight();
  51741. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51742. const float halfThickness = outlineThickness * 0.5f;
  51743. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51744. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51745. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51746. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51747. const Colour baseColour (createBaseColour (backgroundColour,
  51748. button.hasKeyboardFocus (true),
  51749. isMouseOverButton, isButtonDown)
  51750. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51751. drawGlassLozenge (g,
  51752. indentL,
  51753. indentT,
  51754. width - indentL - indentR,
  51755. height - indentT - indentB,
  51756. baseColour, outlineThickness, -1.0f,
  51757. button.isConnectedOnLeft(),
  51758. button.isConnectedOnRight(),
  51759. button.isConnectedOnTop(),
  51760. button.isConnectedOnBottom());
  51761. }
  51762. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51763. {
  51764. return button.getFont();
  51765. }
  51766. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51767. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51768. {
  51769. Font font (getFontForTextButton (button));
  51770. g.setFont (font);
  51771. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51772. : TextButton::textColourOffId)
  51773. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51774. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51775. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51776. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51777. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51778. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51779. g.drawFittedText (button.getButtonText(),
  51780. leftIndent,
  51781. yIndent,
  51782. button.getWidth() - leftIndent - rightIndent,
  51783. button.getHeight() - yIndent * 2,
  51784. Justification::centred, 2);
  51785. }
  51786. void LookAndFeel::drawTickBox (Graphics& g,
  51787. Component& component,
  51788. float x, float y, float w, float h,
  51789. const bool ticked,
  51790. const bool isEnabled,
  51791. const bool isMouseOverButton,
  51792. const bool isButtonDown)
  51793. {
  51794. const float boxSize = w * 0.7f;
  51795. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51796. createBaseColour (component.findColour (TextButton::buttonColourId)
  51797. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51798. true,
  51799. isMouseOverButton,
  51800. isButtonDown),
  51801. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51802. if (ticked)
  51803. {
  51804. Path tick;
  51805. tick.startNewSubPath (1.5f, 3.0f);
  51806. tick.lineTo (3.0f, 6.0f);
  51807. tick.lineTo (6.0f, 0.0f);
  51808. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51809. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51810. .translated (x, y));
  51811. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51812. }
  51813. }
  51814. void LookAndFeel::drawToggleButton (Graphics& g,
  51815. ToggleButton& button,
  51816. bool isMouseOverButton,
  51817. bool isButtonDown)
  51818. {
  51819. if (button.hasKeyboardFocus (true))
  51820. {
  51821. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51822. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51823. }
  51824. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51825. const float tickWidth = fontSize * 1.1f;
  51826. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51827. tickWidth, tickWidth,
  51828. button.getToggleState(),
  51829. button.isEnabled(),
  51830. isMouseOverButton,
  51831. isButtonDown);
  51832. g.setColour (button.findColour (ToggleButton::textColourId));
  51833. g.setFont (fontSize);
  51834. if (! button.isEnabled())
  51835. g.setOpacity (0.5f);
  51836. const int textX = (int) tickWidth + 5;
  51837. g.drawFittedText (button.getButtonText(),
  51838. textX, 0,
  51839. button.getWidth() - textX - 2, button.getHeight(),
  51840. Justification::centredLeft, 10);
  51841. }
  51842. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51843. {
  51844. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51845. const int tickWidth = jmin (24, button.getHeight());
  51846. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51847. button.getHeight());
  51848. }
  51849. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51850. const String& message,
  51851. const String& button1,
  51852. const String& button2,
  51853. const String& button3,
  51854. AlertWindow::AlertIconType iconType,
  51855. int numButtons,
  51856. Component* associatedComponent)
  51857. {
  51858. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51859. if (numButtons == 1)
  51860. {
  51861. aw->addButton (button1, 0,
  51862. KeyPress (KeyPress::escapeKey, 0, 0),
  51863. KeyPress (KeyPress::returnKey, 0, 0));
  51864. }
  51865. else
  51866. {
  51867. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51868. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51869. if (button1ShortCut == button2ShortCut)
  51870. button2ShortCut = KeyPress();
  51871. if (numButtons == 2)
  51872. {
  51873. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51874. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51875. }
  51876. else if (numButtons == 3)
  51877. {
  51878. aw->addButton (button1, 1, button1ShortCut);
  51879. aw->addButton (button2, 2, button2ShortCut);
  51880. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51881. }
  51882. }
  51883. return aw;
  51884. }
  51885. void LookAndFeel::drawAlertBox (Graphics& g,
  51886. AlertWindow& alert,
  51887. const Rectangle<int>& textArea,
  51888. TextLayout& textLayout)
  51889. {
  51890. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51891. int iconSpaceUsed = 0;
  51892. Justification alignment (Justification::horizontallyCentred);
  51893. const int iconWidth = 80;
  51894. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51895. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51896. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51897. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51898. iconSize, iconSize);
  51899. if (alert.getAlertType() != AlertWindow::NoIcon)
  51900. {
  51901. Path icon;
  51902. uint32 colour;
  51903. char character;
  51904. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51905. {
  51906. colour = 0x55ff5555;
  51907. character = '!';
  51908. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51909. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51910. (float) iconRect.getX(), (float) iconRect.getBottom());
  51911. icon = icon.createPathWithRoundedCorners (5.0f);
  51912. }
  51913. else
  51914. {
  51915. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51916. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51917. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51918. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51919. }
  51920. GlyphArrangement ga;
  51921. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51922. String::charToString (character),
  51923. (float) iconRect.getX(), (float) iconRect.getY(),
  51924. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51925. Justification::centred, false);
  51926. ga.createPath (icon);
  51927. icon.setUsingNonZeroWinding (false);
  51928. g.setColour (Colour (colour));
  51929. g.fillPath (icon);
  51930. iconSpaceUsed = iconWidth;
  51931. alignment = Justification::left;
  51932. }
  51933. g.setColour (alert.findColour (AlertWindow::textColourId));
  51934. textLayout.drawWithin (g,
  51935. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51936. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51937. alignment.getFlags() | Justification::top);
  51938. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51939. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51940. }
  51941. int LookAndFeel::getAlertBoxWindowFlags()
  51942. {
  51943. return ComponentPeer::windowAppearsOnTaskbar
  51944. | ComponentPeer::windowHasDropShadow;
  51945. }
  51946. int LookAndFeel::getAlertWindowButtonHeight()
  51947. {
  51948. return 28;
  51949. }
  51950. const Font LookAndFeel::getAlertWindowFont()
  51951. {
  51952. return Font (12.0f);
  51953. }
  51954. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51955. int width, int height,
  51956. double progress, const String& textToShow)
  51957. {
  51958. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51959. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51960. g.fillAll (background);
  51961. if (progress >= 0.0f && progress < 1.0f)
  51962. {
  51963. drawGlassLozenge (g, 1.0f, 1.0f,
  51964. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51965. (float) (height - 2),
  51966. foreground,
  51967. 0.5f, 0.0f,
  51968. true, true, true, true);
  51969. }
  51970. else
  51971. {
  51972. // spinning bar..
  51973. g.setColour (foreground);
  51974. const int stripeWidth = height * 2;
  51975. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51976. Path p;
  51977. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51978. p.addQuadrilateral (x, 0.0f,
  51979. x + stripeWidth * 0.5f, 0.0f,
  51980. x, (float) height,
  51981. x - stripeWidth * 0.5f, (float) height);
  51982. Image im (Image::ARGB, width, height, true);
  51983. {
  51984. Graphics g2 (im);
  51985. drawGlassLozenge (g2, 1.0f, 1.0f,
  51986. (float) (width - 2),
  51987. (float) (height - 2),
  51988. foreground,
  51989. 0.5f, 0.0f,
  51990. true, true, true, true);
  51991. }
  51992. g.setTiledImageFill (im, 0, 0, 0.85f);
  51993. g.fillPath (p);
  51994. }
  51995. if (textToShow.isNotEmpty())
  51996. {
  51997. g.setColour (Colour::contrasting (background, foreground));
  51998. g.setFont (height * 0.6f);
  51999. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52000. }
  52001. }
  52002. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52003. {
  52004. const float radius = jmin (w, h) * 0.4f;
  52005. const float thickness = radius * 0.15f;
  52006. Path p;
  52007. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52008. radius * 0.6f, thickness,
  52009. thickness * 0.5f);
  52010. const float cx = x + w * 0.5f;
  52011. const float cy = y + h * 0.5f;
  52012. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52013. for (int i = 0; i < 12; ++i)
  52014. {
  52015. const int n = (i + 12 - animationIndex) % 12;
  52016. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52017. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52018. .translated (cx, cy));
  52019. }
  52020. }
  52021. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52022. ScrollBar& scrollbar,
  52023. int width, int height,
  52024. int buttonDirection,
  52025. bool /*isScrollbarVertical*/,
  52026. bool /*isMouseOverButton*/,
  52027. bool isButtonDown)
  52028. {
  52029. Path p;
  52030. if (buttonDirection == 0)
  52031. p.addTriangle (width * 0.5f, height * 0.2f,
  52032. width * 0.1f, height * 0.7f,
  52033. width * 0.9f, height * 0.7f);
  52034. else if (buttonDirection == 1)
  52035. p.addTriangle (width * 0.8f, height * 0.5f,
  52036. width * 0.3f, height * 0.1f,
  52037. width * 0.3f, height * 0.9f);
  52038. else if (buttonDirection == 2)
  52039. p.addTriangle (width * 0.5f, height * 0.8f,
  52040. width * 0.1f, height * 0.3f,
  52041. width * 0.9f, height * 0.3f);
  52042. else if (buttonDirection == 3)
  52043. p.addTriangle (width * 0.2f, height * 0.5f,
  52044. width * 0.7f, height * 0.1f,
  52045. width * 0.7f, height * 0.9f);
  52046. if (isButtonDown)
  52047. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52048. else
  52049. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52050. g.fillPath (p);
  52051. g.setColour (Colour (0x80000000));
  52052. g.strokePath (p, PathStrokeType (0.5f));
  52053. }
  52054. void LookAndFeel::drawScrollbar (Graphics& g,
  52055. ScrollBar& scrollbar,
  52056. int x, int y,
  52057. int width, int height,
  52058. bool isScrollbarVertical,
  52059. int thumbStartPosition,
  52060. int thumbSize,
  52061. bool /*isMouseOver*/,
  52062. bool /*isMouseDown*/)
  52063. {
  52064. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52065. Path slotPath, thumbPath;
  52066. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52067. const float slotIndentx2 = slotIndent * 2.0f;
  52068. const float thumbIndent = slotIndent + 1.0f;
  52069. const float thumbIndentx2 = thumbIndent * 2.0f;
  52070. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52071. if (isScrollbarVertical)
  52072. {
  52073. slotPath.addRoundedRectangle (x + slotIndent,
  52074. y + slotIndent,
  52075. width - slotIndentx2,
  52076. height - slotIndentx2,
  52077. (width - slotIndentx2) * 0.5f);
  52078. if (thumbSize > 0)
  52079. thumbPath.addRoundedRectangle (x + thumbIndent,
  52080. thumbStartPosition + thumbIndent,
  52081. width - thumbIndentx2,
  52082. thumbSize - thumbIndentx2,
  52083. (width - thumbIndentx2) * 0.5f);
  52084. gx1 = (float) x;
  52085. gx2 = x + width * 0.7f;
  52086. }
  52087. else
  52088. {
  52089. slotPath.addRoundedRectangle (x + slotIndent,
  52090. y + slotIndent,
  52091. width - slotIndentx2,
  52092. height - slotIndentx2,
  52093. (height - slotIndentx2) * 0.5f);
  52094. if (thumbSize > 0)
  52095. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52096. y + thumbIndent,
  52097. thumbSize - thumbIndentx2,
  52098. height - thumbIndentx2,
  52099. (height - thumbIndentx2) * 0.5f);
  52100. gy1 = (float) y;
  52101. gy2 = y + height * 0.7f;
  52102. }
  52103. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52104. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52105. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52106. g.fillPath (slotPath);
  52107. if (isScrollbarVertical)
  52108. {
  52109. gx1 = x + width * 0.6f;
  52110. gx2 = (float) x + width;
  52111. }
  52112. else
  52113. {
  52114. gy1 = y + height * 0.6f;
  52115. gy2 = (float) y + height;
  52116. }
  52117. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52118. Colour (0x19000000), gx2, gy2, false));
  52119. g.fillPath (slotPath);
  52120. g.setColour (thumbColour);
  52121. g.fillPath (thumbPath);
  52122. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52123. Colours::transparentBlack, gx2, gy2, false));
  52124. g.saveState();
  52125. if (isScrollbarVertical)
  52126. g.reduceClipRegion (x + width / 2, y, width, height);
  52127. else
  52128. g.reduceClipRegion (x, y + height / 2, width, height);
  52129. g.fillPath (thumbPath);
  52130. g.restoreState();
  52131. g.setColour (Colour (0x4c000000));
  52132. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52133. }
  52134. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52135. {
  52136. return 0;
  52137. }
  52138. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52139. {
  52140. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52141. }
  52142. int LookAndFeel::getDefaultScrollbarWidth()
  52143. {
  52144. return 18;
  52145. }
  52146. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52147. {
  52148. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52149. : scrollbar.getHeight());
  52150. }
  52151. const Path LookAndFeel::getTickShape (const float height)
  52152. {
  52153. static const unsigned char tickShapeData[] =
  52154. {
  52155. 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,
  52156. 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,
  52157. 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,
  52158. 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,
  52159. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52160. };
  52161. Path p;
  52162. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52163. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52164. return p;
  52165. }
  52166. const Path LookAndFeel::getCrossShape (const float height)
  52167. {
  52168. static const unsigned char crossShapeData[] =
  52169. {
  52170. 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,
  52171. 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,
  52172. 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,
  52173. 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,
  52174. 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,
  52175. 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,
  52176. 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
  52177. };
  52178. Path p;
  52179. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52180. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52181. return p;
  52182. }
  52183. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52184. {
  52185. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52186. x += (w - boxSize) >> 1;
  52187. y += (h - boxSize) >> 1;
  52188. w = boxSize;
  52189. h = boxSize;
  52190. g.setColour (Colour (0xe5ffffff));
  52191. g.fillRect (x, y, w, h);
  52192. g.setColour (Colour (0x80000000));
  52193. g.drawRect (x, y, w, h);
  52194. const float size = boxSize / 2 + 1.0f;
  52195. const float centre = (float) (boxSize / 2);
  52196. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52197. if (isPlus)
  52198. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52199. }
  52200. void LookAndFeel::drawBubble (Graphics& g,
  52201. float tipX, float tipY,
  52202. float boxX, float boxY,
  52203. float boxW, float boxH)
  52204. {
  52205. int side = 0;
  52206. if (tipX < boxX)
  52207. side = 1;
  52208. else if (tipX > boxX + boxW)
  52209. side = 3;
  52210. else if (tipY > boxY + boxH)
  52211. side = 2;
  52212. const float indent = 2.0f;
  52213. Path p;
  52214. p.addBubble (boxX + indent,
  52215. boxY + indent,
  52216. boxW - indent * 2.0f,
  52217. boxH - indent * 2.0f,
  52218. 5.0f,
  52219. tipX, tipY,
  52220. side,
  52221. 0.5f,
  52222. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52223. //xxx need to take comp as param for colour
  52224. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52225. g.fillPath (p);
  52226. //xxx as above
  52227. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52228. g.strokePath (p, PathStrokeType (1.33f));
  52229. }
  52230. const Font LookAndFeel::getPopupMenuFont()
  52231. {
  52232. return Font (17.0f);
  52233. }
  52234. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52235. const bool isSeparator,
  52236. int standardMenuItemHeight,
  52237. int& idealWidth,
  52238. int& idealHeight)
  52239. {
  52240. if (isSeparator)
  52241. {
  52242. idealWidth = 50;
  52243. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52244. }
  52245. else
  52246. {
  52247. Font font (getPopupMenuFont());
  52248. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52249. font.setHeight (standardMenuItemHeight / 1.3f);
  52250. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52251. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52252. }
  52253. }
  52254. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52255. {
  52256. const Colour background (findColour (PopupMenu::backgroundColourId));
  52257. g.fillAll (background);
  52258. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52259. for (int i = 0; i < height; i += 3)
  52260. g.fillRect (0, i, width, 1);
  52261. #if ! JUCE_MAC
  52262. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52263. g.drawRect (0, 0, width, height);
  52264. #endif
  52265. }
  52266. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52267. int width, int height,
  52268. bool isScrollUpArrow)
  52269. {
  52270. const Colour background (findColour (PopupMenu::backgroundColourId));
  52271. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52272. background.withAlpha (0.0f),
  52273. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52274. false));
  52275. g.fillRect (1, 1, width - 2, height - 2);
  52276. const float hw = width * 0.5f;
  52277. const float arrowW = height * 0.3f;
  52278. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52279. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52280. Path p;
  52281. p.addTriangle (hw - arrowW, y1,
  52282. hw + arrowW, y1,
  52283. hw, y2);
  52284. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52285. g.fillPath (p);
  52286. }
  52287. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52288. int width, int height,
  52289. const bool isSeparator,
  52290. const bool isActive,
  52291. const bool isHighlighted,
  52292. const bool isTicked,
  52293. const bool hasSubMenu,
  52294. const String& text,
  52295. const String& shortcutKeyText,
  52296. Image* image,
  52297. const Colour* const textColourToUse)
  52298. {
  52299. const float halfH = height * 0.5f;
  52300. if (isSeparator)
  52301. {
  52302. const float separatorIndent = 5.5f;
  52303. g.setColour (Colour (0x33000000));
  52304. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52305. g.setColour (Colour (0x66ffffff));
  52306. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52307. }
  52308. else
  52309. {
  52310. Colour textColour (findColour (PopupMenu::textColourId));
  52311. if (textColourToUse != 0)
  52312. textColour = *textColourToUse;
  52313. if (isHighlighted)
  52314. {
  52315. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52316. g.fillRect (1, 1, width - 2, height - 2);
  52317. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52318. }
  52319. else
  52320. {
  52321. g.setColour (textColour);
  52322. }
  52323. if (! isActive)
  52324. g.setOpacity (0.3f);
  52325. Font font (getPopupMenuFont());
  52326. if (font.getHeight() > height / 1.3f)
  52327. font.setHeight (height / 1.3f);
  52328. g.setFont (font);
  52329. const int leftBorder = (height * 5) / 4;
  52330. const int rightBorder = 4;
  52331. if (image != 0)
  52332. {
  52333. g.drawImageWithin (*image,
  52334. 2, 1, leftBorder - 4, height - 2,
  52335. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52336. }
  52337. else if (isTicked)
  52338. {
  52339. const Path tick (getTickShape (1.0f));
  52340. const float th = font.getAscent();
  52341. const float ty = halfH - th * 0.5f;
  52342. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52343. th, true));
  52344. }
  52345. g.drawFittedText (text,
  52346. leftBorder, 0,
  52347. width - (leftBorder + rightBorder), height,
  52348. Justification::centredLeft, 1);
  52349. if (shortcutKeyText.isNotEmpty())
  52350. {
  52351. Font f2 (font);
  52352. f2.setHeight (f2.getHeight() * 0.75f);
  52353. f2.setHorizontalScale (0.95f);
  52354. g.setFont (f2);
  52355. g.drawText (shortcutKeyText,
  52356. leftBorder,
  52357. 0,
  52358. width - (leftBorder + rightBorder + 4),
  52359. height,
  52360. Justification::centredRight,
  52361. true);
  52362. }
  52363. if (hasSubMenu)
  52364. {
  52365. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52366. const float x = width - height * 0.6f;
  52367. Path p;
  52368. p.addTriangle (x, halfH - arrowH * 0.5f,
  52369. x, halfH + arrowH * 0.5f,
  52370. x + arrowH * 0.6f, halfH);
  52371. g.fillPath (p);
  52372. }
  52373. }
  52374. }
  52375. int LookAndFeel::getMenuWindowFlags()
  52376. {
  52377. return ComponentPeer::windowHasDropShadow;
  52378. }
  52379. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52380. bool, MenuBarComponent& menuBar)
  52381. {
  52382. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52383. if (menuBar.isEnabled())
  52384. {
  52385. drawShinyButtonShape (g,
  52386. -4.0f, 0.0f,
  52387. width + 8.0f, (float) height,
  52388. 0.0f,
  52389. baseColour,
  52390. 0.4f,
  52391. true, true, true, true);
  52392. }
  52393. else
  52394. {
  52395. g.fillAll (baseColour);
  52396. }
  52397. }
  52398. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52399. {
  52400. return Font (menuBar.getHeight() * 0.7f);
  52401. }
  52402. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52403. {
  52404. return getMenuBarFont (menuBar, itemIndex, itemText)
  52405. .getStringWidth (itemText) + menuBar.getHeight();
  52406. }
  52407. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52408. int width, int height,
  52409. int itemIndex,
  52410. const String& itemText,
  52411. bool isMouseOverItem,
  52412. bool isMenuOpen,
  52413. bool /*isMouseOverBar*/,
  52414. MenuBarComponent& menuBar)
  52415. {
  52416. if (! menuBar.isEnabled())
  52417. {
  52418. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52419. .withMultipliedAlpha (0.5f));
  52420. }
  52421. else if (isMenuOpen || isMouseOverItem)
  52422. {
  52423. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52424. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52425. }
  52426. else
  52427. {
  52428. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52429. }
  52430. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52431. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52432. }
  52433. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52434. TextEditor& textEditor)
  52435. {
  52436. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52437. }
  52438. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52439. {
  52440. if (textEditor.isEnabled())
  52441. {
  52442. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52443. {
  52444. const int border = 2;
  52445. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52446. g.drawRect (0, 0, width, height, border);
  52447. g.setOpacity (1.0f);
  52448. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52449. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52450. }
  52451. else
  52452. {
  52453. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52454. g.drawRect (0, 0, width, height);
  52455. g.setOpacity (1.0f);
  52456. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52457. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52458. }
  52459. }
  52460. }
  52461. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52462. const bool isButtonDown,
  52463. int buttonX, int buttonY,
  52464. int buttonW, int buttonH,
  52465. ComboBox& box)
  52466. {
  52467. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52468. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52469. {
  52470. g.setColour (box.findColour (TextButton::buttonColourId));
  52471. g.drawRect (0, 0, width, height, 2);
  52472. }
  52473. else
  52474. {
  52475. g.setColour (box.findColour (ComboBox::outlineColourId));
  52476. g.drawRect (0, 0, width, height);
  52477. }
  52478. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52479. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52480. box.hasKeyboardFocus (true),
  52481. false, isButtonDown)
  52482. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52483. drawGlassLozenge (g,
  52484. buttonX + outlineThickness, buttonY + outlineThickness,
  52485. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52486. baseColour, outlineThickness, -1.0f,
  52487. true, true, true, true);
  52488. if (box.isEnabled())
  52489. {
  52490. const float arrowX = 0.3f;
  52491. const float arrowH = 0.2f;
  52492. Path p;
  52493. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52494. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52495. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52496. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52497. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52498. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52499. g.setColour (box.findColour (ComboBox::arrowColourId));
  52500. g.fillPath (p);
  52501. }
  52502. }
  52503. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52504. {
  52505. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52506. }
  52507. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52508. {
  52509. return new Label (String::empty, String::empty);
  52510. }
  52511. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52512. {
  52513. label.setBounds (1, 1,
  52514. box.getWidth() + 3 - box.getHeight(),
  52515. box.getHeight() - 2);
  52516. label.setFont (getComboBoxFont (box));
  52517. }
  52518. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52519. {
  52520. g.fillAll (label.findColour (Label::backgroundColourId));
  52521. if (! label.isBeingEdited())
  52522. {
  52523. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52524. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52525. g.setFont (label.getFont());
  52526. g.drawFittedText (label.getText(),
  52527. label.getHorizontalBorderSize(),
  52528. label.getVerticalBorderSize(),
  52529. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52530. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52531. label.getJustificationType(),
  52532. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52533. label.getMinimumHorizontalScale());
  52534. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52535. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52536. }
  52537. else if (label.isEnabled())
  52538. {
  52539. g.setColour (label.findColour (Label::outlineColourId));
  52540. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52541. }
  52542. }
  52543. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52544. int x, int y,
  52545. int width, int height,
  52546. float /*sliderPos*/,
  52547. float /*minSliderPos*/,
  52548. float /*maxSliderPos*/,
  52549. const Slider::SliderStyle /*style*/,
  52550. Slider& slider)
  52551. {
  52552. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52553. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52554. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52555. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52556. Path indent;
  52557. if (slider.isHorizontal())
  52558. {
  52559. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52560. const float ih = sliderRadius;
  52561. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52562. gradCol2, 0.0f, iy + ih, false));
  52563. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52564. width + sliderRadius, ih,
  52565. 5.0f);
  52566. g.fillPath (indent);
  52567. }
  52568. else
  52569. {
  52570. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52571. const float iw = sliderRadius;
  52572. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52573. gradCol2, ix + iw, 0.0f, false));
  52574. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52575. iw, height + sliderRadius,
  52576. 5.0f);
  52577. g.fillPath (indent);
  52578. }
  52579. g.setColour (Colour (0x4c000000));
  52580. g.strokePath (indent, PathStrokeType (0.5f));
  52581. }
  52582. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52583. int x, int y,
  52584. int width, int height,
  52585. float sliderPos,
  52586. float minSliderPos,
  52587. float maxSliderPos,
  52588. const Slider::SliderStyle style,
  52589. Slider& slider)
  52590. {
  52591. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52592. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52593. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52594. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52595. slider.isMouseButtonDown() && slider.isEnabled()));
  52596. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52597. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52598. {
  52599. float kx, ky;
  52600. if (style == Slider::LinearVertical)
  52601. {
  52602. kx = x + width * 0.5f;
  52603. ky = sliderPos;
  52604. }
  52605. else
  52606. {
  52607. kx = sliderPos;
  52608. ky = y + height * 0.5f;
  52609. }
  52610. drawGlassSphere (g,
  52611. kx - sliderRadius,
  52612. ky - sliderRadius,
  52613. sliderRadius * 2.0f,
  52614. knobColour, outlineThickness);
  52615. }
  52616. else
  52617. {
  52618. if (style == Slider::ThreeValueVertical)
  52619. {
  52620. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52621. sliderPos - sliderRadius,
  52622. sliderRadius * 2.0f,
  52623. knobColour, outlineThickness);
  52624. }
  52625. else if (style == Slider::ThreeValueHorizontal)
  52626. {
  52627. drawGlassSphere (g,sliderPos - sliderRadius,
  52628. y + height * 0.5f - sliderRadius,
  52629. sliderRadius * 2.0f,
  52630. knobColour, outlineThickness);
  52631. }
  52632. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52633. {
  52634. const float sr = jmin (sliderRadius, width * 0.4f);
  52635. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52636. minSliderPos - sliderRadius,
  52637. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52638. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52639. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52640. }
  52641. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52642. {
  52643. const float sr = jmin (sliderRadius, height * 0.4f);
  52644. drawGlassPointer (g, minSliderPos - sr,
  52645. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52646. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52647. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52648. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52649. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52650. }
  52651. }
  52652. }
  52653. void LookAndFeel::drawLinearSlider (Graphics& g,
  52654. int x, int y,
  52655. int width, int height,
  52656. float sliderPos,
  52657. float minSliderPos,
  52658. float maxSliderPos,
  52659. const Slider::SliderStyle style,
  52660. Slider& slider)
  52661. {
  52662. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52663. if (style == Slider::LinearBar)
  52664. {
  52665. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52666. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52667. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52668. false,
  52669. isMouseOver,
  52670. isMouseOver || slider.isMouseButtonDown()));
  52671. drawShinyButtonShape (g,
  52672. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52673. baseColour,
  52674. slider.isEnabled() ? 0.9f : 0.3f,
  52675. true, true, true, true);
  52676. }
  52677. else
  52678. {
  52679. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52680. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52681. }
  52682. }
  52683. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52684. {
  52685. return jmin (7,
  52686. slider.getHeight() / 2,
  52687. slider.getWidth() / 2) + 2;
  52688. }
  52689. void LookAndFeel::drawRotarySlider (Graphics& g,
  52690. int x, int y,
  52691. int width, int height,
  52692. float sliderPos,
  52693. const float rotaryStartAngle,
  52694. const float rotaryEndAngle,
  52695. Slider& slider)
  52696. {
  52697. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52698. const float centreX = x + width * 0.5f;
  52699. const float centreY = y + height * 0.5f;
  52700. const float rx = centreX - radius;
  52701. const float ry = centreY - radius;
  52702. const float rw = radius * 2.0f;
  52703. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52704. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52705. if (radius > 12.0f)
  52706. {
  52707. if (slider.isEnabled())
  52708. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52709. else
  52710. g.setColour (Colour (0x80808080));
  52711. const float thickness = 0.7f;
  52712. {
  52713. Path filledArc;
  52714. filledArc.addPieSegment (rx, ry, rw, rw,
  52715. rotaryStartAngle,
  52716. angle,
  52717. thickness);
  52718. g.fillPath (filledArc);
  52719. }
  52720. if (thickness > 0)
  52721. {
  52722. const float innerRadius = radius * 0.2f;
  52723. Path p;
  52724. p.addTriangle (-innerRadius, 0.0f,
  52725. 0.0f, -radius * thickness * 1.1f,
  52726. innerRadius, 0.0f);
  52727. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52728. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52729. }
  52730. if (slider.isEnabled())
  52731. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52732. else
  52733. g.setColour (Colour (0x80808080));
  52734. Path outlineArc;
  52735. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52736. outlineArc.closeSubPath();
  52737. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52738. }
  52739. else
  52740. {
  52741. if (slider.isEnabled())
  52742. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52743. else
  52744. g.setColour (Colour (0x80808080));
  52745. Path p;
  52746. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52747. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52748. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  52749. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52750. }
  52751. }
  52752. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52753. {
  52754. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52755. }
  52756. class SliderLabelComp : public Label
  52757. {
  52758. public:
  52759. SliderLabelComp() : Label (String::empty, String::empty) {}
  52760. ~SliderLabelComp() {}
  52761. void mouseWheelMove (const MouseEvent&, float, float) {}
  52762. };
  52763. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52764. {
  52765. Label* const l = new SliderLabelComp();
  52766. l->setJustificationType (Justification::centred);
  52767. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52768. l->setColour (Label::backgroundColourId,
  52769. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52770. : slider.findColour (Slider::textBoxBackgroundColourId));
  52771. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52772. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52773. l->setColour (TextEditor::backgroundColourId,
  52774. slider.findColour (Slider::textBoxBackgroundColourId)
  52775. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52776. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52777. return l;
  52778. }
  52779. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52780. {
  52781. return 0;
  52782. }
  52783. static const TextLayout layoutTooltipText (const String& text) throw()
  52784. {
  52785. const float tooltipFontSize = 12.0f;
  52786. const int maxToolTipWidth = 400;
  52787. const Font f (tooltipFontSize, Font::bold);
  52788. TextLayout tl (text, f);
  52789. tl.layout (maxToolTipWidth, Justification::left, true);
  52790. return tl;
  52791. }
  52792. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52793. {
  52794. const TextLayout tl (layoutTooltipText (tipText));
  52795. width = tl.getWidth() + 14;
  52796. height = tl.getHeight() + 6;
  52797. }
  52798. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52799. {
  52800. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52801. const Colour textCol (findColour (TooltipWindow::textColourId));
  52802. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52803. g.setColour (findColour (TooltipWindow::outlineColourId));
  52804. g.drawRect (0, 0, width, height, 1);
  52805. #endif
  52806. const TextLayout tl (layoutTooltipText (text));
  52807. g.setColour (findColour (TooltipWindow::textColourId));
  52808. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52809. }
  52810. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52811. {
  52812. return new TextButton (text, TRANS("click to browse for a different file"));
  52813. }
  52814. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52815. ComboBox* filenameBox,
  52816. Button* browseButton)
  52817. {
  52818. browseButton->setSize (80, filenameComp.getHeight());
  52819. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52820. if (tb != 0)
  52821. tb->changeWidthToFitText();
  52822. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52823. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52824. }
  52825. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52826. int imageX, int imageY, int imageW, int imageH,
  52827. const Colour& overlayColour,
  52828. float imageOpacity,
  52829. ImageButton& button)
  52830. {
  52831. if (! button.isEnabled())
  52832. imageOpacity *= 0.3f;
  52833. if (! overlayColour.isOpaque())
  52834. {
  52835. g.setOpacity (imageOpacity);
  52836. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52837. 0, 0, image->getWidth(), image->getHeight(), false);
  52838. }
  52839. if (! overlayColour.isTransparent())
  52840. {
  52841. g.setColour (overlayColour);
  52842. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52843. 0, 0, image->getWidth(), image->getHeight(), true);
  52844. }
  52845. }
  52846. void LookAndFeel::drawCornerResizer (Graphics& g,
  52847. int w, int h,
  52848. bool /*isMouseOver*/,
  52849. bool /*isMouseDragging*/)
  52850. {
  52851. const float lineThickness = jmin (w, h) * 0.075f;
  52852. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52853. {
  52854. g.setColour (Colours::lightgrey);
  52855. g.drawLine (w * i,
  52856. h + 1.0f,
  52857. w + 1.0f,
  52858. h * i,
  52859. lineThickness);
  52860. g.setColour (Colours::darkgrey);
  52861. g.drawLine (w * i + lineThickness,
  52862. h + 1.0f,
  52863. w + 1.0f,
  52864. h * i + lineThickness,
  52865. lineThickness);
  52866. }
  52867. }
  52868. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52869. const BorderSize& /*borders*/)
  52870. {
  52871. }
  52872. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52873. const BorderSize& /*border*/, ResizableWindow& window)
  52874. {
  52875. g.fillAll (window.getBackgroundColour());
  52876. }
  52877. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52878. const BorderSize& border, ResizableWindow&)
  52879. {
  52880. g.setColour (Colour (0x80000000));
  52881. g.drawRect (0, 0, w, h);
  52882. g.setColour (Colour (0x19000000));
  52883. g.drawRect (border.getLeft() - 1,
  52884. border.getTop() - 1,
  52885. w + 2 - border.getLeftAndRight(),
  52886. h + 2 - border.getTopAndBottom());
  52887. }
  52888. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52889. Graphics& g, int w, int h,
  52890. int titleSpaceX, int titleSpaceW,
  52891. const Image* icon,
  52892. bool drawTitleTextOnLeft)
  52893. {
  52894. const bool isActive = window.isActiveWindow();
  52895. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52896. 0.0f, 0.0f,
  52897. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52898. 0.0f, (float) h, false));
  52899. g.fillAll();
  52900. Font font (h * 0.65f, Font::bold);
  52901. g.setFont (font);
  52902. int textW = font.getStringWidth (window.getName());
  52903. int iconW = 0;
  52904. int iconH = 0;
  52905. if (icon != 0)
  52906. {
  52907. iconH = (int) font.getHeight();
  52908. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52909. }
  52910. textW = jmin (titleSpaceW, textW + iconW);
  52911. int textX = drawTitleTextOnLeft ? titleSpaceX
  52912. : jmax (titleSpaceX, (w - textW) / 2);
  52913. if (textX + textW > titleSpaceX + titleSpaceW)
  52914. textX = titleSpaceX + titleSpaceW - textW;
  52915. if (icon != 0)
  52916. {
  52917. g.setOpacity (isActive ? 1.0f : 0.6f);
  52918. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  52919. RectanglePlacement::centred, false);
  52920. textX += iconW;
  52921. textW -= iconW;
  52922. }
  52923. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52924. g.setColour (findColour (DocumentWindow::textColourId));
  52925. else
  52926. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52927. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52928. }
  52929. class GlassWindowButton : public Button
  52930. {
  52931. public:
  52932. GlassWindowButton (const String& name, const Colour& col,
  52933. const Path& normalShape_,
  52934. const Path& toggledShape_) throw()
  52935. : Button (name),
  52936. colour (col),
  52937. normalShape (normalShape_),
  52938. toggledShape (toggledShape_)
  52939. {
  52940. }
  52941. ~GlassWindowButton()
  52942. {
  52943. }
  52944. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52945. {
  52946. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52947. if (! isEnabled())
  52948. alpha *= 0.5f;
  52949. float x = 0, y = 0, diam;
  52950. if (getWidth() < getHeight())
  52951. {
  52952. diam = (float) getWidth();
  52953. y = (getHeight() - getWidth()) * 0.5f;
  52954. }
  52955. else
  52956. {
  52957. diam = (float) getHeight();
  52958. y = (getWidth() - getHeight()) * 0.5f;
  52959. }
  52960. x += diam * 0.05f;
  52961. y += diam * 0.05f;
  52962. diam *= 0.9f;
  52963. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52964. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52965. g.fillEllipse (x, y, diam, diam);
  52966. x += 2.0f;
  52967. y += 2.0f;
  52968. diam -= 4.0f;
  52969. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52970. Path& p = getToggleState() ? toggledShape : normalShape;
  52971. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52972. diam * 0.4f, diam * 0.4f, true));
  52973. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52974. g.fillPath (p, t);
  52975. }
  52976. juce_UseDebuggingNewOperator
  52977. private:
  52978. Colour colour;
  52979. Path normalShape, toggledShape;
  52980. GlassWindowButton (const GlassWindowButton&);
  52981. GlassWindowButton& operator= (const GlassWindowButton&);
  52982. };
  52983. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52984. {
  52985. Path shape;
  52986. const float crossThickness = 0.25f;
  52987. if (buttonType == DocumentWindow::closeButton)
  52988. {
  52989. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  52990. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  52991. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52992. }
  52993. else if (buttonType == DocumentWindow::minimiseButton)
  52994. {
  52995. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52996. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52997. }
  52998. else if (buttonType == DocumentWindow::maximiseButton)
  52999. {
  53000. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53001. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53002. Path fullscreenShape;
  53003. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53004. fullscreenShape.lineTo (0.0f, 100.0f);
  53005. fullscreenShape.lineTo (0.0f, 0.0f);
  53006. fullscreenShape.lineTo (100.0f, 0.0f);
  53007. fullscreenShape.lineTo (100.0f, 45.0f);
  53008. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53009. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53010. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53011. }
  53012. jassertfalse;
  53013. return 0;
  53014. }
  53015. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53016. int titleBarX,
  53017. int titleBarY,
  53018. int titleBarW,
  53019. int titleBarH,
  53020. Button* minimiseButton,
  53021. Button* maximiseButton,
  53022. Button* closeButton,
  53023. bool positionTitleBarButtonsOnLeft)
  53024. {
  53025. const int buttonW = titleBarH - titleBarH / 8;
  53026. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53027. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53028. if (closeButton != 0)
  53029. {
  53030. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53031. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53032. }
  53033. if (positionTitleBarButtonsOnLeft)
  53034. swapVariables (minimiseButton, maximiseButton);
  53035. if (maximiseButton != 0)
  53036. {
  53037. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53038. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53039. }
  53040. if (minimiseButton != 0)
  53041. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53042. }
  53043. int LookAndFeel::getDefaultMenuBarHeight()
  53044. {
  53045. return 24;
  53046. }
  53047. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53048. {
  53049. return new DropShadower (0.4f, 1, 5, 10);
  53050. }
  53051. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53052. int w, int h,
  53053. bool /*isVerticalBar*/,
  53054. bool isMouseOver,
  53055. bool isMouseDragging)
  53056. {
  53057. float alpha = 0.5f;
  53058. if (isMouseOver || isMouseDragging)
  53059. {
  53060. g.fillAll (Colour (0x190000ff));
  53061. alpha = 1.0f;
  53062. }
  53063. const float cx = w * 0.5f;
  53064. const float cy = h * 0.5f;
  53065. const float cr = jmin (w, h) * 0.4f;
  53066. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53067. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53068. true));
  53069. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53070. }
  53071. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53072. const String& text,
  53073. const Justification& position,
  53074. GroupComponent& group)
  53075. {
  53076. const float textH = 15.0f;
  53077. const float indent = 3.0f;
  53078. const float textEdgeGap = 4.0f;
  53079. float cs = 5.0f;
  53080. Font f (textH);
  53081. Path p;
  53082. float x = indent;
  53083. float y = f.getAscent() - 3.0f;
  53084. float w = jmax (0.0f, width - x * 2.0f);
  53085. float h = jmax (0.0f, height - y - indent);
  53086. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53087. const float cs2 = 2.0f * cs;
  53088. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53089. float textX = cs + textEdgeGap;
  53090. if (position.testFlags (Justification::horizontallyCentred))
  53091. textX = cs + (w - cs2 - textW) * 0.5f;
  53092. else if (position.testFlags (Justification::right))
  53093. textX = w - cs - textW - textEdgeGap;
  53094. p.startNewSubPath (x + textX + textW, y);
  53095. p.lineTo (x + w - cs, y);
  53096. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53097. p.lineTo (x + w, y + h - cs);
  53098. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53099. p.lineTo (x + cs, y + h);
  53100. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53101. p.lineTo (x, y + cs);
  53102. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53103. p.lineTo (x + textX, y);
  53104. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53105. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53106. .withMultipliedAlpha (alpha));
  53107. g.strokePath (p, PathStrokeType (2.0f));
  53108. g.setColour (group.findColour (GroupComponent::textColourId)
  53109. .withMultipliedAlpha (alpha));
  53110. g.setFont (f);
  53111. g.drawText (text,
  53112. roundToInt (x + textX), 0,
  53113. roundToInt (textW),
  53114. roundToInt (textH),
  53115. Justification::centred, true);
  53116. }
  53117. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53118. {
  53119. return 1 + tabDepth / 3;
  53120. }
  53121. int LookAndFeel::getTabButtonSpaceAroundImage()
  53122. {
  53123. return 4;
  53124. }
  53125. void LookAndFeel::createTabButtonShape (Path& p,
  53126. int width, int height,
  53127. int /*tabIndex*/,
  53128. const String& /*text*/,
  53129. Button& /*button*/,
  53130. TabbedButtonBar::Orientation orientation,
  53131. const bool /*isMouseOver*/,
  53132. const bool /*isMouseDown*/,
  53133. const bool /*isFrontTab*/)
  53134. {
  53135. const float w = (float) width;
  53136. const float h = (float) height;
  53137. float length = w;
  53138. float depth = h;
  53139. if (orientation == TabbedButtonBar::TabsAtLeft
  53140. || orientation == TabbedButtonBar::TabsAtRight)
  53141. {
  53142. swapVariables (length, depth);
  53143. }
  53144. const float indent = (float) getTabButtonOverlap ((int) depth);
  53145. const float overhang = 4.0f;
  53146. if (orientation == TabbedButtonBar::TabsAtLeft)
  53147. {
  53148. p.startNewSubPath (w, 0.0f);
  53149. p.lineTo (0.0f, indent);
  53150. p.lineTo (0.0f, h - indent);
  53151. p.lineTo (w, h);
  53152. p.lineTo (w + overhang, h + overhang);
  53153. p.lineTo (w + overhang, -overhang);
  53154. }
  53155. else if (orientation == TabbedButtonBar::TabsAtRight)
  53156. {
  53157. p.startNewSubPath (0.0f, 0.0f);
  53158. p.lineTo (w, indent);
  53159. p.lineTo (w, h - indent);
  53160. p.lineTo (0.0f, h);
  53161. p.lineTo (-overhang, h + overhang);
  53162. p.lineTo (-overhang, -overhang);
  53163. }
  53164. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53165. {
  53166. p.startNewSubPath (0.0f, 0.0f);
  53167. p.lineTo (indent, h);
  53168. p.lineTo (w - indent, h);
  53169. p.lineTo (w, 0.0f);
  53170. p.lineTo (w + overhang, -overhang);
  53171. p.lineTo (-overhang, -overhang);
  53172. }
  53173. else
  53174. {
  53175. p.startNewSubPath (0.0f, h);
  53176. p.lineTo (indent, 0.0f);
  53177. p.lineTo (w - indent, 0.0f);
  53178. p.lineTo (w, h);
  53179. p.lineTo (w + overhang, h + overhang);
  53180. p.lineTo (-overhang, h + overhang);
  53181. }
  53182. p.closeSubPath();
  53183. p = p.createPathWithRoundedCorners (3.0f);
  53184. }
  53185. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53186. const Path& path,
  53187. const Colour& preferredColour,
  53188. int /*tabIndex*/,
  53189. const String& /*text*/,
  53190. Button& button,
  53191. TabbedButtonBar::Orientation /*orientation*/,
  53192. const bool /*isMouseOver*/,
  53193. const bool /*isMouseDown*/,
  53194. const bool isFrontTab)
  53195. {
  53196. g.setColour (isFrontTab ? preferredColour
  53197. : preferredColour.withMultipliedAlpha (0.9f));
  53198. g.fillPath (path);
  53199. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53200. : TabbedButtonBar::tabOutlineColourId, false)
  53201. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53202. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53203. }
  53204. void LookAndFeel::drawTabButtonText (Graphics& g,
  53205. int x, int y, int w, int h,
  53206. const Colour& preferredBackgroundColour,
  53207. int /*tabIndex*/,
  53208. const String& text,
  53209. Button& button,
  53210. TabbedButtonBar::Orientation orientation,
  53211. const bool isMouseOver,
  53212. const bool isMouseDown,
  53213. const bool isFrontTab)
  53214. {
  53215. int length = w;
  53216. int depth = h;
  53217. if (orientation == TabbedButtonBar::TabsAtLeft
  53218. || orientation == TabbedButtonBar::TabsAtRight)
  53219. {
  53220. swapVariables (length, depth);
  53221. }
  53222. Font font (depth * 0.6f);
  53223. font.setUnderline (button.hasKeyboardFocus (false));
  53224. GlyphArrangement textLayout;
  53225. textLayout.addFittedText (font, text.trim(),
  53226. 0.0f, 0.0f, (float) length, (float) depth,
  53227. Justification::centred,
  53228. jmax (1, depth / 12));
  53229. AffineTransform transform;
  53230. if (orientation == TabbedButtonBar::TabsAtLeft)
  53231. {
  53232. transform = transform.rotated (float_Pi * -0.5f)
  53233. .translated ((float) x, (float) (y + h));
  53234. }
  53235. else if (orientation == TabbedButtonBar::TabsAtRight)
  53236. {
  53237. transform = transform.rotated (float_Pi * 0.5f)
  53238. .translated ((float) (x + w), (float) y);
  53239. }
  53240. else
  53241. {
  53242. transform = transform.translated ((float) x, (float) y);
  53243. }
  53244. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53245. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53246. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53247. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53248. else
  53249. g.setColour (preferredBackgroundColour.contrasting());
  53250. if (! (isMouseOver || isMouseDown))
  53251. g.setOpacity (0.8f);
  53252. if (! button.isEnabled())
  53253. g.setOpacity (0.3f);
  53254. textLayout.draw (g, transform);
  53255. }
  53256. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53257. const String& text,
  53258. int tabDepth,
  53259. Button&)
  53260. {
  53261. Font f (tabDepth * 0.6f);
  53262. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53263. }
  53264. void LookAndFeel::drawTabButton (Graphics& g,
  53265. int w, int h,
  53266. const Colour& preferredColour,
  53267. int tabIndex,
  53268. const String& text,
  53269. Button& button,
  53270. TabbedButtonBar::Orientation orientation,
  53271. const bool isMouseOver,
  53272. const bool isMouseDown,
  53273. const bool isFrontTab)
  53274. {
  53275. int length = w;
  53276. int depth = h;
  53277. if (orientation == TabbedButtonBar::TabsAtLeft
  53278. || orientation == TabbedButtonBar::TabsAtRight)
  53279. {
  53280. swapVariables (length, depth);
  53281. }
  53282. Path tabShape;
  53283. createTabButtonShape (tabShape, w, h,
  53284. tabIndex, text, button, orientation,
  53285. isMouseOver, isMouseDown, isFrontTab);
  53286. fillTabButtonShape (g, tabShape, preferredColour,
  53287. tabIndex, text, button, orientation,
  53288. isMouseOver, isMouseDown, isFrontTab);
  53289. const int indent = getTabButtonOverlap (depth);
  53290. int x = 0, y = 0;
  53291. if (orientation == TabbedButtonBar::TabsAtLeft
  53292. || orientation == TabbedButtonBar::TabsAtRight)
  53293. {
  53294. y += indent;
  53295. h -= indent * 2;
  53296. }
  53297. else
  53298. {
  53299. x += indent;
  53300. w -= indent * 2;
  53301. }
  53302. drawTabButtonText (g, x, y, w, h, preferredColour,
  53303. tabIndex, text, button, orientation,
  53304. isMouseOver, isMouseDown, isFrontTab);
  53305. }
  53306. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53307. int w, int h,
  53308. TabbedButtonBar& tabBar,
  53309. TabbedButtonBar::Orientation orientation)
  53310. {
  53311. const float shadowSize = 0.2f;
  53312. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53313. Rectangle<int> shadowRect;
  53314. if (orientation == TabbedButtonBar::TabsAtLeft)
  53315. {
  53316. x1 = (float) w;
  53317. x2 = w * (1.0f - shadowSize);
  53318. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53319. }
  53320. else if (orientation == TabbedButtonBar::TabsAtRight)
  53321. {
  53322. x2 = w * shadowSize;
  53323. shadowRect.setBounds (0, 0, (int) x2, h);
  53324. }
  53325. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53326. {
  53327. y2 = h * shadowSize;
  53328. shadowRect.setBounds (0, 0, w, (int) y2);
  53329. }
  53330. else
  53331. {
  53332. y1 = (float) h;
  53333. y2 = h * (1.0f - shadowSize);
  53334. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53335. }
  53336. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53337. Colours::transparentBlack, x2, y2, false));
  53338. shadowRect.expand (2, 2);
  53339. g.fillRect (shadowRect);
  53340. g.setColour (Colour (0x80000000));
  53341. if (orientation == TabbedButtonBar::TabsAtLeft)
  53342. {
  53343. g.fillRect (w - 1, 0, 1, h);
  53344. }
  53345. else if (orientation == TabbedButtonBar::TabsAtRight)
  53346. {
  53347. g.fillRect (0, 0, 1, h);
  53348. }
  53349. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53350. {
  53351. g.fillRect (0, 0, w, 1);
  53352. }
  53353. else
  53354. {
  53355. g.fillRect (0, h - 1, w, 1);
  53356. }
  53357. }
  53358. Button* LookAndFeel::createTabBarExtrasButton()
  53359. {
  53360. const float thickness = 7.0f;
  53361. const float indent = 22.0f;
  53362. Path p;
  53363. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53364. DrawablePath ellipse;
  53365. ellipse.setPath (p);
  53366. ellipse.setFill (Colour (0x99ffffff));
  53367. p.clear();
  53368. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53369. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53370. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53371. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53372. p.setUsingNonZeroWinding (false);
  53373. DrawablePath dp;
  53374. dp.setPath (p);
  53375. dp.setFill (Colour (0x59000000));
  53376. DrawableComposite normalImage;
  53377. normalImage.insertDrawable (ellipse);
  53378. normalImage.insertDrawable (dp);
  53379. dp.setFill (Colour (0xcc000000));
  53380. DrawableComposite overImage;
  53381. overImage.insertDrawable (ellipse);
  53382. overImage.insertDrawable (dp);
  53383. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53384. db->setImages (&normalImage, &overImage, 0);
  53385. return db;
  53386. }
  53387. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53388. {
  53389. g.fillAll (Colours::white);
  53390. const int w = header.getWidth();
  53391. const int h = header.getHeight();
  53392. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53393. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53394. false));
  53395. g.fillRect (0, h / 2, w, h);
  53396. g.setColour (Colour (0x33000000));
  53397. g.fillRect (0, h - 1, w, 1);
  53398. for (int i = header.getNumColumns (true); --i >= 0;)
  53399. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53400. }
  53401. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53402. int width, int height,
  53403. bool isMouseOver, bool isMouseDown,
  53404. int columnFlags)
  53405. {
  53406. if (isMouseDown)
  53407. g.fillAll (Colour (0x8899aadd));
  53408. else if (isMouseOver)
  53409. g.fillAll (Colour (0x5599aadd));
  53410. int rightOfText = width - 4;
  53411. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53412. {
  53413. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53414. const float bottom = height - top;
  53415. const float w = height * 0.5f;
  53416. const float x = rightOfText - (w * 1.25f);
  53417. rightOfText = (int) x;
  53418. Path sortArrow;
  53419. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53420. g.setColour (Colour (0x99000000));
  53421. g.fillPath (sortArrow);
  53422. }
  53423. g.setColour (Colours::black);
  53424. g.setFont (height * 0.5f, Font::bold);
  53425. const int textX = 4;
  53426. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53427. }
  53428. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53429. {
  53430. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53431. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53432. background.darker (0.1f),
  53433. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53434. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53435. false));
  53436. g.fillAll();
  53437. }
  53438. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53439. {
  53440. return createTabBarExtrasButton();
  53441. }
  53442. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53443. bool isMouseOver, bool isMouseDown,
  53444. ToolbarItemComponent& component)
  53445. {
  53446. if (isMouseDown)
  53447. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53448. else if (isMouseOver)
  53449. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53450. }
  53451. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53452. const String& text, ToolbarItemComponent& component)
  53453. {
  53454. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53455. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53456. const float fontHeight = jmin (14.0f, height * 0.85f);
  53457. g.setFont (fontHeight);
  53458. g.drawFittedText (text,
  53459. x, y, width, height,
  53460. Justification::centred,
  53461. jmax (1, height / (int) fontHeight));
  53462. }
  53463. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53464. bool isOpen, int width, int height)
  53465. {
  53466. const int buttonSize = (height * 3) / 4;
  53467. const int buttonIndent = (height - buttonSize) / 2;
  53468. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53469. const int textX = buttonIndent * 2 + buttonSize + 2;
  53470. g.setColour (Colours::black);
  53471. g.setFont (height * 0.7f, Font::bold);
  53472. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53473. }
  53474. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53475. PropertyComponent&)
  53476. {
  53477. g.setColour (Colour (0x66ffffff));
  53478. g.fillRect (0, 0, width, height - 1);
  53479. }
  53480. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53481. PropertyComponent& component)
  53482. {
  53483. g.setColour (Colours::black);
  53484. if (! component.isEnabled())
  53485. g.setOpacity (0.6f);
  53486. g.setFont (jmin (height, 24) * 0.65f);
  53487. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53488. g.drawFittedText (component.getName(),
  53489. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53490. Justification::centredLeft, 2);
  53491. }
  53492. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53493. {
  53494. return Rectangle<int> (component.getWidth() / 3, 1,
  53495. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53496. }
  53497. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  53498. {
  53499. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  53500. {
  53501. Graphics g2 (content);
  53502. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  53503. g2.fillPath (path);
  53504. g2.setColour (Colours::white.withAlpha (0.8f));
  53505. g2.strokePath (path, PathStrokeType (2.0f));
  53506. }
  53507. DropShadowEffect shadow;
  53508. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  53509. shadow.applyEffect (content, g);
  53510. }
  53511. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53512. const String& instructions,
  53513. GlyphArrangement& text,
  53514. int width)
  53515. {
  53516. text.clear();
  53517. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53518. 8.0f, 22.0f, width - 16.0f,
  53519. Justification::centred);
  53520. text.addJustifiedText (Font (14.0f), instructions,
  53521. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53522. Justification::centred);
  53523. }
  53524. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53525. const String& filename, Image* icon,
  53526. const String& fileSizeDescription,
  53527. const String& fileTimeDescription,
  53528. const bool isDirectory,
  53529. const bool isItemSelected,
  53530. const int /*itemIndex*/)
  53531. {
  53532. if (isItemSelected)
  53533. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53534. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53535. g.setFont (height * 0.7f);
  53536. Image im;
  53537. if (icon != 0)
  53538. im = *icon;
  53539. if (im.isNull())
  53540. im = isDirectory ? getDefaultFolderImage()
  53541. : getDefaultDocumentFileImage();
  53542. const int x = 32;
  53543. if (im.isValid())
  53544. {
  53545. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53546. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53547. false);
  53548. }
  53549. if (width > 450 && ! isDirectory)
  53550. {
  53551. const int sizeX = roundToInt (width * 0.7f);
  53552. const int dateX = roundToInt (width * 0.8f);
  53553. g.drawFittedText (filename,
  53554. x, 0, sizeX - x, height,
  53555. Justification::centredLeft, 1);
  53556. g.setFont (height * 0.5f);
  53557. g.setColour (Colours::darkgrey);
  53558. if (! isDirectory)
  53559. {
  53560. g.drawFittedText (fileSizeDescription,
  53561. sizeX, 0, dateX - sizeX - 8, height,
  53562. Justification::centredRight, 1);
  53563. g.drawFittedText (fileTimeDescription,
  53564. dateX, 0, width - 8 - dateX, height,
  53565. Justification::centredRight, 1);
  53566. }
  53567. }
  53568. else
  53569. {
  53570. g.drawFittedText (filename,
  53571. x, 0, width - x, height,
  53572. Justification::centredLeft, 1);
  53573. }
  53574. }
  53575. Button* LookAndFeel::createFileBrowserGoUpButton()
  53576. {
  53577. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53578. Path arrowPath;
  53579. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  53580. DrawablePath arrowImage;
  53581. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53582. arrowImage.setPath (arrowPath);
  53583. goUpButton->setImages (&arrowImage);
  53584. return goUpButton;
  53585. }
  53586. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53587. DirectoryContentsDisplayComponent* fileListComponent,
  53588. FilePreviewComponent* previewComp,
  53589. ComboBox* currentPathBox,
  53590. TextEditor* filenameBox,
  53591. Button* goUpButton)
  53592. {
  53593. const int x = 8;
  53594. int w = browserComp.getWidth() - x - x;
  53595. if (previewComp != 0)
  53596. {
  53597. const int previewWidth = w / 3;
  53598. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53599. w -= previewWidth + 4;
  53600. }
  53601. int y = 4;
  53602. const int controlsHeight = 22;
  53603. const int bottomSectionHeight = controlsHeight + 8;
  53604. const int upButtonWidth = 50;
  53605. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53606. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53607. y += controlsHeight + 4;
  53608. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53609. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53610. y = listAsComp->getBottom() + 4;
  53611. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53612. }
  53613. const Image LookAndFeel::getDefaultFolderImage()
  53614. {
  53615. 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,
  53616. 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,
  53617. 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,
  53618. 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,
  53619. 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,
  53620. 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,
  53621. 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,
  53622. 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,
  53623. 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,
  53624. 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,
  53625. 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,
  53626. 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,
  53627. 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,
  53628. 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,
  53629. 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,
  53630. 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,
  53631. 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,
  53632. 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,
  53633. 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,
  53634. 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,
  53635. 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,
  53636. 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,
  53637. 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,
  53638. 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,
  53639. 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,
  53640. 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,
  53641. 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,
  53642. 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,
  53643. 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,
  53644. 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,
  53645. 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,
  53646. 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,
  53647. 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,
  53648. 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,
  53649. 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,
  53650. 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,
  53651. 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,
  53652. 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,
  53653. 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,
  53654. 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,
  53655. 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,
  53656. 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,
  53657. 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,
  53658. 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};
  53659. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53660. }
  53661. const Image LookAndFeel::getDefaultDocumentFileImage()
  53662. {
  53663. 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,
  53664. 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,
  53665. 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,
  53666. 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,
  53667. 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,
  53668. 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,
  53669. 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,
  53670. 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,
  53671. 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,
  53672. 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,
  53673. 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,
  53674. 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,
  53675. 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,
  53676. 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,
  53677. 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,
  53678. 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,
  53679. 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,
  53680. 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,
  53681. 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,
  53682. 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,
  53683. 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,
  53684. 174,66,96,130,0,0};
  53685. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53686. }
  53687. void LookAndFeel::playAlertSound()
  53688. {
  53689. PlatformUtilities::beep();
  53690. }
  53691. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53692. {
  53693. g.setColour (Colours::white.withAlpha (0.7f));
  53694. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53695. g.setColour (Colours::black.withAlpha (0.2f));
  53696. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53697. const int totalBlocks = 7;
  53698. const int numBlocks = roundToInt (totalBlocks * level);
  53699. const float w = (width - 6.0f) / (float) totalBlocks;
  53700. for (int i = 0; i < totalBlocks; ++i)
  53701. {
  53702. if (i >= numBlocks)
  53703. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53704. else
  53705. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53706. : Colours::red);
  53707. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53708. }
  53709. }
  53710. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53711. {
  53712. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53713. if (keyDescription.isNotEmpty())
  53714. {
  53715. if (button.isEnabled())
  53716. {
  53717. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53718. g.fillAll (textColour.withAlpha (alpha));
  53719. g.setOpacity (0.3f);
  53720. g.drawBevel (0, 0, width, height, 2);
  53721. }
  53722. g.setColour (textColour);
  53723. g.setFont (height * 0.6f);
  53724. g.drawFittedText (keyDescription,
  53725. 3, 0, width - 6, height,
  53726. Justification::centred, 1);
  53727. }
  53728. else
  53729. {
  53730. const float thickness = 7.0f;
  53731. const float indent = 22.0f;
  53732. Path p;
  53733. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53734. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53735. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53736. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53737. p.setUsingNonZeroWinding (false);
  53738. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53739. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53740. }
  53741. if (button.hasKeyboardFocus (false))
  53742. {
  53743. g.setColour (textColour.withAlpha (0.4f));
  53744. g.drawRect (0, 0, width, height);
  53745. }
  53746. }
  53747. static void createRoundedPath (Path& p,
  53748. const float x, const float y,
  53749. const float w, const float h,
  53750. const float cs,
  53751. const bool curveTopLeft, const bool curveTopRight,
  53752. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53753. {
  53754. const float cs2 = 2.0f * cs;
  53755. if (curveTopLeft)
  53756. {
  53757. p.startNewSubPath (x, y + cs);
  53758. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53759. }
  53760. else
  53761. {
  53762. p.startNewSubPath (x, y);
  53763. }
  53764. if (curveTopRight)
  53765. {
  53766. p.lineTo (x + w - cs, y);
  53767. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53768. }
  53769. else
  53770. {
  53771. p.lineTo (x + w, y);
  53772. }
  53773. if (curveBottomRight)
  53774. {
  53775. p.lineTo (x + w, y + h - cs);
  53776. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53777. }
  53778. else
  53779. {
  53780. p.lineTo (x + w, y + h);
  53781. }
  53782. if (curveBottomLeft)
  53783. {
  53784. p.lineTo (x + cs, y + h);
  53785. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53786. }
  53787. else
  53788. {
  53789. p.lineTo (x, y + h);
  53790. }
  53791. p.closeSubPath();
  53792. }
  53793. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53794. float x, float y, float w, float h,
  53795. float maxCornerSize,
  53796. const Colour& baseColour,
  53797. const float strokeWidth,
  53798. const bool flatOnLeft,
  53799. const bool flatOnRight,
  53800. const bool flatOnTop,
  53801. const bool flatOnBottom) throw()
  53802. {
  53803. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53804. return;
  53805. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53806. Path outline;
  53807. createRoundedPath (outline, x, y, w, h, cs,
  53808. ! (flatOnLeft || flatOnTop),
  53809. ! (flatOnRight || flatOnTop),
  53810. ! (flatOnLeft || flatOnBottom),
  53811. ! (flatOnRight || flatOnBottom));
  53812. ColourGradient cg (baseColour, 0.0f, y,
  53813. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53814. false);
  53815. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53816. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53817. g.setGradientFill (cg);
  53818. g.fillPath (outline);
  53819. g.setColour (Colour (0x80000000));
  53820. g.strokePath (outline, PathStrokeType (strokeWidth));
  53821. }
  53822. void LookAndFeel::drawGlassSphere (Graphics& g,
  53823. const float x, const float y,
  53824. const float diameter,
  53825. const Colour& colour,
  53826. const float outlineThickness) throw()
  53827. {
  53828. if (diameter <= outlineThickness)
  53829. return;
  53830. Path p;
  53831. p.addEllipse (x, y, diameter, diameter);
  53832. {
  53833. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53834. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53835. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53836. g.setGradientFill (cg);
  53837. g.fillPath (p);
  53838. }
  53839. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53840. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53841. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53842. ColourGradient cg (Colours::transparentBlack,
  53843. x + diameter * 0.5f, y + diameter * 0.5f,
  53844. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53845. x, y + diameter * 0.5f, true);
  53846. cg.addColour (0.7, Colours::transparentBlack);
  53847. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53848. g.setGradientFill (cg);
  53849. g.fillPath (p);
  53850. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53851. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53852. }
  53853. void LookAndFeel::drawGlassPointer (Graphics& g,
  53854. const float x, const float y,
  53855. const float diameter,
  53856. const Colour& colour, const float outlineThickness,
  53857. const int direction) throw()
  53858. {
  53859. if (diameter <= outlineThickness)
  53860. return;
  53861. Path p;
  53862. p.startNewSubPath (x + diameter * 0.5f, y);
  53863. p.lineTo (x + diameter, y + diameter * 0.6f);
  53864. p.lineTo (x + diameter, y + diameter);
  53865. p.lineTo (x, y + diameter);
  53866. p.lineTo (x, y + diameter * 0.6f);
  53867. p.closeSubPath();
  53868. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53869. {
  53870. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53871. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53872. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53873. g.setGradientFill (cg);
  53874. g.fillPath (p);
  53875. }
  53876. ColourGradient cg (Colours::transparentBlack,
  53877. x + diameter * 0.5f, y + diameter * 0.5f,
  53878. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53879. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53880. cg.addColour (0.5, Colours::transparentBlack);
  53881. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53882. g.setGradientFill (cg);
  53883. g.fillPath (p);
  53884. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53885. g.strokePath (p, PathStrokeType (outlineThickness));
  53886. }
  53887. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53888. const float x, const float y,
  53889. const float width, const float height,
  53890. const Colour& colour,
  53891. const float outlineThickness,
  53892. const float cornerSize,
  53893. const bool flatOnLeft,
  53894. const bool flatOnRight,
  53895. const bool flatOnTop,
  53896. const bool flatOnBottom) throw()
  53897. {
  53898. if (width <= outlineThickness || height <= outlineThickness)
  53899. return;
  53900. const int intX = (int) x;
  53901. const int intY = (int) y;
  53902. const int intW = (int) width;
  53903. const int intH = (int) height;
  53904. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53905. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53906. const int intEdge = (int) edgeBlurRadius;
  53907. Path outline;
  53908. createRoundedPath (outline, x, y, width, height, cs,
  53909. ! (flatOnLeft || flatOnTop),
  53910. ! (flatOnRight || flatOnTop),
  53911. ! (flatOnLeft || flatOnBottom),
  53912. ! (flatOnRight || flatOnBottom));
  53913. {
  53914. ColourGradient cg (colour.darker (0.2f), 0, y,
  53915. colour.darker (0.2f), 0, y + height, false);
  53916. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53917. cg.addColour (0.4, colour);
  53918. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53919. g.setGradientFill (cg);
  53920. g.fillPath (outline);
  53921. }
  53922. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53923. colour.darker (0.2f), x, y + height * 0.5f, true);
  53924. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53925. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53926. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53927. {
  53928. g.saveState();
  53929. g.setGradientFill (cg);
  53930. g.reduceClipRegion (intX, intY, intEdge, intH);
  53931. g.fillPath (outline);
  53932. g.restoreState();
  53933. }
  53934. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53935. {
  53936. cg.point1.setX (x + width - edgeBlurRadius);
  53937. cg.point2.setX (x + width);
  53938. g.saveState();
  53939. g.setGradientFill (cg);
  53940. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53941. g.fillPath (outline);
  53942. g.restoreState();
  53943. }
  53944. {
  53945. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53946. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53947. Path highlight;
  53948. createRoundedPath (highlight,
  53949. x + leftIndent,
  53950. y + cs * 0.1f,
  53951. width - (leftIndent + rightIndent),
  53952. height * 0.4f, cs * 0.4f,
  53953. ! (flatOnLeft || flatOnTop),
  53954. ! (flatOnRight || flatOnTop),
  53955. ! (flatOnLeft || flatOnBottom),
  53956. ! (flatOnRight || flatOnBottom));
  53957. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53958. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53959. g.fillPath (highlight);
  53960. }
  53961. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53962. g.strokePath (outline, PathStrokeType (outlineThickness));
  53963. }
  53964. END_JUCE_NAMESPACE
  53965. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53966. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53967. BEGIN_JUCE_NAMESPACE
  53968. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53969. {
  53970. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53971. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53972. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53973. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53974. setColour (Slider::thumbColourId, Colours::white);
  53975. setColour (Slider::trackColourId, Colour (0x7f000000));
  53976. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53977. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53978. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53979. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53980. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53981. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53982. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53983. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53984. }
  53985. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53986. {
  53987. }
  53988. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53989. Button& button,
  53990. const Colour& backgroundColour,
  53991. bool isMouseOverButton,
  53992. bool isButtonDown)
  53993. {
  53994. const int width = button.getWidth();
  53995. const int height = button.getHeight();
  53996. const float indent = 2.0f;
  53997. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53998. roundToInt (height * 0.4f));
  53999. Path p;
  54000. p.addRoundedRectangle (indent, indent,
  54001. width - indent * 2.0f,
  54002. height - indent * 2.0f,
  54003. (float) cornerSize);
  54004. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54005. if (isMouseOverButton)
  54006. {
  54007. if (isButtonDown)
  54008. bc = bc.brighter();
  54009. else if (bc.getBrightness() > 0.5f)
  54010. bc = bc.darker (0.1f);
  54011. else
  54012. bc = bc.brighter (0.1f);
  54013. }
  54014. g.setColour (bc);
  54015. g.fillPath (p);
  54016. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54017. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54018. }
  54019. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54020. Component& /*component*/,
  54021. float x, float y, float w, float h,
  54022. const bool ticked,
  54023. const bool isEnabled,
  54024. const bool /*isMouseOverButton*/,
  54025. const bool isButtonDown)
  54026. {
  54027. Path box;
  54028. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54029. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54030. : Colours::lightgrey.withAlpha (0.1f));
  54031. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54032. g.fillPath (box, trans);
  54033. g.setColour (Colours::black.withAlpha (0.6f));
  54034. g.strokePath (box, PathStrokeType (0.9f), trans);
  54035. if (ticked)
  54036. {
  54037. Path tick;
  54038. tick.startNewSubPath (1.5f, 3.0f);
  54039. tick.lineTo (3.0f, 6.0f);
  54040. tick.lineTo (6.0f, 0.0f);
  54041. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54042. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54043. }
  54044. }
  54045. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54046. ToggleButton& button,
  54047. bool isMouseOverButton,
  54048. bool isButtonDown)
  54049. {
  54050. if (button.hasKeyboardFocus (true))
  54051. {
  54052. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54053. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54054. }
  54055. const int tickWidth = jmin (20, button.getHeight() - 4);
  54056. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54057. (float) tickWidth, (float) tickWidth,
  54058. button.getToggleState(),
  54059. button.isEnabled(),
  54060. isMouseOverButton,
  54061. isButtonDown);
  54062. g.setColour (button.findColour (ToggleButton::textColourId));
  54063. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54064. if (! button.isEnabled())
  54065. g.setOpacity (0.5f);
  54066. const int textX = tickWidth + 5;
  54067. g.drawFittedText (button.getButtonText(),
  54068. textX, 4,
  54069. button.getWidth() - textX - 2, button.getHeight() - 8,
  54070. Justification::centredLeft, 10);
  54071. }
  54072. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54073. int width, int height,
  54074. double progress, const String& textToShow)
  54075. {
  54076. if (progress < 0 || progress >= 1.0)
  54077. {
  54078. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54079. }
  54080. else
  54081. {
  54082. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54083. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54084. g.fillAll (background);
  54085. g.setColour (foreground);
  54086. g.fillRect (1, 1,
  54087. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54088. height - 2);
  54089. if (textToShow.isNotEmpty())
  54090. {
  54091. g.setColour (Colour::contrasting (background, foreground));
  54092. g.setFont (height * 0.6f);
  54093. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54094. }
  54095. }
  54096. }
  54097. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54098. ScrollBar& bar,
  54099. int width, int height,
  54100. int buttonDirection,
  54101. bool isScrollbarVertical,
  54102. bool isMouseOverButton,
  54103. bool isButtonDown)
  54104. {
  54105. if (isScrollbarVertical)
  54106. width -= 2;
  54107. else
  54108. height -= 2;
  54109. Path p;
  54110. if (buttonDirection == 0)
  54111. p.addTriangle (width * 0.5f, height * 0.2f,
  54112. width * 0.1f, height * 0.7f,
  54113. width * 0.9f, height * 0.7f);
  54114. else if (buttonDirection == 1)
  54115. p.addTriangle (width * 0.8f, height * 0.5f,
  54116. width * 0.3f, height * 0.1f,
  54117. width * 0.3f, height * 0.9f);
  54118. else if (buttonDirection == 2)
  54119. p.addTriangle (width * 0.5f, height * 0.8f,
  54120. width * 0.1f, height * 0.3f,
  54121. width * 0.9f, height * 0.3f);
  54122. else if (buttonDirection == 3)
  54123. p.addTriangle (width * 0.2f, height * 0.5f,
  54124. width * 0.7f, height * 0.1f,
  54125. width * 0.7f, height * 0.9f);
  54126. if (isButtonDown)
  54127. g.setColour (Colours::white);
  54128. else if (isMouseOverButton)
  54129. g.setColour (Colours::white.withAlpha (0.7f));
  54130. else
  54131. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54132. g.fillPath (p);
  54133. g.setColour (Colours::black.withAlpha (0.5f));
  54134. g.strokePath (p, PathStrokeType (0.5f));
  54135. }
  54136. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54137. ScrollBar& bar,
  54138. int x, int y,
  54139. int width, int height,
  54140. bool isScrollbarVertical,
  54141. int thumbStartPosition,
  54142. int thumbSize,
  54143. bool isMouseOver,
  54144. bool isMouseDown)
  54145. {
  54146. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54147. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54148. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54149. if (thumbSize > 0.0f)
  54150. {
  54151. Rectangle<int> thumb;
  54152. if (isScrollbarVertical)
  54153. {
  54154. width -= 2;
  54155. g.fillRect (x + roundToInt (width * 0.35f), y,
  54156. roundToInt (width * 0.3f), height);
  54157. thumb.setBounds (x + 1, thumbStartPosition,
  54158. width - 2, thumbSize);
  54159. }
  54160. else
  54161. {
  54162. height -= 2;
  54163. g.fillRect (x, y + roundToInt (height * 0.35f),
  54164. width, roundToInt (height * 0.3f));
  54165. thumb.setBounds (thumbStartPosition, y + 1,
  54166. thumbSize, height - 2);
  54167. }
  54168. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54169. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54170. g.fillRect (thumb);
  54171. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54172. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54173. if (thumbSize > 16)
  54174. {
  54175. for (int i = 3; --i >= 0;)
  54176. {
  54177. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54178. g.setColour (Colours::black.withAlpha (0.15f));
  54179. if (isScrollbarVertical)
  54180. {
  54181. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54182. g.setColour (Colours::white.withAlpha (0.15f));
  54183. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54184. }
  54185. else
  54186. {
  54187. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54188. g.setColour (Colours::white.withAlpha (0.15f));
  54189. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54190. }
  54191. }
  54192. }
  54193. }
  54194. }
  54195. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54196. {
  54197. return &scrollbarShadow;
  54198. }
  54199. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54200. {
  54201. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54202. g.setColour (Colours::black.withAlpha (0.6f));
  54203. g.drawRect (0, 0, width, height);
  54204. }
  54205. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54206. bool, MenuBarComponent& menuBar)
  54207. {
  54208. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54209. }
  54210. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54211. {
  54212. if (textEditor.isEnabled())
  54213. {
  54214. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54215. g.drawRect (0, 0, width, height);
  54216. }
  54217. }
  54218. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54219. const bool isButtonDown,
  54220. int buttonX, int buttonY,
  54221. int buttonW, int buttonH,
  54222. ComboBox& box)
  54223. {
  54224. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54225. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54226. : ComboBox::backgroundColourId));
  54227. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54228. g.setColour (box.findColour (ComboBox::outlineColourId));
  54229. g.drawRect (0, 0, width, height);
  54230. const float arrowX = 0.2f;
  54231. const float arrowH = 0.3f;
  54232. if (box.isEnabled())
  54233. {
  54234. Path p;
  54235. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54236. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54237. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54238. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54239. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54240. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54241. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54242. : ComboBox::buttonColourId));
  54243. g.fillPath (p);
  54244. }
  54245. }
  54246. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54247. {
  54248. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54249. f.setHorizontalScale (0.9f);
  54250. return f;
  54251. }
  54252. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54253. {
  54254. Path p;
  54255. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54256. g.setColour (fill);
  54257. g.fillPath (p);
  54258. g.setColour (outline);
  54259. g.strokePath (p, PathStrokeType (0.3f));
  54260. }
  54261. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54262. int x, int y,
  54263. int w, int h,
  54264. float sliderPos,
  54265. float minSliderPos,
  54266. float maxSliderPos,
  54267. const Slider::SliderStyle style,
  54268. Slider& slider)
  54269. {
  54270. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54271. if (style == Slider::LinearBar)
  54272. {
  54273. g.setColour (slider.findColour (Slider::thumbColourId));
  54274. g.fillRect (x, y, (int) sliderPos - x, h);
  54275. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54276. g.drawRect (x, y, (int) sliderPos - x, h);
  54277. }
  54278. else
  54279. {
  54280. g.setColour (slider.findColour (Slider::trackColourId)
  54281. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54282. if (slider.isHorizontal())
  54283. {
  54284. g.fillRect (x, y + roundToInt (h * 0.6f),
  54285. w, roundToInt (h * 0.2f));
  54286. }
  54287. else
  54288. {
  54289. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54290. jmin (4, roundToInt (w * 0.2f)), h);
  54291. }
  54292. float alpha = 0.35f;
  54293. if (slider.isEnabled())
  54294. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54295. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54296. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54297. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54298. {
  54299. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54300. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54301. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54302. fill, outline);
  54303. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54304. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54305. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54306. fill, outline);
  54307. }
  54308. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54309. {
  54310. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54311. minSliderPos - 7.0f, y + h * 0.9f ,
  54312. minSliderPos, y + h * 0.9f,
  54313. fill, outline);
  54314. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54315. maxSliderPos, y + h * 0.9f,
  54316. maxSliderPos + 7.0f, y + h * 0.9f,
  54317. fill, outline);
  54318. }
  54319. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54320. {
  54321. drawTriangle (g, sliderPos, y + h * 0.9f,
  54322. sliderPos - 7.0f, y + h * 0.2f,
  54323. sliderPos + 7.0f, y + h * 0.2f,
  54324. fill, outline);
  54325. }
  54326. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54327. {
  54328. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54329. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54330. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54331. fill, outline);
  54332. }
  54333. }
  54334. }
  54335. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54336. {
  54337. if (isIncrement)
  54338. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54339. else
  54340. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54341. }
  54342. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54343. {
  54344. return &scrollbarShadow;
  54345. }
  54346. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54347. {
  54348. return 8;
  54349. }
  54350. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54351. int w, int h,
  54352. bool isMouseOver,
  54353. bool isMouseDragging)
  54354. {
  54355. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54356. : Colours::darkgrey);
  54357. const float lineThickness = jmin (w, h) * 0.1f;
  54358. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54359. {
  54360. g.drawLine (w * i,
  54361. h + 1.0f,
  54362. w + 1.0f,
  54363. h * i,
  54364. lineThickness);
  54365. }
  54366. }
  54367. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54368. {
  54369. Path shape;
  54370. if (buttonType == DocumentWindow::closeButton)
  54371. {
  54372. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54373. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54374. ShapeButton* const b = new ShapeButton ("close",
  54375. Colour (0x7fff3333),
  54376. Colour (0xd7ff3333),
  54377. Colour (0xf7ff3333));
  54378. b->setShape (shape, true, true, true);
  54379. return b;
  54380. }
  54381. else if (buttonType == DocumentWindow::minimiseButton)
  54382. {
  54383. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54384. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54385. DrawablePath dp;
  54386. dp.setPath (shape);
  54387. dp.setFill (Colours::black.withAlpha (0.3f));
  54388. b->setImages (&dp);
  54389. return b;
  54390. }
  54391. else if (buttonType == DocumentWindow::maximiseButton)
  54392. {
  54393. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54394. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54395. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54396. DrawablePath dp;
  54397. dp.setPath (shape);
  54398. dp.setFill (Colours::black.withAlpha (0.3f));
  54399. b->setImages (&dp);
  54400. return b;
  54401. }
  54402. jassertfalse;
  54403. return 0;
  54404. }
  54405. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54406. int titleBarX,
  54407. int titleBarY,
  54408. int titleBarW,
  54409. int titleBarH,
  54410. Button* minimiseButton,
  54411. Button* maximiseButton,
  54412. Button* closeButton,
  54413. bool positionTitleBarButtonsOnLeft)
  54414. {
  54415. titleBarY += titleBarH / 8;
  54416. titleBarH -= titleBarH / 4;
  54417. const int buttonW = titleBarH;
  54418. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54419. : titleBarX + titleBarW - buttonW - 4;
  54420. if (closeButton != 0)
  54421. {
  54422. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54423. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54424. : -(buttonW + buttonW / 5);
  54425. }
  54426. if (positionTitleBarButtonsOnLeft)
  54427. swapVariables (minimiseButton, maximiseButton);
  54428. if (maximiseButton != 0)
  54429. {
  54430. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54431. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54432. }
  54433. if (minimiseButton != 0)
  54434. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54435. }
  54436. END_JUCE_NAMESPACE
  54437. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54438. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54439. BEGIN_JUCE_NAMESPACE
  54440. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54441. : model (0),
  54442. itemUnderMouse (-1),
  54443. currentPopupIndex (-1),
  54444. topLevelIndexClicked (0),
  54445. lastMouseX (0),
  54446. lastMouseY (0)
  54447. {
  54448. setRepaintsOnMouseActivity (true);
  54449. setWantsKeyboardFocus (false);
  54450. setMouseClickGrabsKeyboardFocus (false);
  54451. setModel (model_);
  54452. }
  54453. MenuBarComponent::~MenuBarComponent()
  54454. {
  54455. setModel (0);
  54456. Desktop::getInstance().removeGlobalMouseListener (this);
  54457. }
  54458. MenuBarModel* MenuBarComponent::getModel() const throw()
  54459. {
  54460. return model;
  54461. }
  54462. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54463. {
  54464. if (model != newModel)
  54465. {
  54466. if (model != 0)
  54467. model->removeListener (this);
  54468. model = newModel;
  54469. if (model != 0)
  54470. model->addListener (this);
  54471. repaint();
  54472. menuBarItemsChanged (0);
  54473. }
  54474. }
  54475. void MenuBarComponent::paint (Graphics& g)
  54476. {
  54477. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54478. getLookAndFeel().drawMenuBarBackground (g,
  54479. getWidth(),
  54480. getHeight(),
  54481. isMouseOverBar,
  54482. *this);
  54483. if (model != 0)
  54484. {
  54485. for (int i = 0; i < menuNames.size(); ++i)
  54486. {
  54487. g.saveState();
  54488. g.setOrigin (xPositions [i], 0);
  54489. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54490. getLookAndFeel().drawMenuBarItem (g,
  54491. xPositions[i + 1] - xPositions[i],
  54492. getHeight(),
  54493. i,
  54494. menuNames[i],
  54495. i == itemUnderMouse,
  54496. i == currentPopupIndex,
  54497. isMouseOverBar,
  54498. *this);
  54499. g.restoreState();
  54500. }
  54501. }
  54502. }
  54503. void MenuBarComponent::resized()
  54504. {
  54505. xPositions.clear();
  54506. int x = 2;
  54507. xPositions.add (x);
  54508. for (int i = 0; i < menuNames.size(); ++i)
  54509. {
  54510. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54511. xPositions.add (x);
  54512. }
  54513. }
  54514. int MenuBarComponent::getItemAt (const int x, const int y)
  54515. {
  54516. for (int i = 0; i < xPositions.size(); ++i)
  54517. if (x >= xPositions[i] && x < xPositions[i + 1])
  54518. return reallyContains (x, y, true) ? i : -1;
  54519. return -1;
  54520. }
  54521. void MenuBarComponent::repaintMenuItem (int index)
  54522. {
  54523. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54524. {
  54525. const int x1 = xPositions [index];
  54526. const int x2 = xPositions [index + 1];
  54527. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54528. }
  54529. }
  54530. void MenuBarComponent::setItemUnderMouse (const int index)
  54531. {
  54532. if (itemUnderMouse != index)
  54533. {
  54534. repaintMenuItem (itemUnderMouse);
  54535. itemUnderMouse = index;
  54536. repaintMenuItem (itemUnderMouse);
  54537. }
  54538. }
  54539. void MenuBarComponent::setOpenItem (int index)
  54540. {
  54541. if (currentPopupIndex != index)
  54542. {
  54543. repaintMenuItem (currentPopupIndex);
  54544. currentPopupIndex = index;
  54545. repaintMenuItem (currentPopupIndex);
  54546. if (index >= 0)
  54547. Desktop::getInstance().addGlobalMouseListener (this);
  54548. else
  54549. Desktop::getInstance().removeGlobalMouseListener (this);
  54550. }
  54551. }
  54552. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54553. {
  54554. setItemUnderMouse (getItemAt (x, y));
  54555. }
  54556. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  54557. {
  54558. public:
  54559. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  54560. : bar (bar_), topLevelIndex (topLevelIndex_)
  54561. {
  54562. }
  54563. ~AsyncCallback() {}
  54564. void modalStateFinished (int returnValue)
  54565. {
  54566. if (bar != 0)
  54567. bar->menuDismissed (topLevelIndex, returnValue);
  54568. }
  54569. private:
  54570. Component::SafePointer<MenuBarComponent> bar;
  54571. const int topLevelIndex;
  54572. AsyncCallback (const AsyncCallback&);
  54573. AsyncCallback& operator= (const AsyncCallback&);
  54574. };
  54575. void MenuBarComponent::showMenu (int index)
  54576. {
  54577. if (index != currentPopupIndex)
  54578. {
  54579. PopupMenu::dismissAllActiveMenus();
  54580. menuBarItemsChanged (0);
  54581. setOpenItem (index);
  54582. setItemUnderMouse (index);
  54583. if (index >= 0)
  54584. {
  54585. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54586. menuNames [itemUnderMouse]));
  54587. if (m.lookAndFeel == 0)
  54588. m.setLookAndFeel (&getLookAndFeel());
  54589. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  54590. m.showMenu (itemPos + getScreenPosition(),
  54591. 0, itemPos.getWidth(), 0, 0, true, this,
  54592. new AsyncCallback (this, index));
  54593. }
  54594. }
  54595. }
  54596. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  54597. {
  54598. topLevelIndexClicked = topLevelIndex;
  54599. postCommandMessage (itemId);
  54600. }
  54601. void MenuBarComponent::handleCommandMessage (int commandId)
  54602. {
  54603. const Point<int> mousePos (getMouseXYRelative());
  54604. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54605. if (! isCurrentlyBlockedByAnotherModalComponent())
  54606. setOpenItem (-1);
  54607. if (commandId != 0 && model != 0)
  54608. model->menuItemSelected (commandId, topLevelIndexClicked);
  54609. }
  54610. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54611. {
  54612. if (e.eventComponent == this)
  54613. updateItemUnderMouse (e.x, e.y);
  54614. }
  54615. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54616. {
  54617. if (e.eventComponent == this)
  54618. updateItemUnderMouse (e.x, e.y);
  54619. }
  54620. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54621. {
  54622. if (currentPopupIndex < 0)
  54623. {
  54624. const MouseEvent e2 (e.getEventRelativeTo (this));
  54625. updateItemUnderMouse (e2.x, e2.y);
  54626. currentPopupIndex = -2;
  54627. showMenu (itemUnderMouse);
  54628. }
  54629. }
  54630. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54631. {
  54632. const MouseEvent e2 (e.getEventRelativeTo (this));
  54633. const int item = getItemAt (e2.x, e2.y);
  54634. if (item >= 0)
  54635. showMenu (item);
  54636. }
  54637. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54638. {
  54639. const MouseEvent e2 (e.getEventRelativeTo (this));
  54640. updateItemUnderMouse (e2.x, e2.y);
  54641. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  54642. {
  54643. setOpenItem (-1);
  54644. PopupMenu::dismissAllActiveMenus();
  54645. }
  54646. }
  54647. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54648. {
  54649. const MouseEvent e2 (e.getEventRelativeTo (this));
  54650. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54651. {
  54652. if (currentPopupIndex >= 0)
  54653. {
  54654. const int item = getItemAt (e2.x, e2.y);
  54655. if (item >= 0)
  54656. showMenu (item);
  54657. }
  54658. else
  54659. {
  54660. updateItemUnderMouse (e2.x, e2.y);
  54661. }
  54662. lastMouseX = e2.x;
  54663. lastMouseY = e2.y;
  54664. }
  54665. }
  54666. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54667. {
  54668. bool used = false;
  54669. const int numMenus = menuNames.size();
  54670. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54671. if (key.isKeyCode (KeyPress::leftKey))
  54672. {
  54673. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54674. used = true;
  54675. }
  54676. else if (key.isKeyCode (KeyPress::rightKey))
  54677. {
  54678. showMenu ((currentIndex + 1) % numMenus);
  54679. used = true;
  54680. }
  54681. return used;
  54682. }
  54683. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54684. {
  54685. StringArray newNames;
  54686. if (model != 0)
  54687. newNames = model->getMenuBarNames();
  54688. if (newNames != menuNames)
  54689. {
  54690. menuNames = newNames;
  54691. repaint();
  54692. resized();
  54693. }
  54694. }
  54695. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54696. const ApplicationCommandTarget::InvocationInfo& info)
  54697. {
  54698. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54699. return;
  54700. for (int i = 0; i < menuNames.size(); ++i)
  54701. {
  54702. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54703. if (menu.containsCommandItem (info.commandID))
  54704. {
  54705. setItemUnderMouse (i);
  54706. startTimer (200);
  54707. break;
  54708. }
  54709. }
  54710. }
  54711. void MenuBarComponent::timerCallback()
  54712. {
  54713. stopTimer();
  54714. const Point<int> mousePos (getMouseXYRelative());
  54715. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54716. }
  54717. END_JUCE_NAMESPACE
  54718. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54719. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54720. BEGIN_JUCE_NAMESPACE
  54721. MenuBarModel::MenuBarModel() throw()
  54722. : manager (0)
  54723. {
  54724. }
  54725. MenuBarModel::~MenuBarModel()
  54726. {
  54727. setApplicationCommandManagerToWatch (0);
  54728. }
  54729. void MenuBarModel::menuItemsChanged()
  54730. {
  54731. triggerAsyncUpdate();
  54732. }
  54733. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54734. {
  54735. if (manager != newManager)
  54736. {
  54737. if (manager != 0)
  54738. manager->removeListener (this);
  54739. manager = newManager;
  54740. if (manager != 0)
  54741. manager->addListener (this);
  54742. }
  54743. }
  54744. void MenuBarModel::addListener (Listener* const newListener) throw()
  54745. {
  54746. listeners.add (newListener);
  54747. }
  54748. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  54749. {
  54750. // Trying to remove a listener that isn't on the list!
  54751. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54752. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54753. jassert (listeners.contains (listenerToRemove));
  54754. listeners.remove (listenerToRemove);
  54755. }
  54756. void MenuBarModel::handleAsyncUpdate()
  54757. {
  54758. listeners.call (&Listener::menuBarItemsChanged, this);
  54759. }
  54760. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54761. {
  54762. listeners.call (&Listener::menuCommandInvoked, this, info);
  54763. }
  54764. void MenuBarModel::applicationCommandListChanged()
  54765. {
  54766. menuItemsChanged();
  54767. }
  54768. END_JUCE_NAMESPACE
  54769. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54770. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54771. BEGIN_JUCE_NAMESPACE
  54772. class PopupMenu::Item
  54773. {
  54774. public:
  54775. Item()
  54776. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54777. usesColour (false), customComp (0), commandManager (0)
  54778. {
  54779. }
  54780. Item (const int itemId_,
  54781. const String& text_,
  54782. const bool active_,
  54783. const bool isTicked_,
  54784. const Image& im,
  54785. const Colour& textColour_,
  54786. const bool usesColour_,
  54787. PopupMenuCustomComponent* const customComp_,
  54788. const PopupMenu* const subMenu_,
  54789. ApplicationCommandManager* const commandManager_)
  54790. : itemId (itemId_), text (text_), textColour (textColour_),
  54791. active (active_), isSeparator (false), isTicked (isTicked_),
  54792. usesColour (usesColour_), image (im), customComp (customComp_),
  54793. commandManager (commandManager_)
  54794. {
  54795. if (subMenu_ != 0)
  54796. subMenu = new PopupMenu (*subMenu_);
  54797. if (commandManager_ != 0 && itemId_ != 0)
  54798. {
  54799. String shortcutKey;
  54800. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54801. ->getKeyPressesAssignedToCommand (itemId_));
  54802. for (int i = 0; i < keyPresses.size(); ++i)
  54803. {
  54804. const String key (keyPresses.getReference(i).getTextDescription());
  54805. if (shortcutKey.isNotEmpty())
  54806. shortcutKey << ", ";
  54807. if (key.length() == 1)
  54808. shortcutKey << "shortcut: '" << key << '\'';
  54809. else
  54810. shortcutKey << key;
  54811. }
  54812. shortcutKey = shortcutKey.trim();
  54813. if (shortcutKey.isNotEmpty())
  54814. text << "<end>" << shortcutKey;
  54815. }
  54816. }
  54817. Item (const Item& other)
  54818. : itemId (other.itemId),
  54819. text (other.text),
  54820. textColour (other.textColour),
  54821. active (other.active),
  54822. isSeparator (other.isSeparator),
  54823. isTicked (other.isTicked),
  54824. usesColour (other.usesColour),
  54825. image (other.image),
  54826. customComp (other.customComp),
  54827. commandManager (other.commandManager)
  54828. {
  54829. if (other.subMenu != 0)
  54830. subMenu = new PopupMenu (*(other.subMenu));
  54831. }
  54832. ~Item()
  54833. {
  54834. customComp = 0;
  54835. }
  54836. bool canBeTriggered() const throw()
  54837. {
  54838. return active && ! (isSeparator || (subMenu != 0));
  54839. }
  54840. bool hasActiveSubMenu() const throw()
  54841. {
  54842. return active && (subMenu != 0);
  54843. }
  54844. const int itemId;
  54845. String text;
  54846. const Colour textColour;
  54847. const bool active, isSeparator, isTicked, usesColour;
  54848. Image image;
  54849. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54850. ScopedPointer <PopupMenu> subMenu;
  54851. ApplicationCommandManager* const commandManager;
  54852. juce_UseDebuggingNewOperator
  54853. private:
  54854. Item& operator= (const Item&);
  54855. };
  54856. class PopupMenu::ItemComponent : public Component
  54857. {
  54858. public:
  54859. ItemComponent (const PopupMenu::Item& itemInfo_)
  54860. : itemInfo (itemInfo_),
  54861. isHighlighted (false)
  54862. {
  54863. if (itemInfo.customComp != 0)
  54864. addAndMakeVisible (itemInfo.customComp);
  54865. }
  54866. ~ItemComponent()
  54867. {
  54868. if (itemInfo.customComp != 0)
  54869. removeChildComponent (itemInfo.customComp);
  54870. }
  54871. void getIdealSize (int& idealWidth,
  54872. int& idealHeight,
  54873. const int standardItemHeight)
  54874. {
  54875. if (itemInfo.customComp != 0)
  54876. {
  54877. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54878. }
  54879. else
  54880. {
  54881. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54882. itemInfo.isSeparator,
  54883. standardItemHeight,
  54884. idealWidth,
  54885. idealHeight);
  54886. }
  54887. }
  54888. void paint (Graphics& g)
  54889. {
  54890. if (itemInfo.customComp == 0)
  54891. {
  54892. String mainText (itemInfo.text);
  54893. String endText;
  54894. const int endIndex = mainText.indexOf ("<end>");
  54895. if (endIndex >= 0)
  54896. {
  54897. endText = mainText.substring (endIndex + 5).trim();
  54898. mainText = mainText.substring (0, endIndex);
  54899. }
  54900. getLookAndFeel()
  54901. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54902. itemInfo.isSeparator,
  54903. itemInfo.active,
  54904. isHighlighted,
  54905. itemInfo.isTicked,
  54906. itemInfo.subMenu != 0,
  54907. mainText, endText,
  54908. itemInfo.image.isValid() ? &itemInfo.image : 0,
  54909. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54910. }
  54911. }
  54912. void resized()
  54913. {
  54914. if (getNumChildComponents() > 0)
  54915. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54916. }
  54917. void setHighlighted (bool shouldBeHighlighted)
  54918. {
  54919. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54920. if (isHighlighted != shouldBeHighlighted)
  54921. {
  54922. isHighlighted = shouldBeHighlighted;
  54923. if (itemInfo.customComp != 0)
  54924. {
  54925. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54926. itemInfo.customComp->repaint();
  54927. }
  54928. repaint();
  54929. }
  54930. }
  54931. PopupMenu::Item itemInfo;
  54932. juce_UseDebuggingNewOperator
  54933. private:
  54934. bool isHighlighted;
  54935. ItemComponent (const ItemComponent&);
  54936. ItemComponent& operator= (const ItemComponent&);
  54937. };
  54938. namespace PopupMenuSettings
  54939. {
  54940. static const int scrollZone = 24;
  54941. static const int borderSize = 2;
  54942. static const int timerInterval = 50;
  54943. static const int dismissCommandId = 0x6287345f;
  54944. }
  54945. class PopupMenu::Window : public Component,
  54946. private Timer
  54947. {
  54948. public:
  54949. Window()
  54950. : Component ("menu"),
  54951. owner (0),
  54952. currentChild (0),
  54953. activeSubMenu (0),
  54954. managerOfChosenCommand (0),
  54955. minimumWidth (0),
  54956. maximumNumColumns (7),
  54957. standardItemHeight (0),
  54958. isOver (false),
  54959. hasBeenOver (false),
  54960. isDown (false),
  54961. needsToScroll (false),
  54962. hideOnExit (false),
  54963. disableMouseMoves (false),
  54964. hasAnyJuceCompHadFocus (false),
  54965. numColumns (0),
  54966. contentHeight (0),
  54967. childYOffset (0),
  54968. timeEnteredCurrentChildComp (0),
  54969. scrollAcceleration (1.0)
  54970. {
  54971. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54972. setWantsKeyboardFocus (true);
  54973. setMouseClickGrabsKeyboardFocus (false);
  54974. setOpaque (true);
  54975. setAlwaysOnTop (true);
  54976. Desktop::getInstance().addGlobalMouseListener (this);
  54977. getActiveWindows().add (this);
  54978. }
  54979. ~Window()
  54980. {
  54981. getActiveWindows().removeValue (this);
  54982. Desktop::getInstance().removeGlobalMouseListener (this);
  54983. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54984. activeSubMenu = 0;
  54985. deleteAllChildren();
  54986. }
  54987. static Window* create (const PopupMenu& menu,
  54988. const bool dismissOnMouseUp,
  54989. Window* const owner_,
  54990. const Rectangle<int>& target,
  54991. const int minimumWidth,
  54992. const int maximumNumColumns,
  54993. const int standardItemHeight,
  54994. const bool alignToRectangle,
  54995. const int itemIdThatMustBeVisible,
  54996. ApplicationCommandManager** managerOfChosenCommand,
  54997. Component* const componentAttachedTo)
  54998. {
  54999. if (menu.items.size() > 0)
  55000. {
  55001. int totalItems = 0;
  55002. ScopedPointer <Window> mw (new Window());
  55003. mw->setLookAndFeel (menu.lookAndFeel);
  55004. mw->setWantsKeyboardFocus (false);
  55005. mw->minimumWidth = minimumWidth;
  55006. mw->maximumNumColumns = maximumNumColumns;
  55007. mw->standardItemHeight = standardItemHeight;
  55008. mw->dismissOnMouseUp = dismissOnMouseUp;
  55009. for (int i = 0; i < menu.items.size(); ++i)
  55010. {
  55011. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55012. mw->addItem (*item);
  55013. ++totalItems;
  55014. }
  55015. if (totalItems > 0)
  55016. {
  55017. mw->owner = owner_;
  55018. mw->managerOfChosenCommand = managerOfChosenCommand;
  55019. mw->componentAttachedTo = componentAttachedTo;
  55020. mw->componentAttachedToOriginal = componentAttachedTo;
  55021. mw->calculateWindowPos (target, alignToRectangle);
  55022. mw->setTopLeftPosition (mw->windowPos.getX(),
  55023. mw->windowPos.getY());
  55024. mw->updateYPositions();
  55025. if (itemIdThatMustBeVisible != 0)
  55026. {
  55027. const int y = target.getY() - mw->windowPos.getY();
  55028. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55029. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55030. }
  55031. mw->resizeToBestWindowPos();
  55032. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55033. | mw->getLookAndFeel().getMenuWindowFlags());
  55034. return mw.release();
  55035. }
  55036. }
  55037. return 0;
  55038. }
  55039. void paint (Graphics& g)
  55040. {
  55041. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55042. }
  55043. void paintOverChildren (Graphics& g)
  55044. {
  55045. if (isScrolling())
  55046. {
  55047. LookAndFeel& lf = getLookAndFeel();
  55048. if (isScrollZoneActive (false))
  55049. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55050. if (isScrollZoneActive (true))
  55051. {
  55052. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55053. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55054. }
  55055. }
  55056. }
  55057. bool isScrollZoneActive (bool bottomOne) const
  55058. {
  55059. return isScrolling()
  55060. && (bottomOne
  55061. ? childYOffset < contentHeight - windowPos.getHeight()
  55062. : childYOffset > 0);
  55063. }
  55064. void addItem (const PopupMenu::Item& item)
  55065. {
  55066. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55067. addAndMakeVisible (mic);
  55068. int itemW = 80;
  55069. int itemH = 16;
  55070. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55071. mic->setSize (itemW, jlimit (2, 600, itemH));
  55072. mic->addMouseListener (this, false);
  55073. }
  55074. // hide this and all sub-comps
  55075. void hide (const PopupMenu::Item* const item)
  55076. {
  55077. if (isVisible())
  55078. {
  55079. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55080. activeSubMenu = 0;
  55081. currentChild = 0;
  55082. exitModalState (item != 0 ? item->itemId : 0);
  55083. setVisible (false);
  55084. if (item != 0
  55085. && item->commandManager != 0
  55086. && item->itemId != 0)
  55087. {
  55088. *managerOfChosenCommand = item->commandManager;
  55089. }
  55090. }
  55091. }
  55092. void dismissMenu (const PopupMenu::Item* const item)
  55093. {
  55094. if (owner != 0)
  55095. {
  55096. owner->dismissMenu (item);
  55097. }
  55098. else
  55099. {
  55100. if (item != 0)
  55101. {
  55102. // need a copy of this on the stack as the one passed in will get deleted during this call
  55103. const PopupMenu::Item mi (*item);
  55104. hide (&mi);
  55105. }
  55106. else
  55107. {
  55108. hide (0);
  55109. }
  55110. }
  55111. }
  55112. void mouseMove (const MouseEvent&)
  55113. {
  55114. timerCallback();
  55115. }
  55116. void mouseDown (const MouseEvent&)
  55117. {
  55118. timerCallback();
  55119. }
  55120. void mouseDrag (const MouseEvent&)
  55121. {
  55122. timerCallback();
  55123. }
  55124. void mouseUp (const MouseEvent&)
  55125. {
  55126. timerCallback();
  55127. }
  55128. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55129. {
  55130. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55131. lastMouse = Point<int> (-1, -1);
  55132. }
  55133. bool keyPressed (const KeyPress& key)
  55134. {
  55135. if (key.isKeyCode (KeyPress::downKey))
  55136. {
  55137. selectNextItem (1);
  55138. }
  55139. else if (key.isKeyCode (KeyPress::upKey))
  55140. {
  55141. selectNextItem (-1);
  55142. }
  55143. else if (key.isKeyCode (KeyPress::leftKey))
  55144. {
  55145. if (owner != 0)
  55146. {
  55147. Component::SafePointer<Window> parentWindow (owner);
  55148. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55149. hide (0);
  55150. if (parentWindow != 0)
  55151. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55152. disableTimerUntilMouseMoves();
  55153. }
  55154. else if (componentAttachedTo != 0)
  55155. {
  55156. componentAttachedTo->keyPressed (key);
  55157. }
  55158. }
  55159. else if (key.isKeyCode (KeyPress::rightKey))
  55160. {
  55161. disableTimerUntilMouseMoves();
  55162. if (showSubMenuFor (currentChild))
  55163. {
  55164. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55165. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55166. activeSubMenu->selectNextItem (1);
  55167. }
  55168. else if (componentAttachedTo != 0)
  55169. {
  55170. componentAttachedTo->keyPressed (key);
  55171. }
  55172. }
  55173. else if (key.isKeyCode (KeyPress::returnKey))
  55174. {
  55175. triggerCurrentlyHighlightedItem();
  55176. }
  55177. else if (key.isKeyCode (KeyPress::escapeKey))
  55178. {
  55179. dismissMenu (0);
  55180. }
  55181. else
  55182. {
  55183. return false;
  55184. }
  55185. return true;
  55186. }
  55187. void inputAttemptWhenModal()
  55188. {
  55189. Component::SafePointer<Component> deletionChecker (this);
  55190. timerCallback();
  55191. if (deletionChecker != 0 && ! isOverAnyMenu())
  55192. {
  55193. if (componentAttachedTo != 0)
  55194. {
  55195. // we want to dismiss the menu, but if we do it synchronously, then
  55196. // the mouse-click will be allowed to pass through. That's good, except
  55197. // when the user clicks on the button that orginally popped the menu up,
  55198. // as they'll expect the menu to go away, and in fact it'll just
  55199. // come back. So only dismiss synchronously if they're not on the original
  55200. // comp that we're attached to.
  55201. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55202. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55203. {
  55204. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55205. return;
  55206. }
  55207. }
  55208. dismissMenu (0);
  55209. }
  55210. }
  55211. void handleCommandMessage (int commandId)
  55212. {
  55213. Component::handleCommandMessage (commandId);
  55214. if (commandId == PopupMenuSettings::dismissCommandId)
  55215. dismissMenu (0);
  55216. }
  55217. void timerCallback()
  55218. {
  55219. if (! isVisible())
  55220. return;
  55221. if (componentAttachedTo != componentAttachedToOriginal)
  55222. {
  55223. dismissMenu (0);
  55224. return;
  55225. }
  55226. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55227. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55228. return;
  55229. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55230. // move rather than a real timer callback
  55231. const Point<int> globalMousePos (Desktop::getMousePosition());
  55232. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55233. const uint32 now = Time::getMillisecondCounter();
  55234. if (now > timeEnteredCurrentChildComp + 100
  55235. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55236. && currentChild->isValidComponent()
  55237. && (! disableMouseMoves)
  55238. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55239. {
  55240. showSubMenuFor (currentChild);
  55241. }
  55242. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55243. {
  55244. highlightItemUnderMouse (globalMousePos, localMousePos);
  55245. }
  55246. bool overScrollArea = false;
  55247. if (isScrolling()
  55248. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55249. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55250. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55251. {
  55252. if (now > lastScroll + 20)
  55253. {
  55254. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55255. int amount = 0;
  55256. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55257. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55258. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55259. lastScroll = now;
  55260. }
  55261. overScrollArea = true;
  55262. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55263. }
  55264. else
  55265. {
  55266. scrollAcceleration = 1.0;
  55267. }
  55268. const bool wasDown = isDown;
  55269. bool isOverAny = isOverAnyMenu();
  55270. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55271. {
  55272. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55273. isOverAny = isOverAnyMenu();
  55274. }
  55275. if (hideOnExit && hasBeenOver && ! isOverAny)
  55276. {
  55277. hide (0);
  55278. }
  55279. else
  55280. {
  55281. isDown = hasBeenOver
  55282. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55283. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55284. bool anyFocused = Process::isForegroundProcess();
  55285. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55286. {
  55287. // because no component at all may have focus, our test here will
  55288. // only be triggered when something has focus and then loses it.
  55289. anyFocused = ! hasAnyJuceCompHadFocus;
  55290. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55291. {
  55292. if (ComponentPeer::getPeer (i)->isFocused())
  55293. {
  55294. anyFocused = true;
  55295. hasAnyJuceCompHadFocus = true;
  55296. break;
  55297. }
  55298. }
  55299. }
  55300. if (! anyFocused)
  55301. {
  55302. if (now > lastFocused + 10)
  55303. {
  55304. wasHiddenBecauseOfAppChange() = true;
  55305. dismissMenu (0);
  55306. return; // may have been deleted by the previous call..
  55307. }
  55308. }
  55309. else if (wasDown && now > menuCreationTime + 250
  55310. && ! (isDown || overScrollArea))
  55311. {
  55312. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55313. if (isOver)
  55314. {
  55315. triggerCurrentlyHighlightedItem();
  55316. }
  55317. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55318. {
  55319. dismissMenu (0);
  55320. }
  55321. return; // may have been deleted by the previous calls..
  55322. }
  55323. else
  55324. {
  55325. lastFocused = now;
  55326. }
  55327. }
  55328. }
  55329. static Array<Window*>& getActiveWindows()
  55330. {
  55331. static Array<Window*> activeMenuWindows;
  55332. return activeMenuWindows;
  55333. }
  55334. static bool& wasHiddenBecauseOfAppChange() throw()
  55335. {
  55336. static bool b = false;
  55337. return b;
  55338. }
  55339. juce_UseDebuggingNewOperator
  55340. private:
  55341. Window* owner;
  55342. PopupMenu::ItemComponent* currentChild;
  55343. ScopedPointer <Window> activeSubMenu;
  55344. ApplicationCommandManager** managerOfChosenCommand;
  55345. Component::SafePointer<Component> componentAttachedTo;
  55346. Component* componentAttachedToOriginal;
  55347. Rectangle<int> windowPos;
  55348. Point<int> lastMouse;
  55349. int minimumWidth, maximumNumColumns, standardItemHeight;
  55350. bool isOver, hasBeenOver, isDown, needsToScroll;
  55351. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55352. int numColumns, contentHeight, childYOffset;
  55353. Array <int> columnWidths;
  55354. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55355. double scrollAcceleration;
  55356. bool overlaps (const Rectangle<int>& r) const
  55357. {
  55358. return r.intersects (getBounds())
  55359. || (owner != 0 && owner->overlaps (r));
  55360. }
  55361. bool isOverAnyMenu() const
  55362. {
  55363. return (owner != 0) ? owner->isOverAnyMenu()
  55364. : isOverChildren();
  55365. }
  55366. bool isOverChildren() const
  55367. {
  55368. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55369. return isVisible()
  55370. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55371. }
  55372. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55373. {
  55374. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55375. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55376. if (activeSubMenu != 0)
  55377. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55378. }
  55379. bool treeContains (const Window* const window) const throw()
  55380. {
  55381. const Window* mw = this;
  55382. while (mw->owner != 0)
  55383. mw = mw->owner;
  55384. while (mw != 0)
  55385. {
  55386. if (mw == window)
  55387. return true;
  55388. mw = mw->activeSubMenu;
  55389. }
  55390. return false;
  55391. }
  55392. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55393. {
  55394. const Rectangle<int> mon (Desktop::getInstance()
  55395. .getMonitorAreaContaining (target.getCentre(),
  55396. #if JUCE_MAC
  55397. true));
  55398. #else
  55399. false)); // on windows, don't stop the menu overlapping the taskbar
  55400. #endif
  55401. int x, y, widthToUse, heightToUse;
  55402. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55403. if (alignToRectangle)
  55404. {
  55405. x = target.getX();
  55406. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55407. const int spaceOver = target.getY() - mon.getY();
  55408. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55409. y = target.getBottom();
  55410. else
  55411. y = target.getY() - heightToUse;
  55412. }
  55413. else
  55414. {
  55415. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55416. if (owner != 0)
  55417. {
  55418. if (owner->owner != 0)
  55419. {
  55420. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55421. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55422. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55423. tendTowardsRight = true;
  55424. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55425. tendTowardsRight = false;
  55426. }
  55427. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55428. {
  55429. tendTowardsRight = true;
  55430. }
  55431. }
  55432. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55433. target.getX() - mon.getX()) - 32;
  55434. if (biggestSpace < widthToUse)
  55435. {
  55436. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55437. if (numColumns > 1)
  55438. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55439. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55440. }
  55441. if (tendTowardsRight)
  55442. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55443. else
  55444. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55445. y = target.getY();
  55446. if (target.getCentreY() > mon.getCentreY())
  55447. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55448. }
  55449. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55450. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55451. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55452. // sets this flag if it's big enough to obscure any of its parent menus
  55453. hideOnExit = (owner != 0)
  55454. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55455. }
  55456. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55457. {
  55458. numColumns = 0;
  55459. contentHeight = 0;
  55460. const int maxMenuH = getParentHeight() - 24;
  55461. int totalW;
  55462. do
  55463. {
  55464. ++numColumns;
  55465. totalW = workOutBestSize (maxMenuW);
  55466. if (totalW > maxMenuW)
  55467. {
  55468. numColumns = jmax (1, numColumns - 1);
  55469. totalW = workOutBestSize (maxMenuW); // to update col widths
  55470. break;
  55471. }
  55472. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55473. {
  55474. break;
  55475. }
  55476. } while (numColumns < maximumNumColumns);
  55477. const int actualH = jmin (contentHeight, maxMenuH);
  55478. needsToScroll = contentHeight > actualH;
  55479. width = updateYPositions();
  55480. height = actualH + PopupMenuSettings::borderSize * 2;
  55481. }
  55482. int workOutBestSize (const int maxMenuW)
  55483. {
  55484. int totalW = 0;
  55485. contentHeight = 0;
  55486. int childNum = 0;
  55487. for (int col = 0; col < numColumns; ++col)
  55488. {
  55489. int i, colW = 50, colH = 0;
  55490. const int numChildren = jmin (getNumChildComponents() - childNum,
  55491. (getNumChildComponents() + numColumns - 1) / numColumns);
  55492. for (i = numChildren; --i >= 0;)
  55493. {
  55494. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55495. colH += getChildComponent (childNum + i)->getHeight();
  55496. }
  55497. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55498. columnWidths.set (col, colW);
  55499. totalW += colW;
  55500. contentHeight = jmax (contentHeight, colH);
  55501. childNum += numChildren;
  55502. }
  55503. if (totalW < minimumWidth)
  55504. {
  55505. totalW = minimumWidth;
  55506. for (int col = 0; col < numColumns; ++col)
  55507. columnWidths.set (0, totalW / numColumns);
  55508. }
  55509. return totalW;
  55510. }
  55511. void ensureItemIsVisible (const int itemId, int wantedY)
  55512. {
  55513. jassert (itemId != 0)
  55514. for (int i = getNumChildComponents(); --i >= 0;)
  55515. {
  55516. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55517. if (m != 0
  55518. && m->itemInfo.itemId == itemId
  55519. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55520. {
  55521. const int currentY = m->getY();
  55522. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55523. {
  55524. if (wantedY < 0)
  55525. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55526. jmax (PopupMenuSettings::scrollZone,
  55527. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55528. currentY);
  55529. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55530. int deltaY = wantedY - currentY;
  55531. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55532. jmin (windowPos.getHeight(), mon.getHeight()));
  55533. const int newY = jlimit (mon.getY(),
  55534. mon.getBottom() - windowPos.getHeight(),
  55535. windowPos.getY() + deltaY);
  55536. deltaY -= newY - windowPos.getY();
  55537. childYOffset -= deltaY;
  55538. windowPos.setPosition (windowPos.getX(), newY);
  55539. updateYPositions();
  55540. }
  55541. break;
  55542. }
  55543. }
  55544. }
  55545. void resizeToBestWindowPos()
  55546. {
  55547. Rectangle<int> r (windowPos);
  55548. if (childYOffset < 0)
  55549. {
  55550. r.setBounds (r.getX(), r.getY() - childYOffset,
  55551. r.getWidth(), r.getHeight() + childYOffset);
  55552. }
  55553. else if (childYOffset > 0)
  55554. {
  55555. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55556. if (spaceAtBottom > 0)
  55557. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55558. }
  55559. setBounds (r);
  55560. updateYPositions();
  55561. }
  55562. void alterChildYPos (const int delta)
  55563. {
  55564. if (isScrolling())
  55565. {
  55566. childYOffset += delta;
  55567. if (delta < 0)
  55568. {
  55569. childYOffset = jmax (childYOffset, 0);
  55570. }
  55571. else if (delta > 0)
  55572. {
  55573. childYOffset = jmin (childYOffset,
  55574. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55575. }
  55576. updateYPositions();
  55577. }
  55578. else
  55579. {
  55580. childYOffset = 0;
  55581. }
  55582. resizeToBestWindowPos();
  55583. repaint();
  55584. }
  55585. int updateYPositions()
  55586. {
  55587. int x = 0;
  55588. int childNum = 0;
  55589. for (int col = 0; col < numColumns; ++col)
  55590. {
  55591. const int numChildren = jmin (getNumChildComponents() - childNum,
  55592. (getNumChildComponents() + numColumns - 1) / numColumns);
  55593. const int colW = columnWidths [col];
  55594. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55595. for (int i = 0; i < numChildren; ++i)
  55596. {
  55597. Component* const c = getChildComponent (childNum + i);
  55598. c->setBounds (x, y, colW, c->getHeight());
  55599. y += c->getHeight();
  55600. }
  55601. x += colW;
  55602. childNum += numChildren;
  55603. }
  55604. return x;
  55605. }
  55606. bool isScrolling() const throw()
  55607. {
  55608. return childYOffset != 0 || needsToScroll;
  55609. }
  55610. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55611. {
  55612. if (currentChild->isValidComponent())
  55613. currentChild->setHighlighted (false);
  55614. currentChild = child;
  55615. if (currentChild != 0)
  55616. {
  55617. currentChild->setHighlighted (true);
  55618. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55619. }
  55620. }
  55621. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55622. {
  55623. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55624. activeSubMenu = 0;
  55625. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55626. {
  55627. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55628. dismissOnMouseUp,
  55629. this,
  55630. childComp->getScreenBounds(),
  55631. 0, maximumNumColumns,
  55632. standardItemHeight,
  55633. false, 0, managerOfChosenCommand,
  55634. componentAttachedTo);
  55635. if (activeSubMenu != 0)
  55636. {
  55637. activeSubMenu->setVisible (true);
  55638. activeSubMenu->enterModalState (false);
  55639. activeSubMenu->toFront (false);
  55640. return true;
  55641. }
  55642. }
  55643. return false;
  55644. }
  55645. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55646. {
  55647. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55648. if (isOver)
  55649. hasBeenOver = true;
  55650. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55651. {
  55652. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55653. if (disableMouseMoves && isOver)
  55654. disableMouseMoves = false;
  55655. }
  55656. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55657. return;
  55658. bool isMovingTowardsMenu = false;
  55659. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55660. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55661. {
  55662. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55663. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55664. // extends from the last mouse pos to the submenu's rectangle..
  55665. float subX = (float) activeSubMenu->getScreenX();
  55666. if (activeSubMenu->getX() > getX())
  55667. {
  55668. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55669. }
  55670. else
  55671. {
  55672. lastMouse += Point<int> (2, 0);
  55673. subX += activeSubMenu->getWidth();
  55674. }
  55675. Path areaTowardsSubMenu;
  55676. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55677. (float) lastMouse.getY(),
  55678. subX,
  55679. (float) activeSubMenu->getScreenY(),
  55680. subX,
  55681. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55682. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55683. }
  55684. lastMouse = globalMousePos;
  55685. if (! isMovingTowardsMenu)
  55686. {
  55687. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55688. if (c == this)
  55689. c = 0;
  55690. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55691. if (mic == 0 && c != 0)
  55692. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55693. if (mic != currentChild
  55694. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55695. {
  55696. if (isOver && (c != 0) && (activeSubMenu != 0))
  55697. {
  55698. activeSubMenu->hide (0);
  55699. }
  55700. if (! isOver)
  55701. mic = 0;
  55702. setCurrentlyHighlightedChild (mic);
  55703. }
  55704. }
  55705. }
  55706. void triggerCurrentlyHighlightedItem()
  55707. {
  55708. if (currentChild->isValidComponent()
  55709. && currentChild->itemInfo.canBeTriggered()
  55710. && (currentChild->itemInfo.customComp == 0
  55711. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55712. {
  55713. dismissMenu (&currentChild->itemInfo);
  55714. }
  55715. }
  55716. void selectNextItem (const int delta)
  55717. {
  55718. disableTimerUntilMouseMoves();
  55719. PopupMenu::ItemComponent* mic = 0;
  55720. bool wasLastOne = (currentChild == 0);
  55721. const int numItems = getNumChildComponents();
  55722. for (int i = 0; i < numItems + 1; ++i)
  55723. {
  55724. int index = (delta > 0) ? i : (numItems - 1 - i);
  55725. index = (index + numItems) % numItems;
  55726. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55727. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55728. && wasLastOne)
  55729. break;
  55730. if (mic == currentChild)
  55731. wasLastOne = true;
  55732. }
  55733. setCurrentlyHighlightedChild (mic);
  55734. }
  55735. void disableTimerUntilMouseMoves()
  55736. {
  55737. disableMouseMoves = true;
  55738. if (owner != 0)
  55739. owner->disableTimerUntilMouseMoves();
  55740. }
  55741. Window (const Window&);
  55742. Window& operator= (const Window&);
  55743. };
  55744. PopupMenu::PopupMenu()
  55745. : lookAndFeel (0),
  55746. separatorPending (false)
  55747. {
  55748. }
  55749. PopupMenu::PopupMenu (const PopupMenu& other)
  55750. : lookAndFeel (other.lookAndFeel),
  55751. separatorPending (false)
  55752. {
  55753. items.addCopiesOf (other.items);
  55754. }
  55755. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55756. {
  55757. if (this != &other)
  55758. {
  55759. lookAndFeel = other.lookAndFeel;
  55760. clear();
  55761. items.addCopiesOf (other.items);
  55762. }
  55763. return *this;
  55764. }
  55765. PopupMenu::~PopupMenu()
  55766. {
  55767. clear();
  55768. }
  55769. void PopupMenu::clear()
  55770. {
  55771. items.clear();
  55772. separatorPending = false;
  55773. }
  55774. void PopupMenu::addSeparatorIfPending()
  55775. {
  55776. if (separatorPending)
  55777. {
  55778. separatorPending = false;
  55779. if (items.size() > 0)
  55780. items.add (new Item());
  55781. }
  55782. }
  55783. void PopupMenu::addItem (const int itemResultId,
  55784. const String& itemText,
  55785. const bool isActive,
  55786. const bool isTicked,
  55787. const Image& iconToUse)
  55788. {
  55789. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55790. // didn't pick anything, so you shouldn't use it as the id
  55791. // for an item..
  55792. addSeparatorIfPending();
  55793. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55794. Colours::black, false, 0, 0, 0));
  55795. }
  55796. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55797. const int commandID,
  55798. const String& displayName)
  55799. {
  55800. jassert (commandManager != 0 && commandID != 0);
  55801. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55802. if (registeredInfo != 0)
  55803. {
  55804. ApplicationCommandInfo info (*registeredInfo);
  55805. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55806. addSeparatorIfPending();
  55807. items.add (new Item (commandID,
  55808. displayName.isNotEmpty() ? displayName
  55809. : info.shortName,
  55810. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55811. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55812. Image::null,
  55813. Colours::black,
  55814. false,
  55815. 0, 0,
  55816. commandManager));
  55817. }
  55818. }
  55819. void PopupMenu::addColouredItem (const int itemResultId,
  55820. const String& itemText,
  55821. const Colour& itemTextColour,
  55822. const bool isActive,
  55823. const bool isTicked,
  55824. const Image& iconToUse)
  55825. {
  55826. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55827. // didn't pick anything, so you shouldn't use it as the id
  55828. // for an item..
  55829. addSeparatorIfPending();
  55830. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55831. itemTextColour, true, 0, 0, 0));
  55832. }
  55833. void PopupMenu::addCustomItem (const int itemResultId,
  55834. PopupMenuCustomComponent* const customComponent)
  55835. {
  55836. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55837. // didn't pick anything, so you shouldn't use it as the id
  55838. // for an item..
  55839. addSeparatorIfPending();
  55840. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  55841. Colours::black, false, customComponent, 0, 0));
  55842. }
  55843. class NormalComponentWrapper : public PopupMenuCustomComponent
  55844. {
  55845. public:
  55846. NormalComponentWrapper (Component* const comp,
  55847. const int w, const int h,
  55848. const bool triggerMenuItemAutomaticallyWhenClicked)
  55849. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55850. width (w),
  55851. height (h)
  55852. {
  55853. addAndMakeVisible (comp);
  55854. }
  55855. ~NormalComponentWrapper() {}
  55856. void getIdealSize (int& idealWidth, int& idealHeight)
  55857. {
  55858. idealWidth = width;
  55859. idealHeight = height;
  55860. }
  55861. void resized()
  55862. {
  55863. if (getChildComponent(0) != 0)
  55864. getChildComponent(0)->setBounds (getLocalBounds());
  55865. }
  55866. juce_UseDebuggingNewOperator
  55867. private:
  55868. const int width, height;
  55869. NormalComponentWrapper (const NormalComponentWrapper&);
  55870. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55871. };
  55872. void PopupMenu::addCustomItem (const int itemResultId,
  55873. Component* customComponent,
  55874. int idealWidth, int idealHeight,
  55875. const bool triggerMenuItemAutomaticallyWhenClicked)
  55876. {
  55877. addCustomItem (itemResultId,
  55878. new NormalComponentWrapper (customComponent,
  55879. idealWidth, idealHeight,
  55880. triggerMenuItemAutomaticallyWhenClicked));
  55881. }
  55882. void PopupMenu::addSubMenu (const String& subMenuName,
  55883. const PopupMenu& subMenu,
  55884. const bool isActive,
  55885. const Image& iconToUse,
  55886. const bool isTicked)
  55887. {
  55888. addSeparatorIfPending();
  55889. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55890. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55891. }
  55892. void PopupMenu::addSeparator()
  55893. {
  55894. separatorPending = true;
  55895. }
  55896. class HeaderItemComponent : public PopupMenuCustomComponent
  55897. {
  55898. public:
  55899. HeaderItemComponent (const String& name)
  55900. : PopupMenuCustomComponent (false)
  55901. {
  55902. setName (name);
  55903. }
  55904. ~HeaderItemComponent()
  55905. {
  55906. }
  55907. void paint (Graphics& g)
  55908. {
  55909. Font f (getLookAndFeel().getPopupMenuFont());
  55910. f.setBold (true);
  55911. g.setFont (f);
  55912. g.setColour (findColour (PopupMenu::headerTextColourId));
  55913. g.drawFittedText (getName(),
  55914. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55915. Justification::bottomLeft, 1);
  55916. }
  55917. void getIdealSize (int& idealWidth,
  55918. int& idealHeight)
  55919. {
  55920. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55921. idealHeight += idealHeight / 2;
  55922. idealWidth += idealWidth / 4;
  55923. }
  55924. juce_UseDebuggingNewOperator
  55925. };
  55926. void PopupMenu::addSectionHeader (const String& title)
  55927. {
  55928. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55929. }
  55930. // This invokes any command manager commands and deletes the menu window when it is dismissed
  55931. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  55932. {
  55933. public:
  55934. PopupMenuCompletionCallback()
  55935. : managerOfChosenCommand (0)
  55936. {
  55937. }
  55938. ~PopupMenuCompletionCallback() {}
  55939. void modalStateFinished (int result)
  55940. {
  55941. if (managerOfChosenCommand != 0 && result != 0)
  55942. {
  55943. ApplicationCommandTarget::InvocationInfo info (result);
  55944. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55945. managerOfChosenCommand->invoke (info, true);
  55946. }
  55947. }
  55948. ApplicationCommandManager* managerOfChosenCommand;
  55949. ScopedPointer<Component> component;
  55950. private:
  55951. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  55952. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  55953. };
  55954. int PopupMenu::showMenu (const Rectangle<int>& target,
  55955. const int itemIdThatMustBeVisible,
  55956. const int minimumWidth,
  55957. const int maximumNumColumns,
  55958. const int standardItemHeight,
  55959. const bool alignToRectangle,
  55960. Component* const componentAttachedTo,
  55961. ModalComponentManager::Callback* userCallback)
  55962. {
  55963. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  55964. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55965. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55966. Window::wasHiddenBecauseOfAppChange() = false;
  55967. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  55968. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  55969. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55970. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  55971. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  55972. &callback->managerOfChosenCommand, componentAttachedTo);
  55973. if (callback->component == 0)
  55974. return 0;
  55975. callbackDeleter.release();
  55976. callback->component->enterModalState (false, userCallbackDeleter.release());
  55977. callback->component->toFront (false); // need to do this after making it modal, or it could
  55978. // be stuck behind other comps that are already modal..
  55979. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  55980. if (userCallback != 0)
  55981. return 0;
  55982. const int result = callback->component->runModalLoop();
  55983. if (! Window::wasHiddenBecauseOfAppChange())
  55984. {
  55985. if (prevTopLevel != 0)
  55986. prevTopLevel->toFront (true);
  55987. if (prevFocused != 0)
  55988. prevFocused->grabKeyboardFocus();
  55989. }
  55990. return result;
  55991. }
  55992. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55993. const int minimumWidth,
  55994. const int maximumNumColumns,
  55995. const int standardItemHeight,
  55996. ModalComponentManager::Callback* callback)
  55997. {
  55998. const Point<int> mousePos (Desktop::getMousePosition());
  55999. return showAt (mousePos.getX(), mousePos.getY(),
  56000. itemIdThatMustBeVisible,
  56001. minimumWidth,
  56002. maximumNumColumns,
  56003. standardItemHeight,
  56004. callback);
  56005. }
  56006. int PopupMenu::showAt (const int screenX,
  56007. const int screenY,
  56008. const int itemIdThatMustBeVisible,
  56009. const int minimumWidth,
  56010. const int maximumNumColumns,
  56011. const int standardItemHeight,
  56012. ModalComponentManager::Callback* callback)
  56013. {
  56014. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56015. itemIdThatMustBeVisible,
  56016. minimumWidth, maximumNumColumns,
  56017. standardItemHeight,
  56018. false, 0, callback);
  56019. }
  56020. int PopupMenu::showAt (Component* componentToAttachTo,
  56021. const int itemIdThatMustBeVisible,
  56022. const int minimumWidth,
  56023. const int maximumNumColumns,
  56024. const int standardItemHeight,
  56025. ModalComponentManager::Callback* callback)
  56026. {
  56027. if (componentToAttachTo != 0)
  56028. {
  56029. return showMenu (componentToAttachTo->getScreenBounds(),
  56030. itemIdThatMustBeVisible,
  56031. minimumWidth,
  56032. maximumNumColumns,
  56033. standardItemHeight,
  56034. true, componentToAttachTo, callback);
  56035. }
  56036. else
  56037. {
  56038. return show (itemIdThatMustBeVisible,
  56039. minimumWidth,
  56040. maximumNumColumns,
  56041. standardItemHeight,
  56042. callback);
  56043. }
  56044. }
  56045. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56046. {
  56047. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56048. {
  56049. Window* const pmw = Window::getActiveWindows()[i];
  56050. if (pmw != 0)
  56051. pmw->dismissMenu (0);
  56052. }
  56053. }
  56054. int PopupMenu::getNumItems() const throw()
  56055. {
  56056. int num = 0;
  56057. for (int i = items.size(); --i >= 0;)
  56058. if (! (items.getUnchecked(i))->isSeparator)
  56059. ++num;
  56060. return num;
  56061. }
  56062. bool PopupMenu::containsCommandItem (const int commandID) const
  56063. {
  56064. for (int i = items.size(); --i >= 0;)
  56065. {
  56066. const Item* mi = items.getUnchecked (i);
  56067. if ((mi->itemId == commandID && mi->commandManager != 0)
  56068. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56069. {
  56070. return true;
  56071. }
  56072. }
  56073. return false;
  56074. }
  56075. bool PopupMenu::containsAnyActiveItems() const throw()
  56076. {
  56077. for (int i = items.size(); --i >= 0;)
  56078. {
  56079. const Item* const mi = items.getUnchecked (i);
  56080. if (mi->subMenu != 0)
  56081. {
  56082. if (mi->subMenu->containsAnyActiveItems())
  56083. return true;
  56084. }
  56085. else if (mi->active)
  56086. {
  56087. return true;
  56088. }
  56089. }
  56090. return false;
  56091. }
  56092. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56093. {
  56094. lookAndFeel = newLookAndFeel;
  56095. }
  56096. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56097. : isHighlighted (false),
  56098. isTriggeredAutomatically (isTriggeredAutomatically_)
  56099. {
  56100. }
  56101. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56102. {
  56103. }
  56104. void PopupMenuCustomComponent::triggerMenuItem()
  56105. {
  56106. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56107. if (mic != 0)
  56108. {
  56109. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56110. if (pmw != 0)
  56111. {
  56112. pmw->dismissMenu (&mic->itemInfo);
  56113. }
  56114. else
  56115. {
  56116. // something must have gone wrong with the component hierarchy if this happens..
  56117. jassertfalse;
  56118. }
  56119. }
  56120. else
  56121. {
  56122. // why isn't this component inside a menu? Not much point triggering the item if
  56123. // there's no menu.
  56124. jassertfalse;
  56125. }
  56126. }
  56127. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56128. : subMenu (0),
  56129. itemId (0),
  56130. isSeparator (false),
  56131. isTicked (false),
  56132. isEnabled (false),
  56133. isCustomComponent (false),
  56134. isSectionHeader (false),
  56135. customColour (0),
  56136. customImage (0),
  56137. menu (menu_),
  56138. index (0)
  56139. {
  56140. }
  56141. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56142. {
  56143. }
  56144. bool PopupMenu::MenuItemIterator::next()
  56145. {
  56146. if (index >= menu.items.size())
  56147. return false;
  56148. const Item* const item = menu.items.getUnchecked (index);
  56149. ++index;
  56150. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56151. subMenu = item->subMenu;
  56152. itemId = item->itemId;
  56153. isSeparator = item->isSeparator;
  56154. isTicked = item->isTicked;
  56155. isEnabled = item->active;
  56156. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56157. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56158. customColour = item->usesColour ? &(item->textColour) : 0;
  56159. customImage = item->image;
  56160. commandManager = item->commandManager;
  56161. return true;
  56162. }
  56163. END_JUCE_NAMESPACE
  56164. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56165. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56166. BEGIN_JUCE_NAMESPACE
  56167. ComponentDragger::ComponentDragger()
  56168. : constrainer (0)
  56169. {
  56170. }
  56171. ComponentDragger::~ComponentDragger()
  56172. {
  56173. }
  56174. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56175. ComponentBoundsConstrainer* const constrainer_)
  56176. {
  56177. jassert (componentToDrag->isValidComponent());
  56178. if (componentToDrag != 0)
  56179. {
  56180. constrainer = constrainer_;
  56181. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56182. }
  56183. }
  56184. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56185. {
  56186. jassert (componentToDrag->isValidComponent());
  56187. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56188. if (componentToDrag != 0)
  56189. {
  56190. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56191. const Component* const parentComp = componentToDrag->getParentComponent();
  56192. if (parentComp != 0)
  56193. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56194. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56195. if (constrainer != 0)
  56196. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56197. else
  56198. componentToDrag->setBounds (bounds);
  56199. }
  56200. }
  56201. END_JUCE_NAMESPACE
  56202. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56203. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56204. BEGIN_JUCE_NAMESPACE
  56205. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56206. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56207. class DragImageComponent : public Component,
  56208. public Timer
  56209. {
  56210. public:
  56211. DragImageComponent (const Image& im,
  56212. const String& desc,
  56213. Component* const sourceComponent,
  56214. Component* const mouseDragSource_,
  56215. DragAndDropContainer* const o,
  56216. const Point<int>& imageOffset_)
  56217. : image (im),
  56218. source (sourceComponent),
  56219. mouseDragSource (mouseDragSource_),
  56220. owner (o),
  56221. dragDesc (desc),
  56222. imageOffset (imageOffset_),
  56223. hasCheckedForExternalDrag (false),
  56224. drawImage (true)
  56225. {
  56226. setSize (im.getWidth(), im.getHeight());
  56227. if (mouseDragSource == 0)
  56228. mouseDragSource = source;
  56229. mouseDragSource->addMouseListener (this, false);
  56230. startTimer (200);
  56231. setInterceptsMouseClicks (false, false);
  56232. setAlwaysOnTop (true);
  56233. }
  56234. ~DragImageComponent()
  56235. {
  56236. if (owner->dragImageComponent == this)
  56237. owner->dragImageComponent.release();
  56238. if (mouseDragSource != 0)
  56239. {
  56240. mouseDragSource->removeMouseListener (this);
  56241. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56242. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56243. }
  56244. }
  56245. void paint (Graphics& g)
  56246. {
  56247. if (isOpaque())
  56248. g.fillAll (Colours::white);
  56249. if (drawImage)
  56250. {
  56251. g.setOpacity (1.0f);
  56252. g.drawImageAt (image, 0, 0);
  56253. }
  56254. }
  56255. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56256. {
  56257. Component* hit = getParentComponent();
  56258. if (hit == 0)
  56259. {
  56260. hit = Desktop::getInstance().findComponentAt (screenPos);
  56261. }
  56262. else
  56263. {
  56264. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56265. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56266. }
  56267. // (note: use a local copy of the dragDesc member in case the callback runs
  56268. // a modal loop and deletes this object before the method completes)
  56269. const String dragDescLocal (dragDesc);
  56270. while (hit != 0)
  56271. {
  56272. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56273. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56274. {
  56275. relativePos = hit->globalPositionToRelative (screenPos);
  56276. return ddt;
  56277. }
  56278. hit = hit->getParentComponent();
  56279. }
  56280. return 0;
  56281. }
  56282. void mouseUp (const MouseEvent& e)
  56283. {
  56284. if (e.originalComponent != this)
  56285. {
  56286. if (mouseDragSource != 0)
  56287. mouseDragSource->removeMouseListener (this);
  56288. bool dropAccepted = false;
  56289. DragAndDropTarget* ddt = 0;
  56290. Point<int> relPos;
  56291. if (isVisible())
  56292. {
  56293. setVisible (false);
  56294. ddt = findTarget (e.getScreenPosition(), relPos);
  56295. // fade this component and remove it - it'll be deleted later by the timer callback
  56296. dropAccepted = ddt != 0;
  56297. setVisible (true);
  56298. if (dropAccepted || source == 0)
  56299. {
  56300. fadeOutComponent (120);
  56301. }
  56302. else
  56303. {
  56304. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56305. source->getHeight() / 2)));
  56306. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56307. getHeight() / 2)));
  56308. fadeOutComponent (120,
  56309. target.getX() - ourCentre.getX(),
  56310. target.getY() - ourCentre.getY());
  56311. }
  56312. }
  56313. if (getParentComponent() != 0)
  56314. getParentComponent()->removeChildComponent (this);
  56315. if (dropAccepted && ddt != 0)
  56316. {
  56317. // (note: use a local copy of the dragDesc member in case the callback runs
  56318. // a modal loop and deletes this object before the method completes)
  56319. const String dragDescLocal (dragDesc);
  56320. currentlyOverComp = 0;
  56321. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56322. }
  56323. // careful - this object could now be deleted..
  56324. }
  56325. }
  56326. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56327. {
  56328. // (note: use a local copy of the dragDesc member in case the callback runs
  56329. // a modal loop and deletes this object before it returns)
  56330. const String dragDescLocal (dragDesc);
  56331. Point<int> newPos (screenPos + imageOffset);
  56332. if (getParentComponent() != 0)
  56333. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56334. //if (newX != getX() || newY != getY())
  56335. {
  56336. setTopLeftPosition (newPos.getX(), newPos.getY());
  56337. Point<int> relPos;
  56338. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56339. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56340. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56341. if (ddtComp != currentlyOverComp)
  56342. {
  56343. if (currentlyOverComp != 0 && source != 0
  56344. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56345. {
  56346. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56347. }
  56348. currentlyOverComp = ddtComp;
  56349. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56350. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56351. }
  56352. DragAndDropTarget* target = getCurrentlyOver();
  56353. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56354. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56355. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56356. {
  56357. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56358. {
  56359. hasCheckedForExternalDrag = true;
  56360. StringArray files;
  56361. bool canMoveFiles = false;
  56362. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56363. && files.size() > 0)
  56364. {
  56365. Component::SafePointer<Component> cdw (this);
  56366. setVisible (false);
  56367. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56368. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56369. if (cdw != 0)
  56370. delete this;
  56371. return;
  56372. }
  56373. }
  56374. }
  56375. }
  56376. }
  56377. void mouseDrag (const MouseEvent& e)
  56378. {
  56379. if (e.originalComponent != this)
  56380. updateLocation (true, e.getScreenPosition());
  56381. }
  56382. void timerCallback()
  56383. {
  56384. if (source == 0)
  56385. {
  56386. delete this;
  56387. }
  56388. else if (! isMouseButtonDownAnywhere())
  56389. {
  56390. if (mouseDragSource != 0)
  56391. mouseDragSource->removeMouseListener (this);
  56392. delete this;
  56393. }
  56394. }
  56395. private:
  56396. Image image;
  56397. Component::SafePointer<Component> source;
  56398. Component::SafePointer<Component> mouseDragSource;
  56399. DragAndDropContainer* const owner;
  56400. Component::SafePointer<Component> currentlyOverComp;
  56401. DragAndDropTarget* getCurrentlyOver()
  56402. {
  56403. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56404. }
  56405. String dragDesc;
  56406. const Point<int> imageOffset;
  56407. bool hasCheckedForExternalDrag, drawImage;
  56408. DragImageComponent (const DragImageComponent&);
  56409. DragImageComponent& operator= (const DragImageComponent&);
  56410. };
  56411. DragAndDropContainer::DragAndDropContainer()
  56412. {
  56413. }
  56414. DragAndDropContainer::~DragAndDropContainer()
  56415. {
  56416. dragImageComponent = 0;
  56417. }
  56418. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56419. Component* sourceComponent,
  56420. const Image& dragImage_,
  56421. const bool allowDraggingToExternalWindows,
  56422. const Point<int>* imageOffsetFromMouse)
  56423. {
  56424. Image dragImage (dragImage_);
  56425. if (dragImageComponent == 0)
  56426. {
  56427. Component* const thisComp = dynamic_cast <Component*> (this);
  56428. if (thisComp == 0)
  56429. {
  56430. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56431. return;
  56432. }
  56433. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56434. if (draggingSource == 0 || ! draggingSource->isDragging())
  56435. {
  56436. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56437. return;
  56438. }
  56439. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56440. Point<int> imageOffset;
  56441. if (dragImage.isNull())
  56442. {
  56443. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56444. .convertedToFormat (Image::ARGB);
  56445. dragImage.multiplyAllAlphas (0.6f);
  56446. const int lo = 150;
  56447. const int hi = 400;
  56448. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56449. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56450. for (int y = dragImage.getHeight(); --y >= 0;)
  56451. {
  56452. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56453. for (int x = dragImage.getWidth(); --x >= 0;)
  56454. {
  56455. const int dx = x - clipped.getX();
  56456. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56457. if (distance > lo)
  56458. {
  56459. const float alpha = (distance > hi) ? 0
  56460. : (hi - distance) / (float) (hi - lo)
  56461. + Random::getSystemRandom().nextFloat() * 0.008f;
  56462. dragImage.multiplyAlphaAt (x, y, alpha);
  56463. }
  56464. }
  56465. }
  56466. imageOffset = -clipped;
  56467. }
  56468. else
  56469. {
  56470. if (imageOffsetFromMouse == 0)
  56471. imageOffset = -dragImage.getBounds().getCentre();
  56472. else
  56473. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56474. }
  56475. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56476. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56477. currentDragDesc = sourceDescription;
  56478. if (allowDraggingToExternalWindows)
  56479. {
  56480. if (! Desktop::canUseSemiTransparentWindows())
  56481. dragImageComponent->setOpaque (true);
  56482. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56483. | ComponentPeer::windowIsTemporary
  56484. | ComponentPeer::windowIgnoresKeyPresses);
  56485. }
  56486. else
  56487. thisComp->addChildComponent (dragImageComponent);
  56488. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56489. dragImageComponent->setVisible (true);
  56490. }
  56491. }
  56492. bool DragAndDropContainer::isDragAndDropActive() const
  56493. {
  56494. return dragImageComponent != 0;
  56495. }
  56496. const String DragAndDropContainer::getCurrentDragDescription() const
  56497. {
  56498. return (dragImageComponent != 0) ? currentDragDesc
  56499. : String::empty;
  56500. }
  56501. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56502. {
  56503. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56504. }
  56505. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56506. {
  56507. return false;
  56508. }
  56509. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56510. {
  56511. }
  56512. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56513. {
  56514. }
  56515. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56516. {
  56517. }
  56518. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56519. {
  56520. return true;
  56521. }
  56522. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56523. {
  56524. }
  56525. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56526. {
  56527. }
  56528. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56529. {
  56530. }
  56531. END_JUCE_NAMESPACE
  56532. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56533. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56534. BEGIN_JUCE_NAMESPACE
  56535. class MouseCursor::SharedCursorHandle
  56536. {
  56537. public:
  56538. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56539. : handle (createStandardMouseCursor (type)),
  56540. refCount (1),
  56541. standardType (type),
  56542. isStandard (true)
  56543. {
  56544. }
  56545. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56546. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56547. refCount (1),
  56548. standardType (MouseCursor::NormalCursor),
  56549. isStandard (false)
  56550. {
  56551. }
  56552. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56553. {
  56554. const ScopedLock sl (getLock());
  56555. for (int i = 0; i < getCursors().size(); ++i)
  56556. {
  56557. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56558. if (sc->standardType == type)
  56559. return sc->retain();
  56560. }
  56561. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56562. getCursors().add (sc);
  56563. return sc;
  56564. }
  56565. SharedCursorHandle* retain() throw()
  56566. {
  56567. ++refCount;
  56568. return this;
  56569. }
  56570. void release()
  56571. {
  56572. if (--refCount == 0)
  56573. {
  56574. if (isStandard)
  56575. {
  56576. const ScopedLock sl (getLock());
  56577. getCursors().removeValue (this);
  56578. }
  56579. delete this;
  56580. }
  56581. }
  56582. void* getHandle() const throw() { return handle; }
  56583. juce_UseDebuggingNewOperator
  56584. private:
  56585. void* const handle;
  56586. Atomic <int> refCount;
  56587. const MouseCursor::StandardCursorType standardType;
  56588. const bool isStandard;
  56589. static CriticalSection& getLock()
  56590. {
  56591. static CriticalSection lock;
  56592. return lock;
  56593. }
  56594. static Array <SharedCursorHandle*>& getCursors()
  56595. {
  56596. static Array <SharedCursorHandle*> cursors;
  56597. return cursors;
  56598. }
  56599. ~SharedCursorHandle()
  56600. {
  56601. deleteMouseCursor (handle, isStandard);
  56602. }
  56603. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56604. };
  56605. MouseCursor::MouseCursor()
  56606. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56607. {
  56608. jassert (cursorHandle != 0);
  56609. }
  56610. MouseCursor::MouseCursor (const StandardCursorType type)
  56611. : cursorHandle (SharedCursorHandle::createStandard (type))
  56612. {
  56613. jassert (cursorHandle != 0);
  56614. }
  56615. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56616. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56617. {
  56618. }
  56619. MouseCursor::MouseCursor (const MouseCursor& other)
  56620. : cursorHandle (other.cursorHandle->retain())
  56621. {
  56622. }
  56623. MouseCursor::~MouseCursor()
  56624. {
  56625. cursorHandle->release();
  56626. }
  56627. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56628. {
  56629. other.cursorHandle->retain();
  56630. cursorHandle->release();
  56631. cursorHandle = other.cursorHandle;
  56632. return *this;
  56633. }
  56634. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56635. {
  56636. return getHandle() == other.getHandle();
  56637. }
  56638. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56639. {
  56640. return getHandle() != other.getHandle();
  56641. }
  56642. void* MouseCursor::getHandle() const throw()
  56643. {
  56644. return cursorHandle->getHandle();
  56645. }
  56646. void MouseCursor::showWaitCursor()
  56647. {
  56648. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56649. }
  56650. void MouseCursor::hideWaitCursor()
  56651. {
  56652. Desktop::getInstance().getMainMouseSource().revealCursor();
  56653. }
  56654. END_JUCE_NAMESPACE
  56655. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56656. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56657. BEGIN_JUCE_NAMESPACE
  56658. MouseEvent::MouseEvent (MouseInputSource& source_,
  56659. const Point<int>& position,
  56660. const ModifierKeys& mods_,
  56661. Component* const eventComponent_,
  56662. Component* const originator,
  56663. const Time& eventTime_,
  56664. const Point<int> mouseDownPos_,
  56665. const Time& mouseDownTime_,
  56666. const int numberOfClicks_,
  56667. const bool mouseWasDragged) throw()
  56668. : x (position.getX()),
  56669. y (position.getY()),
  56670. mods (mods_),
  56671. eventComponent (eventComponent_),
  56672. originalComponent (originator),
  56673. eventTime (eventTime_),
  56674. source (source_),
  56675. mouseDownPos (mouseDownPos_),
  56676. mouseDownTime (mouseDownTime_),
  56677. numberOfClicks (numberOfClicks_),
  56678. wasMovedSinceMouseDown (mouseWasDragged)
  56679. {
  56680. }
  56681. MouseEvent::~MouseEvent() throw()
  56682. {
  56683. }
  56684. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56685. {
  56686. if (otherComponent == 0)
  56687. {
  56688. jassertfalse;
  56689. return *this;
  56690. }
  56691. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56692. mods, otherComponent, originalComponent, eventTime,
  56693. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56694. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56695. }
  56696. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56697. {
  56698. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  56699. eventTime, mouseDownPos, mouseDownTime,
  56700. numberOfClicks, wasMovedSinceMouseDown);
  56701. }
  56702. bool MouseEvent::mouseWasClicked() const throw()
  56703. {
  56704. return ! wasMovedSinceMouseDown;
  56705. }
  56706. int MouseEvent::getMouseDownX() const throw()
  56707. {
  56708. return mouseDownPos.getX();
  56709. }
  56710. int MouseEvent::getMouseDownY() const throw()
  56711. {
  56712. return mouseDownPos.getY();
  56713. }
  56714. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56715. {
  56716. return mouseDownPos;
  56717. }
  56718. int MouseEvent::getDistanceFromDragStartX() const throw()
  56719. {
  56720. return x - mouseDownPos.getX();
  56721. }
  56722. int MouseEvent::getDistanceFromDragStartY() const throw()
  56723. {
  56724. return y - mouseDownPos.getY();
  56725. }
  56726. int MouseEvent::getDistanceFromDragStart() const throw()
  56727. {
  56728. return mouseDownPos.getDistanceFrom (getPosition());
  56729. }
  56730. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56731. {
  56732. return getPosition() - mouseDownPos;
  56733. }
  56734. int MouseEvent::getLengthOfMousePress() const throw()
  56735. {
  56736. if (mouseDownTime.toMilliseconds() > 0)
  56737. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56738. return 0;
  56739. }
  56740. const Point<int> MouseEvent::getPosition() const throw()
  56741. {
  56742. return Point<int> (x, y);
  56743. }
  56744. int MouseEvent::getScreenX() const
  56745. {
  56746. return getScreenPosition().getX();
  56747. }
  56748. int MouseEvent::getScreenY() const
  56749. {
  56750. return getScreenPosition().getY();
  56751. }
  56752. const Point<int> MouseEvent::getScreenPosition() const
  56753. {
  56754. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56755. }
  56756. int MouseEvent::getMouseDownScreenX() const
  56757. {
  56758. return getMouseDownScreenPosition().getX();
  56759. }
  56760. int MouseEvent::getMouseDownScreenY() const
  56761. {
  56762. return getMouseDownScreenPosition().getY();
  56763. }
  56764. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56765. {
  56766. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56767. }
  56768. int MouseEvent::doubleClickTimeOutMs = 400;
  56769. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56770. {
  56771. doubleClickTimeOutMs = newTime;
  56772. }
  56773. int MouseEvent::getDoubleClickTimeout() throw()
  56774. {
  56775. return doubleClickTimeOutMs;
  56776. }
  56777. END_JUCE_NAMESPACE
  56778. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56779. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56780. BEGIN_JUCE_NAMESPACE
  56781. class MouseInputSourceInternal : public AsyncUpdater
  56782. {
  56783. public:
  56784. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56785. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56786. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56787. mouseEventCounter (0)
  56788. {
  56789. zerostruct (mouseDowns);
  56790. }
  56791. ~MouseInputSourceInternal()
  56792. {
  56793. }
  56794. bool isDragging() const throw()
  56795. {
  56796. return buttonState.isAnyMouseButtonDown();
  56797. }
  56798. Component* getComponentUnderMouse() const
  56799. {
  56800. return static_cast <Component*> (componentUnderMouse);
  56801. }
  56802. const ModifierKeys getCurrentModifiers() const
  56803. {
  56804. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56805. }
  56806. ComponentPeer* getPeer()
  56807. {
  56808. if (! ComponentPeer::isValidPeer (lastPeer))
  56809. lastPeer = 0;
  56810. return lastPeer;
  56811. }
  56812. Component* findComponentAt (const Point<int>& screenPos)
  56813. {
  56814. ComponentPeer* const peer = getPeer();
  56815. if (peer != 0)
  56816. {
  56817. Component* const comp = peer->getComponent();
  56818. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56819. // (the contains() call is needed to test for overlapping desktop windows)
  56820. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56821. return comp->getComponentAt (relativePos);
  56822. }
  56823. return 0;
  56824. }
  56825. const Point<int> getScreenPosition() const throw()
  56826. {
  56827. return lastScreenPos + unboundedMouseOffset;
  56828. }
  56829. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56830. {
  56831. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56832. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56833. }
  56834. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56835. {
  56836. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56837. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56838. }
  56839. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56840. {
  56841. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56842. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56843. }
  56844. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56845. {
  56846. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56847. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56848. }
  56849. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56850. {
  56851. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56852. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56853. }
  56854. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56855. {
  56856. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56857. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56858. }
  56859. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56860. {
  56861. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56862. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56863. }
  56864. // (returns true if the button change caused a modal event loop)
  56865. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56866. {
  56867. if (buttonState == newButtonState)
  56868. return false;
  56869. setScreenPos (screenPos, time, false);
  56870. // (ignore secondary clicks when there's already a button down)
  56871. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56872. {
  56873. buttonState = newButtonState;
  56874. return false;
  56875. }
  56876. const int lastCounter = mouseEventCounter;
  56877. if (buttonState.isAnyMouseButtonDown())
  56878. {
  56879. Component* const current = getComponentUnderMouse();
  56880. if (current != 0)
  56881. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56882. enableUnboundedMouseMovement (false, false);
  56883. }
  56884. buttonState = newButtonState;
  56885. if (buttonState.isAnyMouseButtonDown())
  56886. {
  56887. Desktop::getInstance().incrementMouseClickCounter();
  56888. Component* const current = getComponentUnderMouse();
  56889. if (current != 0)
  56890. {
  56891. registerMouseDown (screenPos, time, current);
  56892. sendMouseDown (current, screenPos, time);
  56893. }
  56894. }
  56895. return lastCounter != mouseEventCounter;
  56896. }
  56897. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56898. {
  56899. Component* current = getComponentUnderMouse();
  56900. if (newComponent != current)
  56901. {
  56902. Component::SafePointer<Component> safeNewComp (newComponent);
  56903. const ModifierKeys originalButtonState (buttonState);
  56904. if (current != 0)
  56905. {
  56906. setButtons (screenPos, time, ModifierKeys());
  56907. sendMouseExit (current, screenPos, time);
  56908. buttonState = originalButtonState;
  56909. }
  56910. componentUnderMouse = safeNewComp;
  56911. current = getComponentUnderMouse();
  56912. if (current != 0)
  56913. sendMouseEnter (current, screenPos, time);
  56914. revealCursor (false);
  56915. setButtons (screenPos, time, originalButtonState);
  56916. }
  56917. }
  56918. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56919. {
  56920. ModifierKeys::updateCurrentModifiers();
  56921. if (newPeer != lastPeer)
  56922. {
  56923. setComponentUnderMouse (0, screenPos, time);
  56924. lastPeer = newPeer;
  56925. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56926. }
  56927. }
  56928. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56929. {
  56930. if (! isDragging())
  56931. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56932. if (newScreenPos != lastScreenPos || forceUpdate)
  56933. {
  56934. cancelPendingUpdate();
  56935. lastScreenPos = newScreenPos;
  56936. Component* const current = getComponentUnderMouse();
  56937. if (current != 0)
  56938. {
  56939. if (isDragging())
  56940. {
  56941. registerMouseDrag (newScreenPos);
  56942. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56943. if (isUnboundedMouseModeOn)
  56944. handleUnboundedDrag (current);
  56945. }
  56946. else
  56947. {
  56948. sendMouseMove (current, newScreenPos, time);
  56949. }
  56950. }
  56951. revealCursor (false);
  56952. }
  56953. }
  56954. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56955. {
  56956. jassert (newPeer != 0);
  56957. lastTime = time;
  56958. ++mouseEventCounter;
  56959. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56960. if (isDragging() && newMods.isAnyMouseButtonDown())
  56961. {
  56962. setScreenPos (screenPos, time, false);
  56963. }
  56964. else
  56965. {
  56966. setPeer (newPeer, screenPos, time);
  56967. ComponentPeer* peer = getPeer();
  56968. if (peer != 0)
  56969. {
  56970. if (setButtons (screenPos, time, newMods))
  56971. return; // some modal events have been dispatched, so the current event is now out-of-date
  56972. peer = getPeer();
  56973. if (peer != 0)
  56974. setScreenPos (screenPos, time, false);
  56975. }
  56976. }
  56977. }
  56978. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56979. {
  56980. jassert (peer != 0);
  56981. lastTime = time;
  56982. ++mouseEventCounter;
  56983. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56984. setPeer (peer, screenPos, time);
  56985. setScreenPos (screenPos, time, false);
  56986. triggerFakeMove();
  56987. if (! isDragging())
  56988. {
  56989. Component* current = getComponentUnderMouse();
  56990. if (current != 0)
  56991. sendMouseWheel (current, screenPos, time, x, y);
  56992. }
  56993. }
  56994. const Time getLastMouseDownTime() const throw()
  56995. {
  56996. return Time (mouseDowns[0].time);
  56997. }
  56998. const Point<int> getLastMouseDownPosition() const throw()
  56999. {
  57000. return mouseDowns[0].position;
  57001. }
  57002. int getNumberOfMultipleClicks() const throw()
  57003. {
  57004. int numClicks = 0;
  57005. if (mouseDowns[0].time != 0)
  57006. {
  57007. if (! mouseMovedSignificantlySincePressed)
  57008. ++numClicks;
  57009. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57010. {
  57011. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57012. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57013. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57014. {
  57015. ++numClicks;
  57016. }
  57017. else
  57018. {
  57019. break;
  57020. }
  57021. }
  57022. }
  57023. return numClicks;
  57024. }
  57025. bool hasMouseMovedSignificantlySincePressed() const throw()
  57026. {
  57027. return mouseMovedSignificantlySincePressed
  57028. || lastTime > mouseDowns[0].time + 300;
  57029. }
  57030. void triggerFakeMove()
  57031. {
  57032. triggerAsyncUpdate();
  57033. }
  57034. void handleAsyncUpdate()
  57035. {
  57036. if (! isDragging())
  57037. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  57038. }
  57039. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57040. {
  57041. enable = enable && isDragging();
  57042. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57043. if (enable != isUnboundedMouseModeOn)
  57044. {
  57045. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57046. {
  57047. // when released, return the mouse to within the component's bounds
  57048. Component* current = getComponentUnderMouse();
  57049. if (current != 0)
  57050. Desktop::setMousePosition (current->getScreenBounds()
  57051. .getConstrainedPoint (current->getMouseXYRelative()));
  57052. }
  57053. isUnboundedMouseModeOn = enable;
  57054. unboundedMouseOffset = Point<int>();
  57055. revealCursor (true);
  57056. }
  57057. }
  57058. void handleUnboundedDrag (Component* current)
  57059. {
  57060. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57061. if (! screenArea.contains (lastScreenPos))
  57062. {
  57063. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57064. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57065. Desktop::setMousePosition (componentCentre);
  57066. }
  57067. else if (isCursorVisibleUntilOffscreen
  57068. && (! unboundedMouseOffset.isOrigin())
  57069. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57070. {
  57071. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57072. unboundedMouseOffset = Point<int>();
  57073. }
  57074. }
  57075. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57076. {
  57077. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57078. {
  57079. cursor = MouseCursor::NoCursor;
  57080. forcedUpdate = true;
  57081. }
  57082. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57083. {
  57084. currentCursorHandle = cursor.getHandle();
  57085. cursor.showInWindow (getPeer());
  57086. }
  57087. }
  57088. void hideCursor()
  57089. {
  57090. showMouseCursor (MouseCursor::NoCursor, true);
  57091. }
  57092. void revealCursor (bool forcedUpdate)
  57093. {
  57094. MouseCursor mc (MouseCursor::NormalCursor);
  57095. Component* current = getComponentUnderMouse();
  57096. if (current != 0)
  57097. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57098. showMouseCursor (mc, forcedUpdate);
  57099. }
  57100. int index;
  57101. bool isMouseDevice;
  57102. Point<int> lastScreenPos;
  57103. ModifierKeys buttonState;
  57104. private:
  57105. MouseInputSource& source;
  57106. Component::SafePointer<Component> componentUnderMouse;
  57107. ComponentPeer* lastPeer;
  57108. Point<int> unboundedMouseOffset;
  57109. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57110. void* currentCursorHandle;
  57111. int mouseEventCounter;
  57112. struct RecentMouseDown
  57113. {
  57114. Point<int> position;
  57115. int64 time;
  57116. Component* component;
  57117. };
  57118. RecentMouseDown mouseDowns[4];
  57119. bool mouseMovedSignificantlySincePressed;
  57120. int64 lastTime;
  57121. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57122. {
  57123. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57124. mouseDowns[i] = mouseDowns[i - 1];
  57125. mouseDowns[0].position = screenPos;
  57126. mouseDowns[0].time = time;
  57127. mouseDowns[0].component = component;
  57128. mouseMovedSignificantlySincePressed = false;
  57129. }
  57130. void registerMouseDrag (const Point<int>& screenPos) throw()
  57131. {
  57132. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57133. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57134. }
  57135. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57136. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57137. };
  57138. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57139. {
  57140. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57141. }
  57142. MouseInputSource::~MouseInputSource()
  57143. {
  57144. }
  57145. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57146. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57147. bool MouseInputSource::canHover() const { return isMouse(); }
  57148. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57149. int MouseInputSource::getIndex() const { return pimpl->index; }
  57150. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57151. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57152. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57153. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57154. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57155. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57156. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57157. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57158. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57159. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57160. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57161. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57162. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57163. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57164. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57165. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57166. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57167. {
  57168. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57169. }
  57170. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57171. {
  57172. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57173. }
  57174. END_JUCE_NAMESPACE
  57175. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57176. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57177. BEGIN_JUCE_NAMESPACE
  57178. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57179. : source (0),
  57180. hoverTimeMillisecs (hoverTimeMillisecs_),
  57181. hasJustHovered (false)
  57182. {
  57183. internalTimer.owner = this;
  57184. }
  57185. MouseHoverDetector::~MouseHoverDetector()
  57186. {
  57187. setHoverComponent (0);
  57188. }
  57189. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57190. {
  57191. hoverTimeMillisecs = newTimeInMillisecs;
  57192. }
  57193. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57194. {
  57195. if (source != newSourceComponent)
  57196. {
  57197. internalTimer.stopTimer();
  57198. hasJustHovered = false;
  57199. if (source != 0)
  57200. {
  57201. // ! you need to delete the hover detector before deleting its component
  57202. jassert (source->isValidComponent());
  57203. source->removeMouseListener (&internalTimer);
  57204. }
  57205. source = newSourceComponent;
  57206. if (newSourceComponent != 0)
  57207. newSourceComponent->addMouseListener (&internalTimer, false);
  57208. }
  57209. }
  57210. void MouseHoverDetector::hoverTimerCallback()
  57211. {
  57212. internalTimer.stopTimer();
  57213. if (source != 0)
  57214. {
  57215. const Point<int> pos (source->getMouseXYRelative());
  57216. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57217. {
  57218. hasJustHovered = true;
  57219. mouseHovered (pos.getX(), pos.getY());
  57220. }
  57221. }
  57222. }
  57223. void MouseHoverDetector::checkJustHoveredCallback()
  57224. {
  57225. if (hasJustHovered)
  57226. {
  57227. hasJustHovered = false;
  57228. mouseMovedAfterHover();
  57229. }
  57230. }
  57231. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57232. {
  57233. owner->hoverTimerCallback();
  57234. }
  57235. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57236. {
  57237. stopTimer();
  57238. owner->checkJustHoveredCallback();
  57239. }
  57240. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57241. {
  57242. stopTimer();
  57243. owner->checkJustHoveredCallback();
  57244. }
  57245. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57246. {
  57247. stopTimer();
  57248. owner->checkJustHoveredCallback();
  57249. }
  57250. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57251. {
  57252. stopTimer();
  57253. owner->checkJustHoveredCallback();
  57254. }
  57255. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57256. {
  57257. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57258. {
  57259. lastX = e.x;
  57260. lastY = e.y;
  57261. if (owner->source != 0)
  57262. startTimer (owner->hoverTimeMillisecs);
  57263. owner->checkJustHoveredCallback();
  57264. }
  57265. }
  57266. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57267. {
  57268. stopTimer();
  57269. owner->checkJustHoveredCallback();
  57270. }
  57271. END_JUCE_NAMESPACE
  57272. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57273. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57274. BEGIN_JUCE_NAMESPACE
  57275. void MouseListener::mouseEnter (const MouseEvent&)
  57276. {
  57277. }
  57278. void MouseListener::mouseExit (const MouseEvent&)
  57279. {
  57280. }
  57281. void MouseListener::mouseDown (const MouseEvent&)
  57282. {
  57283. }
  57284. void MouseListener::mouseUp (const MouseEvent&)
  57285. {
  57286. }
  57287. void MouseListener::mouseDrag (const MouseEvent&)
  57288. {
  57289. }
  57290. void MouseListener::mouseMove (const MouseEvent&)
  57291. {
  57292. }
  57293. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57294. {
  57295. }
  57296. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57297. {
  57298. }
  57299. END_JUCE_NAMESPACE
  57300. /*** End of inlined file: juce_MouseListener.cpp ***/
  57301. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57302. BEGIN_JUCE_NAMESPACE
  57303. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57304. const String& buttonTextWhenTrue,
  57305. const String& buttonTextWhenFalse)
  57306. : PropertyComponent (name),
  57307. onText (buttonTextWhenTrue),
  57308. offText (buttonTextWhenFalse)
  57309. {
  57310. addAndMakeVisible (&button);
  57311. button.setClickingTogglesState (false);
  57312. button.addButtonListener (this);
  57313. }
  57314. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57315. const String& name,
  57316. const String& buttonText)
  57317. : PropertyComponent (name),
  57318. onText (buttonText),
  57319. offText (buttonText)
  57320. {
  57321. addAndMakeVisible (&button);
  57322. button.setClickingTogglesState (false);
  57323. button.setButtonText (buttonText);
  57324. button.getToggleStateValue().referTo (valueToControl);
  57325. button.setClickingTogglesState (true);
  57326. }
  57327. BooleanPropertyComponent::~BooleanPropertyComponent()
  57328. {
  57329. }
  57330. void BooleanPropertyComponent::setState (const bool newState)
  57331. {
  57332. button.setToggleState (newState, true);
  57333. }
  57334. bool BooleanPropertyComponent::getState() const
  57335. {
  57336. return button.getToggleState();
  57337. }
  57338. void BooleanPropertyComponent::paint (Graphics& g)
  57339. {
  57340. PropertyComponent::paint (g);
  57341. g.setColour (Colours::white);
  57342. g.fillRect (button.getBounds());
  57343. g.setColour (findColour (ComboBox::outlineColourId));
  57344. g.drawRect (button.getBounds());
  57345. }
  57346. void BooleanPropertyComponent::refresh()
  57347. {
  57348. button.setToggleState (getState(), false);
  57349. button.setButtonText (button.getToggleState() ? onText : offText);
  57350. }
  57351. void BooleanPropertyComponent::buttonClicked (Button*)
  57352. {
  57353. setState (! getState());
  57354. }
  57355. END_JUCE_NAMESPACE
  57356. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57357. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57358. BEGIN_JUCE_NAMESPACE
  57359. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57360. const bool triggerOnMouseDown)
  57361. : PropertyComponent (name)
  57362. {
  57363. addAndMakeVisible (&button);
  57364. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57365. button.addButtonListener (this);
  57366. }
  57367. ButtonPropertyComponent::~ButtonPropertyComponent()
  57368. {
  57369. }
  57370. void ButtonPropertyComponent::refresh()
  57371. {
  57372. button.setButtonText (getButtonText());
  57373. }
  57374. void ButtonPropertyComponent::buttonClicked (Button*)
  57375. {
  57376. buttonClicked();
  57377. }
  57378. END_JUCE_NAMESPACE
  57379. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57380. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57381. BEGIN_JUCE_NAMESPACE
  57382. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57383. public Value::Listener
  57384. {
  57385. public:
  57386. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57387. : sourceValue (sourceValue_),
  57388. mappings (mappings_)
  57389. {
  57390. sourceValue.addListener (this);
  57391. }
  57392. ~RemapperValueSource() {}
  57393. const var getValue() const
  57394. {
  57395. return mappings.indexOf (sourceValue.getValue()) + 1;
  57396. }
  57397. void setValue (const var& newValue)
  57398. {
  57399. const var remappedVal (mappings [(int) newValue - 1]);
  57400. if (remappedVal != sourceValue)
  57401. sourceValue = remappedVal;
  57402. }
  57403. void valueChanged (Value&)
  57404. {
  57405. sendChangeMessage (true);
  57406. }
  57407. juce_UseDebuggingNewOperator
  57408. protected:
  57409. Value sourceValue;
  57410. Array<var> mappings;
  57411. RemapperValueSource (const RemapperValueSource&);
  57412. const RemapperValueSource& operator= (const RemapperValueSource&);
  57413. };
  57414. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57415. : PropertyComponent (name),
  57416. isCustomClass (true)
  57417. {
  57418. }
  57419. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57420. const String& name,
  57421. const StringArray& choices_,
  57422. const Array <var>& correspondingValues)
  57423. : PropertyComponent (name),
  57424. choices (choices_),
  57425. isCustomClass (false)
  57426. {
  57427. // The array of corresponding values must contain one value for each of the items in
  57428. // the choices array!
  57429. jassert (correspondingValues.size() == choices.size());
  57430. createComboBox();
  57431. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57432. }
  57433. ChoicePropertyComponent::~ChoicePropertyComponent()
  57434. {
  57435. }
  57436. void ChoicePropertyComponent::createComboBox()
  57437. {
  57438. addAndMakeVisible (&comboBox);
  57439. for (int i = 0; i < choices.size(); ++i)
  57440. {
  57441. if (choices[i].isNotEmpty())
  57442. comboBox.addItem (choices[i], i + 1);
  57443. else
  57444. comboBox.addSeparator();
  57445. }
  57446. comboBox.setEditableText (false);
  57447. }
  57448. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57449. {
  57450. jassertfalse; // you need to override this method in your subclass!
  57451. }
  57452. int ChoicePropertyComponent::getIndex() const
  57453. {
  57454. jassertfalse; // you need to override this method in your subclass!
  57455. return -1;
  57456. }
  57457. const StringArray& ChoicePropertyComponent::getChoices() const
  57458. {
  57459. return choices;
  57460. }
  57461. void ChoicePropertyComponent::refresh()
  57462. {
  57463. if (isCustomClass)
  57464. {
  57465. if (! comboBox.isVisible())
  57466. {
  57467. createComboBox();
  57468. comboBox.addListener (this);
  57469. }
  57470. comboBox.setSelectedId (getIndex() + 1, true);
  57471. }
  57472. }
  57473. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57474. {
  57475. if (isCustomClass)
  57476. {
  57477. const int newIndex = comboBox.getSelectedId() - 1;
  57478. if (newIndex != getIndex())
  57479. setIndex (newIndex);
  57480. }
  57481. }
  57482. END_JUCE_NAMESPACE
  57483. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57484. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57485. BEGIN_JUCE_NAMESPACE
  57486. PropertyComponent::PropertyComponent (const String& name,
  57487. const int preferredHeight_)
  57488. : Component (name),
  57489. preferredHeight (preferredHeight_)
  57490. {
  57491. jassert (name.isNotEmpty());
  57492. }
  57493. PropertyComponent::~PropertyComponent()
  57494. {
  57495. }
  57496. void PropertyComponent::paint (Graphics& g)
  57497. {
  57498. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57499. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57500. }
  57501. void PropertyComponent::resized()
  57502. {
  57503. if (getNumChildComponents() > 0)
  57504. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57505. }
  57506. void PropertyComponent::enablementChanged()
  57507. {
  57508. repaint();
  57509. }
  57510. END_JUCE_NAMESPACE
  57511. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57512. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57513. BEGIN_JUCE_NAMESPACE
  57514. class PropertyPanel::PropertyHolderComponent : public Component
  57515. {
  57516. public:
  57517. PropertyHolderComponent()
  57518. {
  57519. }
  57520. ~PropertyHolderComponent()
  57521. {
  57522. deleteAllChildren();
  57523. }
  57524. void paint (Graphics&)
  57525. {
  57526. }
  57527. void updateLayout (int width);
  57528. void refreshAll() const;
  57529. private:
  57530. PropertyHolderComponent (const PropertyHolderComponent&);
  57531. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57532. };
  57533. class PropertySectionComponent : public Component
  57534. {
  57535. public:
  57536. PropertySectionComponent (const String& sectionTitle,
  57537. const Array <PropertyComponent*>& newProperties,
  57538. const bool open)
  57539. : Component (sectionTitle),
  57540. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57541. isOpen_ (open)
  57542. {
  57543. for (int i = newProperties.size(); --i >= 0;)
  57544. {
  57545. addAndMakeVisible (newProperties.getUnchecked(i));
  57546. newProperties.getUnchecked(i)->refresh();
  57547. }
  57548. }
  57549. ~PropertySectionComponent()
  57550. {
  57551. deleteAllChildren();
  57552. }
  57553. void paint (Graphics& g)
  57554. {
  57555. if (titleHeight > 0)
  57556. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57557. }
  57558. void resized()
  57559. {
  57560. int y = titleHeight;
  57561. for (int i = getNumChildComponents(); --i >= 0;)
  57562. {
  57563. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57564. if (pec != 0)
  57565. {
  57566. const int prefH = pec->getPreferredHeight();
  57567. pec->setBounds (1, y, getWidth() - 2, prefH);
  57568. y += prefH;
  57569. }
  57570. }
  57571. }
  57572. int getPreferredHeight() const
  57573. {
  57574. int y = titleHeight;
  57575. if (isOpen())
  57576. {
  57577. for (int i = 0; i < getNumChildComponents(); ++i)
  57578. {
  57579. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57580. if (pec != 0)
  57581. y += pec->getPreferredHeight();
  57582. }
  57583. }
  57584. return y;
  57585. }
  57586. void setOpen (const bool open)
  57587. {
  57588. if (isOpen_ != open)
  57589. {
  57590. isOpen_ = open;
  57591. for (int i = 0; i < getNumChildComponents(); ++i)
  57592. {
  57593. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57594. if (pec != 0)
  57595. pec->setVisible (open);
  57596. }
  57597. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57598. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57599. if (pp != 0)
  57600. pp->resized();
  57601. }
  57602. }
  57603. bool isOpen() const
  57604. {
  57605. return isOpen_;
  57606. }
  57607. void refreshAll() const
  57608. {
  57609. for (int i = 0; i < getNumChildComponents(); ++i)
  57610. {
  57611. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57612. if (pec != 0)
  57613. pec->refresh();
  57614. }
  57615. }
  57616. void mouseDown (const MouseEvent&)
  57617. {
  57618. }
  57619. void mouseUp (const MouseEvent& e)
  57620. {
  57621. if (e.getMouseDownX() < titleHeight
  57622. && e.x < titleHeight
  57623. && e.y < titleHeight
  57624. && e.getNumberOfClicks() != 2)
  57625. {
  57626. setOpen (! isOpen());
  57627. }
  57628. }
  57629. void mouseDoubleClick (const MouseEvent& e)
  57630. {
  57631. if (e.y < titleHeight)
  57632. setOpen (! isOpen());
  57633. }
  57634. private:
  57635. int titleHeight;
  57636. bool isOpen_;
  57637. PropertySectionComponent (const PropertySectionComponent&);
  57638. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57639. };
  57640. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57641. {
  57642. int y = 0;
  57643. for (int i = getNumChildComponents(); --i >= 0;)
  57644. {
  57645. PropertySectionComponent* const section
  57646. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57647. if (section != 0)
  57648. {
  57649. const int prefH = section->getPreferredHeight();
  57650. section->setBounds (0, y, width, prefH);
  57651. y += prefH;
  57652. }
  57653. }
  57654. setSize (width, y);
  57655. repaint();
  57656. }
  57657. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57658. {
  57659. for (int i = getNumChildComponents(); --i >= 0;)
  57660. {
  57661. PropertySectionComponent* const section
  57662. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57663. if (section != 0)
  57664. section->refreshAll();
  57665. }
  57666. }
  57667. PropertyPanel::PropertyPanel()
  57668. {
  57669. messageWhenEmpty = TRANS("(nothing selected)");
  57670. addAndMakeVisible (&viewport);
  57671. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57672. viewport.setFocusContainer (true);
  57673. }
  57674. PropertyPanel::~PropertyPanel()
  57675. {
  57676. clear();
  57677. }
  57678. void PropertyPanel::paint (Graphics& g)
  57679. {
  57680. if (propertyHolderComponent->getNumChildComponents() == 0)
  57681. {
  57682. g.setColour (Colours::black.withAlpha (0.5f));
  57683. g.setFont (14.0f);
  57684. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57685. Justification::centred, true);
  57686. }
  57687. }
  57688. void PropertyPanel::resized()
  57689. {
  57690. viewport.setBounds (getLocalBounds());
  57691. updatePropHolderLayout();
  57692. }
  57693. void PropertyPanel::clear()
  57694. {
  57695. if (propertyHolderComponent->getNumChildComponents() > 0)
  57696. {
  57697. propertyHolderComponent->deleteAllChildren();
  57698. repaint();
  57699. }
  57700. }
  57701. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57702. {
  57703. if (propertyHolderComponent->getNumChildComponents() == 0)
  57704. repaint();
  57705. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57706. newProperties,
  57707. true), 0);
  57708. updatePropHolderLayout();
  57709. }
  57710. void PropertyPanel::addSection (const String& sectionTitle,
  57711. const Array <PropertyComponent*>& newProperties,
  57712. const bool shouldBeOpen)
  57713. {
  57714. jassert (sectionTitle.isNotEmpty());
  57715. if (propertyHolderComponent->getNumChildComponents() == 0)
  57716. repaint();
  57717. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57718. newProperties,
  57719. shouldBeOpen), 0);
  57720. updatePropHolderLayout();
  57721. }
  57722. void PropertyPanel::updatePropHolderLayout() const
  57723. {
  57724. const int maxWidth = viewport.getMaximumVisibleWidth();
  57725. propertyHolderComponent->updateLayout (maxWidth);
  57726. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  57727. if (maxWidth != newMaxWidth)
  57728. {
  57729. // need to do this twice because of scrollbars changing the size, etc.
  57730. propertyHolderComponent->updateLayout (newMaxWidth);
  57731. }
  57732. }
  57733. void PropertyPanel::refreshAll() const
  57734. {
  57735. propertyHolderComponent->refreshAll();
  57736. }
  57737. const StringArray PropertyPanel::getSectionNames() const
  57738. {
  57739. StringArray s;
  57740. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57741. {
  57742. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57743. if (section != 0 && section->getName().isNotEmpty())
  57744. s.add (section->getName());
  57745. }
  57746. return s;
  57747. }
  57748. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57749. {
  57750. int index = 0;
  57751. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57752. {
  57753. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57754. if (section != 0 && section->getName().isNotEmpty())
  57755. {
  57756. if (index == sectionIndex)
  57757. return section->isOpen();
  57758. ++index;
  57759. }
  57760. }
  57761. return false;
  57762. }
  57763. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57764. {
  57765. int index = 0;
  57766. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57767. {
  57768. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57769. if (section != 0 && section->getName().isNotEmpty())
  57770. {
  57771. if (index == sectionIndex)
  57772. {
  57773. section->setOpen (shouldBeOpen);
  57774. break;
  57775. }
  57776. ++index;
  57777. }
  57778. }
  57779. }
  57780. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57781. {
  57782. int index = 0;
  57783. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57784. {
  57785. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57786. if (section != 0 && section->getName().isNotEmpty())
  57787. {
  57788. if (index == sectionIndex)
  57789. {
  57790. section->setEnabled (shouldBeEnabled);
  57791. break;
  57792. }
  57793. ++index;
  57794. }
  57795. }
  57796. }
  57797. XmlElement* PropertyPanel::getOpennessState() const
  57798. {
  57799. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57800. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  57801. const StringArray sections (getSectionNames());
  57802. for (int i = 0; i < sections.size(); ++i)
  57803. {
  57804. if (sections[i].isNotEmpty())
  57805. {
  57806. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57807. e->setAttribute ("name", sections[i]);
  57808. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57809. }
  57810. }
  57811. return xml;
  57812. }
  57813. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57814. {
  57815. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57816. {
  57817. const StringArray sections (getSectionNames());
  57818. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57819. {
  57820. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57821. e->getBoolAttribute ("open"));
  57822. }
  57823. viewport.setViewPosition (viewport.getViewPositionX(),
  57824. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  57825. }
  57826. }
  57827. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57828. {
  57829. if (messageWhenEmpty != newMessage)
  57830. {
  57831. messageWhenEmpty = newMessage;
  57832. repaint();
  57833. }
  57834. }
  57835. const String& PropertyPanel::getMessageWhenEmpty() const
  57836. {
  57837. return messageWhenEmpty;
  57838. }
  57839. END_JUCE_NAMESPACE
  57840. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57841. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57842. BEGIN_JUCE_NAMESPACE
  57843. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57844. const double rangeMin,
  57845. const double rangeMax,
  57846. const double interval,
  57847. const double skewFactor)
  57848. : PropertyComponent (name)
  57849. {
  57850. addAndMakeVisible (&slider);
  57851. slider.setRange (rangeMin, rangeMax, interval);
  57852. slider.setSkewFactor (skewFactor);
  57853. slider.setSliderStyle (Slider::LinearBar);
  57854. slider.addListener (this);
  57855. }
  57856. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57857. const String& name,
  57858. const double rangeMin,
  57859. const double rangeMax,
  57860. const double interval,
  57861. const double skewFactor)
  57862. : PropertyComponent (name)
  57863. {
  57864. addAndMakeVisible (&slider);
  57865. slider.setRange (rangeMin, rangeMax, interval);
  57866. slider.setSkewFactor (skewFactor);
  57867. slider.setSliderStyle (Slider::LinearBar);
  57868. slider.getValueObject().referTo (valueToControl);
  57869. }
  57870. SliderPropertyComponent::~SliderPropertyComponent()
  57871. {
  57872. }
  57873. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57874. {
  57875. }
  57876. double SliderPropertyComponent::getValue() const
  57877. {
  57878. return slider.getValue();
  57879. }
  57880. void SliderPropertyComponent::refresh()
  57881. {
  57882. slider.setValue (getValue(), false);
  57883. }
  57884. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57885. {
  57886. if (getValue() != slider.getValue())
  57887. setValue (slider.getValue());
  57888. }
  57889. END_JUCE_NAMESPACE
  57890. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57891. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57892. BEGIN_JUCE_NAMESPACE
  57893. class TextPropLabel : public Label
  57894. {
  57895. TextPropertyComponent& owner;
  57896. int maxChars;
  57897. bool isMultiline;
  57898. public:
  57899. TextPropLabel (TextPropertyComponent& owner_,
  57900. const int maxChars_, const bool isMultiline_)
  57901. : Label (String::empty, String::empty),
  57902. owner (owner_),
  57903. maxChars (maxChars_),
  57904. isMultiline (isMultiline_)
  57905. {
  57906. setEditable (true, true, false);
  57907. setColour (backgroundColourId, Colours::white);
  57908. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57909. }
  57910. ~TextPropLabel()
  57911. {
  57912. }
  57913. TextEditor* createEditorComponent()
  57914. {
  57915. TextEditor* const textEditor = Label::createEditorComponent();
  57916. textEditor->setInputRestrictions (maxChars);
  57917. if (isMultiline)
  57918. {
  57919. textEditor->setMultiLine (true, true);
  57920. textEditor->setReturnKeyStartsNewLine (true);
  57921. }
  57922. return textEditor;
  57923. }
  57924. void textWasEdited()
  57925. {
  57926. owner.textWasEdited();
  57927. }
  57928. };
  57929. TextPropertyComponent::TextPropertyComponent (const String& name,
  57930. const int maxNumChars,
  57931. const bool isMultiLine)
  57932. : PropertyComponent (name)
  57933. {
  57934. createEditor (maxNumChars, isMultiLine);
  57935. }
  57936. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57937. const String& name,
  57938. const int maxNumChars,
  57939. const bool isMultiLine)
  57940. : PropertyComponent (name)
  57941. {
  57942. createEditor (maxNumChars, isMultiLine);
  57943. textEditor->getTextValue().referTo (valueToControl);
  57944. }
  57945. TextPropertyComponent::~TextPropertyComponent()
  57946. {
  57947. deleteAllChildren();
  57948. }
  57949. void TextPropertyComponent::setText (const String& newText)
  57950. {
  57951. textEditor->setText (newText, true);
  57952. }
  57953. const String TextPropertyComponent::getText() const
  57954. {
  57955. return textEditor->getText();
  57956. }
  57957. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57958. {
  57959. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57960. if (isMultiLine)
  57961. {
  57962. textEditor->setJustificationType (Justification::topLeft);
  57963. preferredHeight = 120;
  57964. }
  57965. }
  57966. void TextPropertyComponent::refresh()
  57967. {
  57968. textEditor->setText (getText(), false);
  57969. }
  57970. void TextPropertyComponent::textWasEdited()
  57971. {
  57972. const String newText (textEditor->getText());
  57973. if (getText() != newText)
  57974. setText (newText);
  57975. }
  57976. END_JUCE_NAMESPACE
  57977. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57978. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57979. BEGIN_JUCE_NAMESPACE
  57980. class SimpleDeviceManagerInputLevelMeter : public Component,
  57981. public Timer
  57982. {
  57983. public:
  57984. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57985. : manager (manager_),
  57986. level (0)
  57987. {
  57988. startTimer (50);
  57989. manager->enableInputLevelMeasurement (true);
  57990. }
  57991. ~SimpleDeviceManagerInputLevelMeter()
  57992. {
  57993. manager->enableInputLevelMeasurement (false);
  57994. }
  57995. void timerCallback()
  57996. {
  57997. const float newLevel = (float) manager->getCurrentInputLevel();
  57998. if (std::abs (level - newLevel) > 0.005f)
  57999. {
  58000. level = newLevel;
  58001. repaint();
  58002. }
  58003. }
  58004. void paint (Graphics& g)
  58005. {
  58006. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58007. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58008. }
  58009. private:
  58010. AudioDeviceManager* const manager;
  58011. float level;
  58012. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58013. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58014. };
  58015. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58016. public ListBoxModel
  58017. {
  58018. public:
  58019. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58020. const String& noItemsMessage_,
  58021. const int minNumber_,
  58022. const int maxNumber_)
  58023. : ListBox (String::empty, 0),
  58024. deviceManager (deviceManager_),
  58025. noItemsMessage (noItemsMessage_),
  58026. minNumber (minNumber_),
  58027. maxNumber (maxNumber_)
  58028. {
  58029. items = MidiInput::getDevices();
  58030. setModel (this);
  58031. setOutlineThickness (1);
  58032. }
  58033. ~MidiInputSelectorComponentListBox()
  58034. {
  58035. }
  58036. int getNumRows()
  58037. {
  58038. return items.size();
  58039. }
  58040. void paintListBoxItem (int row,
  58041. Graphics& g,
  58042. int width, int height,
  58043. bool rowIsSelected)
  58044. {
  58045. if (((unsigned int) row) < (unsigned int) items.size())
  58046. {
  58047. if (rowIsSelected)
  58048. g.fillAll (findColour (TextEditor::highlightColourId)
  58049. .withMultipliedAlpha (0.3f));
  58050. const String item (items [row]);
  58051. bool enabled = deviceManager.isMidiInputEnabled (item);
  58052. const int x = getTickX();
  58053. const float tickW = height * 0.75f;
  58054. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58055. enabled, true, true, false);
  58056. g.setFont (height * 0.6f);
  58057. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58058. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58059. }
  58060. }
  58061. void listBoxItemClicked (int row, const MouseEvent& e)
  58062. {
  58063. selectRow (row);
  58064. if (e.x < getTickX())
  58065. flipEnablement (row);
  58066. }
  58067. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58068. {
  58069. flipEnablement (row);
  58070. }
  58071. void returnKeyPressed (int row)
  58072. {
  58073. flipEnablement (row);
  58074. }
  58075. void paint (Graphics& g)
  58076. {
  58077. ListBox::paint (g);
  58078. if (items.size() == 0)
  58079. {
  58080. g.setColour (Colours::grey);
  58081. g.setFont (13.0f);
  58082. g.drawText (noItemsMessage,
  58083. 0, 0, getWidth(), getHeight() / 2,
  58084. Justification::centred, true);
  58085. }
  58086. }
  58087. int getBestHeight (const int preferredHeight)
  58088. {
  58089. const int extra = getOutlineThickness() * 2;
  58090. return jmax (getRowHeight() * 2 + extra,
  58091. jmin (getRowHeight() * getNumRows() + extra,
  58092. preferredHeight));
  58093. }
  58094. juce_UseDebuggingNewOperator
  58095. private:
  58096. AudioDeviceManager& deviceManager;
  58097. const String noItemsMessage;
  58098. StringArray items;
  58099. int minNumber, maxNumber;
  58100. void flipEnablement (const int row)
  58101. {
  58102. if (((unsigned int) row) < (unsigned int) items.size())
  58103. {
  58104. const String item (items [row]);
  58105. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58106. }
  58107. }
  58108. int getTickX() const
  58109. {
  58110. return getRowHeight() + 5;
  58111. }
  58112. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58113. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58114. };
  58115. class AudioDeviceSettingsPanel : public Component,
  58116. public ChangeListener,
  58117. public ComboBox::Listener,
  58118. public Button::Listener
  58119. {
  58120. public:
  58121. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58122. AudioIODeviceType::DeviceSetupDetails& setup_,
  58123. const bool hideAdvancedOptionsWithButton)
  58124. : type (type_),
  58125. setup (setup_)
  58126. {
  58127. if (hideAdvancedOptionsWithButton)
  58128. {
  58129. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58130. showAdvancedSettingsButton->addButtonListener (this);
  58131. }
  58132. type->scanForDevices();
  58133. setup.manager->addChangeListener (this);
  58134. changeListenerCallback (0);
  58135. }
  58136. ~AudioDeviceSettingsPanel()
  58137. {
  58138. setup.manager->removeChangeListener (this);
  58139. }
  58140. void resized()
  58141. {
  58142. const int lx = proportionOfWidth (0.35f);
  58143. const int w = proportionOfWidth (0.4f);
  58144. const int h = 24;
  58145. const int space = 6;
  58146. const int dh = h + space;
  58147. int y = 0;
  58148. if (outputDeviceDropDown != 0)
  58149. {
  58150. outputDeviceDropDown->setBounds (lx, y, w, h);
  58151. if (testButton != 0)
  58152. testButton->setBounds (proportionOfWidth (0.77f),
  58153. outputDeviceDropDown->getY(),
  58154. proportionOfWidth (0.18f),
  58155. h);
  58156. y += dh;
  58157. }
  58158. if (inputDeviceDropDown != 0)
  58159. {
  58160. inputDeviceDropDown->setBounds (lx, y, w, h);
  58161. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58162. inputDeviceDropDown->getY(),
  58163. proportionOfWidth (0.18f),
  58164. h);
  58165. y += dh;
  58166. }
  58167. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58168. if (outputChanList != 0)
  58169. {
  58170. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58171. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58172. y += bh + space;
  58173. }
  58174. if (inputChanList != 0)
  58175. {
  58176. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58177. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58178. y += bh + space;
  58179. }
  58180. y += space * 2;
  58181. if (showAdvancedSettingsButton != 0)
  58182. {
  58183. showAdvancedSettingsButton->changeWidthToFitText (h);
  58184. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58185. }
  58186. if (sampleRateDropDown != 0)
  58187. {
  58188. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58189. || ! showAdvancedSettingsButton->isVisible());
  58190. sampleRateDropDown->setBounds (lx, y, w, h);
  58191. y += dh;
  58192. }
  58193. if (bufferSizeDropDown != 0)
  58194. {
  58195. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58196. || ! showAdvancedSettingsButton->isVisible());
  58197. bufferSizeDropDown->setBounds (lx, y, w, h);
  58198. y += dh;
  58199. }
  58200. if (showUIButton != 0)
  58201. {
  58202. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58203. || ! showAdvancedSettingsButton->isVisible());
  58204. showUIButton->changeWidthToFitText (h);
  58205. showUIButton->setTopLeftPosition (lx, y);
  58206. }
  58207. }
  58208. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58209. {
  58210. if (comboBoxThatHasChanged == 0)
  58211. return;
  58212. AudioDeviceManager::AudioDeviceSetup config;
  58213. setup.manager->getAudioDeviceSetup (config);
  58214. String error;
  58215. if (comboBoxThatHasChanged == outputDeviceDropDown
  58216. || comboBoxThatHasChanged == inputDeviceDropDown)
  58217. {
  58218. if (outputDeviceDropDown != 0)
  58219. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58220. : outputDeviceDropDown->getText();
  58221. if (inputDeviceDropDown != 0)
  58222. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58223. : inputDeviceDropDown->getText();
  58224. if (! type->hasSeparateInputsAndOutputs())
  58225. config.inputDeviceName = config.outputDeviceName;
  58226. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58227. config.useDefaultInputChannels = true;
  58228. else
  58229. config.useDefaultOutputChannels = true;
  58230. error = setup.manager->setAudioDeviceSetup (config, true);
  58231. showCorrectDeviceName (inputDeviceDropDown, true);
  58232. showCorrectDeviceName (outputDeviceDropDown, false);
  58233. updateControlPanelButton();
  58234. resized();
  58235. }
  58236. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58237. {
  58238. if (sampleRateDropDown->getSelectedId() > 0)
  58239. {
  58240. config.sampleRate = sampleRateDropDown->getSelectedId();
  58241. error = setup.manager->setAudioDeviceSetup (config, true);
  58242. }
  58243. }
  58244. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58245. {
  58246. if (bufferSizeDropDown->getSelectedId() > 0)
  58247. {
  58248. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58249. error = setup.manager->setAudioDeviceSetup (config, true);
  58250. }
  58251. }
  58252. if (error.isNotEmpty())
  58253. {
  58254. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58255. "Error when trying to open audio device!",
  58256. error);
  58257. }
  58258. }
  58259. void buttonClicked (Button* button)
  58260. {
  58261. if (button == showAdvancedSettingsButton)
  58262. {
  58263. showAdvancedSettingsButton->setVisible (false);
  58264. resized();
  58265. }
  58266. else if (button == showUIButton)
  58267. {
  58268. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58269. if (device != 0 && device->showControlPanel())
  58270. {
  58271. setup.manager->closeAudioDevice();
  58272. setup.manager->restartLastAudioDevice();
  58273. getTopLevelComponent()->toFront (true);
  58274. }
  58275. }
  58276. else if (button == testButton && testButton != 0)
  58277. {
  58278. setup.manager->playTestSound();
  58279. }
  58280. }
  58281. void updateControlPanelButton()
  58282. {
  58283. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58284. showUIButton = 0;
  58285. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58286. {
  58287. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58288. TRANS ("opens the device's own control panel")));
  58289. showUIButton->addButtonListener (this);
  58290. }
  58291. resized();
  58292. }
  58293. void changeListenerCallback (void*)
  58294. {
  58295. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58296. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58297. {
  58298. if (outputDeviceDropDown == 0)
  58299. {
  58300. outputDeviceDropDown = new ComboBox (String::empty);
  58301. outputDeviceDropDown->addListener (this);
  58302. addAndMakeVisible (outputDeviceDropDown);
  58303. outputDeviceLabel = new Label (String::empty,
  58304. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58305. : TRANS ("device:"));
  58306. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58307. if (setup.maxNumOutputChannels > 0)
  58308. {
  58309. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58310. testButton->addButtonListener (this);
  58311. }
  58312. }
  58313. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58314. }
  58315. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58316. {
  58317. if (inputDeviceDropDown == 0)
  58318. {
  58319. inputDeviceDropDown = new ComboBox (String::empty);
  58320. inputDeviceDropDown->addListener (this);
  58321. addAndMakeVisible (inputDeviceDropDown);
  58322. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58323. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58324. addAndMakeVisible (inputLevelMeter
  58325. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58326. }
  58327. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58328. }
  58329. updateControlPanelButton();
  58330. showCorrectDeviceName (inputDeviceDropDown, true);
  58331. showCorrectDeviceName (outputDeviceDropDown, false);
  58332. if (currentDevice != 0)
  58333. {
  58334. if (setup.maxNumOutputChannels > 0
  58335. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58336. {
  58337. if (outputChanList == 0)
  58338. {
  58339. addAndMakeVisible (outputChanList
  58340. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58341. TRANS ("(no audio output channels found)")));
  58342. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58343. outputChanLabel->attachToComponent (outputChanList, true);
  58344. }
  58345. outputChanList->refresh();
  58346. }
  58347. else
  58348. {
  58349. outputChanLabel = 0;
  58350. outputChanList = 0;
  58351. }
  58352. if (setup.maxNumInputChannels > 0
  58353. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58354. {
  58355. if (inputChanList == 0)
  58356. {
  58357. addAndMakeVisible (inputChanList
  58358. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58359. TRANS ("(no audio input channels found)")));
  58360. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58361. inputChanLabel->attachToComponent (inputChanList, true);
  58362. }
  58363. inputChanList->refresh();
  58364. }
  58365. else
  58366. {
  58367. inputChanLabel = 0;
  58368. inputChanList = 0;
  58369. }
  58370. // sample rate..
  58371. {
  58372. if (sampleRateDropDown == 0)
  58373. {
  58374. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58375. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58376. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58377. }
  58378. else
  58379. {
  58380. sampleRateDropDown->clear();
  58381. sampleRateDropDown->removeListener (this);
  58382. }
  58383. const int numRates = currentDevice->getNumSampleRates();
  58384. for (int i = 0; i < numRates; ++i)
  58385. {
  58386. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58387. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58388. }
  58389. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58390. sampleRateDropDown->addListener (this);
  58391. }
  58392. // buffer size
  58393. {
  58394. if (bufferSizeDropDown == 0)
  58395. {
  58396. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58397. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58398. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58399. }
  58400. else
  58401. {
  58402. bufferSizeDropDown->clear();
  58403. bufferSizeDropDown->removeListener (this);
  58404. }
  58405. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58406. double currentRate = currentDevice->getCurrentSampleRate();
  58407. if (currentRate == 0)
  58408. currentRate = 48000.0;
  58409. for (int i = 0; i < numBufferSizes; ++i)
  58410. {
  58411. const int bs = currentDevice->getBufferSizeSamples (i);
  58412. bufferSizeDropDown->addItem (String (bs)
  58413. + " samples ("
  58414. + String (bs * 1000.0 / currentRate, 1)
  58415. + " ms)",
  58416. bs);
  58417. }
  58418. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58419. bufferSizeDropDown->addListener (this);
  58420. }
  58421. }
  58422. else
  58423. {
  58424. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58425. sampleRateLabel = 0;
  58426. bufferSizeLabel = 0;
  58427. sampleRateDropDown = 0;
  58428. bufferSizeDropDown = 0;
  58429. if (outputDeviceDropDown != 0)
  58430. outputDeviceDropDown->setSelectedId (-1, true);
  58431. if (inputDeviceDropDown != 0)
  58432. inputDeviceDropDown->setSelectedId (-1, true);
  58433. }
  58434. resized();
  58435. setSize (getWidth(), getLowestY() + 4);
  58436. }
  58437. private:
  58438. AudioIODeviceType* const type;
  58439. const AudioIODeviceType::DeviceSetupDetails setup;
  58440. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58441. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58442. ScopedPointer<TextButton> testButton;
  58443. ScopedPointer<Component> inputLevelMeter;
  58444. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58445. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58446. {
  58447. if (box != 0)
  58448. {
  58449. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58450. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58451. box->setSelectedId (index + 1, true);
  58452. if (testButton != 0 && ! isInput)
  58453. testButton->setEnabled (index >= 0);
  58454. }
  58455. }
  58456. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58457. {
  58458. const StringArray devs (type->getDeviceNames (isInputs));
  58459. combo.clear (true);
  58460. for (int i = 0; i < devs.size(); ++i)
  58461. combo.addItem (devs[i], i + 1);
  58462. combo.addItem (TRANS("<< none >>"), -1);
  58463. combo.setSelectedId (-1, true);
  58464. }
  58465. int getLowestY() const
  58466. {
  58467. int y = 0;
  58468. for (int i = getNumChildComponents(); --i >= 0;)
  58469. y = jmax (y, getChildComponent (i)->getBottom());
  58470. return y;
  58471. }
  58472. public:
  58473. class ChannelSelectorListBox : public ListBox,
  58474. public ListBoxModel
  58475. {
  58476. public:
  58477. enum BoxType
  58478. {
  58479. audioInputType,
  58480. audioOutputType
  58481. };
  58482. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58483. const BoxType type_,
  58484. const String& noItemsMessage_)
  58485. : ListBox (String::empty, 0),
  58486. setup (setup_),
  58487. type (type_),
  58488. noItemsMessage (noItemsMessage_)
  58489. {
  58490. refresh();
  58491. setModel (this);
  58492. setOutlineThickness (1);
  58493. }
  58494. ~ChannelSelectorListBox()
  58495. {
  58496. }
  58497. void refresh()
  58498. {
  58499. items.clear();
  58500. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58501. if (currentDevice != 0)
  58502. {
  58503. if (type == audioInputType)
  58504. items = currentDevice->getInputChannelNames();
  58505. else if (type == audioOutputType)
  58506. items = currentDevice->getOutputChannelNames();
  58507. if (setup.useStereoPairs)
  58508. {
  58509. StringArray pairs;
  58510. for (int i = 0; i < items.size(); i += 2)
  58511. {
  58512. const String name (items[i]);
  58513. const String name2 (items[i + 1]);
  58514. String commonBit;
  58515. for (int j = 0; j < name.length(); ++j)
  58516. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58517. commonBit = name.substring (0, j);
  58518. // Make sure we only split the name at a space, because otherwise, things
  58519. // like "input 11" + "input 12" would become "input 11 + 2"
  58520. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58521. commonBit = commonBit.dropLastCharacters (1);
  58522. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58523. }
  58524. items = pairs;
  58525. }
  58526. }
  58527. updateContent();
  58528. repaint();
  58529. }
  58530. int getNumRows()
  58531. {
  58532. return items.size();
  58533. }
  58534. void paintListBoxItem (int row,
  58535. Graphics& g,
  58536. int width, int height,
  58537. bool rowIsSelected)
  58538. {
  58539. if (((unsigned int) row) < (unsigned int) items.size())
  58540. {
  58541. if (rowIsSelected)
  58542. g.fillAll (findColour (TextEditor::highlightColourId)
  58543. .withMultipliedAlpha (0.3f));
  58544. const String item (items [row]);
  58545. bool enabled = false;
  58546. AudioDeviceManager::AudioDeviceSetup config;
  58547. setup.manager->getAudioDeviceSetup (config);
  58548. if (setup.useStereoPairs)
  58549. {
  58550. if (type == audioInputType)
  58551. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58552. else if (type == audioOutputType)
  58553. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58554. }
  58555. else
  58556. {
  58557. if (type == audioInputType)
  58558. enabled = config.inputChannels [row];
  58559. else if (type == audioOutputType)
  58560. enabled = config.outputChannels [row];
  58561. }
  58562. const int x = getTickX();
  58563. const float tickW = height * 0.75f;
  58564. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58565. enabled, true, true, false);
  58566. g.setFont (height * 0.6f);
  58567. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58568. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58569. }
  58570. }
  58571. void listBoxItemClicked (int row, const MouseEvent& e)
  58572. {
  58573. selectRow (row);
  58574. if (e.x < getTickX())
  58575. flipEnablement (row);
  58576. }
  58577. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58578. {
  58579. flipEnablement (row);
  58580. }
  58581. void returnKeyPressed (int row)
  58582. {
  58583. flipEnablement (row);
  58584. }
  58585. void paint (Graphics& g)
  58586. {
  58587. ListBox::paint (g);
  58588. if (items.size() == 0)
  58589. {
  58590. g.setColour (Colours::grey);
  58591. g.setFont (13.0f);
  58592. g.drawText (noItemsMessage,
  58593. 0, 0, getWidth(), getHeight() / 2,
  58594. Justification::centred, true);
  58595. }
  58596. }
  58597. int getBestHeight (int maxHeight)
  58598. {
  58599. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58600. getNumRows())
  58601. + getOutlineThickness() * 2;
  58602. }
  58603. juce_UseDebuggingNewOperator
  58604. private:
  58605. const AudioIODeviceType::DeviceSetupDetails setup;
  58606. const BoxType type;
  58607. const String noItemsMessage;
  58608. StringArray items;
  58609. void flipEnablement (const int row)
  58610. {
  58611. jassert (type == audioInputType || type == audioOutputType);
  58612. if (((unsigned int) row) < (unsigned int) items.size())
  58613. {
  58614. AudioDeviceManager::AudioDeviceSetup config;
  58615. setup.manager->getAudioDeviceSetup (config);
  58616. if (setup.useStereoPairs)
  58617. {
  58618. BigInteger bits;
  58619. BigInteger& original = (type == audioInputType ? config.inputChannels
  58620. : config.outputChannels);
  58621. int i;
  58622. for (i = 0; i < 256; i += 2)
  58623. bits.setBit (i / 2, original [i] || original [i + 1]);
  58624. if (type == audioInputType)
  58625. {
  58626. config.useDefaultInputChannels = false;
  58627. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58628. }
  58629. else
  58630. {
  58631. config.useDefaultOutputChannels = false;
  58632. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58633. }
  58634. for (i = 0; i < 256; ++i)
  58635. original.setBit (i, bits [i / 2]);
  58636. }
  58637. else
  58638. {
  58639. if (type == audioInputType)
  58640. {
  58641. config.useDefaultInputChannels = false;
  58642. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58643. }
  58644. else
  58645. {
  58646. config.useDefaultOutputChannels = false;
  58647. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58648. }
  58649. }
  58650. String error (setup.manager->setAudioDeviceSetup (config, true));
  58651. if (! error.isEmpty())
  58652. {
  58653. //xxx
  58654. }
  58655. }
  58656. }
  58657. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58658. {
  58659. const int numActive = chans.countNumberOfSetBits();
  58660. if (chans [index])
  58661. {
  58662. if (numActive > minNumber)
  58663. chans.setBit (index, false);
  58664. }
  58665. else
  58666. {
  58667. if (numActive >= maxNumber)
  58668. {
  58669. const int firstActiveChan = chans.findNextSetBit();
  58670. chans.setBit (index > firstActiveChan
  58671. ? firstActiveChan : chans.getHighestBit(),
  58672. false);
  58673. }
  58674. chans.setBit (index, true);
  58675. }
  58676. }
  58677. int getTickX() const
  58678. {
  58679. return getRowHeight() + 5;
  58680. }
  58681. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58682. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58683. };
  58684. private:
  58685. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  58686. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58687. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58688. };
  58689. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58690. const int minInputChannels_,
  58691. const int maxInputChannels_,
  58692. const int minOutputChannels_,
  58693. const int maxOutputChannels_,
  58694. const bool showMidiInputOptions,
  58695. const bool showMidiOutputSelector,
  58696. const bool showChannelsAsStereoPairs_,
  58697. const bool hideAdvancedOptionsWithButton_)
  58698. : deviceManager (deviceManager_),
  58699. deviceTypeDropDown (0),
  58700. deviceTypeDropDownLabel (0),
  58701. minOutputChannels (minOutputChannels_),
  58702. maxOutputChannels (maxOutputChannels_),
  58703. minInputChannels (minInputChannels_),
  58704. maxInputChannels (maxInputChannels_),
  58705. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58706. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58707. {
  58708. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58709. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58710. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58711. {
  58712. deviceTypeDropDown = new ComboBox (String::empty);
  58713. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58714. {
  58715. deviceTypeDropDown
  58716. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58717. i + 1);
  58718. }
  58719. addAndMakeVisible (deviceTypeDropDown);
  58720. deviceTypeDropDown->addListener (this);
  58721. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58722. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58723. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58724. }
  58725. if (showMidiInputOptions)
  58726. {
  58727. addAndMakeVisible (midiInputsList
  58728. = new MidiInputSelectorComponentListBox (deviceManager,
  58729. TRANS("(no midi inputs available)"),
  58730. 0, 0));
  58731. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58732. midiInputsLabel->setJustificationType (Justification::topRight);
  58733. midiInputsLabel->attachToComponent (midiInputsList, true);
  58734. }
  58735. else
  58736. {
  58737. midiInputsList = 0;
  58738. midiInputsLabel = 0;
  58739. }
  58740. if (showMidiOutputSelector)
  58741. {
  58742. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58743. midiOutputSelector->addListener (this);
  58744. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58745. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58746. }
  58747. else
  58748. {
  58749. midiOutputSelector = 0;
  58750. midiOutputLabel = 0;
  58751. }
  58752. deviceManager_.addChangeListener (this);
  58753. changeListenerCallback (0);
  58754. }
  58755. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58756. {
  58757. deviceManager.removeChangeListener (this);
  58758. }
  58759. void AudioDeviceSelectorComponent::resized()
  58760. {
  58761. const int lx = proportionOfWidth (0.35f);
  58762. const int w = proportionOfWidth (0.4f);
  58763. const int h = 24;
  58764. const int space = 6;
  58765. const int dh = h + space;
  58766. int y = 15;
  58767. if (deviceTypeDropDown != 0)
  58768. {
  58769. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58770. y += dh + space * 2;
  58771. }
  58772. if (audioDeviceSettingsComp != 0)
  58773. {
  58774. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58775. y += audioDeviceSettingsComp->getHeight() + space;
  58776. }
  58777. if (midiInputsList != 0)
  58778. {
  58779. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58780. midiInputsList->setBounds (lx, y, w, bh);
  58781. y += bh + space;
  58782. }
  58783. if (midiOutputSelector != 0)
  58784. midiOutputSelector->setBounds (lx, y, w, h);
  58785. }
  58786. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58787. {
  58788. if (child == audioDeviceSettingsComp)
  58789. resized();
  58790. }
  58791. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58792. {
  58793. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58794. if (device != 0 && device->hasControlPanel())
  58795. {
  58796. if (device->showControlPanel())
  58797. deviceManager.restartLastAudioDevice();
  58798. getTopLevelComponent()->toFront (true);
  58799. }
  58800. }
  58801. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58802. {
  58803. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58804. {
  58805. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58806. if (type != 0)
  58807. {
  58808. audioDeviceSettingsComp = 0;
  58809. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58810. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58811. }
  58812. }
  58813. else if (comboBoxThatHasChanged == midiOutputSelector)
  58814. {
  58815. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58816. }
  58817. }
  58818. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58819. {
  58820. if (deviceTypeDropDown != 0)
  58821. {
  58822. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58823. }
  58824. if (audioDeviceSettingsComp == 0
  58825. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58826. {
  58827. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58828. audioDeviceSettingsComp = 0;
  58829. AudioIODeviceType* const type
  58830. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58831. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58832. if (type != 0)
  58833. {
  58834. AudioIODeviceType::DeviceSetupDetails details;
  58835. details.manager = &deviceManager;
  58836. details.minNumInputChannels = minInputChannels;
  58837. details.maxNumInputChannels = maxInputChannels;
  58838. details.minNumOutputChannels = minOutputChannels;
  58839. details.maxNumOutputChannels = maxOutputChannels;
  58840. details.useStereoPairs = showChannelsAsStereoPairs;
  58841. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58842. if (audioDeviceSettingsComp != 0)
  58843. {
  58844. addAndMakeVisible (audioDeviceSettingsComp);
  58845. audioDeviceSettingsComp->resized();
  58846. }
  58847. }
  58848. }
  58849. if (midiInputsList != 0)
  58850. {
  58851. midiInputsList->updateContent();
  58852. midiInputsList->repaint();
  58853. }
  58854. if (midiOutputSelector != 0)
  58855. {
  58856. midiOutputSelector->clear();
  58857. const StringArray midiOuts (MidiOutput::getDevices());
  58858. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58859. midiOutputSelector->addSeparator();
  58860. for (int i = 0; i < midiOuts.size(); ++i)
  58861. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58862. int current = -1;
  58863. if (deviceManager.getDefaultMidiOutput() != 0)
  58864. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58865. midiOutputSelector->setSelectedId (current, true);
  58866. }
  58867. resized();
  58868. }
  58869. END_JUCE_NAMESPACE
  58870. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58871. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58872. BEGIN_JUCE_NAMESPACE
  58873. BubbleComponent::BubbleComponent()
  58874. : side (0),
  58875. allowablePlacements (above | below | left | right),
  58876. arrowTipX (0.0f),
  58877. arrowTipY (0.0f)
  58878. {
  58879. setInterceptsMouseClicks (false, false);
  58880. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58881. setComponentEffect (&shadow);
  58882. }
  58883. BubbleComponent::~BubbleComponent()
  58884. {
  58885. }
  58886. void BubbleComponent::paint (Graphics& g)
  58887. {
  58888. int x = content.getX();
  58889. int y = content.getY();
  58890. int w = content.getWidth();
  58891. int h = content.getHeight();
  58892. int cw, ch;
  58893. getContentSize (cw, ch);
  58894. if (side == 3)
  58895. x += w - cw;
  58896. else if (side != 1)
  58897. x += (w - cw) / 2;
  58898. w = cw;
  58899. if (side == 2)
  58900. y += h - ch;
  58901. else if (side != 0)
  58902. y += (h - ch) / 2;
  58903. h = ch;
  58904. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58905. (float) x, (float) y,
  58906. (float) w, (float) h);
  58907. const int cx = x + (w - cw) / 2;
  58908. const int cy = y + (h - ch) / 2;
  58909. const int indent = 3;
  58910. g.setOrigin (cx + indent, cy + indent);
  58911. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58912. paintContent (g, cw - indent * 2, ch - indent * 2);
  58913. }
  58914. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58915. {
  58916. allowablePlacements = newPlacement;
  58917. }
  58918. void BubbleComponent::setPosition (Component* componentToPointTo)
  58919. {
  58920. jassert (componentToPointTo->isValidComponent());
  58921. Point<int> pos;
  58922. if (getParentComponent() != 0)
  58923. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58924. else
  58925. pos = componentToPointTo->relativePositionToGlobal (pos);
  58926. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58927. }
  58928. void BubbleComponent::setPosition (const int arrowTipX_,
  58929. const int arrowTipY_)
  58930. {
  58931. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58932. }
  58933. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58934. {
  58935. Rectangle<int> availableSpace;
  58936. if (getParentComponent() != 0)
  58937. {
  58938. availableSpace.setSize (getParentComponent()->getWidth(),
  58939. getParentComponent()->getHeight());
  58940. }
  58941. else
  58942. {
  58943. availableSpace = getParentMonitorArea();
  58944. }
  58945. int x = 0;
  58946. int y = 0;
  58947. int w = 150;
  58948. int h = 30;
  58949. getContentSize (w, h);
  58950. w += 30;
  58951. h += 30;
  58952. const float edgeIndent = 2.0f;
  58953. const int arrowLength = jmin (10, h / 3, w / 3);
  58954. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58955. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58956. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58957. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58958. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58959. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58960. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58961. {
  58962. spaceLeft = spaceRight = 0;
  58963. }
  58964. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58965. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58966. {
  58967. spaceAbove = spaceBelow = 0;
  58968. }
  58969. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58970. {
  58971. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58972. arrowTipX = w * 0.5f;
  58973. content.setSize (w, h - arrowLength);
  58974. if (spaceAbove >= spaceBelow)
  58975. {
  58976. // above
  58977. y = rectangleToPointTo.getY() - h;
  58978. content.setPosition (0, 0);
  58979. arrowTipY = h - edgeIndent;
  58980. side = 2;
  58981. }
  58982. else
  58983. {
  58984. // below
  58985. y = rectangleToPointTo.getBottom();
  58986. content.setPosition (0, arrowLength);
  58987. arrowTipY = edgeIndent;
  58988. side = 0;
  58989. }
  58990. }
  58991. else
  58992. {
  58993. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58994. arrowTipY = h * 0.5f;
  58995. content.setSize (w - arrowLength, h);
  58996. if (spaceLeft > spaceRight)
  58997. {
  58998. // on the left
  58999. x = rectangleToPointTo.getX() - w;
  59000. content.setPosition (0, 0);
  59001. arrowTipX = w - edgeIndent;
  59002. side = 3;
  59003. }
  59004. else
  59005. {
  59006. // on the right
  59007. x = rectangleToPointTo.getRight();
  59008. content.setPosition (arrowLength, 0);
  59009. arrowTipX = edgeIndent;
  59010. side = 1;
  59011. }
  59012. }
  59013. setBounds (x, y, w, h);
  59014. }
  59015. END_JUCE_NAMESPACE
  59016. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59017. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59018. BEGIN_JUCE_NAMESPACE
  59019. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59020. : fadeOutLength (fadeOutLengthMs),
  59021. deleteAfterUse (false)
  59022. {
  59023. }
  59024. BubbleMessageComponent::~BubbleMessageComponent()
  59025. {
  59026. fadeOutComponent (fadeOutLength);
  59027. }
  59028. void BubbleMessageComponent::showAt (int x, int y,
  59029. const String& text,
  59030. const int numMillisecondsBeforeRemoving,
  59031. const bool removeWhenMouseClicked,
  59032. const bool deleteSelfAfterUse)
  59033. {
  59034. textLayout.clear();
  59035. textLayout.setText (text, Font (14.0f));
  59036. textLayout.layout (256, Justification::centredLeft, true);
  59037. setPosition (x, y);
  59038. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59039. }
  59040. void BubbleMessageComponent::showAt (Component* const component,
  59041. const String& text,
  59042. const int numMillisecondsBeforeRemoving,
  59043. const bool removeWhenMouseClicked,
  59044. const bool deleteSelfAfterUse)
  59045. {
  59046. textLayout.clear();
  59047. textLayout.setText (text, Font (14.0f));
  59048. textLayout.layout (256, Justification::centredLeft, true);
  59049. setPosition (component);
  59050. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59051. }
  59052. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59053. const bool removeWhenMouseClicked,
  59054. const bool deleteSelfAfterUse)
  59055. {
  59056. setVisible (true);
  59057. deleteAfterUse = deleteSelfAfterUse;
  59058. if (numMillisecondsBeforeRemoving > 0)
  59059. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59060. else
  59061. expiryTime = 0;
  59062. startTimer (77);
  59063. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59064. if (! (removeWhenMouseClicked && isShowing()))
  59065. mouseClickCounter += 0xfffff;
  59066. repaint();
  59067. }
  59068. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59069. {
  59070. w = textLayout.getWidth() + 16;
  59071. h = textLayout.getHeight() + 16;
  59072. }
  59073. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59074. {
  59075. g.setColour (findColour (TooltipWindow::textColourId));
  59076. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59077. }
  59078. void BubbleMessageComponent::timerCallback()
  59079. {
  59080. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59081. {
  59082. stopTimer();
  59083. setVisible (false);
  59084. if (deleteAfterUse)
  59085. delete this;
  59086. }
  59087. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59088. {
  59089. stopTimer();
  59090. fadeOutComponent (fadeOutLength);
  59091. if (deleteAfterUse)
  59092. delete this;
  59093. }
  59094. }
  59095. END_JUCE_NAMESPACE
  59096. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59097. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59098. BEGIN_JUCE_NAMESPACE
  59099. class ColourComponentSlider : public Slider
  59100. {
  59101. public:
  59102. ColourComponentSlider (const String& name)
  59103. : Slider (name)
  59104. {
  59105. setRange (0.0, 255.0, 1.0);
  59106. }
  59107. ~ColourComponentSlider()
  59108. {
  59109. }
  59110. const String getTextFromValue (double value)
  59111. {
  59112. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59113. }
  59114. double getValueFromText (const String& text)
  59115. {
  59116. return (double) text.getHexValue32();
  59117. }
  59118. private:
  59119. ColourComponentSlider (const ColourComponentSlider&);
  59120. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59121. };
  59122. class ColourSpaceMarker : public Component
  59123. {
  59124. public:
  59125. ColourSpaceMarker()
  59126. {
  59127. setInterceptsMouseClicks (false, false);
  59128. }
  59129. ~ColourSpaceMarker()
  59130. {
  59131. }
  59132. void paint (Graphics& g)
  59133. {
  59134. g.setColour (Colour::greyLevel (0.1f));
  59135. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59136. g.setColour (Colour::greyLevel (0.9f));
  59137. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59138. }
  59139. private:
  59140. ColourSpaceMarker (const ColourSpaceMarker&);
  59141. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59142. };
  59143. class ColourSelector::ColourSpaceView : public Component
  59144. {
  59145. public:
  59146. ColourSpaceView (ColourSelector* owner_,
  59147. float& h_, float& s_, float& v_,
  59148. const int edgeSize)
  59149. : owner (owner_),
  59150. h (h_), s (s_), v (v_),
  59151. lastHue (0.0f),
  59152. edge (edgeSize)
  59153. {
  59154. addAndMakeVisible (&marker);
  59155. setMouseCursor (MouseCursor::CrosshairCursor);
  59156. }
  59157. ~ColourSpaceView()
  59158. {
  59159. }
  59160. void paint (Graphics& g)
  59161. {
  59162. if (colours.isNull())
  59163. {
  59164. const int width = getWidth() / 2;
  59165. const int height = getHeight() / 2;
  59166. colours = Image (Image::RGB, width, height, false);
  59167. Image::BitmapData pixels (colours, true);
  59168. for (int y = 0; y < height; ++y)
  59169. {
  59170. const float val = 1.0f - y / (float) height;
  59171. for (int x = 0; x < width; ++x)
  59172. {
  59173. const float sat = x / (float) width;
  59174. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59175. }
  59176. }
  59177. }
  59178. g.setOpacity (1.0f);
  59179. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59180. 0, 0, colours.getWidth(), colours.getHeight());
  59181. }
  59182. void mouseDown (const MouseEvent& e)
  59183. {
  59184. mouseDrag (e);
  59185. }
  59186. void mouseDrag (const MouseEvent& e)
  59187. {
  59188. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59189. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59190. owner->setSV (sat, val);
  59191. }
  59192. void updateIfNeeded()
  59193. {
  59194. if (lastHue != h)
  59195. {
  59196. lastHue = h;
  59197. colours = Image::null;
  59198. repaint();
  59199. }
  59200. updateMarker();
  59201. }
  59202. void resized()
  59203. {
  59204. colours = Image::null;
  59205. updateMarker();
  59206. }
  59207. private:
  59208. ColourSelector* const owner;
  59209. float& h;
  59210. float& s;
  59211. float& v;
  59212. float lastHue;
  59213. ColourSpaceMarker marker;
  59214. const int edge;
  59215. Image colours;
  59216. void updateMarker()
  59217. {
  59218. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59219. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59220. edge * 2, edge * 2);
  59221. }
  59222. ColourSpaceView (const ColourSpaceView&);
  59223. ColourSpaceView& operator= (const ColourSpaceView&);
  59224. };
  59225. class HueSelectorMarker : public Component
  59226. {
  59227. public:
  59228. HueSelectorMarker()
  59229. {
  59230. setInterceptsMouseClicks (false, false);
  59231. }
  59232. ~HueSelectorMarker()
  59233. {
  59234. }
  59235. void paint (Graphics& g)
  59236. {
  59237. Path p;
  59238. p.addTriangle (1.0f, 1.0f,
  59239. getWidth() * 0.3f, getHeight() * 0.5f,
  59240. 1.0f, getHeight() - 1.0f);
  59241. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59242. getWidth() * 0.7f, getHeight() * 0.5f,
  59243. getWidth() - 1.0f, getHeight() - 1.0f);
  59244. g.setColour (Colours::white.withAlpha (0.75f));
  59245. g.fillPath (p);
  59246. g.setColour (Colours::black.withAlpha (0.75f));
  59247. g.strokePath (p, PathStrokeType (1.2f));
  59248. }
  59249. private:
  59250. HueSelectorMarker (const HueSelectorMarker&);
  59251. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59252. };
  59253. class ColourSelector::HueSelectorComp : public Component
  59254. {
  59255. public:
  59256. HueSelectorComp (ColourSelector* owner_,
  59257. float& h_, float& s_, float& v_,
  59258. const int edgeSize)
  59259. : owner (owner_),
  59260. h (h_), s (s_), v (v_),
  59261. lastHue (0.0f),
  59262. edge (edgeSize)
  59263. {
  59264. addAndMakeVisible (&marker);
  59265. }
  59266. ~HueSelectorComp()
  59267. {
  59268. }
  59269. void paint (Graphics& g)
  59270. {
  59271. const float yScale = 1.0f / (getHeight() - edge * 2);
  59272. const Rectangle<int> clip (g.getClipBounds());
  59273. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59274. {
  59275. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59276. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59277. }
  59278. }
  59279. void resized()
  59280. {
  59281. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59282. getWidth(), edge * 2);
  59283. }
  59284. void mouseDown (const MouseEvent& e)
  59285. {
  59286. mouseDrag (e);
  59287. }
  59288. void mouseDrag (const MouseEvent& e)
  59289. {
  59290. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59291. owner->setHue (hue);
  59292. }
  59293. void updateIfNeeded()
  59294. {
  59295. resized();
  59296. }
  59297. private:
  59298. ColourSelector* const owner;
  59299. float& h;
  59300. float& s;
  59301. float& v;
  59302. float lastHue;
  59303. HueSelectorMarker marker;
  59304. const int edge;
  59305. HueSelectorComp (const HueSelectorComp&);
  59306. HueSelectorComp& operator= (const HueSelectorComp&);
  59307. };
  59308. class ColourSelector::SwatchComponent : public Component
  59309. {
  59310. public:
  59311. SwatchComponent (ColourSelector* owner_, int index_)
  59312. : owner (owner_),
  59313. index (index_)
  59314. {
  59315. }
  59316. ~SwatchComponent()
  59317. {
  59318. }
  59319. void paint (Graphics& g)
  59320. {
  59321. const Colour colour (owner->getSwatchColour (index));
  59322. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59323. Colour (0xffdddddd).overlaidWith (colour),
  59324. Colour (0xffffffff).overlaidWith (colour));
  59325. }
  59326. void mouseDown (const MouseEvent&)
  59327. {
  59328. PopupMenu m;
  59329. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59330. m.addSeparator();
  59331. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59332. const int r = m.showAt (this);
  59333. if (r == 1)
  59334. {
  59335. owner->setCurrentColour (owner->getSwatchColour (index));
  59336. }
  59337. else if (r == 2)
  59338. {
  59339. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59340. {
  59341. owner->setSwatchColour (index, owner->getCurrentColour());
  59342. repaint();
  59343. }
  59344. }
  59345. }
  59346. private:
  59347. ColourSelector* const owner;
  59348. const int index;
  59349. SwatchComponent (const SwatchComponent&);
  59350. SwatchComponent& operator= (const SwatchComponent&);
  59351. };
  59352. ColourSelector::ColourSelector (const int flags_,
  59353. const int edgeGap_,
  59354. const int gapAroundColourSpaceComponent)
  59355. : colour (Colours::white),
  59356. colourSpace (0),
  59357. hueSelector (0),
  59358. flags (flags_),
  59359. edgeGap (edgeGap_)
  59360. {
  59361. // not much point having a selector with no components in it!
  59362. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59363. updateHSV();
  59364. if ((flags & showSliders) != 0)
  59365. {
  59366. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59367. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59368. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59369. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59370. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59371. for (int i = 4; --i >= 0;)
  59372. sliders[i]->addListener (this);
  59373. }
  59374. else
  59375. {
  59376. zeromem (sliders, sizeof (sliders));
  59377. }
  59378. if ((flags & showColourspace) != 0)
  59379. {
  59380. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59381. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59382. }
  59383. update();
  59384. }
  59385. ColourSelector::~ColourSelector()
  59386. {
  59387. dispatchPendingMessages();
  59388. swatchComponents.clear();
  59389. deleteAllChildren();
  59390. }
  59391. const Colour ColourSelector::getCurrentColour() const
  59392. {
  59393. return ((flags & showAlphaChannel) != 0) ? colour
  59394. : colour.withAlpha ((uint8) 0xff);
  59395. }
  59396. void ColourSelector::setCurrentColour (const Colour& c)
  59397. {
  59398. if (c != colour)
  59399. {
  59400. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59401. updateHSV();
  59402. update();
  59403. }
  59404. }
  59405. void ColourSelector::setHue (float newH)
  59406. {
  59407. newH = jlimit (0.0f, 1.0f, newH);
  59408. if (h != newH)
  59409. {
  59410. h = newH;
  59411. colour = Colour (h, s, v, colour.getFloatAlpha());
  59412. update();
  59413. }
  59414. }
  59415. void ColourSelector::setSV (float newS, float newV)
  59416. {
  59417. newS = jlimit (0.0f, 1.0f, newS);
  59418. newV = jlimit (0.0f, 1.0f, newV);
  59419. if (s != newS || v != newV)
  59420. {
  59421. s = newS;
  59422. v = newV;
  59423. colour = Colour (h, s, v, colour.getFloatAlpha());
  59424. update();
  59425. }
  59426. }
  59427. void ColourSelector::updateHSV()
  59428. {
  59429. colour.getHSB (h, s, v);
  59430. }
  59431. void ColourSelector::update()
  59432. {
  59433. if (sliders[0] != 0)
  59434. {
  59435. sliders[0]->setValue ((int) colour.getRed());
  59436. sliders[1]->setValue ((int) colour.getGreen());
  59437. sliders[2]->setValue ((int) colour.getBlue());
  59438. sliders[3]->setValue ((int) colour.getAlpha());
  59439. }
  59440. if (colourSpace != 0)
  59441. {
  59442. colourSpace->updateIfNeeded();
  59443. hueSelector->updateIfNeeded();
  59444. }
  59445. if ((flags & showColourAtTop) != 0)
  59446. repaint (previewArea);
  59447. sendChangeMessage (this);
  59448. }
  59449. void ColourSelector::paint (Graphics& g)
  59450. {
  59451. g.fillAll (findColour (backgroundColourId));
  59452. if ((flags & showColourAtTop) != 0)
  59453. {
  59454. const Colour currentColour (getCurrentColour());
  59455. g.fillCheckerBoard (previewArea, 10, 10,
  59456. Colour (0xffdddddd).overlaidWith (currentColour),
  59457. Colour (0xffffffff).overlaidWith (currentColour));
  59458. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59459. g.setFont (14.0f, true);
  59460. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59461. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59462. Justification::centred, false);
  59463. }
  59464. if ((flags & showSliders) != 0)
  59465. {
  59466. g.setColour (findColour (labelTextColourId));
  59467. g.setFont (11.0f);
  59468. for (int i = 4; --i >= 0;)
  59469. {
  59470. if (sliders[i]->isVisible())
  59471. g.drawText (sliders[i]->getName() + ":",
  59472. 0, sliders[i]->getY(),
  59473. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59474. Justification::centredRight, false);
  59475. }
  59476. }
  59477. }
  59478. void ColourSelector::resized()
  59479. {
  59480. const int swatchesPerRow = 8;
  59481. const int swatchHeight = 22;
  59482. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59483. const int numSwatches = getNumSwatches();
  59484. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59485. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59486. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59487. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59488. int y = topSpace;
  59489. if ((flags & showColourspace) != 0)
  59490. {
  59491. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59492. colourSpace->setBounds (edgeGap, y,
  59493. getWidth() - hueWidth - edgeGap - 4,
  59494. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59495. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59496. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59497. colourSpace->getHeight());
  59498. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59499. }
  59500. if ((flags & showSliders) != 0)
  59501. {
  59502. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59503. for (int i = 0; i < numSliders; ++i)
  59504. {
  59505. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59506. proportionOfWidth (0.72f), sliderHeight - 2);
  59507. y += sliderHeight;
  59508. }
  59509. }
  59510. if (numSwatches > 0)
  59511. {
  59512. const int startX = 8;
  59513. const int xGap = 4;
  59514. const int yGap = 4;
  59515. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59516. y += edgeGap;
  59517. if (swatchComponents.size() != numSwatches)
  59518. {
  59519. swatchComponents.clear();
  59520. for (int i = 0; i < numSwatches; ++i)
  59521. {
  59522. SwatchComponent* const sc = new SwatchComponent (this, i);
  59523. swatchComponents.add (sc);
  59524. addAndMakeVisible (sc);
  59525. }
  59526. }
  59527. int x = startX;
  59528. for (int i = 0; i < swatchComponents.size(); ++i)
  59529. {
  59530. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59531. sc->setBounds (x + xGap / 2,
  59532. y + yGap / 2,
  59533. swatchWidth - xGap,
  59534. swatchHeight - yGap);
  59535. if (((i + 1) % swatchesPerRow) == 0)
  59536. {
  59537. x = startX;
  59538. y += swatchHeight;
  59539. }
  59540. else
  59541. {
  59542. x += swatchWidth;
  59543. }
  59544. }
  59545. }
  59546. }
  59547. void ColourSelector::sliderValueChanged (Slider*)
  59548. {
  59549. if (sliders[0] != 0)
  59550. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59551. (uint8) sliders[1]->getValue(),
  59552. (uint8) sliders[2]->getValue(),
  59553. (uint8) sliders[3]->getValue()));
  59554. }
  59555. int ColourSelector::getNumSwatches() const
  59556. {
  59557. return 0;
  59558. }
  59559. const Colour ColourSelector::getSwatchColour (const int) const
  59560. {
  59561. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59562. return Colours::black;
  59563. }
  59564. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59565. {
  59566. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59567. }
  59568. END_JUCE_NAMESPACE
  59569. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59570. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59571. BEGIN_JUCE_NAMESPACE
  59572. class ShadowWindow : public Component
  59573. {
  59574. Component* owner;
  59575. Image shadowImageSections [12];
  59576. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59577. public:
  59578. ShadowWindow (Component* const owner_,
  59579. const int type_,
  59580. const Image shadowImageSections_ [12])
  59581. : owner (owner_),
  59582. type (type_)
  59583. {
  59584. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  59585. shadowImageSections [i] = shadowImageSections_ [i];
  59586. setInterceptsMouseClicks (false, false);
  59587. if (owner_->isOnDesktop())
  59588. {
  59589. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59590. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59591. | ComponentPeer::windowIsTemporary
  59592. | ComponentPeer::windowIgnoresKeyPresses);
  59593. }
  59594. else if (owner_->getParentComponent() != 0)
  59595. {
  59596. owner_->getParentComponent()->addChildComponent (this);
  59597. }
  59598. }
  59599. ~ShadowWindow()
  59600. {
  59601. }
  59602. void paint (Graphics& g)
  59603. {
  59604. const Image& topLeft = shadowImageSections [type * 3];
  59605. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  59606. const Image& filler = shadowImageSections [type * 3 + 2];
  59607. g.setOpacity (1.0f);
  59608. if (type < 2)
  59609. {
  59610. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59611. g.drawImage (topLeft,
  59612. 0, 0, topLeft.getWidth(), imH,
  59613. 0, 0, topLeft.getWidth(), imH);
  59614. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59615. g.drawImage (bottomRight,
  59616. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59617. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59618. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59619. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59620. }
  59621. else
  59622. {
  59623. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59624. g.drawImage (topLeft,
  59625. 0, 0, imW, topLeft.getHeight(),
  59626. 0, 0, imW, topLeft.getHeight());
  59627. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59628. g.drawImage (bottomRight,
  59629. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59630. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59631. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59632. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59633. }
  59634. }
  59635. void resized()
  59636. {
  59637. repaint(); // (needed for correct repainting)
  59638. }
  59639. private:
  59640. ShadowWindow (const ShadowWindow&);
  59641. ShadowWindow& operator= (const ShadowWindow&);
  59642. };
  59643. DropShadower::DropShadower (const float alpha_,
  59644. const int xOffset_,
  59645. const int yOffset_,
  59646. const float blurRadius_)
  59647. : owner (0),
  59648. numShadows (0),
  59649. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59650. xOffset (xOffset_),
  59651. yOffset (yOffset_),
  59652. alpha (alpha_),
  59653. blurRadius (blurRadius_),
  59654. inDestructor (false),
  59655. reentrant (false)
  59656. {
  59657. }
  59658. DropShadower::~DropShadower()
  59659. {
  59660. if (owner != 0)
  59661. owner->removeComponentListener (this);
  59662. inDestructor = true;
  59663. deleteShadowWindows();
  59664. }
  59665. void DropShadower::deleteShadowWindows()
  59666. {
  59667. if (numShadows > 0)
  59668. {
  59669. int i;
  59670. for (i = numShadows; --i >= 0;)
  59671. delete shadowWindows[i];
  59672. numShadows = 0;
  59673. }
  59674. }
  59675. void DropShadower::setOwner (Component* componentToFollow)
  59676. {
  59677. if (componentToFollow != owner)
  59678. {
  59679. if (owner != 0)
  59680. owner->removeComponentListener (this);
  59681. // (the component can't be null)
  59682. jassert (componentToFollow != 0);
  59683. owner = componentToFollow;
  59684. jassert (owner != 0);
  59685. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59686. owner->addComponentListener (this);
  59687. updateShadows();
  59688. }
  59689. }
  59690. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59691. {
  59692. updateShadows();
  59693. }
  59694. void DropShadower::componentBroughtToFront (Component&)
  59695. {
  59696. bringShadowWindowsToFront();
  59697. }
  59698. void DropShadower::componentChildrenChanged (Component&)
  59699. {
  59700. }
  59701. void DropShadower::componentParentHierarchyChanged (Component&)
  59702. {
  59703. deleteShadowWindows();
  59704. updateShadows();
  59705. }
  59706. void DropShadower::componentVisibilityChanged (Component&)
  59707. {
  59708. updateShadows();
  59709. }
  59710. void DropShadower::updateShadows()
  59711. {
  59712. if (reentrant || inDestructor || (owner == 0))
  59713. return;
  59714. reentrant = true;
  59715. ComponentPeer* const nw = owner->getPeer();
  59716. const bool isOwnerVisible = owner->isVisible()
  59717. && (nw == 0 || ! nw->isMinimised());
  59718. const bool createShadowWindows = numShadows == 0
  59719. && owner->getWidth() > 0
  59720. && owner->getHeight() > 0
  59721. && isOwnerVisible
  59722. && (Desktop::canUseSemiTransparentWindows()
  59723. || owner->getParentComponent() != 0);
  59724. if (createShadowWindows)
  59725. {
  59726. // keep a cached version of the image to save doing the gaussian too often
  59727. String imageId;
  59728. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59729. const int hash = imageId.hashCode();
  59730. Image bigIm (ImageCache::getFromHashCode (hash));
  59731. if (bigIm.isNull())
  59732. {
  59733. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59734. Graphics bigG (bigIm);
  59735. bigG.setColour (Colours::black.withAlpha (alpha));
  59736. bigG.fillRect (shadowEdge + xOffset,
  59737. shadowEdge + yOffset,
  59738. bigIm.getWidth() - (shadowEdge * 2),
  59739. bigIm.getHeight() - (shadowEdge * 2));
  59740. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59741. blurKernel.createGaussianBlur (blurRadius);
  59742. blurKernel.applyToImage (bigIm, bigIm,
  59743. Rectangle<int> (xOffset, yOffset,
  59744. bigIm.getWidth(), bigIm.getHeight()));
  59745. ImageCache::addImageToCache (bigIm, hash);
  59746. }
  59747. const int iw = bigIm.getWidth();
  59748. const int ih = bigIm.getHeight();
  59749. const int shadowEdge2 = shadowEdge * 2;
  59750. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59751. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59752. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59753. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59754. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59755. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59756. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59757. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59758. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59759. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59760. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59761. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59762. for (int i = 0; i < 4; ++i)
  59763. {
  59764. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59765. ++numShadows;
  59766. }
  59767. }
  59768. if (numShadows > 0)
  59769. {
  59770. for (int i = numShadows; --i >= 0;)
  59771. {
  59772. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59773. shadowWindows[i]->setVisible (isOwnerVisible);
  59774. }
  59775. const int x = owner->getX();
  59776. const int y = owner->getY() - shadowEdge;
  59777. const int w = owner->getWidth();
  59778. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59779. shadowWindows[0]->setBounds (x - shadowEdge,
  59780. y,
  59781. shadowEdge,
  59782. h);
  59783. shadowWindows[1]->setBounds (x + w,
  59784. y,
  59785. shadowEdge,
  59786. h);
  59787. shadowWindows[2]->setBounds (x,
  59788. y,
  59789. w,
  59790. shadowEdge);
  59791. shadowWindows[3]->setBounds (x,
  59792. owner->getBottom(),
  59793. w,
  59794. shadowEdge);
  59795. }
  59796. reentrant = false;
  59797. if (createShadowWindows)
  59798. bringShadowWindowsToFront();
  59799. }
  59800. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  59801. const int sx, const int sy)
  59802. {
  59803. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  59804. Graphics g (shadowImageSections[num]);
  59805. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59806. }
  59807. void DropShadower::bringShadowWindowsToFront()
  59808. {
  59809. if (! (inDestructor || reentrant))
  59810. {
  59811. updateShadows();
  59812. reentrant = true;
  59813. for (int i = numShadows; --i >= 0;)
  59814. shadowWindows[i]->toBehind (owner);
  59815. reentrant = false;
  59816. }
  59817. }
  59818. END_JUCE_NAMESPACE
  59819. /*** End of inlined file: juce_DropShadower.cpp ***/
  59820. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59821. BEGIN_JUCE_NAMESPACE
  59822. class MagnifyingPeer : public ComponentPeer
  59823. {
  59824. public:
  59825. MagnifyingPeer (Component* const component_,
  59826. MagnifierComponent* const magnifierComp_)
  59827. : ComponentPeer (component_, 0),
  59828. magnifierComp (magnifierComp_)
  59829. {
  59830. }
  59831. ~MagnifyingPeer()
  59832. {
  59833. }
  59834. void* getNativeHandle() const { return 0; }
  59835. void setVisible (bool) {}
  59836. void setTitle (const String&) {}
  59837. void setPosition (int, int) {}
  59838. void setSize (int, int) {}
  59839. void setBounds (int, int, int, int, bool) {}
  59840. void setMinimised (bool) {}
  59841. bool isMinimised() const { return false; }
  59842. void setFullScreen (bool) {}
  59843. bool isFullScreen() const { return false; }
  59844. const BorderSize getFrameSize() const { return BorderSize (0); }
  59845. bool setAlwaysOnTop (bool) { return true; }
  59846. void toFront (bool) {}
  59847. void toBehind (ComponentPeer*) {}
  59848. void setIcon (const Image&) {}
  59849. bool isFocused() const
  59850. {
  59851. return magnifierComp->hasKeyboardFocus (true);
  59852. }
  59853. void grabFocus()
  59854. {
  59855. ComponentPeer* peer = magnifierComp->getPeer();
  59856. if (peer != 0)
  59857. peer->grabFocus();
  59858. }
  59859. void textInputRequired (const Point<int>& position)
  59860. {
  59861. ComponentPeer* peer = magnifierComp->getPeer();
  59862. if (peer != 0)
  59863. peer->textInputRequired (position);
  59864. }
  59865. const Rectangle<int> getBounds() const
  59866. {
  59867. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59868. component->getWidth(), component->getHeight());
  59869. }
  59870. const Point<int> getScreenPosition() const
  59871. {
  59872. return magnifierComp->getScreenPosition();
  59873. }
  59874. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59875. {
  59876. const double zoom = magnifierComp->getScaleFactor();
  59877. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59878. roundToInt (relativePosition.getY() * zoom)));
  59879. }
  59880. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59881. {
  59882. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59883. const double zoom = magnifierComp->getScaleFactor();
  59884. return Point<int> (roundToInt (p.getX() / zoom),
  59885. roundToInt (p.getY() / zoom));
  59886. }
  59887. bool contains (const Point<int>& position, bool) const
  59888. {
  59889. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59890. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59891. }
  59892. void repaint (const Rectangle<int>& area)
  59893. {
  59894. const double zoom = magnifierComp->getScaleFactor();
  59895. magnifierComp->repaint ((int) (area.getX() * zoom),
  59896. (int) (area.getY() * zoom),
  59897. roundToInt (area.getWidth() * zoom) + 1,
  59898. roundToInt (area.getHeight() * zoom) + 1);
  59899. }
  59900. void performAnyPendingRepaintsNow()
  59901. {
  59902. }
  59903. juce_UseDebuggingNewOperator
  59904. private:
  59905. MagnifierComponent* const magnifierComp;
  59906. MagnifyingPeer (const MagnifyingPeer&);
  59907. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59908. };
  59909. class PeerHolderComp : public Component
  59910. {
  59911. public:
  59912. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59913. : magnifierComp (magnifierComp_)
  59914. {
  59915. setVisible (true);
  59916. }
  59917. ~PeerHolderComp()
  59918. {
  59919. }
  59920. ComponentPeer* createNewPeer (int, void*)
  59921. {
  59922. return new MagnifyingPeer (this, magnifierComp);
  59923. }
  59924. void childBoundsChanged (Component* c)
  59925. {
  59926. if (c != 0)
  59927. {
  59928. setSize (c->getWidth(), c->getHeight());
  59929. magnifierComp->childBoundsChanged (this);
  59930. }
  59931. }
  59932. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59933. {
  59934. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59935. Component* const p = magnifierComp->getParentComponent();
  59936. if (p != 0)
  59937. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59938. }
  59939. private:
  59940. MagnifierComponent* const magnifierComp;
  59941. PeerHolderComp (const PeerHolderComp&);
  59942. PeerHolderComp& operator= (const PeerHolderComp&);
  59943. };
  59944. MagnifierComponent::MagnifierComponent (Component* const content_,
  59945. const bool deleteContentCompWhenNoLongerNeeded)
  59946. : content (content_),
  59947. scaleFactor (0.0),
  59948. peer (0),
  59949. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59950. quality (Graphics::lowResamplingQuality),
  59951. mouseSource (0, true)
  59952. {
  59953. holderComp = new PeerHolderComp (this);
  59954. setScaleFactor (1.0);
  59955. }
  59956. MagnifierComponent::~MagnifierComponent()
  59957. {
  59958. delete holderComp;
  59959. if (deleteContent)
  59960. delete content;
  59961. }
  59962. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59963. {
  59964. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59965. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59966. if (scaleFactor != newScaleFactor)
  59967. {
  59968. scaleFactor = newScaleFactor;
  59969. if (scaleFactor == 1.0)
  59970. {
  59971. holderComp->removeFromDesktop();
  59972. peer = 0;
  59973. addChildComponent (content);
  59974. childBoundsChanged (content);
  59975. }
  59976. else
  59977. {
  59978. holderComp->addAndMakeVisible (content);
  59979. holderComp->childBoundsChanged (content);
  59980. childBoundsChanged (holderComp);
  59981. holderComp->addToDesktop (0);
  59982. peer = holderComp->getPeer();
  59983. }
  59984. repaint();
  59985. }
  59986. }
  59987. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59988. {
  59989. quality = newQuality;
  59990. }
  59991. void MagnifierComponent::paint (Graphics& g)
  59992. {
  59993. const int w = holderComp->getWidth();
  59994. const int h = holderComp->getHeight();
  59995. if (w == 0 || h == 0)
  59996. return;
  59997. const Rectangle<int> r (g.getClipBounds());
  59998. const int srcX = (int) (r.getX() / scaleFactor);
  59999. const int srcY = (int) (r.getY() / scaleFactor);
  60000. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60001. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60002. if (scaleFactor >= 1.0)
  60003. {
  60004. ++srcW;
  60005. ++srcH;
  60006. }
  60007. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60008. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60009. {
  60010. Graphics g2 (temp);
  60011. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60012. holderComp->paintEntireComponent (g2);
  60013. }
  60014. g.setImageResamplingQuality (quality);
  60015. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60016. }
  60017. void MagnifierComponent::childBoundsChanged (Component* c)
  60018. {
  60019. if (c != 0)
  60020. setSize (roundToInt (c->getWidth() * scaleFactor),
  60021. roundToInt (c->getHeight() * scaleFactor));
  60022. }
  60023. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60024. {
  60025. if (peer != 0)
  60026. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60027. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60028. }
  60029. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60030. {
  60031. passOnMouseEventToPeer (e);
  60032. }
  60033. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60034. {
  60035. passOnMouseEventToPeer (e);
  60036. }
  60037. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60038. {
  60039. passOnMouseEventToPeer (e);
  60040. }
  60041. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60042. {
  60043. passOnMouseEventToPeer (e);
  60044. }
  60045. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60046. {
  60047. passOnMouseEventToPeer (e);
  60048. }
  60049. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60050. {
  60051. passOnMouseEventToPeer (e);
  60052. }
  60053. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60054. {
  60055. if (peer != 0)
  60056. peer->handleMouseWheel (e.source.getIndex(),
  60057. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60058. ix * 256.0f, iy * 256.0f);
  60059. else
  60060. Component::mouseWheelMove (e, ix, iy);
  60061. }
  60062. int MagnifierComponent::scaleInt (const int n) const
  60063. {
  60064. return roundToInt (n / scaleFactor);
  60065. }
  60066. END_JUCE_NAMESPACE
  60067. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60068. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60069. BEGIN_JUCE_NAMESPACE
  60070. class MidiKeyboardUpDownButton : public Button
  60071. {
  60072. public:
  60073. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60074. const int delta_)
  60075. : Button (String::empty),
  60076. owner (owner_),
  60077. delta (delta_)
  60078. {
  60079. setOpaque (true);
  60080. }
  60081. ~MidiKeyboardUpDownButton()
  60082. {
  60083. }
  60084. void clicked()
  60085. {
  60086. int note = owner->getLowestVisibleKey();
  60087. if (delta < 0)
  60088. note = (note - 1) / 12;
  60089. else
  60090. note = note / 12 + 1;
  60091. owner->setLowestVisibleKey (note * 12);
  60092. }
  60093. void paintButton (Graphics& g,
  60094. bool isMouseOverButton,
  60095. bool isButtonDown)
  60096. {
  60097. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60098. isMouseOverButton, isButtonDown,
  60099. delta > 0);
  60100. }
  60101. private:
  60102. MidiKeyboardComponent* const owner;
  60103. const int delta;
  60104. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60105. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60106. };
  60107. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60108. const Orientation orientation_)
  60109. : state (state_),
  60110. xOffset (0),
  60111. blackNoteLength (1),
  60112. keyWidth (16.0f),
  60113. orientation (orientation_),
  60114. midiChannel (1),
  60115. midiInChannelMask (0xffff),
  60116. velocity (1.0f),
  60117. noteUnderMouse (-1),
  60118. mouseDownNote (-1),
  60119. rangeStart (0),
  60120. rangeEnd (127),
  60121. firstKey (12 * 4),
  60122. canScroll (true),
  60123. mouseDragging (false),
  60124. useMousePositionForVelocity (true),
  60125. keyMappingOctave (6),
  60126. octaveNumForMiddleC (3)
  60127. {
  60128. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60129. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60130. // initialise with a default set of querty key-mappings..
  60131. const char* const keymap = "awsedftgyhujkolp;";
  60132. for (int i = String (keymap).length(); --i >= 0;)
  60133. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60134. setOpaque (true);
  60135. setWantsKeyboardFocus (true);
  60136. state.addListener (this);
  60137. }
  60138. MidiKeyboardComponent::~MidiKeyboardComponent()
  60139. {
  60140. state.removeListener (this);
  60141. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60142. deleteAllChildren();
  60143. }
  60144. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60145. {
  60146. keyWidth = widthInPixels;
  60147. resized();
  60148. }
  60149. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60150. {
  60151. if (orientation != newOrientation)
  60152. {
  60153. orientation = newOrientation;
  60154. resized();
  60155. }
  60156. }
  60157. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60158. const int highestNote)
  60159. {
  60160. jassert (lowestNote >= 0 && lowestNote <= 127);
  60161. jassert (highestNote >= 0 && highestNote <= 127);
  60162. jassert (lowestNote <= highestNote);
  60163. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60164. {
  60165. rangeStart = jlimit (0, 127, lowestNote);
  60166. rangeEnd = jlimit (0, 127, highestNote);
  60167. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60168. resized();
  60169. }
  60170. }
  60171. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60172. {
  60173. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60174. if (noteNumber != firstKey)
  60175. {
  60176. firstKey = noteNumber;
  60177. sendChangeMessage (this);
  60178. resized();
  60179. }
  60180. }
  60181. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60182. {
  60183. if (canScroll != canScroll_)
  60184. {
  60185. canScroll = canScroll_;
  60186. resized();
  60187. }
  60188. }
  60189. void MidiKeyboardComponent::colourChanged()
  60190. {
  60191. repaint();
  60192. }
  60193. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60194. {
  60195. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60196. if (midiChannel != midiChannelNumber)
  60197. {
  60198. resetAnyKeysInUse();
  60199. midiChannel = jlimit (1, 16, midiChannelNumber);
  60200. }
  60201. }
  60202. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60203. {
  60204. midiInChannelMask = midiChannelMask;
  60205. triggerAsyncUpdate();
  60206. }
  60207. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60208. {
  60209. velocity = jlimit (0.0f, 1.0f, velocity_);
  60210. useMousePositionForVelocity = useMousePositionForVelocity_;
  60211. }
  60212. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60213. {
  60214. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60215. static const float blackNoteWidth = 0.7f;
  60216. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60217. 1.0f, 2 - blackNoteWidth * 0.4f,
  60218. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60219. 4.0f, 5 - blackNoteWidth * 0.5f,
  60220. 5.0f, 6 - blackNoteWidth * 0.3f,
  60221. 6.0f };
  60222. static const float widths[] = { 1.0f, blackNoteWidth,
  60223. 1.0f, blackNoteWidth,
  60224. 1.0f, 1.0f, blackNoteWidth,
  60225. 1.0f, blackNoteWidth,
  60226. 1.0f, blackNoteWidth,
  60227. 1.0f };
  60228. const int octave = midiNoteNumber / 12;
  60229. const int note = midiNoteNumber % 12;
  60230. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60231. w = roundToInt (widths [note] * keyWidth_);
  60232. }
  60233. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60234. {
  60235. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60236. int rx, rw;
  60237. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60238. x -= xOffset + rx;
  60239. }
  60240. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60241. {
  60242. int x, y;
  60243. getKeyPos (midiNoteNumber, x, y);
  60244. return x;
  60245. }
  60246. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60247. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60248. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60249. {
  60250. if (! reallyContains (pos.getX(), pos.getY(), false))
  60251. return -1;
  60252. Point<int> p (pos);
  60253. if (orientation != horizontalKeyboard)
  60254. {
  60255. p = Point<int> (p.getY(), p.getX());
  60256. if (orientation == verticalKeyboardFacingLeft)
  60257. p = Point<int> (p.getX(), getWidth() - p.getY());
  60258. else
  60259. p = Point<int> (getHeight() - p.getX(), p.getY());
  60260. }
  60261. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60262. }
  60263. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60264. {
  60265. if (pos.getY() < blackNoteLength)
  60266. {
  60267. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60268. {
  60269. for (int i = 0; i < 5; ++i)
  60270. {
  60271. const int note = octaveStart + blackNotes [i];
  60272. if (note >= rangeStart && note <= rangeEnd)
  60273. {
  60274. int kx, kw;
  60275. getKeyPos (note, kx, kw);
  60276. kx += xOffset;
  60277. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60278. {
  60279. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60280. return note;
  60281. }
  60282. }
  60283. }
  60284. }
  60285. }
  60286. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60287. {
  60288. for (int i = 0; i < 7; ++i)
  60289. {
  60290. const int note = octaveStart + whiteNotes [i];
  60291. if (note >= rangeStart && note <= rangeEnd)
  60292. {
  60293. int kx, kw;
  60294. getKeyPos (note, kx, kw);
  60295. kx += xOffset;
  60296. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60297. {
  60298. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60299. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60300. return note;
  60301. }
  60302. }
  60303. }
  60304. }
  60305. mousePositionVelocity = 0;
  60306. return -1;
  60307. }
  60308. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60309. {
  60310. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60311. {
  60312. int x, w;
  60313. getKeyPos (noteNum, x, w);
  60314. if (orientation == horizontalKeyboard)
  60315. repaint (x, 0, w, getHeight());
  60316. else if (orientation == verticalKeyboardFacingLeft)
  60317. repaint (0, x, getWidth(), w);
  60318. else if (orientation == verticalKeyboardFacingRight)
  60319. repaint (0, getHeight() - x - w, getWidth(), w);
  60320. }
  60321. }
  60322. void MidiKeyboardComponent::paint (Graphics& g)
  60323. {
  60324. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60325. const Colour lineColour (findColour (keySeparatorLineColourId));
  60326. const Colour textColour (findColour (textLabelColourId));
  60327. int x, w, octave;
  60328. for (octave = 0; octave < 128; octave += 12)
  60329. {
  60330. for (int white = 0; white < 7; ++white)
  60331. {
  60332. const int noteNum = octave + whiteNotes [white];
  60333. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60334. {
  60335. getKeyPos (noteNum, x, w);
  60336. if (orientation == horizontalKeyboard)
  60337. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60338. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60339. noteUnderMouse == noteNum,
  60340. lineColour, textColour);
  60341. else if (orientation == verticalKeyboardFacingLeft)
  60342. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60343. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60344. noteUnderMouse == noteNum,
  60345. lineColour, textColour);
  60346. else if (orientation == verticalKeyboardFacingRight)
  60347. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60348. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60349. noteUnderMouse == noteNum,
  60350. lineColour, textColour);
  60351. }
  60352. }
  60353. }
  60354. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60355. if (orientation == verticalKeyboardFacingLeft)
  60356. {
  60357. x1 = getWidth() - 1.0f;
  60358. x2 = getWidth() - 5.0f;
  60359. }
  60360. else if (orientation == verticalKeyboardFacingRight)
  60361. x2 = 5.0f;
  60362. else
  60363. y2 = 5.0f;
  60364. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60365. Colours::transparentBlack, x2, y2, false));
  60366. getKeyPos (rangeEnd, x, w);
  60367. x += w;
  60368. if (orientation == verticalKeyboardFacingLeft)
  60369. g.fillRect (getWidth() - 5, 0, 5, x);
  60370. else if (orientation == verticalKeyboardFacingRight)
  60371. g.fillRect (0, 0, 5, x);
  60372. else
  60373. g.fillRect (0, 0, x, 5);
  60374. g.setColour (lineColour);
  60375. if (orientation == verticalKeyboardFacingLeft)
  60376. g.fillRect (0, 0, 1, x);
  60377. else if (orientation == verticalKeyboardFacingRight)
  60378. g.fillRect (getWidth() - 1, 0, 1, x);
  60379. else
  60380. g.fillRect (0, getHeight() - 1, x, 1);
  60381. const Colour blackNoteColour (findColour (blackNoteColourId));
  60382. for (octave = 0; octave < 128; octave += 12)
  60383. {
  60384. for (int black = 0; black < 5; ++black)
  60385. {
  60386. const int noteNum = octave + blackNotes [black];
  60387. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60388. {
  60389. getKeyPos (noteNum, x, w);
  60390. if (orientation == horizontalKeyboard)
  60391. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60392. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60393. noteUnderMouse == noteNum,
  60394. blackNoteColour);
  60395. else if (orientation == verticalKeyboardFacingLeft)
  60396. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60397. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60398. noteUnderMouse == noteNum,
  60399. blackNoteColour);
  60400. else if (orientation == verticalKeyboardFacingRight)
  60401. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60402. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60403. noteUnderMouse == noteNum,
  60404. blackNoteColour);
  60405. }
  60406. }
  60407. }
  60408. }
  60409. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60410. Graphics& g, int x, int y, int w, int h,
  60411. bool isDown, bool isOver,
  60412. const Colour& lineColour,
  60413. const Colour& textColour)
  60414. {
  60415. Colour c (Colours::transparentWhite);
  60416. if (isDown)
  60417. c = findColour (keyDownOverlayColourId);
  60418. if (isOver)
  60419. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60420. g.setColour (c);
  60421. g.fillRect (x, y, w, h);
  60422. const String text (getWhiteNoteText (midiNoteNumber));
  60423. if (! text.isEmpty())
  60424. {
  60425. g.setColour (textColour);
  60426. Font f (jmin (12.0f, keyWidth * 0.9f));
  60427. f.setHorizontalScale (0.8f);
  60428. g.setFont (f);
  60429. Justification justification (Justification::centredBottom);
  60430. if (orientation == verticalKeyboardFacingLeft)
  60431. justification = Justification::centredLeft;
  60432. else if (orientation == verticalKeyboardFacingRight)
  60433. justification = Justification::centredRight;
  60434. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60435. }
  60436. g.setColour (lineColour);
  60437. if (orientation == horizontalKeyboard)
  60438. g.fillRect (x, y, 1, h);
  60439. else if (orientation == verticalKeyboardFacingLeft)
  60440. g.fillRect (x, y, w, 1);
  60441. else if (orientation == verticalKeyboardFacingRight)
  60442. g.fillRect (x, y + h - 1, w, 1);
  60443. if (midiNoteNumber == rangeEnd)
  60444. {
  60445. if (orientation == horizontalKeyboard)
  60446. g.fillRect (x + w, y, 1, h);
  60447. else if (orientation == verticalKeyboardFacingLeft)
  60448. g.fillRect (x, y + h, w, 1);
  60449. else if (orientation == verticalKeyboardFacingRight)
  60450. g.fillRect (x, y - 1, w, 1);
  60451. }
  60452. }
  60453. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60454. Graphics& g, int x, int y, int w, int h,
  60455. bool isDown, bool isOver,
  60456. const Colour& noteFillColour)
  60457. {
  60458. Colour c (noteFillColour);
  60459. if (isDown)
  60460. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60461. if (isOver)
  60462. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60463. g.setColour (c);
  60464. g.fillRect (x, y, w, h);
  60465. if (isDown)
  60466. {
  60467. g.setColour (noteFillColour);
  60468. g.drawRect (x, y, w, h);
  60469. }
  60470. else
  60471. {
  60472. const int xIndent = jmax (1, jmin (w, h) / 8);
  60473. g.setColour (c.brighter());
  60474. if (orientation == horizontalKeyboard)
  60475. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60476. else if (orientation == verticalKeyboardFacingLeft)
  60477. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60478. else if (orientation == verticalKeyboardFacingRight)
  60479. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60480. }
  60481. }
  60482. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60483. {
  60484. octaveNumForMiddleC = octaveNumForMiddleC_;
  60485. repaint();
  60486. }
  60487. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60488. {
  60489. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60490. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60491. return String::empty;
  60492. }
  60493. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60494. const bool isMouseOver_,
  60495. const bool isButtonDown,
  60496. const bool movesOctavesUp)
  60497. {
  60498. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60499. float angle;
  60500. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60501. angle = movesOctavesUp ? 0.0f : 0.5f;
  60502. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60503. angle = movesOctavesUp ? 0.25f : 0.75f;
  60504. else
  60505. angle = movesOctavesUp ? 0.75f : 0.25f;
  60506. Path path;
  60507. path.lineTo (0.0f, 1.0f);
  60508. path.lineTo (1.0f, 0.5f);
  60509. path.closeSubPath();
  60510. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60511. g.setColour (findColour (upDownButtonArrowColourId)
  60512. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60513. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60514. w - 2.0f,
  60515. h - 2.0f,
  60516. true));
  60517. }
  60518. void MidiKeyboardComponent::resized()
  60519. {
  60520. int w = getWidth();
  60521. int h = getHeight();
  60522. if (w > 0 && h > 0)
  60523. {
  60524. if (orientation != horizontalKeyboard)
  60525. swapVariables (w, h);
  60526. blackNoteLength = roundToInt (h * 0.7f);
  60527. int kx2, kw2;
  60528. getKeyPos (rangeEnd, kx2, kw2);
  60529. kx2 += kw2;
  60530. if (firstKey != rangeStart)
  60531. {
  60532. int kx1, kw1;
  60533. getKeyPos (rangeStart, kx1, kw1);
  60534. if (kx2 - kx1 <= w)
  60535. {
  60536. firstKey = rangeStart;
  60537. sendChangeMessage (this);
  60538. repaint();
  60539. }
  60540. }
  60541. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60542. scrollDown->setVisible (showScrollButtons);
  60543. scrollUp->setVisible (showScrollButtons);
  60544. xOffset = 0;
  60545. if (showScrollButtons)
  60546. {
  60547. const int scrollButtonW = jmin (12, w / 2);
  60548. if (orientation == horizontalKeyboard)
  60549. {
  60550. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60551. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60552. }
  60553. else if (orientation == verticalKeyboardFacingLeft)
  60554. {
  60555. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60556. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60557. }
  60558. else if (orientation == verticalKeyboardFacingRight)
  60559. {
  60560. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60561. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60562. }
  60563. int endOfLastKey, kw;
  60564. getKeyPos (rangeEnd, endOfLastKey, kw);
  60565. endOfLastKey += kw;
  60566. float mousePositionVelocity;
  60567. const int spaceAvailable = w - scrollButtonW * 2;
  60568. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60569. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60570. {
  60571. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60572. sendChangeMessage (this);
  60573. }
  60574. int newOffset = 0;
  60575. getKeyPos (firstKey, newOffset, kw);
  60576. xOffset = newOffset - scrollButtonW;
  60577. }
  60578. else
  60579. {
  60580. firstKey = rangeStart;
  60581. }
  60582. timerCallback();
  60583. repaint();
  60584. }
  60585. }
  60586. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60587. {
  60588. triggerAsyncUpdate();
  60589. }
  60590. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60591. {
  60592. triggerAsyncUpdate();
  60593. }
  60594. void MidiKeyboardComponent::handleAsyncUpdate()
  60595. {
  60596. for (int i = rangeStart; i <= rangeEnd; ++i)
  60597. {
  60598. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60599. {
  60600. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60601. repaintNote (i);
  60602. }
  60603. }
  60604. }
  60605. void MidiKeyboardComponent::resetAnyKeysInUse()
  60606. {
  60607. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60608. {
  60609. state.allNotesOff (midiChannel);
  60610. keysPressed.clear();
  60611. mouseDownNote = -1;
  60612. }
  60613. }
  60614. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60615. {
  60616. float mousePositionVelocity = 0.0f;
  60617. const int newNote = (mouseDragging || isMouseOver())
  60618. ? xyToNote (pos, mousePositionVelocity) : -1;
  60619. if (noteUnderMouse != newNote)
  60620. {
  60621. if (mouseDownNote >= 0)
  60622. {
  60623. state.noteOff (midiChannel, mouseDownNote);
  60624. mouseDownNote = -1;
  60625. }
  60626. if (mouseDragging && newNote >= 0)
  60627. {
  60628. if (! useMousePositionForVelocity)
  60629. mousePositionVelocity = 1.0f;
  60630. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60631. mouseDownNote = newNote;
  60632. }
  60633. repaintNote (noteUnderMouse);
  60634. noteUnderMouse = newNote;
  60635. repaintNote (noteUnderMouse);
  60636. }
  60637. else if (mouseDownNote >= 0 && ! mouseDragging)
  60638. {
  60639. state.noteOff (midiChannel, mouseDownNote);
  60640. mouseDownNote = -1;
  60641. }
  60642. }
  60643. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60644. {
  60645. updateNoteUnderMouse (e.getPosition());
  60646. stopTimer();
  60647. }
  60648. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60649. {
  60650. float mousePositionVelocity;
  60651. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60652. if (newNote >= 0)
  60653. mouseDraggedToKey (newNote, e);
  60654. updateNoteUnderMouse (e.getPosition());
  60655. }
  60656. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60657. {
  60658. return true;
  60659. }
  60660. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60661. {
  60662. }
  60663. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60664. {
  60665. float mousePositionVelocity;
  60666. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60667. mouseDragging = false;
  60668. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60669. {
  60670. repaintNote (noteUnderMouse);
  60671. noteUnderMouse = -1;
  60672. mouseDragging = true;
  60673. updateNoteUnderMouse (e.getPosition());
  60674. startTimer (500);
  60675. }
  60676. }
  60677. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60678. {
  60679. mouseDragging = false;
  60680. updateNoteUnderMouse (e.getPosition());
  60681. stopTimer();
  60682. }
  60683. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60684. {
  60685. updateNoteUnderMouse (e.getPosition());
  60686. }
  60687. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60688. {
  60689. updateNoteUnderMouse (e.getPosition());
  60690. }
  60691. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60692. {
  60693. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60694. }
  60695. void MidiKeyboardComponent::timerCallback()
  60696. {
  60697. updateNoteUnderMouse (getMouseXYRelative());
  60698. }
  60699. void MidiKeyboardComponent::clearKeyMappings()
  60700. {
  60701. resetAnyKeysInUse();
  60702. keyPressNotes.clear();
  60703. keyPresses.clear();
  60704. }
  60705. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60706. const int midiNoteOffsetFromC)
  60707. {
  60708. removeKeyPressForNote (midiNoteOffsetFromC);
  60709. keyPressNotes.add (midiNoteOffsetFromC);
  60710. keyPresses.add (key);
  60711. }
  60712. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60713. {
  60714. for (int i = keyPressNotes.size(); --i >= 0;)
  60715. {
  60716. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60717. {
  60718. keyPressNotes.remove (i);
  60719. keyPresses.remove (i);
  60720. }
  60721. }
  60722. }
  60723. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60724. {
  60725. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60726. keyMappingOctave = newOctaveNumber;
  60727. }
  60728. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60729. {
  60730. bool keyPressUsed = false;
  60731. for (int i = keyPresses.size(); --i >= 0;)
  60732. {
  60733. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60734. if (keyPresses.getReference(i).isCurrentlyDown())
  60735. {
  60736. if (! keysPressed [note])
  60737. {
  60738. keysPressed.setBit (note);
  60739. state.noteOn (midiChannel, note, velocity);
  60740. keyPressUsed = true;
  60741. }
  60742. }
  60743. else
  60744. {
  60745. if (keysPressed [note])
  60746. {
  60747. keysPressed.clearBit (note);
  60748. state.noteOff (midiChannel, note);
  60749. keyPressUsed = true;
  60750. }
  60751. }
  60752. }
  60753. return keyPressUsed;
  60754. }
  60755. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60756. {
  60757. resetAnyKeysInUse();
  60758. }
  60759. END_JUCE_NAMESPACE
  60760. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60761. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60762. #if JUCE_OPENGL
  60763. BEGIN_JUCE_NAMESPACE
  60764. extern void juce_glViewport (const int w, const int h);
  60765. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60766. const int alphaBits_,
  60767. const int depthBufferBits_,
  60768. const int stencilBufferBits_)
  60769. : redBits (bitsPerRGBComponent),
  60770. greenBits (bitsPerRGBComponent),
  60771. blueBits (bitsPerRGBComponent),
  60772. alphaBits (alphaBits_),
  60773. depthBufferBits (depthBufferBits_),
  60774. stencilBufferBits (stencilBufferBits_),
  60775. accumulationBufferRedBits (0),
  60776. accumulationBufferGreenBits (0),
  60777. accumulationBufferBlueBits (0),
  60778. accumulationBufferAlphaBits (0),
  60779. fullSceneAntiAliasingNumSamples (0)
  60780. {
  60781. }
  60782. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60783. : redBits (other.redBits),
  60784. greenBits (other.greenBits),
  60785. blueBits (other.blueBits),
  60786. alphaBits (other.alphaBits),
  60787. depthBufferBits (other.depthBufferBits),
  60788. stencilBufferBits (other.stencilBufferBits),
  60789. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60790. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60791. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60792. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60793. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60794. {
  60795. }
  60796. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60797. {
  60798. redBits = other.redBits;
  60799. greenBits = other.greenBits;
  60800. blueBits = other.blueBits;
  60801. alphaBits = other.alphaBits;
  60802. depthBufferBits = other.depthBufferBits;
  60803. stencilBufferBits = other.stencilBufferBits;
  60804. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60805. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60806. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60807. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60808. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60809. return *this;
  60810. }
  60811. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60812. {
  60813. return redBits == other.redBits
  60814. && greenBits == other.greenBits
  60815. && blueBits == other.blueBits
  60816. && alphaBits == other.alphaBits
  60817. && depthBufferBits == other.depthBufferBits
  60818. && stencilBufferBits == other.stencilBufferBits
  60819. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60820. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60821. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60822. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60823. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60824. }
  60825. static Array<OpenGLContext*> knownContexts;
  60826. OpenGLContext::OpenGLContext() throw()
  60827. {
  60828. knownContexts.add (this);
  60829. }
  60830. OpenGLContext::~OpenGLContext()
  60831. {
  60832. knownContexts.removeValue (this);
  60833. }
  60834. OpenGLContext* OpenGLContext::getCurrentContext()
  60835. {
  60836. for (int i = knownContexts.size(); --i >= 0;)
  60837. {
  60838. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60839. if (oglc->isActive())
  60840. return oglc;
  60841. }
  60842. return 0;
  60843. }
  60844. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60845. {
  60846. public:
  60847. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60848. : ComponentMovementWatcher (owner_),
  60849. owner (owner_),
  60850. wasShowing (false)
  60851. {
  60852. }
  60853. ~OpenGLComponentWatcher() {}
  60854. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60855. {
  60856. owner->updateContextPosition();
  60857. }
  60858. void componentPeerChanged()
  60859. {
  60860. const ScopedLock sl (owner->getContextLock());
  60861. owner->deleteContext();
  60862. }
  60863. void componentVisibilityChanged (Component&)
  60864. {
  60865. const bool isShowingNow = owner->isShowing();
  60866. if (wasShowing != isShowingNow)
  60867. {
  60868. wasShowing = isShowingNow;
  60869. if (! isShowingNow)
  60870. {
  60871. const ScopedLock sl (owner->getContextLock());
  60872. owner->deleteContext();
  60873. }
  60874. }
  60875. }
  60876. juce_UseDebuggingNewOperator
  60877. private:
  60878. OpenGLComponent* const owner;
  60879. bool wasShowing;
  60880. };
  60881. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60882. : type (type_),
  60883. contextToShareListsWith (0),
  60884. needToUpdateViewport (true)
  60885. {
  60886. setOpaque (true);
  60887. componentWatcher = new OpenGLComponentWatcher (this);
  60888. }
  60889. OpenGLComponent::~OpenGLComponent()
  60890. {
  60891. deleteContext();
  60892. componentWatcher = 0;
  60893. }
  60894. void OpenGLComponent::deleteContext()
  60895. {
  60896. const ScopedLock sl (contextLock);
  60897. context = 0;
  60898. }
  60899. void OpenGLComponent::updateContextPosition()
  60900. {
  60901. needToUpdateViewport = true;
  60902. if (getWidth() > 0 && getHeight() > 0)
  60903. {
  60904. Component* const topComp = getTopLevelComponent();
  60905. if (topComp->getPeer() != 0)
  60906. {
  60907. const ScopedLock sl (contextLock);
  60908. if (context != 0)
  60909. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60910. getScreenY() - topComp->getScreenY(),
  60911. getWidth(),
  60912. getHeight(),
  60913. topComp->getHeight());
  60914. }
  60915. }
  60916. }
  60917. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60918. {
  60919. OpenGLPixelFormat pf;
  60920. const ScopedLock sl (contextLock);
  60921. if (context != 0)
  60922. pf = context->getPixelFormat();
  60923. return pf;
  60924. }
  60925. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60926. {
  60927. if (! (preferredPixelFormat == formatToUse))
  60928. {
  60929. const ScopedLock sl (contextLock);
  60930. deleteContext();
  60931. preferredPixelFormat = formatToUse;
  60932. }
  60933. }
  60934. void OpenGLComponent::shareWith (OpenGLContext* c)
  60935. {
  60936. if (contextToShareListsWith != c)
  60937. {
  60938. const ScopedLock sl (contextLock);
  60939. deleteContext();
  60940. contextToShareListsWith = c;
  60941. }
  60942. }
  60943. bool OpenGLComponent::makeCurrentContextActive()
  60944. {
  60945. if (context == 0)
  60946. {
  60947. const ScopedLock sl (contextLock);
  60948. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60949. {
  60950. context = createContext();
  60951. if (context != 0)
  60952. {
  60953. updateContextPosition();
  60954. if (context->makeActive())
  60955. newOpenGLContextCreated();
  60956. }
  60957. }
  60958. }
  60959. return context != 0 && context->makeActive();
  60960. }
  60961. void OpenGLComponent::makeCurrentContextInactive()
  60962. {
  60963. if (context != 0)
  60964. context->makeInactive();
  60965. }
  60966. bool OpenGLComponent::isActiveContext() const throw()
  60967. {
  60968. return context != 0 && context->isActive();
  60969. }
  60970. void OpenGLComponent::swapBuffers()
  60971. {
  60972. if (context != 0)
  60973. context->swapBuffers();
  60974. }
  60975. void OpenGLComponent::paint (Graphics&)
  60976. {
  60977. if (renderAndSwapBuffers())
  60978. {
  60979. ComponentPeer* const peer = getPeer();
  60980. if (peer != 0)
  60981. {
  60982. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60983. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60984. }
  60985. }
  60986. }
  60987. bool OpenGLComponent::renderAndSwapBuffers()
  60988. {
  60989. const ScopedLock sl (contextLock);
  60990. if (! makeCurrentContextActive())
  60991. return false;
  60992. if (needToUpdateViewport)
  60993. {
  60994. needToUpdateViewport = false;
  60995. juce_glViewport (getWidth(), getHeight());
  60996. }
  60997. renderOpenGL();
  60998. swapBuffers();
  60999. return true;
  61000. }
  61001. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61002. {
  61003. Component::internalRepaint (x, y, w, h);
  61004. if (context != 0)
  61005. context->repaint();
  61006. }
  61007. END_JUCE_NAMESPACE
  61008. #endif
  61009. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61010. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61011. BEGIN_JUCE_NAMESPACE
  61012. PreferencesPanel::PreferencesPanel()
  61013. : buttonSize (70)
  61014. {
  61015. }
  61016. PreferencesPanel::~PreferencesPanel()
  61017. {
  61018. currentPage = 0;
  61019. deleteAllChildren();
  61020. }
  61021. void PreferencesPanel::addSettingsPage (const String& title,
  61022. const Drawable* icon,
  61023. const Drawable* overIcon,
  61024. const Drawable* downIcon)
  61025. {
  61026. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61027. button->setImages (icon, overIcon, downIcon);
  61028. button->setRadioGroupId (1);
  61029. button->addButtonListener (this);
  61030. button->setClickingTogglesState (true);
  61031. button->setWantsKeyboardFocus (false);
  61032. addAndMakeVisible (button);
  61033. resized();
  61034. if (currentPage == 0)
  61035. setCurrentPage (title);
  61036. }
  61037. void PreferencesPanel::addSettingsPage (const String& title,
  61038. const void* imageData,
  61039. const int imageDataSize)
  61040. {
  61041. DrawableImage icon, iconOver, iconDown;
  61042. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61043. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61044. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61045. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61046. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61047. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61048. }
  61049. class PrefsDialogWindow : public DialogWindow
  61050. {
  61051. public:
  61052. PrefsDialogWindow (const String& dialogtitle,
  61053. const Colour& backgroundColour)
  61054. : DialogWindow (dialogtitle, backgroundColour, true)
  61055. {
  61056. }
  61057. ~PrefsDialogWindow()
  61058. {
  61059. }
  61060. void closeButtonPressed()
  61061. {
  61062. exitModalState (0);
  61063. }
  61064. private:
  61065. PrefsDialogWindow (const PrefsDialogWindow&);
  61066. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61067. };
  61068. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61069. int dialogWidth,
  61070. int dialogHeight,
  61071. const Colour& backgroundColour)
  61072. {
  61073. setSize (dialogWidth, dialogHeight);
  61074. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61075. dw.setContentComponent (this, true, true);
  61076. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61077. dw.runModalLoop();
  61078. dw.setContentComponent (0, false, false);
  61079. }
  61080. void PreferencesPanel::resized()
  61081. {
  61082. int x = 0;
  61083. for (int i = 0; i < getNumChildComponents(); ++i)
  61084. {
  61085. Component* c = getChildComponent (i);
  61086. if (dynamic_cast <DrawableButton*> (c) == 0)
  61087. {
  61088. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61089. }
  61090. else
  61091. {
  61092. c->setBounds (x, 0, buttonSize, buttonSize);
  61093. x += buttonSize;
  61094. }
  61095. }
  61096. }
  61097. void PreferencesPanel::paint (Graphics& g)
  61098. {
  61099. g.setColour (Colours::grey);
  61100. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61101. }
  61102. void PreferencesPanel::setCurrentPage (const String& pageName)
  61103. {
  61104. if (currentPageName != pageName)
  61105. {
  61106. currentPageName = pageName;
  61107. currentPage = 0;
  61108. currentPage = createComponentForPage (pageName);
  61109. if (currentPage != 0)
  61110. {
  61111. addAndMakeVisible (currentPage);
  61112. currentPage->toBack();
  61113. resized();
  61114. }
  61115. for (int i = 0; i < getNumChildComponents(); ++i)
  61116. {
  61117. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61118. if (db != 0 && db->getName() == pageName)
  61119. {
  61120. db->setToggleState (true, false);
  61121. break;
  61122. }
  61123. }
  61124. }
  61125. }
  61126. void PreferencesPanel::buttonClicked (Button*)
  61127. {
  61128. for (int i = 0; i < getNumChildComponents(); ++i)
  61129. {
  61130. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61131. if (db != 0 && db->getToggleState())
  61132. {
  61133. setCurrentPage (db->getName());
  61134. break;
  61135. }
  61136. }
  61137. }
  61138. END_JUCE_NAMESPACE
  61139. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61140. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61141. #if JUCE_WINDOWS || JUCE_LINUX
  61142. BEGIN_JUCE_NAMESPACE
  61143. SystemTrayIconComponent::SystemTrayIconComponent()
  61144. {
  61145. addToDesktop (0);
  61146. }
  61147. SystemTrayIconComponent::~SystemTrayIconComponent()
  61148. {
  61149. }
  61150. END_JUCE_NAMESPACE
  61151. #endif
  61152. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61153. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61154. BEGIN_JUCE_NAMESPACE
  61155. class AlertWindowTextEditor : public TextEditor
  61156. {
  61157. public:
  61158. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61159. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61160. {
  61161. setSelectAllWhenFocused (true);
  61162. }
  61163. ~AlertWindowTextEditor()
  61164. {
  61165. }
  61166. void returnPressed()
  61167. {
  61168. // pass these up the component hierarchy to be trigger the buttons
  61169. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61170. }
  61171. void escapePressed()
  61172. {
  61173. // pass these up the component hierarchy to be trigger the buttons
  61174. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61175. }
  61176. private:
  61177. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61178. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61179. static juce_wchar getDefaultPasswordChar() throw()
  61180. {
  61181. #if JUCE_LINUX
  61182. return 0x2022;
  61183. #else
  61184. return 0x25cf;
  61185. #endif
  61186. }
  61187. };
  61188. AlertWindow::AlertWindow (const String& title,
  61189. const String& message,
  61190. AlertIconType iconType,
  61191. Component* associatedComponent_)
  61192. : TopLevelWindow (title, true),
  61193. alertIconType (iconType),
  61194. associatedComponent (associatedComponent_)
  61195. {
  61196. if (message.isEmpty())
  61197. text = " "; // to force an update if the message is empty
  61198. setMessage (message);
  61199. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61200. {
  61201. Component* const c = Desktop::getInstance().getComponent (i);
  61202. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61203. {
  61204. setAlwaysOnTop (true);
  61205. break;
  61206. }
  61207. }
  61208. if (JUCEApplication::getInstance() == 0)
  61209. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61210. lookAndFeelChanged();
  61211. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61212. }
  61213. AlertWindow::~AlertWindow()
  61214. {
  61215. for (int i = customComps.size(); --i >= 0;)
  61216. removeChildComponent ((Component*) customComps[i]);
  61217. deleteAllChildren();
  61218. }
  61219. void AlertWindow::userTriedToCloseWindow()
  61220. {
  61221. exitModalState (0);
  61222. }
  61223. void AlertWindow::setMessage (const String& message)
  61224. {
  61225. const String newMessage (message.substring (0, 2048));
  61226. if (text != newMessage)
  61227. {
  61228. text = newMessage;
  61229. font.setHeight (15.0f);
  61230. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61231. textLayout.setText (getName() + "\n\n", titleFont);
  61232. textLayout.appendText (text, font);
  61233. updateLayout (true);
  61234. repaint();
  61235. }
  61236. }
  61237. void AlertWindow::buttonClicked (Button* button)
  61238. {
  61239. for (int i = 0; i < buttons.size(); i++)
  61240. {
  61241. TextButton* const c = (TextButton*) buttons[i];
  61242. if (button->getName() == c->getName())
  61243. {
  61244. if (c->getParentComponent() != 0)
  61245. c->getParentComponent()->exitModalState (c->getCommandID());
  61246. break;
  61247. }
  61248. }
  61249. }
  61250. void AlertWindow::addButton (const String& name,
  61251. const int returnValue,
  61252. const KeyPress& shortcutKey1,
  61253. const KeyPress& shortcutKey2)
  61254. {
  61255. TextButton* const b = new TextButton (name, String::empty);
  61256. b->setWantsKeyboardFocus (true);
  61257. b->setMouseClickGrabsKeyboardFocus (false);
  61258. b->setCommandToTrigger (0, returnValue, false);
  61259. b->addShortcut (shortcutKey1);
  61260. b->addShortcut (shortcutKey2);
  61261. b->addButtonListener (this);
  61262. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61263. addAndMakeVisible (b, 0);
  61264. buttons.add (b);
  61265. updateLayout (false);
  61266. }
  61267. int AlertWindow::getNumButtons() const
  61268. {
  61269. return buttons.size();
  61270. }
  61271. void AlertWindow::triggerButtonClick (const String& buttonName)
  61272. {
  61273. for (int i = buttons.size(); --i >= 0;)
  61274. {
  61275. TextButton* const b = (TextButton*) buttons[i];
  61276. if (buttonName == b->getName())
  61277. {
  61278. b->triggerClick();
  61279. break;
  61280. }
  61281. }
  61282. }
  61283. void AlertWindow::addTextEditor (const String& name,
  61284. const String& initialContents,
  61285. const String& onScreenLabel,
  61286. const bool isPasswordBox)
  61287. {
  61288. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61289. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61290. tc->setFont (font);
  61291. tc->setText (initialContents);
  61292. tc->setCaretPosition (initialContents.length());
  61293. addAndMakeVisible (tc);
  61294. textBoxes.add (tc);
  61295. allComps.add (tc);
  61296. textboxNames.add (onScreenLabel);
  61297. updateLayout (false);
  61298. }
  61299. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61300. {
  61301. for (int i = textBoxes.size(); --i >= 0;)
  61302. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61303. return ((TextEditor*)textBoxes[i])->getText();
  61304. return String::empty;
  61305. }
  61306. void AlertWindow::addComboBox (const String& name,
  61307. const StringArray& items,
  61308. const String& onScreenLabel)
  61309. {
  61310. ComboBox* const cb = new ComboBox (name);
  61311. for (int i = 0; i < items.size(); ++i)
  61312. cb->addItem (items[i], i + 1);
  61313. addAndMakeVisible (cb);
  61314. cb->setSelectedItemIndex (0);
  61315. comboBoxes.add (cb);
  61316. allComps.add (cb);
  61317. comboBoxNames.add (onScreenLabel);
  61318. updateLayout (false);
  61319. }
  61320. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61321. {
  61322. for (int i = comboBoxes.size(); --i >= 0;)
  61323. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61324. return (ComboBox*) comboBoxes[i];
  61325. return 0;
  61326. }
  61327. class AlertTextComp : public TextEditor
  61328. {
  61329. public:
  61330. AlertTextComp (const String& message,
  61331. const Font& font)
  61332. {
  61333. setReadOnly (true);
  61334. setMultiLine (true, true);
  61335. setCaretVisible (false);
  61336. setScrollbarsShown (true);
  61337. lookAndFeelChanged();
  61338. setWantsKeyboardFocus (false);
  61339. setFont (font);
  61340. setText (message, false);
  61341. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61342. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61343. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61344. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61345. }
  61346. ~AlertTextComp()
  61347. {
  61348. }
  61349. int getPreferredWidth() const throw() { return bestWidth; }
  61350. void updateLayout (const int width)
  61351. {
  61352. TextLayout text;
  61353. text.appendText (getText(), getFont());
  61354. text.layout (width - 8, Justification::topLeft, true);
  61355. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61356. }
  61357. private:
  61358. int bestWidth;
  61359. AlertTextComp (const AlertTextComp&);
  61360. AlertTextComp& operator= (const AlertTextComp&);
  61361. };
  61362. void AlertWindow::addTextBlock (const String& textBlock)
  61363. {
  61364. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61365. textBlocks.add (c);
  61366. allComps.add (c);
  61367. addAndMakeVisible (c);
  61368. updateLayout (false);
  61369. }
  61370. void AlertWindow::addProgressBarComponent (double& progressValue)
  61371. {
  61372. ProgressBar* const pb = new ProgressBar (progressValue);
  61373. progressBars.add (pb);
  61374. allComps.add (pb);
  61375. addAndMakeVisible (pb);
  61376. updateLayout (false);
  61377. }
  61378. void AlertWindow::addCustomComponent (Component* const component)
  61379. {
  61380. customComps.add (component);
  61381. allComps.add (component);
  61382. addAndMakeVisible (component);
  61383. updateLayout (false);
  61384. }
  61385. int AlertWindow::getNumCustomComponents() const
  61386. {
  61387. return customComps.size();
  61388. }
  61389. Component* AlertWindow::getCustomComponent (const int index) const
  61390. {
  61391. return (Component*) customComps [index];
  61392. }
  61393. Component* AlertWindow::removeCustomComponent (const int index)
  61394. {
  61395. Component* const c = getCustomComponent (index);
  61396. if (c != 0)
  61397. {
  61398. customComps.removeValue (c);
  61399. allComps.removeValue (c);
  61400. removeChildComponent (c);
  61401. updateLayout (false);
  61402. }
  61403. return c;
  61404. }
  61405. void AlertWindow::paint (Graphics& g)
  61406. {
  61407. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61408. g.setColour (findColour (textColourId));
  61409. g.setFont (getLookAndFeel().getAlertWindowFont());
  61410. int i;
  61411. for (i = textBoxes.size(); --i >= 0;)
  61412. {
  61413. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61414. g.drawFittedText (textboxNames[i],
  61415. te->getX(), te->getY() - 14,
  61416. te->getWidth(), 14,
  61417. Justification::centredLeft, 1);
  61418. }
  61419. for (i = comboBoxNames.size(); --i >= 0;)
  61420. {
  61421. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61422. g.drawFittedText (comboBoxNames[i],
  61423. cb->getX(), cb->getY() - 14,
  61424. cb->getWidth(), 14,
  61425. Justification::centredLeft, 1);
  61426. }
  61427. for (i = customComps.size(); --i >= 0;)
  61428. {
  61429. const Component* const c = (Component*) customComps[i];
  61430. g.drawFittedText (c->getName(),
  61431. c->getX(), c->getY() - 14,
  61432. c->getWidth(), 14,
  61433. Justification::centredLeft, 1);
  61434. }
  61435. }
  61436. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61437. {
  61438. const int titleH = 24;
  61439. const int iconWidth = 80;
  61440. const int wid = jmax (font.getStringWidth (text),
  61441. font.getStringWidth (getName()));
  61442. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61443. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61444. const int edgeGap = 10;
  61445. const int labelHeight = 18;
  61446. int iconSpace;
  61447. if (alertIconType == NoIcon)
  61448. {
  61449. textLayout.layout (w, Justification::horizontallyCentred, true);
  61450. iconSpace = 0;
  61451. }
  61452. else
  61453. {
  61454. textLayout.layout (w, Justification::left, true);
  61455. iconSpace = iconWidth;
  61456. }
  61457. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61458. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61459. const int textLayoutH = textLayout.getHeight();
  61460. const int textBottom = 16 + titleH + textLayoutH;
  61461. int h = textBottom;
  61462. int buttonW = 40;
  61463. int i;
  61464. for (i = 0; i < buttons.size(); ++i)
  61465. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61466. w = jmax (buttonW, w);
  61467. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61468. if (buttons.size() > 0)
  61469. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61470. for (i = customComps.size(); --i >= 0;)
  61471. {
  61472. Component* c = (Component*) customComps[i];
  61473. w = jmax (w, (c->getWidth() * 100) / 80);
  61474. h += 10 + c->getHeight();
  61475. if (c->getName().isNotEmpty())
  61476. h += labelHeight;
  61477. }
  61478. for (i = textBlocks.size(); --i >= 0;)
  61479. {
  61480. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61481. w = jmax (w, ac->getPreferredWidth());
  61482. }
  61483. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61484. for (i = textBlocks.size(); --i >= 0;)
  61485. {
  61486. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61487. ac->updateLayout ((int) (w * 0.8f));
  61488. h += ac->getHeight() + 10;
  61489. }
  61490. h = jmin (getParentHeight() - 50, h);
  61491. if (onlyIncreaseSize)
  61492. {
  61493. w = jmax (w, getWidth());
  61494. h = jmax (h, getHeight());
  61495. }
  61496. if (! isVisible())
  61497. {
  61498. centreAroundComponent (associatedComponent, w, h);
  61499. }
  61500. else
  61501. {
  61502. const int cx = getX() + getWidth() / 2;
  61503. const int cy = getY() + getHeight() / 2;
  61504. setBounds (cx - w / 2,
  61505. cy - h / 2,
  61506. w, h);
  61507. }
  61508. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61509. const int spacer = 16;
  61510. int totalWidth = -spacer;
  61511. for (i = buttons.size(); --i >= 0;)
  61512. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61513. int x = (w - totalWidth) / 2;
  61514. int y = (int) (getHeight() * 0.95f);
  61515. for (i = 0; i < buttons.size(); ++i)
  61516. {
  61517. TextButton* const c = (TextButton*) buttons[i];
  61518. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61519. c->setTopLeftPosition (x, ny);
  61520. if (ny < y)
  61521. y = ny;
  61522. x += c->getWidth() + spacer;
  61523. c->toFront (false);
  61524. }
  61525. y = textBottom;
  61526. for (i = 0; i < allComps.size(); ++i)
  61527. {
  61528. Component* const c = (Component*) allComps[i];
  61529. h = 22;
  61530. const int comboIndex = comboBoxes.indexOf (c);
  61531. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61532. y += labelHeight;
  61533. const int tbIndex = textBoxes.indexOf (c);
  61534. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61535. y += labelHeight;
  61536. if (customComps.contains (c))
  61537. {
  61538. if (c->getName().isNotEmpty())
  61539. y += labelHeight;
  61540. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61541. h = c->getHeight();
  61542. }
  61543. else if (textBlocks.contains (c))
  61544. {
  61545. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61546. h = c->getHeight();
  61547. }
  61548. else
  61549. {
  61550. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61551. }
  61552. y += h + 10;
  61553. }
  61554. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61555. }
  61556. bool AlertWindow::containsAnyExtraComponents() const
  61557. {
  61558. return textBoxes.size()
  61559. + comboBoxes.size()
  61560. + progressBars.size()
  61561. + customComps.size() > 0;
  61562. }
  61563. void AlertWindow::mouseDown (const MouseEvent&)
  61564. {
  61565. dragger.startDraggingComponent (this, &constrainer);
  61566. }
  61567. void AlertWindow::mouseDrag (const MouseEvent& e)
  61568. {
  61569. dragger.dragComponent (this, e);
  61570. }
  61571. bool AlertWindow::keyPressed (const KeyPress& key)
  61572. {
  61573. for (int i = buttons.size(); --i >= 0;)
  61574. {
  61575. TextButton* const b = (TextButton*) buttons[i];
  61576. if (b->isRegisteredForShortcut (key))
  61577. {
  61578. b->triggerClick();
  61579. return true;
  61580. }
  61581. }
  61582. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61583. {
  61584. exitModalState (0);
  61585. return true;
  61586. }
  61587. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61588. {
  61589. ((TextButton*) buttons.getFirst())->triggerClick();
  61590. return true;
  61591. }
  61592. return false;
  61593. }
  61594. void AlertWindow::lookAndFeelChanged()
  61595. {
  61596. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61597. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61598. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61599. }
  61600. int AlertWindow::getDesktopWindowStyleFlags() const
  61601. {
  61602. return getLookAndFeel().getAlertBoxWindowFlags();
  61603. }
  61604. struct AlertWindowInfo
  61605. {
  61606. String title, message, button1, button2, button3;
  61607. AlertWindow::AlertIconType iconType;
  61608. int numButtons;
  61609. Component::SafePointer<Component> associatedComponent;
  61610. int run() const
  61611. {
  61612. return (int) (pointer_sized_int)
  61613. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61614. }
  61615. private:
  61616. int show() const
  61617. {
  61618. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61619. : LookAndFeel::getDefaultLookAndFeel();
  61620. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61621. iconType, numButtons, associatedComponent));
  61622. jassert (alertBox != 0); // you have to return one of these!
  61623. return alertBox->runModalLoop();
  61624. }
  61625. static void* showCallback (void* userData)
  61626. {
  61627. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61628. }
  61629. };
  61630. void AlertWindow::showMessageBox (AlertIconType iconType,
  61631. const String& title,
  61632. const String& message,
  61633. const String& buttonText,
  61634. Component* associatedComponent)
  61635. {
  61636. AlertWindowInfo info;
  61637. info.title = title;
  61638. info.message = message;
  61639. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61640. info.iconType = iconType;
  61641. info.numButtons = 1;
  61642. info.associatedComponent = associatedComponent;
  61643. info.run();
  61644. }
  61645. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61646. const String& title,
  61647. const String& message,
  61648. const String& button1Text,
  61649. const String& button2Text,
  61650. Component* associatedComponent)
  61651. {
  61652. AlertWindowInfo info;
  61653. info.title = title;
  61654. info.message = message;
  61655. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61656. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61657. info.iconType = iconType;
  61658. info.numButtons = 2;
  61659. info.associatedComponent = associatedComponent;
  61660. return info.run() != 0;
  61661. }
  61662. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61663. const String& title,
  61664. const String& message,
  61665. const String& button1Text,
  61666. const String& button2Text,
  61667. const String& button3Text,
  61668. Component* associatedComponent)
  61669. {
  61670. AlertWindowInfo info;
  61671. info.title = title;
  61672. info.message = message;
  61673. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61674. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61675. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61676. info.iconType = iconType;
  61677. info.numButtons = 3;
  61678. info.associatedComponent = associatedComponent;
  61679. return info.run();
  61680. }
  61681. END_JUCE_NAMESPACE
  61682. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61683. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61684. BEGIN_JUCE_NAMESPACE
  61685. CallOutBox::CallOutBox (Component& contentComponent,
  61686. Component& componentToPointTo,
  61687. Component* const parentComponent)
  61688. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61689. {
  61690. addAndMakeVisible (&content);
  61691. if (parentComponent != 0)
  61692. {
  61693. updatePosition (parentComponent->getLocalBounds(),
  61694. componentToPointTo.getLocalBounds()
  61695. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  61696. parentComponent->addAndMakeVisible (this);
  61697. }
  61698. else
  61699. {
  61700. updatePosition (componentToPointTo.getScreenBounds(),
  61701. componentToPointTo.getParentMonitorArea());
  61702. addToDesktop (ComponentPeer::windowIsTemporary);
  61703. }
  61704. }
  61705. CallOutBox::~CallOutBox()
  61706. {
  61707. }
  61708. void CallOutBox::setArrowSize (const float newSize)
  61709. {
  61710. arrowSize = newSize;
  61711. borderSpace = jmax (20, (int) arrowSize);
  61712. refreshPath();
  61713. }
  61714. void CallOutBox::paint (Graphics& g)
  61715. {
  61716. if (background.isNull())
  61717. {
  61718. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61719. Graphics g (background);
  61720. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  61721. }
  61722. g.setColour (Colours::black);
  61723. g.drawImageAt (background, 0, 0);
  61724. }
  61725. void CallOutBox::resized()
  61726. {
  61727. content.setTopLeftPosition (borderSpace, borderSpace);
  61728. refreshPath();
  61729. }
  61730. void CallOutBox::moved()
  61731. {
  61732. refreshPath();
  61733. }
  61734. void CallOutBox::childBoundsChanged (Component*)
  61735. {
  61736. updatePosition (targetArea, availableArea);
  61737. }
  61738. bool CallOutBox::hitTest (int x, int y)
  61739. {
  61740. return outline.contains ((float) x, (float) y);
  61741. }
  61742. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61743. void CallOutBox::inputAttemptWhenModal()
  61744. {
  61745. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61746. if (targetArea.contains (mousePos))
  61747. {
  61748. // if you click on the area that originally popped-up the callout, you expect it
  61749. // to get rid of the box, but deleting the box here allows the click to pass through and
  61750. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61751. postCommandMessage (callOutBoxDismissCommandId);
  61752. }
  61753. else
  61754. {
  61755. exitModalState (0);
  61756. setVisible (false);
  61757. }
  61758. }
  61759. void CallOutBox::handleCommandMessage (int commandId)
  61760. {
  61761. Component::handleCommandMessage (commandId);
  61762. if (commandId == callOutBoxDismissCommandId)
  61763. {
  61764. exitModalState (0);
  61765. setVisible (false);
  61766. }
  61767. }
  61768. bool CallOutBox::keyPressed (const KeyPress& key)
  61769. {
  61770. if (key.isKeyCode (KeyPress::escapeKey))
  61771. {
  61772. inputAttemptWhenModal();
  61773. return true;
  61774. }
  61775. return false;
  61776. }
  61777. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61778. {
  61779. targetArea = newAreaToPointTo;
  61780. availableArea = newAreaToFitIn;
  61781. Rectangle<int> bounds (0, 0,
  61782. content.getWidth() + borderSpace * 2,
  61783. content.getHeight() + borderSpace * 2);
  61784. const int hw = bounds.getWidth() / 2;
  61785. const int hh = bounds.getHeight() / 2;
  61786. const float hwReduced = (float) (hw - borderSpace * 3);
  61787. const float hhReduced = (float) (hh - borderSpace * 3);
  61788. const float arrowIndent = borderSpace - arrowSize;
  61789. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61790. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61791. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61792. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61793. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61794. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61795. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61796. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61797. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61798. float nearest = 1.0e9f;
  61799. for (int i = 0; i < 4; ++i)
  61800. {
  61801. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61802. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61803. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61804. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61805. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61806. distanceFromCentre *= 2.0f;
  61807. if (distanceFromCentre < nearest)
  61808. {
  61809. nearest = distanceFromCentre;
  61810. targetPoint = targets[i];
  61811. bounds.setPosition ((int) (centre.getX() - hw),
  61812. (int) (centre.getY() - hh));
  61813. }
  61814. }
  61815. setBounds (bounds);
  61816. }
  61817. void CallOutBox::refreshPath()
  61818. {
  61819. repaint();
  61820. background = Image::null;
  61821. outline.clear();
  61822. const float gap = 4.5f;
  61823. const float cornerSize = 9.0f;
  61824. const float cornerSize2 = 2.0f * cornerSize;
  61825. const float arrowBaseWidth = arrowSize * 0.7f;
  61826. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61827. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61828. outline.startNewSubPath (left + cornerSize, top);
  61829. if (targetY <= top)
  61830. {
  61831. outline.lineTo (targetX - arrowBaseWidth, top);
  61832. outline.lineTo (targetX, targetY);
  61833. outline.lineTo (targetX + arrowBaseWidth, top);
  61834. }
  61835. outline.lineTo (right - cornerSize, top);
  61836. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61837. if (targetX >= right)
  61838. {
  61839. outline.lineTo (right, targetY - arrowBaseWidth);
  61840. outline.lineTo (targetX, targetY);
  61841. outline.lineTo (right, targetY + arrowBaseWidth);
  61842. }
  61843. outline.lineTo (right, bottom - cornerSize);
  61844. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61845. if (targetY >= bottom)
  61846. {
  61847. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61848. outline.lineTo (targetX, targetY);
  61849. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61850. }
  61851. outline.lineTo (left + cornerSize, bottom);
  61852. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61853. if (targetX <= left)
  61854. {
  61855. outline.lineTo (left, targetY + arrowBaseWidth);
  61856. outline.lineTo (targetX, targetY);
  61857. outline.lineTo (left, targetY - arrowBaseWidth);
  61858. }
  61859. outline.lineTo (left, top + cornerSize);
  61860. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61861. outline.closeSubPath();
  61862. }
  61863. END_JUCE_NAMESPACE
  61864. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61865. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61866. BEGIN_JUCE_NAMESPACE
  61867. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61868. static Array <ComponentPeer*> heavyweightPeers;
  61869. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61870. : component (component_),
  61871. styleFlags (styleFlags_),
  61872. lastPaintTime (0),
  61873. constrainer (0),
  61874. lastDragAndDropCompUnderMouse (0),
  61875. fakeMouseMessageSent (false),
  61876. isWindowMinimised (false)
  61877. {
  61878. heavyweightPeers.add (this);
  61879. }
  61880. ComponentPeer::~ComponentPeer()
  61881. {
  61882. heavyweightPeers.removeValue (this);
  61883. Desktop::getInstance().triggerFocusCallback();
  61884. }
  61885. int ComponentPeer::getNumPeers() throw()
  61886. {
  61887. return heavyweightPeers.size();
  61888. }
  61889. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61890. {
  61891. return heavyweightPeers [index];
  61892. }
  61893. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61894. {
  61895. for (int i = heavyweightPeers.size(); --i >= 0;)
  61896. {
  61897. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61898. if (peer->getComponent() == component)
  61899. return peer;
  61900. }
  61901. return 0;
  61902. }
  61903. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61904. {
  61905. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61906. }
  61907. void ComponentPeer::updateCurrentModifiers() throw()
  61908. {
  61909. ModifierKeys::updateCurrentModifiers();
  61910. }
  61911. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61912. {
  61913. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61914. jassert (mouse != 0); // not enough sources!
  61915. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61916. }
  61917. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61918. {
  61919. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61920. jassert (mouse != 0); // not enough sources!
  61921. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61922. }
  61923. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61924. {
  61925. Graphics g (&contextToPaintTo);
  61926. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61927. g.saveState();
  61928. #endif
  61929. JUCE_TRY
  61930. {
  61931. component->paintEntireComponent (g);
  61932. }
  61933. JUCE_CATCH_EXCEPTION
  61934. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61935. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61936. // clearly when things are being repainted.
  61937. {
  61938. g.restoreState();
  61939. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61940. (uint8) Random::getSystemRandom().nextInt (255),
  61941. (uint8) Random::getSystemRandom().nextInt (255),
  61942. (uint8) 0x50));
  61943. }
  61944. #endif
  61945. }
  61946. bool ComponentPeer::handleKeyPress (const int keyCode,
  61947. const juce_wchar textCharacter)
  61948. {
  61949. updateCurrentModifiers();
  61950. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61951. ? Component::getCurrentlyFocusedComponent()
  61952. : component;
  61953. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61954. {
  61955. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61956. if (currentModalComp != 0)
  61957. target = currentModalComp;
  61958. }
  61959. const KeyPress keyInfo (keyCode,
  61960. ModifierKeys::getCurrentModifiers().getRawFlags()
  61961. & ModifierKeys::allKeyboardModifiers,
  61962. textCharacter);
  61963. bool keyWasUsed = false;
  61964. while (target != 0)
  61965. {
  61966. const Component::SafePointer<Component> deletionChecker (target);
  61967. if (target->keyListeners_ != 0)
  61968. {
  61969. for (int i = target->keyListeners_->size(); --i >= 0;)
  61970. {
  61971. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  61972. if (keyWasUsed || deletionChecker == 0)
  61973. return keyWasUsed;
  61974. i = jmin (i, target->keyListeners_->size());
  61975. }
  61976. }
  61977. keyWasUsed = target->keyPressed (keyInfo);
  61978. if (keyWasUsed || deletionChecker == 0)
  61979. break;
  61980. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61981. {
  61982. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61983. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61984. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61985. break;
  61986. }
  61987. target = target->parentComponent_;
  61988. }
  61989. return keyWasUsed;
  61990. }
  61991. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61992. {
  61993. updateCurrentModifiers();
  61994. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61995. ? Component::getCurrentlyFocusedComponent()
  61996. : component;
  61997. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61998. {
  61999. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62000. if (currentModalComp != 0)
  62001. target = currentModalComp;
  62002. }
  62003. bool keyWasUsed = false;
  62004. while (target != 0)
  62005. {
  62006. const Component::SafePointer<Component> deletionChecker (target);
  62007. keyWasUsed = target->keyStateChanged (isKeyDown);
  62008. if (keyWasUsed || deletionChecker == 0)
  62009. break;
  62010. if (target->keyListeners_ != 0)
  62011. {
  62012. for (int i = target->keyListeners_->size(); --i >= 0;)
  62013. {
  62014. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62015. if (keyWasUsed || deletionChecker == 0)
  62016. return keyWasUsed;
  62017. i = jmin (i, target->keyListeners_->size());
  62018. }
  62019. }
  62020. target = target->parentComponent_;
  62021. }
  62022. return keyWasUsed;
  62023. }
  62024. void ComponentPeer::handleModifierKeysChange()
  62025. {
  62026. updateCurrentModifiers();
  62027. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62028. if (target == 0)
  62029. target = Component::getCurrentlyFocusedComponent();
  62030. if (target == 0)
  62031. target = component;
  62032. if (target != 0)
  62033. target->internalModifierKeysChanged();
  62034. }
  62035. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62036. {
  62037. Component* const c = Component::getCurrentlyFocusedComponent();
  62038. if (component->isParentOf (c))
  62039. {
  62040. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62041. if (ti != 0 && ti->isTextInputActive())
  62042. return ti;
  62043. }
  62044. return 0;
  62045. }
  62046. void ComponentPeer::handleBroughtToFront()
  62047. {
  62048. updateCurrentModifiers();
  62049. if (component != 0)
  62050. component->internalBroughtToFront();
  62051. }
  62052. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62053. {
  62054. constrainer = newConstrainer;
  62055. }
  62056. void ComponentPeer::handleMovedOrResized()
  62057. {
  62058. jassert (component->isValidComponent());
  62059. updateCurrentModifiers();
  62060. const bool nowMinimised = isMinimised();
  62061. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62062. {
  62063. const Component::SafePointer<Component> deletionChecker (component);
  62064. const Rectangle<int> newBounds (getBounds());
  62065. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62066. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62067. if (wasMoved || wasResized)
  62068. {
  62069. component->bounds_ = newBounds;
  62070. if (wasResized)
  62071. component->repaint();
  62072. component->sendMovedResizedMessages (wasMoved, wasResized);
  62073. if (deletionChecker == 0)
  62074. return;
  62075. }
  62076. }
  62077. if (isWindowMinimised != nowMinimised)
  62078. {
  62079. isWindowMinimised = nowMinimised;
  62080. component->minimisationStateChanged (nowMinimised);
  62081. component->sendVisibilityChangeMessage();
  62082. }
  62083. if (! isFullScreen())
  62084. lastNonFullscreenBounds = component->getBounds();
  62085. }
  62086. void ComponentPeer::handleFocusGain()
  62087. {
  62088. updateCurrentModifiers();
  62089. if (component->isParentOf (lastFocusedComponent))
  62090. {
  62091. Component::currentlyFocusedComponent = lastFocusedComponent;
  62092. Desktop::getInstance().triggerFocusCallback();
  62093. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62094. }
  62095. else
  62096. {
  62097. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62098. component->grabKeyboardFocus();
  62099. else
  62100. Component::bringModalComponentToFront();
  62101. }
  62102. }
  62103. void ComponentPeer::handleFocusLoss()
  62104. {
  62105. updateCurrentModifiers();
  62106. if (component->hasKeyboardFocus (true))
  62107. {
  62108. lastFocusedComponent = Component::currentlyFocusedComponent;
  62109. if (lastFocusedComponent != 0)
  62110. {
  62111. Component::currentlyFocusedComponent = 0;
  62112. Desktop::getInstance().triggerFocusCallback();
  62113. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62114. }
  62115. }
  62116. }
  62117. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62118. {
  62119. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62120. ? static_cast <Component*> (lastFocusedComponent)
  62121. : component;
  62122. }
  62123. void ComponentPeer::handleScreenSizeChange()
  62124. {
  62125. updateCurrentModifiers();
  62126. component->parentSizeChanged();
  62127. handleMovedOrResized();
  62128. }
  62129. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62130. {
  62131. lastNonFullscreenBounds = newBounds;
  62132. }
  62133. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62134. {
  62135. return lastNonFullscreenBounds;
  62136. }
  62137. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62138. const StringArray& files,
  62139. FileDragAndDropTarget* const lastOne)
  62140. {
  62141. while (c != 0)
  62142. {
  62143. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62144. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62145. return t;
  62146. c = c->getParentComponent();
  62147. }
  62148. return 0;
  62149. }
  62150. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62151. {
  62152. updateCurrentModifiers();
  62153. FileDragAndDropTarget* lastTarget
  62154. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62155. FileDragAndDropTarget* newTarget = 0;
  62156. Component* const compUnderMouse = component->getComponentAt (position);
  62157. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62158. {
  62159. lastDragAndDropCompUnderMouse = compUnderMouse;
  62160. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62161. if (newTarget != lastTarget)
  62162. {
  62163. if (lastTarget != 0)
  62164. lastTarget->fileDragExit (files);
  62165. dragAndDropTargetComponent = 0;
  62166. if (newTarget != 0)
  62167. {
  62168. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62169. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62170. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62171. }
  62172. }
  62173. }
  62174. else
  62175. {
  62176. newTarget = lastTarget;
  62177. }
  62178. if (newTarget != 0)
  62179. {
  62180. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62181. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62182. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62183. }
  62184. }
  62185. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62186. {
  62187. handleFileDragMove (files, Point<int> (-1, -1));
  62188. jassert (dragAndDropTargetComponent == 0);
  62189. lastDragAndDropCompUnderMouse = 0;
  62190. }
  62191. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62192. {
  62193. handleFileDragMove (files, position);
  62194. if (dragAndDropTargetComponent != 0)
  62195. {
  62196. FileDragAndDropTarget* const target
  62197. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62198. dragAndDropTargetComponent = 0;
  62199. lastDragAndDropCompUnderMouse = 0;
  62200. if (target != 0)
  62201. {
  62202. Component* const targetComp = dynamic_cast <Component*> (target);
  62203. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62204. {
  62205. targetComp->internalModalInputAttempt();
  62206. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62207. return;
  62208. }
  62209. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62210. target->filesDropped (files, pos.getX(), pos.getY());
  62211. }
  62212. }
  62213. }
  62214. void ComponentPeer::handleUserClosingWindow()
  62215. {
  62216. updateCurrentModifiers();
  62217. component->userTriedToCloseWindow();
  62218. }
  62219. void ComponentPeer::bringModalComponentToFront()
  62220. {
  62221. Component::bringModalComponentToFront();
  62222. }
  62223. void ComponentPeer::clearMaskedRegion()
  62224. {
  62225. maskedRegion.clear();
  62226. }
  62227. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62228. {
  62229. maskedRegion.add (x, y, w, h);
  62230. }
  62231. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  62232. {
  62233. StringArray s;
  62234. s.add ("Software Renderer");
  62235. return s;
  62236. }
  62237. int ComponentPeer::getCurrentRenderingEngine() throw()
  62238. {
  62239. return 0;
  62240. }
  62241. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  62242. {
  62243. }
  62244. END_JUCE_NAMESPACE
  62245. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62246. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62247. BEGIN_JUCE_NAMESPACE
  62248. DialogWindow::DialogWindow (const String& name,
  62249. const Colour& backgroundColour_,
  62250. const bool escapeKeyTriggersCloseButton_,
  62251. const bool addToDesktop_)
  62252. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62253. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62254. {
  62255. }
  62256. DialogWindow::~DialogWindow()
  62257. {
  62258. }
  62259. void DialogWindow::resized()
  62260. {
  62261. DocumentWindow::resized();
  62262. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62263. if (escapeKeyTriggersCloseButton
  62264. && getCloseButton() != 0
  62265. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62266. {
  62267. getCloseButton()->addShortcut (esc);
  62268. }
  62269. }
  62270. class TempDialogWindow : public DialogWindow
  62271. {
  62272. public:
  62273. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62274. : DialogWindow (title, colour, escapeCloses, true)
  62275. {
  62276. if (JUCEApplication::getInstance() == 0)
  62277. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62278. }
  62279. ~TempDialogWindow()
  62280. {
  62281. }
  62282. void closeButtonPressed()
  62283. {
  62284. setVisible (false);
  62285. }
  62286. private:
  62287. TempDialogWindow (const TempDialogWindow&);
  62288. TempDialogWindow& operator= (const TempDialogWindow&);
  62289. };
  62290. int DialogWindow::showModalDialog (const String& dialogTitle,
  62291. Component* contentComponent,
  62292. Component* componentToCentreAround,
  62293. const Colour& colour,
  62294. const bool escapeKeyTriggersCloseButton,
  62295. const bool shouldBeResizable,
  62296. const bool useBottomRightCornerResizer)
  62297. {
  62298. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62299. dw.setContentComponent (contentComponent, true, true);
  62300. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62301. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62302. const int result = dw.runModalLoop();
  62303. dw.setContentComponent (0, false);
  62304. return result;
  62305. }
  62306. END_JUCE_NAMESPACE
  62307. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62308. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62309. BEGIN_JUCE_NAMESPACE
  62310. class DocumentWindow::ButtonListenerProxy : public Button::Listener
  62311. {
  62312. public:
  62313. ButtonListenerProxy (DocumentWindow& owner_)
  62314. : owner (owner_)
  62315. {
  62316. }
  62317. void buttonClicked (Button* button)
  62318. {
  62319. if (button == owner.getMinimiseButton())
  62320. owner.minimiseButtonPressed();
  62321. else if (button == owner.getMaximiseButton())
  62322. owner.maximiseButtonPressed();
  62323. else if (button == owner.getCloseButton())
  62324. owner.closeButtonPressed();
  62325. }
  62326. juce_UseDebuggingNewOperator
  62327. private:
  62328. DocumentWindow& owner;
  62329. ButtonListenerProxy (const ButtonListenerProxy&);
  62330. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62331. };
  62332. DocumentWindow::DocumentWindow (const String& title,
  62333. const Colour& backgroundColour,
  62334. const int requiredButtons_,
  62335. const bool addToDesktop_)
  62336. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62337. titleBarHeight (26),
  62338. menuBarHeight (24),
  62339. requiredButtons (requiredButtons_),
  62340. #if JUCE_MAC
  62341. positionTitleBarButtonsOnLeft (true),
  62342. #else
  62343. positionTitleBarButtonsOnLeft (false),
  62344. #endif
  62345. drawTitleTextCentred (true),
  62346. menuBarModel (0)
  62347. {
  62348. setResizeLimits (128, 128, 32768, 32768);
  62349. lookAndFeelChanged();
  62350. }
  62351. DocumentWindow::~DocumentWindow()
  62352. {
  62353. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62354. titleBarButtons[i] = 0;
  62355. menuBar = 0;
  62356. }
  62357. void DocumentWindow::repaintTitleBar()
  62358. {
  62359. repaint (getTitleBarArea());
  62360. }
  62361. void DocumentWindow::setName (const String& newName)
  62362. {
  62363. if (newName != getName())
  62364. {
  62365. Component::setName (newName);
  62366. repaintTitleBar();
  62367. }
  62368. }
  62369. void DocumentWindow::setIcon (const Image& imageToUse)
  62370. {
  62371. titleBarIcon = imageToUse;
  62372. repaintTitleBar();
  62373. }
  62374. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62375. {
  62376. titleBarHeight = newHeight;
  62377. resized();
  62378. repaintTitleBar();
  62379. }
  62380. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62381. const bool positionTitleBarButtonsOnLeft_)
  62382. {
  62383. requiredButtons = requiredButtons_;
  62384. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62385. lookAndFeelChanged();
  62386. }
  62387. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62388. {
  62389. drawTitleTextCentred = textShouldBeCentred;
  62390. repaintTitleBar();
  62391. }
  62392. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62393. const int menuBarHeight_)
  62394. {
  62395. if (menuBarModel != menuBarModel_)
  62396. {
  62397. menuBar = 0;
  62398. menuBarModel = menuBarModel_;
  62399. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62400. : getLookAndFeel().getDefaultMenuBarHeight();
  62401. if (menuBarModel != 0)
  62402. {
  62403. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62404. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62405. menuBar->setEnabled (isActiveWindow());
  62406. }
  62407. resized();
  62408. }
  62409. }
  62410. void DocumentWindow::closeButtonPressed()
  62411. {
  62412. /* If you've got a close button, you have to override this method to get
  62413. rid of your window!
  62414. If the window is just a pop-up, you should override this method and make
  62415. it delete the window in whatever way is appropriate for your app. E.g. you
  62416. might just want to call "delete this".
  62417. If your app is centred around this window such that the whole app should quit when
  62418. the window is closed, then you will probably want to use this method as an opportunity
  62419. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62420. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62421. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62422. or closing it via the taskbar icon on Windows).
  62423. */
  62424. jassertfalse;
  62425. }
  62426. void DocumentWindow::minimiseButtonPressed()
  62427. {
  62428. setMinimised (true);
  62429. }
  62430. void DocumentWindow::maximiseButtonPressed()
  62431. {
  62432. setFullScreen (! isFullScreen());
  62433. }
  62434. void DocumentWindow::paint (Graphics& g)
  62435. {
  62436. ResizableWindow::paint (g);
  62437. if (resizableBorder == 0)
  62438. {
  62439. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62440. const BorderSize border (getBorderThickness());
  62441. g.fillRect (0, 0, getWidth(), border.getTop());
  62442. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62443. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62444. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62445. }
  62446. const Rectangle<int> titleBarArea (getTitleBarArea());
  62447. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62448. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62449. int titleSpaceX1 = 6;
  62450. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62451. for (int i = 0; i < 3; ++i)
  62452. {
  62453. if (titleBarButtons[i] != 0)
  62454. {
  62455. if (positionTitleBarButtonsOnLeft)
  62456. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62457. else
  62458. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62459. }
  62460. }
  62461. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62462. titleBarArea.getWidth(),
  62463. titleBarArea.getHeight(),
  62464. titleSpaceX1,
  62465. jmax (1, titleSpaceX2 - titleSpaceX1),
  62466. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62467. ! drawTitleTextCentred);
  62468. }
  62469. void DocumentWindow::resized()
  62470. {
  62471. ResizableWindow::resized();
  62472. if (titleBarButtons[1] != 0)
  62473. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62474. const Rectangle<int> titleBarArea (getTitleBarArea());
  62475. getLookAndFeel()
  62476. .positionDocumentWindowButtons (*this,
  62477. titleBarArea.getX(), titleBarArea.getY(),
  62478. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62479. titleBarButtons[0],
  62480. titleBarButtons[1],
  62481. titleBarButtons[2],
  62482. positionTitleBarButtonsOnLeft);
  62483. if (menuBar != 0)
  62484. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62485. titleBarArea.getWidth(), menuBarHeight);
  62486. }
  62487. const BorderSize DocumentWindow::getBorderThickness()
  62488. {
  62489. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62490. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62491. }
  62492. const BorderSize DocumentWindow::getContentComponentBorder()
  62493. {
  62494. BorderSize border (getBorderThickness());
  62495. border.setTop (border.getTop()
  62496. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62497. + (menuBar != 0 ? menuBarHeight : 0));
  62498. return border;
  62499. }
  62500. int DocumentWindow::getTitleBarHeight() const
  62501. {
  62502. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62503. }
  62504. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62505. {
  62506. const BorderSize border (getBorderThickness());
  62507. return Rectangle<int> (border.getLeft(), border.getTop(),
  62508. getWidth() - border.getLeftAndRight(),
  62509. getTitleBarHeight());
  62510. }
  62511. Button* DocumentWindow::getCloseButton() const throw()
  62512. {
  62513. return titleBarButtons[2];
  62514. }
  62515. Button* DocumentWindow::getMinimiseButton() const throw()
  62516. {
  62517. return titleBarButtons[0];
  62518. }
  62519. Button* DocumentWindow::getMaximiseButton() const throw()
  62520. {
  62521. return titleBarButtons[1];
  62522. }
  62523. int DocumentWindow::getDesktopWindowStyleFlags() const
  62524. {
  62525. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62526. if ((requiredButtons & minimiseButton) != 0)
  62527. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62528. if ((requiredButtons & maximiseButton) != 0)
  62529. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62530. if ((requiredButtons & closeButton) != 0)
  62531. styleFlags |= ComponentPeer::windowHasCloseButton;
  62532. return styleFlags;
  62533. }
  62534. void DocumentWindow::lookAndFeelChanged()
  62535. {
  62536. int i;
  62537. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62538. titleBarButtons[i] = 0;
  62539. if (! isUsingNativeTitleBar())
  62540. {
  62541. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62542. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62543. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62544. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62545. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62546. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62547. for (i = 0; i < 3; ++i)
  62548. {
  62549. if (titleBarButtons[i] != 0)
  62550. {
  62551. if (buttonListener == 0)
  62552. buttonListener = new ButtonListenerProxy (*this);
  62553. titleBarButtons[i]->addButtonListener (buttonListener);
  62554. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62555. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62556. Component::addAndMakeVisible (titleBarButtons[i]);
  62557. }
  62558. }
  62559. if (getCloseButton() != 0)
  62560. {
  62561. #if JUCE_MAC
  62562. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62563. #else
  62564. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62565. #endif
  62566. }
  62567. }
  62568. activeWindowStatusChanged();
  62569. ResizableWindow::lookAndFeelChanged();
  62570. }
  62571. void DocumentWindow::parentHierarchyChanged()
  62572. {
  62573. lookAndFeelChanged();
  62574. }
  62575. void DocumentWindow::activeWindowStatusChanged()
  62576. {
  62577. ResizableWindow::activeWindowStatusChanged();
  62578. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62579. if (titleBarButtons[i] != 0)
  62580. titleBarButtons[i]->setEnabled (isActiveWindow());
  62581. if (menuBar != 0)
  62582. menuBar->setEnabled (isActiveWindow());
  62583. }
  62584. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62585. {
  62586. if (getTitleBarArea().contains (e.x, e.y)
  62587. && getMaximiseButton() != 0)
  62588. {
  62589. getMaximiseButton()->triggerClick();
  62590. }
  62591. }
  62592. void DocumentWindow::userTriedToCloseWindow()
  62593. {
  62594. closeButtonPressed();
  62595. }
  62596. END_JUCE_NAMESPACE
  62597. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62598. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62599. BEGIN_JUCE_NAMESPACE
  62600. ResizableWindow::ResizableWindow (const String& name,
  62601. const bool addToDesktop_)
  62602. : TopLevelWindow (name, addToDesktop_),
  62603. resizeToFitContent (false),
  62604. fullscreen (false),
  62605. lastNonFullScreenPos (50, 50, 256, 256),
  62606. constrainer (0)
  62607. #if JUCE_DEBUG
  62608. , hasBeenResized (false)
  62609. #endif
  62610. {
  62611. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62612. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62613. if (addToDesktop_)
  62614. Component::addToDesktop (getDesktopWindowStyleFlags());
  62615. }
  62616. ResizableWindow::ResizableWindow (const String& name,
  62617. const Colour& backgroundColour_,
  62618. const bool addToDesktop_)
  62619. : TopLevelWindow (name, addToDesktop_),
  62620. resizeToFitContent (false),
  62621. fullscreen (false),
  62622. lastNonFullScreenPos (50, 50, 256, 256),
  62623. constrainer (0)
  62624. #if JUCE_DEBUG
  62625. , hasBeenResized (false)
  62626. #endif
  62627. {
  62628. setBackgroundColour (backgroundColour_);
  62629. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62630. if (addToDesktop_)
  62631. Component::addToDesktop (getDesktopWindowStyleFlags());
  62632. }
  62633. ResizableWindow::~ResizableWindow()
  62634. {
  62635. resizableCorner = 0;
  62636. resizableBorder = 0;
  62637. delete static_cast <Component*> (contentComponent);
  62638. contentComponent = 0;
  62639. // have you been adding your own components directly to this window..? tut tut tut.
  62640. // Read the instructions for using a ResizableWindow!
  62641. jassert (getNumChildComponents() == 0);
  62642. }
  62643. int ResizableWindow::getDesktopWindowStyleFlags() const
  62644. {
  62645. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62646. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62647. styleFlags |= ComponentPeer::windowIsResizable;
  62648. return styleFlags;
  62649. }
  62650. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62651. const bool deleteOldOne,
  62652. const bool resizeToFit)
  62653. {
  62654. resizeToFitContent = resizeToFit;
  62655. if (newContentComponent != static_cast <Component*> (contentComponent))
  62656. {
  62657. if (deleteOldOne)
  62658. delete static_cast <Component*> (contentComponent); // (avoid using a scoped pointer for this, so that it survives
  62659. // external deletion of the content comp)
  62660. else
  62661. removeChildComponent (contentComponent);
  62662. contentComponent = newContentComponent;
  62663. Component::addAndMakeVisible (contentComponent);
  62664. }
  62665. if (resizeToFit)
  62666. childBoundsChanged (contentComponent);
  62667. resized(); // must always be called to position the new content comp
  62668. }
  62669. void ResizableWindow::setContentComponentSize (int width, int height)
  62670. {
  62671. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62672. const BorderSize border (getContentComponentBorder());
  62673. setSize (width + border.getLeftAndRight(),
  62674. height + border.getTopAndBottom());
  62675. }
  62676. const BorderSize ResizableWindow::getBorderThickness()
  62677. {
  62678. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62679. }
  62680. const BorderSize ResizableWindow::getContentComponentBorder()
  62681. {
  62682. return getBorderThickness();
  62683. }
  62684. void ResizableWindow::moved()
  62685. {
  62686. updateLastPos();
  62687. }
  62688. void ResizableWindow::visibilityChanged()
  62689. {
  62690. TopLevelWindow::visibilityChanged();
  62691. updateLastPos();
  62692. }
  62693. void ResizableWindow::resized()
  62694. {
  62695. if (resizableBorder != 0)
  62696. {
  62697. resizableBorder->setVisible (! isFullScreen());
  62698. resizableBorder->setBorderThickness (getBorderThickness());
  62699. resizableBorder->setSize (getWidth(), getHeight());
  62700. resizableBorder->toBack();
  62701. }
  62702. if (resizableCorner != 0)
  62703. {
  62704. resizableCorner->setVisible (! isFullScreen());
  62705. const int resizerSize = 18;
  62706. resizableCorner->setBounds (getWidth() - resizerSize,
  62707. getHeight() - resizerSize,
  62708. resizerSize, resizerSize);
  62709. }
  62710. if (contentComponent != 0)
  62711. contentComponent->setBoundsInset (getContentComponentBorder());
  62712. updateLastPos();
  62713. #if JUCE_DEBUG
  62714. hasBeenResized = true;
  62715. #endif
  62716. }
  62717. void ResizableWindow::childBoundsChanged (Component* child)
  62718. {
  62719. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62720. {
  62721. // not going to look very good if this component has a zero size..
  62722. jassert (child->getWidth() > 0);
  62723. jassert (child->getHeight() > 0);
  62724. const BorderSize borders (getContentComponentBorder());
  62725. setSize (child->getWidth() + borders.getLeftAndRight(),
  62726. child->getHeight() + borders.getTopAndBottom());
  62727. }
  62728. }
  62729. void ResizableWindow::activeWindowStatusChanged()
  62730. {
  62731. const BorderSize border (getContentComponentBorder());
  62732. Rectangle<int> area (getLocalBounds());
  62733. repaint (area.removeFromTop (border.getTop()));
  62734. repaint (area.removeFromLeft (border.getLeft()));
  62735. repaint (area.removeFromRight (border.getRight()));
  62736. repaint (area.removeFromBottom (border.getBottom()));
  62737. }
  62738. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62739. const bool useBottomRightCornerResizer)
  62740. {
  62741. if (shouldBeResizable)
  62742. {
  62743. if (useBottomRightCornerResizer)
  62744. {
  62745. resizableBorder = 0;
  62746. if (resizableCorner == 0)
  62747. {
  62748. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62749. resizableCorner->setAlwaysOnTop (true);
  62750. }
  62751. }
  62752. else
  62753. {
  62754. resizableCorner = 0;
  62755. if (resizableBorder == 0)
  62756. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62757. }
  62758. }
  62759. else
  62760. {
  62761. resizableCorner = 0;
  62762. resizableBorder = 0;
  62763. }
  62764. if (isUsingNativeTitleBar())
  62765. recreateDesktopWindow();
  62766. childBoundsChanged (contentComponent);
  62767. resized();
  62768. }
  62769. bool ResizableWindow::isResizable() const throw()
  62770. {
  62771. return resizableCorner != 0
  62772. || resizableBorder != 0;
  62773. }
  62774. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62775. const int newMinimumHeight,
  62776. const int newMaximumWidth,
  62777. const int newMaximumHeight) throw()
  62778. {
  62779. // if you've set up a custom constrainer then these settings won't have any effect..
  62780. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62781. if (constrainer == 0)
  62782. setConstrainer (&defaultConstrainer);
  62783. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62784. newMaximumWidth, newMaximumHeight);
  62785. setBoundsConstrained (getBounds());
  62786. }
  62787. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62788. {
  62789. if (constrainer != newConstrainer)
  62790. {
  62791. constrainer = newConstrainer;
  62792. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62793. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62794. resizableCorner = 0;
  62795. resizableBorder = 0;
  62796. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62797. ComponentPeer* const peer = getPeer();
  62798. if (peer != 0)
  62799. peer->setConstrainer (newConstrainer);
  62800. }
  62801. }
  62802. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62803. {
  62804. if (constrainer != 0)
  62805. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62806. else
  62807. setBounds (bounds);
  62808. }
  62809. void ResizableWindow::paint (Graphics& g)
  62810. {
  62811. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62812. getBorderThickness(), *this);
  62813. if (! isFullScreen())
  62814. {
  62815. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62816. getBorderThickness(), *this);
  62817. }
  62818. #if JUCE_DEBUG
  62819. /* If this fails, then you've probably written a subclass with a resized()
  62820. callback but forgotten to make it call its parent class's resized() method.
  62821. It's important when you override methods like resized(), moved(),
  62822. etc., that you make sure the base class methods also get called.
  62823. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62824. because your content should all be inside the content component - and it's the
  62825. content component's resized() method that you should be using to do your
  62826. layout.
  62827. */
  62828. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62829. #endif
  62830. }
  62831. void ResizableWindow::lookAndFeelChanged()
  62832. {
  62833. resized();
  62834. if (isOnDesktop())
  62835. {
  62836. Component::addToDesktop (getDesktopWindowStyleFlags());
  62837. ComponentPeer* const peer = getPeer();
  62838. if (peer != 0)
  62839. peer->setConstrainer (constrainer);
  62840. }
  62841. }
  62842. const Colour ResizableWindow::getBackgroundColour() const throw()
  62843. {
  62844. return findColour (backgroundColourId, false);
  62845. }
  62846. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62847. {
  62848. Colour backgroundColour (newColour);
  62849. if (! Desktop::canUseSemiTransparentWindows())
  62850. backgroundColour = newColour.withAlpha (1.0f);
  62851. setColour (backgroundColourId, backgroundColour);
  62852. setOpaque (backgroundColour.isOpaque());
  62853. repaint();
  62854. }
  62855. bool ResizableWindow::isFullScreen() const
  62856. {
  62857. if (isOnDesktop())
  62858. {
  62859. ComponentPeer* const peer = getPeer();
  62860. return peer != 0 && peer->isFullScreen();
  62861. }
  62862. return fullscreen;
  62863. }
  62864. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62865. {
  62866. if (shouldBeFullScreen != isFullScreen())
  62867. {
  62868. updateLastPos();
  62869. fullscreen = shouldBeFullScreen;
  62870. if (isOnDesktop())
  62871. {
  62872. ComponentPeer* const peer = getPeer();
  62873. if (peer != 0)
  62874. {
  62875. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62876. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62877. peer->setFullScreen (shouldBeFullScreen);
  62878. if (! shouldBeFullScreen)
  62879. setBounds (lastPos);
  62880. }
  62881. else
  62882. {
  62883. jassertfalse;
  62884. }
  62885. }
  62886. else
  62887. {
  62888. if (shouldBeFullScreen)
  62889. setBounds (0, 0, getParentWidth(), getParentHeight());
  62890. else
  62891. setBounds (lastNonFullScreenPos);
  62892. }
  62893. resized();
  62894. }
  62895. }
  62896. bool ResizableWindow::isMinimised() const
  62897. {
  62898. ComponentPeer* const peer = getPeer();
  62899. return (peer != 0) && peer->isMinimised();
  62900. }
  62901. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62902. {
  62903. if (shouldMinimise != isMinimised())
  62904. {
  62905. ComponentPeer* const peer = getPeer();
  62906. if (peer != 0)
  62907. {
  62908. updateLastPos();
  62909. peer->setMinimised (shouldMinimise);
  62910. }
  62911. else
  62912. {
  62913. jassertfalse;
  62914. }
  62915. }
  62916. }
  62917. void ResizableWindow::updateLastPos()
  62918. {
  62919. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62920. {
  62921. lastNonFullScreenPos = getBounds();
  62922. }
  62923. }
  62924. void ResizableWindow::parentSizeChanged()
  62925. {
  62926. if (isFullScreen() && getParentComponent() != 0)
  62927. {
  62928. setBounds (0, 0, getParentWidth(), getParentHeight());
  62929. }
  62930. }
  62931. const String ResizableWindow::getWindowStateAsString()
  62932. {
  62933. updateLastPos();
  62934. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62935. }
  62936. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62937. {
  62938. StringArray tokens;
  62939. tokens.addTokens (s, false);
  62940. tokens.removeEmptyStrings();
  62941. tokens.trim();
  62942. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62943. const int firstCoord = fs ? 1 : 0;
  62944. if (tokens.size() != firstCoord + 4)
  62945. return false;
  62946. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62947. tokens[firstCoord + 1].getIntValue(),
  62948. tokens[firstCoord + 2].getIntValue(),
  62949. tokens[firstCoord + 3].getIntValue());
  62950. if (newPos.isEmpty())
  62951. return false;
  62952. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62953. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62954. if (peer != 0)
  62955. peer->getFrameSize().addTo (newPos);
  62956. if (! screen.contains (newPos))
  62957. {
  62958. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62959. jmin (newPos.getHeight(), screen.getHeight()));
  62960. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62961. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62962. }
  62963. if (peer != 0)
  62964. {
  62965. peer->getFrameSize().subtractFrom (newPos);
  62966. peer->setNonFullScreenBounds (newPos);
  62967. }
  62968. lastNonFullScreenPos = newPos;
  62969. setFullScreen (fs);
  62970. if (! fs)
  62971. setBoundsConstrained (newPos);
  62972. return true;
  62973. }
  62974. void ResizableWindow::mouseDown (const MouseEvent&)
  62975. {
  62976. if (! isFullScreen())
  62977. dragger.startDraggingComponent (this, constrainer);
  62978. }
  62979. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62980. {
  62981. if (! isFullScreen())
  62982. dragger.dragComponent (this, e);
  62983. }
  62984. #if JUCE_DEBUG
  62985. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62986. {
  62987. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62988. manages its child components automatically, and if you add your own it'll cause
  62989. trouble. Instead, use setContentComponent() to give it a component which
  62990. will be automatically resized and kept in the right place - then you can add
  62991. subcomponents to the content comp. See the notes for the ResizableWindow class
  62992. for more info.
  62993. If you really know what you're doing and want to avoid this assertion, just call
  62994. Component::addChildComponent directly.
  62995. */
  62996. jassertfalse;
  62997. Component::addChildComponent (child, zOrder);
  62998. }
  62999. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63000. {
  63001. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63002. manages its child components automatically, and if you add your own it'll cause
  63003. trouble. Instead, use setContentComponent() to give it a component which
  63004. will be automatically resized and kept in the right place - then you can add
  63005. subcomponents to the content comp. See the notes for the ResizableWindow class
  63006. for more info.
  63007. If you really know what you're doing and want to avoid this assertion, just call
  63008. Component::addAndMakeVisible directly.
  63009. */
  63010. jassertfalse;
  63011. Component::addAndMakeVisible (child, zOrder);
  63012. }
  63013. #endif
  63014. END_JUCE_NAMESPACE
  63015. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63016. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63017. BEGIN_JUCE_NAMESPACE
  63018. SplashScreen::SplashScreen()
  63019. {
  63020. setOpaque (true);
  63021. }
  63022. SplashScreen::~SplashScreen()
  63023. {
  63024. }
  63025. void SplashScreen::show (const String& title,
  63026. const Image& backgroundImage_,
  63027. const int minimumTimeToDisplayFor,
  63028. const bool useDropShadow,
  63029. const bool removeOnMouseClick)
  63030. {
  63031. backgroundImage = backgroundImage_;
  63032. jassert (backgroundImage_.isValid());
  63033. if (backgroundImage_.isValid())
  63034. {
  63035. setOpaque (! backgroundImage_.hasAlphaChannel());
  63036. show (title,
  63037. backgroundImage_.getWidth(),
  63038. backgroundImage_.getHeight(),
  63039. minimumTimeToDisplayFor,
  63040. useDropShadow,
  63041. removeOnMouseClick);
  63042. }
  63043. }
  63044. void SplashScreen::show (const String& title,
  63045. const int width,
  63046. const int height,
  63047. const int minimumTimeToDisplayFor,
  63048. const bool useDropShadow,
  63049. const bool removeOnMouseClick)
  63050. {
  63051. setName (title);
  63052. setAlwaysOnTop (true);
  63053. setVisible (true);
  63054. centreWithSize (width, height);
  63055. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63056. toFront (false);
  63057. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63058. repaint();
  63059. originalClickCounter = removeOnMouseClick
  63060. ? Desktop::getMouseButtonClickCounter()
  63061. : std::numeric_limits<int>::max();
  63062. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63063. startTimer (50);
  63064. }
  63065. void SplashScreen::paint (Graphics& g)
  63066. {
  63067. g.setOpacity (1.0f);
  63068. g.drawImage (backgroundImage,
  63069. 0, 0, getWidth(), getHeight(),
  63070. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63071. }
  63072. void SplashScreen::timerCallback()
  63073. {
  63074. if (Time::getCurrentTime() > earliestTimeToDelete
  63075. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63076. {
  63077. delete this;
  63078. }
  63079. }
  63080. END_JUCE_NAMESPACE
  63081. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63082. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63083. BEGIN_JUCE_NAMESPACE
  63084. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63085. const bool hasProgressBar,
  63086. const bool hasCancelButton,
  63087. const int timeOutMsWhenCancelling_,
  63088. const String& cancelButtonText)
  63089. : Thread ("Juce Progress Window"),
  63090. progress (0.0),
  63091. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63092. {
  63093. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63094. .createAlertWindow (title, String::empty, cancelButtonText,
  63095. String::empty, String::empty,
  63096. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63097. if (hasProgressBar)
  63098. alertWindow->addProgressBarComponent (progress);
  63099. }
  63100. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63101. {
  63102. stopThread (timeOutMsWhenCancelling);
  63103. }
  63104. bool ThreadWithProgressWindow::runThread (const int priority)
  63105. {
  63106. startThread (priority);
  63107. startTimer (100);
  63108. {
  63109. const ScopedLock sl (messageLock);
  63110. alertWindow->setMessage (message);
  63111. }
  63112. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63113. stopThread (timeOutMsWhenCancelling);
  63114. alertWindow->setVisible (false);
  63115. return finishedNaturally;
  63116. }
  63117. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63118. {
  63119. progress = newProgress;
  63120. }
  63121. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63122. {
  63123. const ScopedLock sl (messageLock);
  63124. message = newStatusMessage;
  63125. }
  63126. void ThreadWithProgressWindow::timerCallback()
  63127. {
  63128. if (! isThreadRunning())
  63129. {
  63130. // thread has finished normally..
  63131. alertWindow->exitModalState (1);
  63132. alertWindow->setVisible (false);
  63133. }
  63134. else
  63135. {
  63136. const ScopedLock sl (messageLock);
  63137. alertWindow->setMessage (message);
  63138. }
  63139. }
  63140. END_JUCE_NAMESPACE
  63141. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63142. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63143. BEGIN_JUCE_NAMESPACE
  63144. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63145. const int millisecondsBeforeTipAppears_)
  63146. : Component ("tooltip"),
  63147. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63148. mouseClicks (0),
  63149. lastHideTime (0),
  63150. lastComponentUnderMouse (0),
  63151. changedCompsSinceShown (true)
  63152. {
  63153. if (Desktop::getInstance().getMainMouseSource().canHover())
  63154. startTimer (123);
  63155. setAlwaysOnTop (true);
  63156. setOpaque (true);
  63157. if (parentComponent != 0)
  63158. parentComponent->addChildComponent (this);
  63159. }
  63160. TooltipWindow::~TooltipWindow()
  63161. {
  63162. hide();
  63163. }
  63164. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63165. {
  63166. millisecondsBeforeTipAppears = newTimeMs;
  63167. }
  63168. void TooltipWindow::paint (Graphics& g)
  63169. {
  63170. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63171. }
  63172. void TooltipWindow::mouseEnter (const MouseEvent&)
  63173. {
  63174. hide();
  63175. }
  63176. void TooltipWindow::showFor (const String& tip)
  63177. {
  63178. jassert (tip.isNotEmpty());
  63179. tipShowing = tip;
  63180. Point<int> mousePos (Desktop::getMousePosition());
  63181. if (getParentComponent() != 0)
  63182. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63183. int x, y, w, h;
  63184. getLookAndFeel().getTooltipSize (tip, w, h);
  63185. if (mousePos.getX() > getParentWidth() / 2)
  63186. x = mousePos.getX() - (w + 12);
  63187. else
  63188. x = mousePos.getX() + 24;
  63189. if (mousePos.getY() > getParentHeight() / 2)
  63190. y = mousePos.getY() - (h + 6);
  63191. else
  63192. y = mousePos.getY() + 6;
  63193. setBounds (x, y, w, h);
  63194. setVisible (true);
  63195. if (getParentComponent() == 0)
  63196. {
  63197. addToDesktop (ComponentPeer::windowHasDropShadow
  63198. | ComponentPeer::windowIsTemporary
  63199. | ComponentPeer::windowIgnoresKeyPresses);
  63200. }
  63201. toFront (false);
  63202. }
  63203. const String TooltipWindow::getTipFor (Component* const c)
  63204. {
  63205. if (c != 0
  63206. && Process::isForegroundProcess()
  63207. && ! Component::isMouseButtonDownAnywhere())
  63208. {
  63209. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63210. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63211. return ttc->getTooltip();
  63212. }
  63213. return String::empty;
  63214. }
  63215. void TooltipWindow::hide()
  63216. {
  63217. tipShowing = String::empty;
  63218. removeFromDesktop();
  63219. setVisible (false);
  63220. }
  63221. void TooltipWindow::timerCallback()
  63222. {
  63223. const unsigned int now = Time::getApproximateMillisecondCounter();
  63224. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63225. const String newTip (getTipFor (newComp));
  63226. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63227. lastComponentUnderMouse = newComp;
  63228. lastTipUnderMouse = newTip;
  63229. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63230. const bool mouseWasClicked = clickCount > mouseClicks;
  63231. mouseClicks = clickCount;
  63232. const Point<int> mousePos (Desktop::getMousePosition());
  63233. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63234. lastMousePos = mousePos;
  63235. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63236. lastCompChangeTime = now;
  63237. if (isVisible() || now < lastHideTime + 500)
  63238. {
  63239. // if a tip is currently visible (or has just disappeared), update to a new one
  63240. // immediately if needed..
  63241. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63242. {
  63243. if (isVisible())
  63244. {
  63245. lastHideTime = now;
  63246. hide();
  63247. }
  63248. }
  63249. else if (tipChanged)
  63250. {
  63251. showFor (newTip);
  63252. }
  63253. }
  63254. else
  63255. {
  63256. // if there isn't currently a tip, but one is needed, only let it
  63257. // appear after a timeout..
  63258. if (newTip.isNotEmpty()
  63259. && newTip != tipShowing
  63260. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63261. {
  63262. showFor (newTip);
  63263. }
  63264. }
  63265. }
  63266. END_JUCE_NAMESPACE
  63267. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63268. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63269. BEGIN_JUCE_NAMESPACE
  63270. /** Keeps track of the active top level window.
  63271. */
  63272. class TopLevelWindowManager : public Timer,
  63273. public DeletedAtShutdown
  63274. {
  63275. public:
  63276. TopLevelWindowManager()
  63277. : currentActive (0)
  63278. {
  63279. }
  63280. ~TopLevelWindowManager()
  63281. {
  63282. clearSingletonInstance();
  63283. }
  63284. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63285. void timerCallback()
  63286. {
  63287. startTimer (jmin (1731, getTimerInterval() * 2));
  63288. TopLevelWindow* active = 0;
  63289. if (Process::isForegroundProcess())
  63290. {
  63291. active = currentActive;
  63292. Component* const c = Component::getCurrentlyFocusedComponent();
  63293. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63294. if (tlw == 0 && c != 0)
  63295. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63296. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63297. if (tlw != 0)
  63298. active = tlw;
  63299. }
  63300. if (active != currentActive)
  63301. {
  63302. currentActive = active;
  63303. for (int i = windows.size(); --i >= 0;)
  63304. {
  63305. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63306. tlw->setWindowActive (isWindowActive (tlw));
  63307. i = jmin (i, windows.size() - 1);
  63308. }
  63309. Desktop::getInstance().triggerFocusCallback();
  63310. }
  63311. }
  63312. bool addWindow (TopLevelWindow* const w)
  63313. {
  63314. windows.add (w);
  63315. startTimer (10);
  63316. return isWindowActive (w);
  63317. }
  63318. void removeWindow (TopLevelWindow* const w)
  63319. {
  63320. startTimer (10);
  63321. if (currentActive == w)
  63322. currentActive = 0;
  63323. windows.removeValue (w);
  63324. if (windows.size() == 0)
  63325. deleteInstance();
  63326. }
  63327. Array <TopLevelWindow*> windows;
  63328. private:
  63329. TopLevelWindow* currentActive;
  63330. bool isWindowActive (TopLevelWindow* const tlw) const
  63331. {
  63332. return (tlw == currentActive
  63333. || tlw->isParentOf (currentActive)
  63334. || tlw->hasKeyboardFocus (true))
  63335. && tlw->isShowing();
  63336. }
  63337. TopLevelWindowManager (const TopLevelWindowManager&);
  63338. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63339. };
  63340. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63341. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63342. {
  63343. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63344. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63345. }
  63346. TopLevelWindow::TopLevelWindow (const String& name,
  63347. const bool addToDesktop_)
  63348. : Component (name),
  63349. useDropShadow (true),
  63350. useNativeTitleBar (false),
  63351. windowIsActive_ (false)
  63352. {
  63353. setOpaque (true);
  63354. if (addToDesktop_)
  63355. Component::addToDesktop (getDesktopWindowStyleFlags());
  63356. else
  63357. setDropShadowEnabled (true);
  63358. setWantsKeyboardFocus (true);
  63359. setBroughtToFrontOnMouseClick (true);
  63360. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63361. }
  63362. TopLevelWindow::~TopLevelWindow()
  63363. {
  63364. shadower = 0;
  63365. TopLevelWindowManager::getInstance()->removeWindow (this);
  63366. }
  63367. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63368. {
  63369. if (hasKeyboardFocus (true))
  63370. TopLevelWindowManager::getInstance()->timerCallback();
  63371. else
  63372. TopLevelWindowManager::getInstance()->startTimer (10);
  63373. }
  63374. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63375. {
  63376. if (windowIsActive_ != isNowActive)
  63377. {
  63378. windowIsActive_ = isNowActive;
  63379. activeWindowStatusChanged();
  63380. }
  63381. }
  63382. void TopLevelWindow::activeWindowStatusChanged()
  63383. {
  63384. }
  63385. void TopLevelWindow::parentHierarchyChanged()
  63386. {
  63387. setDropShadowEnabled (useDropShadow);
  63388. }
  63389. void TopLevelWindow::visibilityChanged()
  63390. {
  63391. if (isShowing())
  63392. toFront (true);
  63393. }
  63394. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63395. {
  63396. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63397. if (useDropShadow)
  63398. styleFlags |= ComponentPeer::windowHasDropShadow;
  63399. if (useNativeTitleBar)
  63400. styleFlags |= ComponentPeer::windowHasTitleBar;
  63401. return styleFlags;
  63402. }
  63403. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63404. {
  63405. useDropShadow = useShadow;
  63406. if (isOnDesktop())
  63407. {
  63408. shadower = 0;
  63409. Component::addToDesktop (getDesktopWindowStyleFlags());
  63410. }
  63411. else
  63412. {
  63413. if (useShadow && isOpaque())
  63414. {
  63415. if (shadower == 0)
  63416. {
  63417. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63418. if (shadower != 0)
  63419. shadower->setOwner (this);
  63420. }
  63421. }
  63422. else
  63423. {
  63424. shadower = 0;
  63425. }
  63426. }
  63427. }
  63428. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63429. {
  63430. if (useNativeTitleBar != useNativeTitleBar_)
  63431. {
  63432. useNativeTitleBar = useNativeTitleBar_;
  63433. recreateDesktopWindow();
  63434. sendLookAndFeelChange();
  63435. }
  63436. }
  63437. void TopLevelWindow::recreateDesktopWindow()
  63438. {
  63439. if (isOnDesktop())
  63440. {
  63441. Component::addToDesktop (getDesktopWindowStyleFlags());
  63442. toFront (true);
  63443. }
  63444. }
  63445. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63446. {
  63447. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63448. because this class needs to make sure its layout corresponds with settings like whether
  63449. it's got a native title bar or not.
  63450. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63451. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63452. method, then add or remove whatever flags are necessary from this value before returning it.
  63453. */
  63454. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63455. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63456. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63457. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63458. sendLookAndFeelChange();
  63459. }
  63460. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63461. {
  63462. if (c == 0)
  63463. c = TopLevelWindow::getActiveTopLevelWindow();
  63464. if (c == 0)
  63465. {
  63466. centreWithSize (width, height);
  63467. }
  63468. else
  63469. {
  63470. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63471. (c->getHeight() - height) / 2)));
  63472. Rectangle<int> parentArea (c->getParentMonitorArea());
  63473. if (getParentComponent() != 0)
  63474. {
  63475. p = getParentComponent()->globalPositionToRelative (p);
  63476. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63477. }
  63478. parentArea.reduce (12, 12);
  63479. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63480. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63481. width, height);
  63482. }
  63483. }
  63484. int TopLevelWindow::getNumTopLevelWindows() throw()
  63485. {
  63486. return TopLevelWindowManager::getInstance()->windows.size();
  63487. }
  63488. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63489. {
  63490. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63491. }
  63492. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63493. {
  63494. TopLevelWindow* best = 0;
  63495. int bestNumTWLParents = -1;
  63496. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63497. {
  63498. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63499. if (tlw->isActiveWindow())
  63500. {
  63501. int numTWLParents = 0;
  63502. const Component* c = tlw->getParentComponent();
  63503. while (c != 0)
  63504. {
  63505. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63506. ++numTWLParents;
  63507. c = c->getParentComponent();
  63508. }
  63509. if (bestNumTWLParents < numTWLParents)
  63510. {
  63511. best = tlw;
  63512. bestNumTWLParents = numTWLParents;
  63513. }
  63514. }
  63515. }
  63516. return best;
  63517. }
  63518. END_JUCE_NAMESPACE
  63519. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63520. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63521. BEGIN_JUCE_NAMESPACE
  63522. namespace RelativeCoordinateHelpers
  63523. {
  63524. static bool isOrigin (const String& name)
  63525. {
  63526. return name.isEmpty()
  63527. || name == RelativeCoordinate::Strings::parentLeft
  63528. || name == RelativeCoordinate::Strings::parentTop;
  63529. }
  63530. static const String getExtentAnchorName (const bool isHorizontal) throw()
  63531. {
  63532. return isHorizontal ? RelativeCoordinate::Strings::parentRight
  63533. : RelativeCoordinate::Strings::parentBottom;
  63534. }
  63535. static const String getObjectName (const String& fullName)
  63536. {
  63537. return fullName.upToFirstOccurrenceOf (".", false, false);
  63538. }
  63539. static const String getEdgeName (const String& fullName)
  63540. {
  63541. return fullName.fromFirstOccurrenceOf (".", false, false);
  63542. }
  63543. static const RelativeCoordinate findCoordinate (const String& name, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63544. {
  63545. return nameFinder != 0 ? nameFinder->findNamedCoordinate (getObjectName (name), getEdgeName (name))
  63546. : RelativeCoordinate();
  63547. }
  63548. struct RecursionException : public std::runtime_error
  63549. {
  63550. RecursionException() : std::runtime_error ("Recursive RelativeCoordinate expression")
  63551. {
  63552. }
  63553. };
  63554. static void skipWhitespace (const juce_wchar* const s, int& i)
  63555. {
  63556. while (CharacterFunctions::isWhitespace (s[i]))
  63557. ++i;
  63558. }
  63559. static void skipComma (const juce_wchar* const s, int& i)
  63560. {
  63561. skipWhitespace (s, i);
  63562. if (s[i] == ',')
  63563. ++i;
  63564. }
  63565. static const String readAnchorName (const juce_wchar* const s, int& i)
  63566. {
  63567. skipWhitespace (s, i);
  63568. if (CharacterFunctions::isLetter (s[i]) || s[i] == '_')
  63569. {
  63570. int start = i;
  63571. while (CharacterFunctions::isLetterOrDigit (s[i]) || s[i] == '_' || s[i] == '.')
  63572. ++i;
  63573. return String (s + start, i - start);
  63574. }
  63575. return String::empty;
  63576. }
  63577. static double readNumber (const juce_wchar* const s, int& i)
  63578. {
  63579. skipWhitespace (s, i);
  63580. int start = i;
  63581. if (CharacterFunctions::isDigit (s[i]) || s[i] == '.' || s[i] == '-')
  63582. ++i;
  63583. while (CharacterFunctions::isDigit (s[i]) || s[i] == '.')
  63584. ++i;
  63585. if ((s[i] == 'e' || s[i] == 'E')
  63586. && (CharacterFunctions::isDigit (s[i + 1])
  63587. || s[i + 1] == '-'
  63588. || s[i + 1] == '+'))
  63589. {
  63590. i += 2;
  63591. while (CharacterFunctions::isDigit (s[i]))
  63592. ++i;
  63593. }
  63594. const double value = String (s + start, i - start).getDoubleValue();
  63595. while (CharacterFunctions::isWhitespace (s[i]) || s[i] == ',')
  63596. ++i;
  63597. return value;
  63598. }
  63599. static const RelativeCoordinate readNextCoordinate (const juce_wchar* const s, int& i, const bool isHorizontal)
  63600. {
  63601. String anchor1 (readAnchorName (s, i));
  63602. double value = 0;
  63603. if (anchor1.isNotEmpty())
  63604. {
  63605. skipWhitespace (s, i);
  63606. if (s[i] == '+')
  63607. value = readNumber (s, ++i);
  63608. else if (s[i] == '-')
  63609. value = -readNumber (s, ++i);
  63610. return RelativeCoordinate (value, anchor1);
  63611. }
  63612. else
  63613. {
  63614. value = readNumber (s, i);
  63615. skipWhitespace (s, i);
  63616. if (s[i] == '%')
  63617. {
  63618. value /= 100.0;
  63619. skipWhitespace (s, ++i);
  63620. String anchor2;
  63621. if (s[i] == '*')
  63622. {
  63623. anchor1 = readAnchorName (s, ++i);
  63624. skipWhitespace (s, i);
  63625. if (s[i] == '-' && s[i + 1] == '>')
  63626. {
  63627. i += 2;
  63628. anchor2 = readAnchorName (s, i);
  63629. }
  63630. else
  63631. {
  63632. anchor2 = anchor1;
  63633. anchor1 = String::empty;
  63634. }
  63635. }
  63636. else
  63637. {
  63638. anchor1 = String::empty;
  63639. anchor2 = getExtentAnchorName (isHorizontal);
  63640. }
  63641. return RelativeCoordinate (value, anchor1, anchor2);
  63642. }
  63643. return RelativeCoordinate (value);
  63644. }
  63645. }
  63646. static const String limitedAccuracyString (const double n)
  63647. {
  63648. if (! (n < -0.001 || n > 0.001)) // to detect NaN and inf as well as for rounding
  63649. return "0";
  63650. return String (n, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".");
  63651. }
  63652. }
  63653. const String RelativeCoordinate::Strings::parent ("parent");
  63654. const String RelativeCoordinate::Strings::left ("left");
  63655. const String RelativeCoordinate::Strings::right ("right");
  63656. const String RelativeCoordinate::Strings::top ("top");
  63657. const String RelativeCoordinate::Strings::bottom ("bottom");
  63658. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  63659. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  63660. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  63661. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  63662. RelativeCoordinate::RelativeCoordinate()
  63663. : value (0)
  63664. {
  63665. }
  63666. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63667. : value (absoluteDistanceFromOrigin)
  63668. {
  63669. }
  63670. RelativeCoordinate::RelativeCoordinate (const double absoluteDistance, const String& source)
  63671. : anchor1 (source.trim()),
  63672. value (absoluteDistance)
  63673. {
  63674. }
  63675. RelativeCoordinate::RelativeCoordinate (const double relativeProportion, const String& pos1, const String& pos2)
  63676. : anchor1 (pos1.trim()),
  63677. anchor2 (pos2.trim()),
  63678. value (relativeProportion)
  63679. {
  63680. }
  63681. RelativeCoordinate::RelativeCoordinate (const String& s, const bool isHorizontal)
  63682. : value (0)
  63683. {
  63684. int i = 0;
  63685. *this = RelativeCoordinateHelpers::readNextCoordinate (s, i, isHorizontal);
  63686. }
  63687. RelativeCoordinate::~RelativeCoordinate()
  63688. {
  63689. }
  63690. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63691. {
  63692. return value == other.value && anchor1 == other.anchor1 && anchor2 == other.anchor2;
  63693. }
  63694. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63695. {
  63696. return ! operator== (other);
  63697. }
  63698. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate1() const
  63699. {
  63700. return RelativeCoordinate (0.0, anchor1);
  63701. }
  63702. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate2() const
  63703. {
  63704. return RelativeCoordinate (0.0, anchor2);
  63705. }
  63706. double RelativeCoordinate::resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter)
  63707. {
  63708. if (RelativeCoordinateHelpers::isOrigin (anchorName))
  63709. return 0.0;
  63710. return RelativeCoordinateHelpers::findCoordinate (anchorName, nameFinder).resolve (nameFinder, recursionCounter + 1);
  63711. }
  63712. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const
  63713. {
  63714. if (recursionCounter > 150)
  63715. {
  63716. jassertfalse
  63717. throw RelativeCoordinateHelpers::RecursionException();
  63718. }
  63719. const double pos1 = resolveAnchor (anchor1, nameFinder, recursionCounter);
  63720. return isProportional() ? pos1 + (resolveAnchor (anchor2, nameFinder, recursionCounter) - pos1) * value
  63721. : pos1 + value;
  63722. }
  63723. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder) const
  63724. {
  63725. try
  63726. {
  63727. return resolve (nameFinder, 0);
  63728. }
  63729. catch (RelativeCoordinateHelpers::RecursionException&)
  63730. {}
  63731. return 0.0;
  63732. }
  63733. bool RelativeCoordinate::isRecursive (const NamedCoordinateFinder* nameFinder) const
  63734. {
  63735. try
  63736. {
  63737. (void) resolve (nameFinder, 0);
  63738. }
  63739. catch (RelativeCoordinateHelpers::RecursionException&)
  63740. {
  63741. return true;
  63742. }
  63743. return false;
  63744. }
  63745. void RelativeCoordinate::moveToAbsolute (double newPos, const NamedCoordinateFinder* nameFinder)
  63746. {
  63747. try
  63748. {
  63749. const double pos1 = resolveAnchor (anchor1, nameFinder, 0);
  63750. if (isProportional())
  63751. {
  63752. const double size = resolveAnchor (anchor2, nameFinder, 0) - pos1;
  63753. if (size != 0)
  63754. value = (newPos - pos1) / size;
  63755. }
  63756. else
  63757. {
  63758. value = newPos - pos1;
  63759. }
  63760. }
  63761. catch (RelativeCoordinateHelpers::RecursionException&)
  63762. {}
  63763. }
  63764. void RelativeCoordinate::toggleProportionality (const NamedCoordinateFinder* nameFinder,
  63765. const String& proportionalAnchor1, const String& proportionalAnchor2)
  63766. {
  63767. const double oldValue = resolve (nameFinder);
  63768. anchor1 = proportionalAnchor1;
  63769. anchor2 = isProportional() ? String::empty : proportionalAnchor2;
  63770. moveToAbsolute (oldValue, nameFinder);
  63771. }
  63772. bool RelativeCoordinate::references (const String& coordName, const NamedCoordinateFinder* nameFinder) const
  63773. {
  63774. using namespace RelativeCoordinateHelpers;
  63775. if (isOrigin (anchor1) && ! isProportional())
  63776. return isOrigin (coordName);
  63777. return anchor1 == coordName
  63778. || anchor2 == coordName
  63779. || findCoordinate (anchor1, nameFinder).references (coordName, nameFinder)
  63780. || (isProportional() && findCoordinate (anchor2, nameFinder).references (coordName, nameFinder));
  63781. }
  63782. bool RelativeCoordinate::isDynamic() const
  63783. {
  63784. return anchor2.isNotEmpty() || ! RelativeCoordinateHelpers::isOrigin (anchor1);
  63785. }
  63786. const String RelativeCoordinate::toString() const
  63787. {
  63788. using namespace RelativeCoordinateHelpers;
  63789. if (isProportional())
  63790. {
  63791. const String percent (limitedAccuracyString (value * 100.0));
  63792. if (isOrigin (anchor1))
  63793. {
  63794. if (anchor2 == Strings::parentRight || anchor2 == Strings::parentBottom)
  63795. return percent + "%";
  63796. else
  63797. return percent + "% * " + anchor2;
  63798. }
  63799. else
  63800. return percent + "% * " + anchor1 + " -> " + anchor2;
  63801. }
  63802. else
  63803. {
  63804. if (isOrigin (anchor1))
  63805. return limitedAccuracyString (value);
  63806. else if (value > 0)
  63807. return anchor1 + " + " + limitedAccuracyString (value);
  63808. else if (value < 0)
  63809. return anchor1 + " - " + limitedAccuracyString (-value);
  63810. else
  63811. return anchor1;
  63812. }
  63813. }
  63814. const double RelativeCoordinate::getEditableNumber() const
  63815. {
  63816. return isProportional() ? value * 100.0 : value;
  63817. }
  63818. void RelativeCoordinate::setEditableNumber (const double newValue)
  63819. {
  63820. value = isProportional() ? newValue / 100.0 : newValue;
  63821. }
  63822. const String RelativeCoordinate::getAnchorName1 (const String& returnValueIfOrigin) const
  63823. {
  63824. return RelativeCoordinateHelpers::isOrigin (anchor1) ? returnValueIfOrigin : anchor1;
  63825. }
  63826. const String RelativeCoordinate::getAnchorName2 (const String& returnValueIfOrigin) const
  63827. {
  63828. return RelativeCoordinateHelpers::isOrigin (anchor2) ? returnValueIfOrigin : anchor2;
  63829. }
  63830. void RelativeCoordinate::changeAnchor1 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  63831. {
  63832. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  63833. const double oldValue = resolve (nameFinder);
  63834. anchor1 = RelativeCoordinateHelpers::isOrigin (newAnchorName) ? String::empty : newAnchorName;
  63835. moveToAbsolute (oldValue, nameFinder);
  63836. }
  63837. void RelativeCoordinate::changeAnchor2 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  63838. {
  63839. jassert (isProportional());
  63840. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  63841. const double oldValue = resolve (nameFinder);
  63842. anchor2 = RelativeCoordinateHelpers::isOrigin (newAnchorName) ? String::empty : newAnchorName;
  63843. moveToAbsolute (oldValue, nameFinder);
  63844. }
  63845. void RelativeCoordinate::renameAnchorIfUsed (const String& oldName, const String& newName, const NamedCoordinateFinder* nameFinder)
  63846. {
  63847. using namespace RelativeCoordinateHelpers;
  63848. jassert (oldName.isNotEmpty());
  63849. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  63850. if (newName.isEmpty())
  63851. {
  63852. if (getObjectName (anchor1) == oldName
  63853. || getObjectName (anchor2) == oldName)
  63854. {
  63855. value = resolve (nameFinder);
  63856. anchor1 = String::empty;
  63857. anchor2 = String::empty;
  63858. }
  63859. }
  63860. else
  63861. {
  63862. if (getObjectName (anchor1) == oldName)
  63863. anchor1 = newName + "." + getEdgeName (anchor1);
  63864. if (getObjectName (anchor2) == oldName)
  63865. anchor2 = newName + "." + getEdgeName (anchor2);
  63866. }
  63867. }
  63868. RelativePoint::RelativePoint()
  63869. {
  63870. }
  63871. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  63872. : x (absolutePoint.getX()), y (absolutePoint.getY())
  63873. {
  63874. }
  63875. RelativePoint::RelativePoint (const float x_, const float y_)
  63876. : x (x_), y (y_)
  63877. {
  63878. }
  63879. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  63880. : x (x_), y (y_)
  63881. {
  63882. }
  63883. RelativePoint::RelativePoint (const String& s)
  63884. {
  63885. int i = 0;
  63886. x = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63887. RelativeCoordinateHelpers::skipComma (s, i);
  63888. y = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63889. }
  63890. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  63891. {
  63892. return x == other.x && y == other.y;
  63893. }
  63894. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  63895. {
  63896. return ! operator== (other);
  63897. }
  63898. const Point<float> RelativePoint::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  63899. {
  63900. return Point<float> ((float) x.resolve (nameFinder),
  63901. (float) y.resolve (nameFinder));
  63902. }
  63903. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63904. {
  63905. x.moveToAbsolute (newPos.getX(), nameFinder);
  63906. y.moveToAbsolute (newPos.getY(), nameFinder);
  63907. }
  63908. const String RelativePoint::toString() const
  63909. {
  63910. return x.toString() + ", " + y.toString();
  63911. }
  63912. void RelativePoint::renameAnchorIfUsed (const String& oldName, const String& newName, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63913. {
  63914. x.renameAnchorIfUsed (oldName, newName, nameFinder);
  63915. y.renameAnchorIfUsed (oldName, newName, nameFinder);
  63916. }
  63917. bool RelativePoint::isDynamic() const
  63918. {
  63919. return x.isDynamic() || y.isDynamic();
  63920. }
  63921. RelativeRectangle::RelativeRectangle()
  63922. {
  63923. }
  63924. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  63925. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  63926. : left (left_), right (right_), top (top_), bottom (bottom_)
  63927. {
  63928. }
  63929. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  63930. : left (rect.getX()),
  63931. right (rect.getWidth(), componentName + "." + RelativeCoordinate::Strings::left),
  63932. top (rect.getY()),
  63933. bottom (rect.getHeight(), componentName + "." + RelativeCoordinate::Strings::top)
  63934. {
  63935. }
  63936. RelativeRectangle::RelativeRectangle (const String& s)
  63937. {
  63938. int i = 0;
  63939. left = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63940. RelativeCoordinateHelpers::skipComma (s, i);
  63941. top = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63942. RelativeCoordinateHelpers::skipComma (s, i);
  63943. right = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  63944. RelativeCoordinateHelpers::skipComma (s, i);
  63945. bottom = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  63946. }
  63947. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  63948. {
  63949. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  63950. }
  63951. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  63952. {
  63953. return ! operator== (other);
  63954. }
  63955. const Rectangle<float> RelativeRectangle::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  63956. {
  63957. const double l = left.resolve (nameFinder);
  63958. const double r = right.resolve (nameFinder);
  63959. const double t = top.resolve (nameFinder);
  63960. const double b = bottom.resolve (nameFinder);
  63961. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  63962. }
  63963. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63964. {
  63965. left.moveToAbsolute (newPos.getX(), nameFinder);
  63966. right.moveToAbsolute (newPos.getRight(), nameFinder);
  63967. top.moveToAbsolute (newPos.getY(), nameFinder);
  63968. bottom.moveToAbsolute (newPos.getBottom(), nameFinder);
  63969. }
  63970. const String RelativeRectangle::toString() const
  63971. {
  63972. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  63973. }
  63974. void RelativeRectangle::renameAnchorIfUsed (const String& oldName, const String& newName,
  63975. const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  63976. {
  63977. left.renameAnchorIfUsed (oldName, newName, nameFinder);
  63978. right.renameAnchorIfUsed (oldName, newName, nameFinder);
  63979. top.renameAnchorIfUsed (oldName, newName, nameFinder);
  63980. bottom.renameAnchorIfUsed (oldName, newName, nameFinder);
  63981. }
  63982. RelativePointPath::RelativePointPath()
  63983. : usesNonZeroWinding (true),
  63984. containsDynamicPoints (false)
  63985. {
  63986. }
  63987. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  63988. : usesNonZeroWinding (true),
  63989. containsDynamicPoints (false)
  63990. {
  63991. ValueTree state (DrawablePath::valueTreeType);
  63992. other.writeTo (state, 0);
  63993. parse (state);
  63994. }
  63995. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  63996. : usesNonZeroWinding (true),
  63997. containsDynamicPoints (false)
  63998. {
  63999. parse (drawable);
  64000. }
  64001. RelativePointPath::RelativePointPath (const Path& path)
  64002. {
  64003. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64004. Path::Iterator i (path);
  64005. while (i.next())
  64006. {
  64007. switch (i.elementType)
  64008. {
  64009. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64010. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64011. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64012. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64013. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64014. default: jassertfalse; break;
  64015. }
  64016. }
  64017. }
  64018. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64019. {
  64020. DrawablePath::ValueTreeWrapper wrapper (state);
  64021. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64022. ValueTree pathTree (wrapper.getPathState());
  64023. pathTree.removeAllChildren (undoManager);
  64024. for (int i = 0; i < elements.size(); ++i)
  64025. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64026. }
  64027. void RelativePointPath::parse (const ValueTree& state)
  64028. {
  64029. DrawablePath::ValueTreeWrapper wrapper (state);
  64030. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64031. RelativePoint points[3];
  64032. const ValueTree pathTree (wrapper.getPathState());
  64033. const int num = pathTree.getNumChildren();
  64034. for (int i = 0; i < num; ++i)
  64035. {
  64036. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64037. const int numCps = e.getNumControlPoints();
  64038. for (int j = 0; j < numCps; ++j)
  64039. {
  64040. points[j] = e.getControlPoint (j);
  64041. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64042. }
  64043. const Identifier type (e.getType());
  64044. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64045. elements.add (new StartSubPath (points[0]));
  64046. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64047. elements.add (new CloseSubPath());
  64048. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64049. elements.add (new LineTo (points[0]));
  64050. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64051. elements.add (new QuadraticTo (points[0], points[1]));
  64052. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64053. elements.add (new CubicTo (points[0], points[1], points[2]));
  64054. else
  64055. jassertfalse;
  64056. }
  64057. }
  64058. RelativePointPath::~RelativePointPath()
  64059. {
  64060. }
  64061. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64062. {
  64063. elements.swapWithArray (other.elements);
  64064. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64065. }
  64066. void RelativePointPath::createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder)
  64067. {
  64068. for (int i = 0; i < elements.size(); ++i)
  64069. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64070. }
  64071. bool RelativePointPath::containsAnyDynamicPoints() const
  64072. {
  64073. return containsDynamicPoints;
  64074. }
  64075. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64076. {
  64077. }
  64078. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64079. : ElementBase (startSubPathElement), startPos (pos)
  64080. {
  64081. }
  64082. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64083. {
  64084. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64085. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64086. return v;
  64087. }
  64088. void RelativePointPath::StartSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64089. {
  64090. path.startNewSubPath (startPos.resolve (coordFinder));
  64091. }
  64092. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64093. {
  64094. numPoints = 1;
  64095. return &startPos;
  64096. }
  64097. RelativePointPath::CloseSubPath::CloseSubPath()
  64098. : ElementBase (closeSubPathElement)
  64099. {
  64100. }
  64101. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64102. {
  64103. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64104. }
  64105. void RelativePointPath::CloseSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder*) const
  64106. {
  64107. path.closeSubPath();
  64108. }
  64109. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64110. {
  64111. numPoints = 0;
  64112. return 0;
  64113. }
  64114. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64115. : ElementBase (lineToElement), endPoint (endPoint_)
  64116. {
  64117. }
  64118. const ValueTree RelativePointPath::LineTo::createTree() const
  64119. {
  64120. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64121. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64122. return v;
  64123. }
  64124. void RelativePointPath::LineTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64125. {
  64126. path.lineTo (endPoint.resolve (coordFinder));
  64127. }
  64128. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64129. {
  64130. numPoints = 1;
  64131. return &endPoint;
  64132. }
  64133. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64134. : ElementBase (quadraticToElement)
  64135. {
  64136. controlPoints[0] = controlPoint;
  64137. controlPoints[1] = endPoint;
  64138. }
  64139. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64140. {
  64141. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64142. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64143. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64144. return v;
  64145. }
  64146. void RelativePointPath::QuadraticTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64147. {
  64148. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64149. controlPoints[1].resolve (coordFinder));
  64150. }
  64151. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64152. {
  64153. numPoints = 2;
  64154. return controlPoints;
  64155. }
  64156. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64157. : ElementBase (cubicToElement)
  64158. {
  64159. controlPoints[0] = controlPoint1;
  64160. controlPoints[1] = controlPoint2;
  64161. controlPoints[2] = endPoint;
  64162. }
  64163. const ValueTree RelativePointPath::CubicTo::createTree() const
  64164. {
  64165. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64166. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64167. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64168. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64169. return v;
  64170. }
  64171. void RelativePointPath::CubicTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  64172. {
  64173. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64174. controlPoints[1].resolve (coordFinder),
  64175. controlPoints[2].resolve (coordFinder));
  64176. }
  64177. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64178. {
  64179. numPoints = 3;
  64180. return controlPoints;
  64181. }
  64182. RelativeParallelogram::RelativeParallelogram()
  64183. {
  64184. }
  64185. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64186. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64187. {
  64188. }
  64189. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64190. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64191. {
  64192. }
  64193. RelativeParallelogram::~RelativeParallelogram()
  64194. {
  64195. }
  64196. void RelativeParallelogram::resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64197. {
  64198. points[0] = topLeft.resolve (coordFinder);
  64199. points[1] = topRight.resolve (coordFinder);
  64200. points[2] = bottomLeft.resolve (coordFinder);
  64201. }
  64202. void RelativeParallelogram::resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64203. {
  64204. resolveThreePoints (points, coordFinder);
  64205. points[3] = points[1] + (points[2] - points[0]);
  64206. }
  64207. const Rectangle<float> RelativeParallelogram::getBounds (RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64208. {
  64209. Point<float> points[4];
  64210. resolveFourCorners (points, coordFinder);
  64211. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64212. }
  64213. void RelativeParallelogram::getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  64214. {
  64215. Point<float> points[4];
  64216. resolveFourCorners (points, coordFinder);
  64217. path.startNewSubPath (points[0]);
  64218. path.lineTo (points[1]);
  64219. path.lineTo (points[3]);
  64220. path.lineTo (points[2]);
  64221. path.closeSubPath();
  64222. }
  64223. const AffineTransform RelativeParallelogram::resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* const coordFinder)
  64224. {
  64225. Point<float> corners[3];
  64226. resolveThreePoints (corners, coordFinder);
  64227. const Line<float> top (corners[0], corners[1]);
  64228. const Line<float> left (corners[0], corners[2]);
  64229. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64230. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64231. topRight.moveToAbsolute (newTopRight, coordFinder);
  64232. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64233. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64234. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64235. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64236. }
  64237. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64238. {
  64239. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64240. }
  64241. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64242. {
  64243. return ! operator== (other);
  64244. }
  64245. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64246. {
  64247. const Point<float> tr (corners[1] - corners[0]);
  64248. const Point<float> bl (corners[2] - corners[0]);
  64249. target -= corners[0];
  64250. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64251. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64252. }
  64253. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64254. {
  64255. return corners[0]
  64256. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64257. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64258. }
  64259. END_JUCE_NAMESPACE
  64260. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64261. #endif
  64262. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64263. /*** Start of inlined file: juce_Colour.cpp ***/
  64264. BEGIN_JUCE_NAMESPACE
  64265. namespace ColourHelpers
  64266. {
  64267. static uint8 floatAlphaToInt (const float alpha) throw()
  64268. {
  64269. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64270. }
  64271. static void convertHSBtoRGB (float h, float s, float v,
  64272. uint8& r, uint8& g, uint8& b) throw()
  64273. {
  64274. v = jlimit (0.0f, 1.0f, v);
  64275. v *= 255.0f;
  64276. const uint8 intV = (uint8) roundToInt (v);
  64277. if (s <= 0)
  64278. {
  64279. r = intV;
  64280. g = intV;
  64281. b = intV;
  64282. }
  64283. else
  64284. {
  64285. s = jmin (1.0f, s);
  64286. h = jlimit (0.0f, 1.0f, h);
  64287. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64288. const float f = h - std::floor (h);
  64289. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64290. const float y = v * (1.0f - s * f);
  64291. const float z = v * (1.0f - (s * (1.0f - f)));
  64292. if (h < 1.0f)
  64293. {
  64294. r = intV;
  64295. g = (uint8) roundToInt (z);
  64296. b = x;
  64297. }
  64298. else if (h < 2.0f)
  64299. {
  64300. r = (uint8) roundToInt (y);
  64301. g = intV;
  64302. b = x;
  64303. }
  64304. else if (h < 3.0f)
  64305. {
  64306. r = x;
  64307. g = intV;
  64308. b = (uint8) roundToInt (z);
  64309. }
  64310. else if (h < 4.0f)
  64311. {
  64312. r = x;
  64313. g = (uint8) roundToInt (y);
  64314. b = intV;
  64315. }
  64316. else if (h < 5.0f)
  64317. {
  64318. r = (uint8) roundToInt (z);
  64319. g = x;
  64320. b = intV;
  64321. }
  64322. else if (h < 6.0f)
  64323. {
  64324. r = intV;
  64325. g = x;
  64326. b = (uint8) roundToInt (y);
  64327. }
  64328. else
  64329. {
  64330. r = 0;
  64331. g = 0;
  64332. b = 0;
  64333. }
  64334. }
  64335. }
  64336. }
  64337. Colour::Colour() throw()
  64338. : argb (0)
  64339. {
  64340. }
  64341. Colour::Colour (const Colour& other) throw()
  64342. : argb (other.argb)
  64343. {
  64344. }
  64345. Colour& Colour::operator= (const Colour& other) throw()
  64346. {
  64347. argb = other.argb;
  64348. return *this;
  64349. }
  64350. bool Colour::operator== (const Colour& other) const throw()
  64351. {
  64352. return argb.getARGB() == other.argb.getARGB();
  64353. }
  64354. bool Colour::operator!= (const Colour& other) const throw()
  64355. {
  64356. return argb.getARGB() != other.argb.getARGB();
  64357. }
  64358. Colour::Colour (const uint32 argb_) throw()
  64359. : argb (argb_)
  64360. {
  64361. }
  64362. Colour::Colour (const uint8 red,
  64363. const uint8 green,
  64364. const uint8 blue) throw()
  64365. {
  64366. argb.setARGB (0xff, red, green, blue);
  64367. }
  64368. const Colour Colour::fromRGB (const uint8 red,
  64369. const uint8 green,
  64370. const uint8 blue) throw()
  64371. {
  64372. return Colour (red, green, blue);
  64373. }
  64374. Colour::Colour (const uint8 red,
  64375. const uint8 green,
  64376. const uint8 blue,
  64377. const uint8 alpha) throw()
  64378. {
  64379. argb.setARGB (alpha, red, green, blue);
  64380. }
  64381. const Colour Colour::fromRGBA (const uint8 red,
  64382. const uint8 green,
  64383. const uint8 blue,
  64384. const uint8 alpha) throw()
  64385. {
  64386. return Colour (red, green, blue, alpha);
  64387. }
  64388. Colour::Colour (const uint8 red,
  64389. const uint8 green,
  64390. const uint8 blue,
  64391. const float alpha) throw()
  64392. {
  64393. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64394. }
  64395. const Colour Colour::fromRGBAFloat (const uint8 red,
  64396. const uint8 green,
  64397. const uint8 blue,
  64398. const float alpha) throw()
  64399. {
  64400. return Colour (red, green, blue, alpha);
  64401. }
  64402. Colour::Colour (const float hue,
  64403. const float saturation,
  64404. const float brightness,
  64405. const float alpha) throw()
  64406. {
  64407. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64408. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64409. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64410. }
  64411. const Colour Colour::fromHSV (const float hue,
  64412. const float saturation,
  64413. const float brightness,
  64414. const float alpha) throw()
  64415. {
  64416. return Colour (hue, saturation, brightness, alpha);
  64417. }
  64418. Colour::Colour (const float hue,
  64419. const float saturation,
  64420. const float brightness,
  64421. const uint8 alpha) throw()
  64422. {
  64423. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64424. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64425. argb.setARGB (alpha, r, g, b);
  64426. }
  64427. Colour::~Colour() throw()
  64428. {
  64429. }
  64430. const PixelARGB Colour::getPixelARGB() const throw()
  64431. {
  64432. PixelARGB p (argb);
  64433. p.premultiply();
  64434. return p;
  64435. }
  64436. uint32 Colour::getARGB() const throw()
  64437. {
  64438. return argb.getARGB();
  64439. }
  64440. bool Colour::isTransparent() const throw()
  64441. {
  64442. return getAlpha() == 0;
  64443. }
  64444. bool Colour::isOpaque() const throw()
  64445. {
  64446. return getAlpha() == 0xff;
  64447. }
  64448. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64449. {
  64450. PixelARGB newCol (argb);
  64451. newCol.setAlpha (newAlpha);
  64452. return Colour (newCol.getARGB());
  64453. }
  64454. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64455. {
  64456. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64457. PixelARGB newCol (argb);
  64458. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64459. return Colour (newCol.getARGB());
  64460. }
  64461. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64462. {
  64463. jassert (alphaMultiplier >= 0);
  64464. PixelARGB newCol (argb);
  64465. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64466. return Colour (newCol.getARGB());
  64467. }
  64468. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64469. {
  64470. const int destAlpha = getAlpha();
  64471. if (destAlpha > 0)
  64472. {
  64473. const int invA = 0xff - (int) src.getAlpha();
  64474. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64475. if (resA > 0)
  64476. {
  64477. const int da = (invA * destAlpha) / resA;
  64478. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64479. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64480. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64481. (uint8) resA);
  64482. }
  64483. return *this;
  64484. }
  64485. else
  64486. {
  64487. return src;
  64488. }
  64489. }
  64490. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64491. {
  64492. if (proportionOfOther <= 0)
  64493. return *this;
  64494. if (proportionOfOther >= 1.0f)
  64495. return other;
  64496. PixelARGB c1 (getPixelARGB());
  64497. const PixelARGB c2 (other.getPixelARGB());
  64498. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64499. c1.unpremultiply();
  64500. return Colour (c1.getARGB());
  64501. }
  64502. float Colour::getFloatRed() const throw()
  64503. {
  64504. return getRed() / 255.0f;
  64505. }
  64506. float Colour::getFloatGreen() const throw()
  64507. {
  64508. return getGreen() / 255.0f;
  64509. }
  64510. float Colour::getFloatBlue() const throw()
  64511. {
  64512. return getBlue() / 255.0f;
  64513. }
  64514. float Colour::getFloatAlpha() const throw()
  64515. {
  64516. return getAlpha() / 255.0f;
  64517. }
  64518. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64519. {
  64520. const int r = getRed();
  64521. const int g = getGreen();
  64522. const int b = getBlue();
  64523. const int hi = jmax (r, g, b);
  64524. const int lo = jmin (r, g, b);
  64525. if (hi != 0)
  64526. {
  64527. s = (hi - lo) / (float) hi;
  64528. if (s != 0)
  64529. {
  64530. const float invDiff = 1.0f / (hi - lo);
  64531. const float red = (hi - r) * invDiff;
  64532. const float green = (hi - g) * invDiff;
  64533. const float blue = (hi - b) * invDiff;
  64534. if (r == hi)
  64535. h = blue - green;
  64536. else if (g == hi)
  64537. h = 2.0f + red - blue;
  64538. else
  64539. h = 4.0f + green - red;
  64540. h *= 1.0f / 6.0f;
  64541. if (h < 0)
  64542. ++h;
  64543. }
  64544. else
  64545. {
  64546. h = 0;
  64547. }
  64548. }
  64549. else
  64550. {
  64551. s = 0;
  64552. h = 0;
  64553. }
  64554. v = hi / 255.0f;
  64555. }
  64556. float Colour::getHue() const throw()
  64557. {
  64558. float h, s, b;
  64559. getHSB (h, s, b);
  64560. return h;
  64561. }
  64562. const Colour Colour::withHue (const float hue) const throw()
  64563. {
  64564. float h, s, b;
  64565. getHSB (h, s, b);
  64566. return Colour (hue, s, b, getAlpha());
  64567. }
  64568. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64569. {
  64570. float h, s, b;
  64571. getHSB (h, s, b);
  64572. h += amountToRotate;
  64573. h -= std::floor (h);
  64574. return Colour (h, s, b, getAlpha());
  64575. }
  64576. float Colour::getSaturation() const throw()
  64577. {
  64578. float h, s, b;
  64579. getHSB (h, s, b);
  64580. return s;
  64581. }
  64582. const Colour Colour::withSaturation (const float saturation) const throw()
  64583. {
  64584. float h, s, b;
  64585. getHSB (h, s, b);
  64586. return Colour (h, saturation, b, getAlpha());
  64587. }
  64588. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64589. {
  64590. float h, s, b;
  64591. getHSB (h, s, b);
  64592. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64593. }
  64594. float Colour::getBrightness() const throw()
  64595. {
  64596. float h, s, b;
  64597. getHSB (h, s, b);
  64598. return b;
  64599. }
  64600. const Colour Colour::withBrightness (const float brightness) const throw()
  64601. {
  64602. float h, s, b;
  64603. getHSB (h, s, b);
  64604. return Colour (h, s, brightness, getAlpha());
  64605. }
  64606. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64607. {
  64608. float h, s, b;
  64609. getHSB (h, s, b);
  64610. b *= amount;
  64611. if (b > 1.0f)
  64612. b = 1.0f;
  64613. return Colour (h, s, b, getAlpha());
  64614. }
  64615. const Colour Colour::brighter (float amount) const throw()
  64616. {
  64617. amount = 1.0f / (1.0f + amount);
  64618. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64619. (uint8) (255 - (amount * (255 - getGreen()))),
  64620. (uint8) (255 - (amount * (255 - getBlue()))),
  64621. getAlpha());
  64622. }
  64623. const Colour Colour::darker (float amount) const throw()
  64624. {
  64625. amount = 1.0f / (1.0f + amount);
  64626. return Colour ((uint8) (amount * getRed()),
  64627. (uint8) (amount * getGreen()),
  64628. (uint8) (amount * getBlue()),
  64629. getAlpha());
  64630. }
  64631. const Colour Colour::greyLevel (const float brightness) throw()
  64632. {
  64633. const uint8 level
  64634. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  64635. return Colour (level, level, level);
  64636. }
  64637. const Colour Colour::contrasting (const float amount) const throw()
  64638. {
  64639. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  64640. ? Colours::black
  64641. : Colours::white).withAlpha (amount));
  64642. }
  64643. const Colour Colour::contrasting (const Colour& colour1,
  64644. const Colour& colour2) throw()
  64645. {
  64646. const float b1 = colour1.getBrightness();
  64647. const float b2 = colour2.getBrightness();
  64648. float best = 0.0f;
  64649. float bestDist = 0.0f;
  64650. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  64651. {
  64652. const float d1 = std::abs (i - b1);
  64653. const float d2 = std::abs (i - b2);
  64654. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  64655. if (dist > bestDist)
  64656. {
  64657. best = i;
  64658. bestDist = dist;
  64659. }
  64660. }
  64661. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  64662. .withBrightness (best);
  64663. }
  64664. const String Colour::toString() const
  64665. {
  64666. return String::toHexString ((int) argb.getARGB());
  64667. }
  64668. const Colour Colour::fromString (const String& encodedColourString)
  64669. {
  64670. return Colour ((uint32) encodedColourString.getHexValue32());
  64671. }
  64672. const String Colour::toDisplayString (const bool includeAlphaValue) const
  64673. {
  64674. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  64675. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  64676. .toUpperCase();
  64677. }
  64678. END_JUCE_NAMESPACE
  64679. /*** End of inlined file: juce_Colour.cpp ***/
  64680. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  64681. BEGIN_JUCE_NAMESPACE
  64682. ColourGradient::ColourGradient() throw()
  64683. {
  64684. #if JUCE_DEBUG
  64685. point1.setX (987654.0f);
  64686. #endif
  64687. }
  64688. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  64689. const Colour& colour2, const float x2_, const float y2_,
  64690. const bool isRadial_)
  64691. : point1 (x1_, y1_),
  64692. point2 (x2_, y2_),
  64693. isRadial (isRadial_)
  64694. {
  64695. colours.add (ColourPoint (0.0, colour1));
  64696. colours.add (ColourPoint (1.0, colour2));
  64697. }
  64698. ColourGradient::~ColourGradient()
  64699. {
  64700. }
  64701. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  64702. {
  64703. return point1 == other.point1 && point2 == other.point2
  64704. && isRadial == other.isRadial
  64705. && colours == other.colours;
  64706. }
  64707. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  64708. {
  64709. return ! operator== (other);
  64710. }
  64711. void ColourGradient::clearColours()
  64712. {
  64713. colours.clear();
  64714. }
  64715. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  64716. {
  64717. // must be within the two end-points
  64718. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  64719. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  64720. int i;
  64721. for (i = 0; i < colours.size(); ++i)
  64722. if (colours.getReference(i).position > pos)
  64723. break;
  64724. colours.insert (i, ColourPoint (pos, colour));
  64725. return i;
  64726. }
  64727. void ColourGradient::removeColour (int index)
  64728. {
  64729. jassert (index > 0 && index < colours.size() - 1);
  64730. colours.remove (index);
  64731. }
  64732. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  64733. {
  64734. for (int i = 0; i < colours.size(); ++i)
  64735. {
  64736. Colour& c = colours.getReference(i).colour;
  64737. c = c.withMultipliedAlpha (multiplier);
  64738. }
  64739. }
  64740. int ColourGradient::getNumColours() const throw()
  64741. {
  64742. return colours.size();
  64743. }
  64744. double ColourGradient::getColourPosition (const int index) const throw()
  64745. {
  64746. if (((unsigned int) index) < (unsigned int) colours.size())
  64747. return colours.getReference (index).position;
  64748. return 0;
  64749. }
  64750. const Colour ColourGradient::getColour (const int index) const throw()
  64751. {
  64752. if (((unsigned int) index) < (unsigned int) colours.size())
  64753. return colours.getReference (index).colour;
  64754. return Colour();
  64755. }
  64756. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  64757. {
  64758. if (((unsigned int) index) < (unsigned int) colours.size())
  64759. colours.getReference (index).colour = newColour;
  64760. }
  64761. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  64762. {
  64763. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64764. if (position <= 0 || colours.size() <= 1)
  64765. return colours.getReference(0).colour;
  64766. int i = colours.size() - 1;
  64767. while (position < colours.getReference(i).position)
  64768. --i;
  64769. const ColourPoint& p1 = colours.getReference (i);
  64770. if (i >= colours.size() - 1)
  64771. return p1.colour;
  64772. const ColourPoint& p2 = colours.getReference (i + 1);
  64773. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  64774. }
  64775. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  64776. {
  64777. #if JUCE_DEBUG
  64778. // trying to use the object without setting its co-ordinates? Have a careful read of
  64779. // the comments for the constructors.
  64780. jassert (point1.getX() != 987654.0f);
  64781. #endif
  64782. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  64783. 3 * (int) point1.transformedBy (transform)
  64784. .getDistanceFrom (point2.transformedBy (transform)));
  64785. lookupTable.malloc (numEntries);
  64786. if (colours.size() >= 2)
  64787. {
  64788. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64789. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  64790. int index = 0;
  64791. for (int j = 1; j < colours.size(); ++j)
  64792. {
  64793. const ColourPoint& p = colours.getReference (j);
  64794. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  64795. const PixelARGB pix2 (p.colour.getPixelARGB());
  64796. for (int i = 0; i < numToDo; ++i)
  64797. {
  64798. jassert (index >= 0 && index < numEntries);
  64799. lookupTable[index] = pix1;
  64800. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  64801. ++index;
  64802. }
  64803. pix1 = pix2;
  64804. }
  64805. while (index < numEntries)
  64806. lookupTable [index++] = pix1;
  64807. }
  64808. else
  64809. {
  64810. jassertfalse; // no colours specified!
  64811. }
  64812. return numEntries;
  64813. }
  64814. bool ColourGradient::isOpaque() const throw()
  64815. {
  64816. for (int i = 0; i < colours.size(); ++i)
  64817. if (! colours.getReference(i).colour.isOpaque())
  64818. return false;
  64819. return true;
  64820. }
  64821. bool ColourGradient::isInvisible() const throw()
  64822. {
  64823. for (int i = 0; i < colours.size(); ++i)
  64824. if (! colours.getReference(i).colour.isTransparent())
  64825. return false;
  64826. return true;
  64827. }
  64828. END_JUCE_NAMESPACE
  64829. /*** End of inlined file: juce_ColourGradient.cpp ***/
  64830. /*** Start of inlined file: juce_Colours.cpp ***/
  64831. BEGIN_JUCE_NAMESPACE
  64832. const Colour Colours::transparentBlack (0);
  64833. const Colour Colours::transparentWhite (0x00ffffff);
  64834. const Colour Colours::aliceblue (0xfff0f8ff);
  64835. const Colour Colours::antiquewhite (0xfffaebd7);
  64836. const Colour Colours::aqua (0xff00ffff);
  64837. const Colour Colours::aquamarine (0xff7fffd4);
  64838. const Colour Colours::azure (0xfff0ffff);
  64839. const Colour Colours::beige (0xfff5f5dc);
  64840. const Colour Colours::bisque (0xffffe4c4);
  64841. const Colour Colours::black (0xff000000);
  64842. const Colour Colours::blanchedalmond (0xffffebcd);
  64843. const Colour Colours::blue (0xff0000ff);
  64844. const Colour Colours::blueviolet (0xff8a2be2);
  64845. const Colour Colours::brown (0xffa52a2a);
  64846. const Colour Colours::burlywood (0xffdeb887);
  64847. const Colour Colours::cadetblue (0xff5f9ea0);
  64848. const Colour Colours::chartreuse (0xff7fff00);
  64849. const Colour Colours::chocolate (0xffd2691e);
  64850. const Colour Colours::coral (0xffff7f50);
  64851. const Colour Colours::cornflowerblue (0xff6495ed);
  64852. const Colour Colours::cornsilk (0xfffff8dc);
  64853. const Colour Colours::crimson (0xffdc143c);
  64854. const Colour Colours::cyan (0xff00ffff);
  64855. const Colour Colours::darkblue (0xff00008b);
  64856. const Colour Colours::darkcyan (0xff008b8b);
  64857. const Colour Colours::darkgoldenrod (0xffb8860b);
  64858. const Colour Colours::darkgrey (0xff555555);
  64859. const Colour Colours::darkgreen (0xff006400);
  64860. const Colour Colours::darkkhaki (0xffbdb76b);
  64861. const Colour Colours::darkmagenta (0xff8b008b);
  64862. const Colour Colours::darkolivegreen (0xff556b2f);
  64863. const Colour Colours::darkorange (0xffff8c00);
  64864. const Colour Colours::darkorchid (0xff9932cc);
  64865. const Colour Colours::darkred (0xff8b0000);
  64866. const Colour Colours::darksalmon (0xffe9967a);
  64867. const Colour Colours::darkseagreen (0xff8fbc8f);
  64868. const Colour Colours::darkslateblue (0xff483d8b);
  64869. const Colour Colours::darkslategrey (0xff2f4f4f);
  64870. const Colour Colours::darkturquoise (0xff00ced1);
  64871. const Colour Colours::darkviolet (0xff9400d3);
  64872. const Colour Colours::deeppink (0xffff1493);
  64873. const Colour Colours::deepskyblue (0xff00bfff);
  64874. const Colour Colours::dimgrey (0xff696969);
  64875. const Colour Colours::dodgerblue (0xff1e90ff);
  64876. const Colour Colours::firebrick (0xffb22222);
  64877. const Colour Colours::floralwhite (0xfffffaf0);
  64878. const Colour Colours::forestgreen (0xff228b22);
  64879. const Colour Colours::fuchsia (0xffff00ff);
  64880. const Colour Colours::gainsboro (0xffdcdcdc);
  64881. const Colour Colours::gold (0xffffd700);
  64882. const Colour Colours::goldenrod (0xffdaa520);
  64883. const Colour Colours::grey (0xff808080);
  64884. const Colour Colours::green (0xff008000);
  64885. const Colour Colours::greenyellow (0xffadff2f);
  64886. const Colour Colours::honeydew (0xfff0fff0);
  64887. const Colour Colours::hotpink (0xffff69b4);
  64888. const Colour Colours::indianred (0xffcd5c5c);
  64889. const Colour Colours::indigo (0xff4b0082);
  64890. const Colour Colours::ivory (0xfffffff0);
  64891. const Colour Colours::khaki (0xfff0e68c);
  64892. const Colour Colours::lavender (0xffe6e6fa);
  64893. const Colour Colours::lavenderblush (0xfffff0f5);
  64894. const Colour Colours::lemonchiffon (0xfffffacd);
  64895. const Colour Colours::lightblue (0xffadd8e6);
  64896. const Colour Colours::lightcoral (0xfff08080);
  64897. const Colour Colours::lightcyan (0xffe0ffff);
  64898. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  64899. const Colour Colours::lightgreen (0xff90ee90);
  64900. const Colour Colours::lightgrey (0xffd3d3d3);
  64901. const Colour Colours::lightpink (0xffffb6c1);
  64902. const Colour Colours::lightsalmon (0xffffa07a);
  64903. const Colour Colours::lightseagreen (0xff20b2aa);
  64904. const Colour Colours::lightskyblue (0xff87cefa);
  64905. const Colour Colours::lightslategrey (0xff778899);
  64906. const Colour Colours::lightsteelblue (0xffb0c4de);
  64907. const Colour Colours::lightyellow (0xffffffe0);
  64908. const Colour Colours::lime (0xff00ff00);
  64909. const Colour Colours::limegreen (0xff32cd32);
  64910. const Colour Colours::linen (0xfffaf0e6);
  64911. const Colour Colours::magenta (0xffff00ff);
  64912. const Colour Colours::maroon (0xff800000);
  64913. const Colour Colours::mediumaquamarine (0xff66cdaa);
  64914. const Colour Colours::mediumblue (0xff0000cd);
  64915. const Colour Colours::mediumorchid (0xffba55d3);
  64916. const Colour Colours::mediumpurple (0xff9370db);
  64917. const Colour Colours::mediumseagreen (0xff3cb371);
  64918. const Colour Colours::mediumslateblue (0xff7b68ee);
  64919. const Colour Colours::mediumspringgreen (0xff00fa9a);
  64920. const Colour Colours::mediumturquoise (0xff48d1cc);
  64921. const Colour Colours::mediumvioletred (0xffc71585);
  64922. const Colour Colours::midnightblue (0xff191970);
  64923. const Colour Colours::mintcream (0xfff5fffa);
  64924. const Colour Colours::mistyrose (0xffffe4e1);
  64925. const Colour Colours::navajowhite (0xffffdead);
  64926. const Colour Colours::navy (0xff000080);
  64927. const Colour Colours::oldlace (0xfffdf5e6);
  64928. const Colour Colours::olive (0xff808000);
  64929. const Colour Colours::olivedrab (0xff6b8e23);
  64930. const Colour Colours::orange (0xffffa500);
  64931. const Colour Colours::orangered (0xffff4500);
  64932. const Colour Colours::orchid (0xffda70d6);
  64933. const Colour Colours::palegoldenrod (0xffeee8aa);
  64934. const Colour Colours::palegreen (0xff98fb98);
  64935. const Colour Colours::paleturquoise (0xffafeeee);
  64936. const Colour Colours::palevioletred (0xffdb7093);
  64937. const Colour Colours::papayawhip (0xffffefd5);
  64938. const Colour Colours::peachpuff (0xffffdab9);
  64939. const Colour Colours::peru (0xffcd853f);
  64940. const Colour Colours::pink (0xffffc0cb);
  64941. const Colour Colours::plum (0xffdda0dd);
  64942. const Colour Colours::powderblue (0xffb0e0e6);
  64943. const Colour Colours::purple (0xff800080);
  64944. const Colour Colours::red (0xffff0000);
  64945. const Colour Colours::rosybrown (0xffbc8f8f);
  64946. const Colour Colours::royalblue (0xff4169e1);
  64947. const Colour Colours::saddlebrown (0xff8b4513);
  64948. const Colour Colours::salmon (0xfffa8072);
  64949. const Colour Colours::sandybrown (0xfff4a460);
  64950. const Colour Colours::seagreen (0xff2e8b57);
  64951. const Colour Colours::seashell (0xfffff5ee);
  64952. const Colour Colours::sienna (0xffa0522d);
  64953. const Colour Colours::silver (0xffc0c0c0);
  64954. const Colour Colours::skyblue (0xff87ceeb);
  64955. const Colour Colours::slateblue (0xff6a5acd);
  64956. const Colour Colours::slategrey (0xff708090);
  64957. const Colour Colours::snow (0xfffffafa);
  64958. const Colour Colours::springgreen (0xff00ff7f);
  64959. const Colour Colours::steelblue (0xff4682b4);
  64960. const Colour Colours::tan (0xffd2b48c);
  64961. const Colour Colours::teal (0xff008080);
  64962. const Colour Colours::thistle (0xffd8bfd8);
  64963. const Colour Colours::tomato (0xffff6347);
  64964. const Colour Colours::turquoise (0xff40e0d0);
  64965. const Colour Colours::violet (0xffee82ee);
  64966. const Colour Colours::wheat (0xfff5deb3);
  64967. const Colour Colours::white (0xffffffff);
  64968. const Colour Colours::whitesmoke (0xfff5f5f5);
  64969. const Colour Colours::yellow (0xffffff00);
  64970. const Colour Colours::yellowgreen (0xff9acd32);
  64971. const Colour Colours::findColourForName (const String& colourName,
  64972. const Colour& defaultColour)
  64973. {
  64974. static const int presets[] =
  64975. {
  64976. // (first value is the string's hashcode, second is ARGB)
  64977. 0x05978fff, 0xff000000, /* black */
  64978. 0x06bdcc29, 0xffffffff, /* white */
  64979. 0x002e305a, 0xff0000ff, /* blue */
  64980. 0x00308adf, 0xff808080, /* grey */
  64981. 0x05e0cf03, 0xff008000, /* green */
  64982. 0x0001b891, 0xffff0000, /* red */
  64983. 0xd43c6474, 0xffffff00, /* yellow */
  64984. 0x620886da, 0xfff0f8ff, /* aliceblue */
  64985. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  64986. 0x002dcebc, 0xff00ffff, /* aqua */
  64987. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  64988. 0x0590228f, 0xfff0ffff, /* azure */
  64989. 0x05947fe4, 0xfff5f5dc, /* beige */
  64990. 0xad388e35, 0xffffe4c4, /* bisque */
  64991. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  64992. 0x39129959, 0xff8a2be2, /* blueviolet */
  64993. 0x059a8136, 0xffa52a2a, /* brown */
  64994. 0x89cea8f9, 0xffdeb887, /* burlywood */
  64995. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  64996. 0x6b748956, 0xff7fff00, /* chartreuse */
  64997. 0x2903623c, 0xffd2691e, /* chocolate */
  64998. 0x05a74431, 0xffff7f50, /* coral */
  64999. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65000. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65001. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65002. 0x002ed323, 0xff00ffff, /* cyan */
  65003. 0x67cc74d0, 0xff00008b, /* darkblue */
  65004. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65005. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65006. 0x67cecf55, 0xff555555, /* darkgrey */
  65007. 0x920b194d, 0xff006400, /* darkgreen */
  65008. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65009. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65010. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65011. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65012. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65013. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65014. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65015. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65016. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65017. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65018. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65019. 0xc8769375, 0xff9400d3, /* darkviolet */
  65020. 0x25832862, 0xffff1493, /* deeppink */
  65021. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65022. 0x634c8b67, 0xff696969, /* dimgrey */
  65023. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65024. 0xef19e3cb, 0xffb22222, /* firebrick */
  65025. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65026. 0xd086fd06, 0xff228b22, /* forestgreen */
  65027. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65028. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65029. 0x00308060, 0xffffd700, /* gold */
  65030. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65031. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65032. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65033. 0x41892743, 0xffff69b4, /* hotpink */
  65034. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65035. 0xb969fed2, 0xff4b0082, /* indigo */
  65036. 0x05fef6a9, 0xfffffff0, /* ivory */
  65037. 0x06149302, 0xfff0e68c, /* khaki */
  65038. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65039. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65040. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65041. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65042. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65043. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65044. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65045. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65046. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65047. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65048. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65049. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65050. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65051. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65052. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65053. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65054. 0x0032afd5, 0xff00ff00, /* lime */
  65055. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65056. 0x06234efa, 0xfffaf0e6, /* linen */
  65057. 0x316858a9, 0xffff00ff, /* magenta */
  65058. 0xbf8ca470, 0xff800000, /* maroon */
  65059. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65060. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65061. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65062. 0x07556b71, 0xff9370db, /* mediumpurple */
  65063. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65064. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65065. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65066. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65067. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65068. 0x168eb32a, 0xff191970, /* midnightblue */
  65069. 0x4306b960, 0xfff5fffa, /* mintcream */
  65070. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65071. 0xe97218a6, 0xffffdead, /* navajowhite */
  65072. 0x00337bb6, 0xff000080, /* navy */
  65073. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65074. 0x064ee1db, 0xff808000, /* olive */
  65075. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65076. 0xc3de262e, 0xffffa500, /* orange */
  65077. 0x58bebba3, 0xffff4500, /* orangered */
  65078. 0xc3def8a3, 0xffda70d6, /* orchid */
  65079. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65080. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65081. 0x74022737, 0xffafeeee, /* paleturquoise */
  65082. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65083. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65084. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65085. 0x003472f8, 0xffcd853f, /* peru */
  65086. 0x00348176, 0xffffc0cb, /* pink */
  65087. 0x00348d94, 0xffdda0dd, /* plum */
  65088. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65089. 0xc5c507bc, 0xff800080, /* purple */
  65090. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65091. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65092. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65093. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65094. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65095. 0x34636c14, 0xff2e8b57, /* seagreen */
  65096. 0x3507fb41, 0xfffff5ee, /* seashell */
  65097. 0xca348772, 0xffa0522d, /* sienna */
  65098. 0xca37d30d, 0xffc0c0c0, /* silver */
  65099. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65100. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65101. 0x44ab37f8, 0xff708090, /* slategrey */
  65102. 0x0035f183, 0xfffffafa, /* snow */
  65103. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65104. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65105. 0x0001bfa1, 0xffd2b48c, /* tan */
  65106. 0x0036425c, 0xff008080, /* teal */
  65107. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65108. 0xcc41600a, 0xffff6347, /* tomato */
  65109. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65110. 0xcf57947f, 0xffee82ee, /* violet */
  65111. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65112. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65113. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65114. };
  65115. const int hash = colourName.trim().toLowerCase().hashCode();
  65116. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65117. if (presets [i] == hash)
  65118. return Colour (presets [i + 1]);
  65119. return defaultColour;
  65120. }
  65121. END_JUCE_NAMESPACE
  65122. /*** End of inlined file: juce_Colours.cpp ***/
  65123. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65124. BEGIN_JUCE_NAMESPACE
  65125. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65126. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65127. const Path& path, const AffineTransform& transform)
  65128. : bounds (bounds_),
  65129. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65130. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65131. needToCheckEmptinesss (true)
  65132. {
  65133. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65134. int* t = table;
  65135. for (int i = bounds.getHeight(); --i >= 0;)
  65136. {
  65137. *t = 0;
  65138. t += lineStrideElements;
  65139. }
  65140. const int topLimit = bounds.getY() << 8;
  65141. const int heightLimit = bounds.getHeight() << 8;
  65142. const int leftLimit = bounds.getX() << 8;
  65143. const int rightLimit = bounds.getRight() << 8;
  65144. PathFlatteningIterator iter (path, transform);
  65145. while (iter.next())
  65146. {
  65147. int y1 = roundToInt (iter.y1 * 256.0f);
  65148. int y2 = roundToInt (iter.y2 * 256.0f);
  65149. if (y1 != y2)
  65150. {
  65151. y1 -= topLimit;
  65152. y2 -= topLimit;
  65153. const int startY = y1;
  65154. int direction = -1;
  65155. if (y1 > y2)
  65156. {
  65157. swapVariables (y1, y2);
  65158. direction = 1;
  65159. }
  65160. if (y1 < 0)
  65161. y1 = 0;
  65162. if (y2 > heightLimit)
  65163. y2 = heightLimit;
  65164. if (y1 < y2)
  65165. {
  65166. const double startX = 256.0f * iter.x1;
  65167. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65168. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65169. do
  65170. {
  65171. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65172. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65173. if (x < leftLimit)
  65174. x = leftLimit;
  65175. else if (x >= rightLimit)
  65176. x = rightLimit - 1;
  65177. addEdgePoint (x, y1 >> 8, direction * step);
  65178. y1 += step;
  65179. }
  65180. while (y1 < y2);
  65181. }
  65182. }
  65183. }
  65184. sanitiseLevels (path.isUsingNonZeroWinding());
  65185. }
  65186. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65187. : bounds (rectangleToAdd),
  65188. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65189. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65190. needToCheckEmptinesss (true)
  65191. {
  65192. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65193. table[0] = 0;
  65194. const int x1 = rectangleToAdd.getX() << 8;
  65195. const int x2 = rectangleToAdd.getRight() << 8;
  65196. int* t = table;
  65197. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65198. {
  65199. t[0] = 2;
  65200. t[1] = x1;
  65201. t[2] = 255;
  65202. t[3] = x2;
  65203. t[4] = 0;
  65204. t += lineStrideElements;
  65205. }
  65206. }
  65207. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65208. : bounds (rectanglesToAdd.getBounds()),
  65209. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65210. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65211. needToCheckEmptinesss (true)
  65212. {
  65213. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65214. int* t = table;
  65215. for (int i = bounds.getHeight(); --i >= 0;)
  65216. {
  65217. *t = 0;
  65218. t += lineStrideElements;
  65219. }
  65220. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65221. {
  65222. const Rectangle<int>* const r = iter.getRectangle();
  65223. const int x1 = r->getX() << 8;
  65224. const int x2 = r->getRight() << 8;
  65225. int y = r->getY() - bounds.getY();
  65226. for (int j = r->getHeight(); --j >= 0;)
  65227. {
  65228. addEdgePoint (x1, y, 255);
  65229. addEdgePoint (x2, y, -255);
  65230. ++y;
  65231. }
  65232. }
  65233. sanitiseLevels (true);
  65234. }
  65235. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65236. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65237. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65238. 2 + (int) rectangleToAdd.getWidth(),
  65239. 2 + (int) rectangleToAdd.getHeight())),
  65240. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65241. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65242. needToCheckEmptinesss (true)
  65243. {
  65244. jassert (! rectangleToAdd.isEmpty());
  65245. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65246. table[0] = 0;
  65247. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65248. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65249. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65250. jassert (y1 < 256);
  65251. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65252. if (x2 <= x1 || y2 <= y1)
  65253. {
  65254. bounds.setHeight (0);
  65255. return;
  65256. }
  65257. int lineY = 0;
  65258. int* t = table;
  65259. if ((y1 >> 8) == (y2 >> 8))
  65260. {
  65261. t[0] = 2;
  65262. t[1] = x1;
  65263. t[2] = y2 - y1;
  65264. t[3] = x2;
  65265. t[4] = 0;
  65266. ++lineY;
  65267. t += lineStrideElements;
  65268. }
  65269. else
  65270. {
  65271. t[0] = 2;
  65272. t[1] = x1;
  65273. t[2] = 255 - (y1 & 255);
  65274. t[3] = x2;
  65275. t[4] = 0;
  65276. ++lineY;
  65277. t += lineStrideElements;
  65278. while (lineY < (y2 >> 8))
  65279. {
  65280. t[0] = 2;
  65281. t[1] = x1;
  65282. t[2] = 255;
  65283. t[3] = x2;
  65284. t[4] = 0;
  65285. ++lineY;
  65286. t += lineStrideElements;
  65287. }
  65288. jassert (lineY < bounds.getHeight());
  65289. t[0] = 2;
  65290. t[1] = x1;
  65291. t[2] = y2 & 255;
  65292. t[3] = x2;
  65293. t[4] = 0;
  65294. ++lineY;
  65295. t += lineStrideElements;
  65296. }
  65297. while (lineY < bounds.getHeight())
  65298. {
  65299. t[0] = 0;
  65300. t += lineStrideElements;
  65301. ++lineY;
  65302. }
  65303. }
  65304. EdgeTable::EdgeTable (const EdgeTable& other)
  65305. {
  65306. operator= (other);
  65307. }
  65308. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65309. {
  65310. bounds = other.bounds;
  65311. maxEdgesPerLine = other.maxEdgesPerLine;
  65312. lineStrideElements = other.lineStrideElements;
  65313. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65314. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65315. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65316. return *this;
  65317. }
  65318. EdgeTable::~EdgeTable()
  65319. {
  65320. }
  65321. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65322. {
  65323. while (--numLines >= 0)
  65324. {
  65325. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65326. src += srcLineStride;
  65327. dest += destLineStride;
  65328. }
  65329. }
  65330. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65331. {
  65332. // Convert the table from relative windings to absolute levels..
  65333. int* lineStart = table;
  65334. for (int i = bounds.getHeight(); --i >= 0;)
  65335. {
  65336. int* line = lineStart;
  65337. lineStart += lineStrideElements;
  65338. int num = *line;
  65339. if (num == 0)
  65340. continue;
  65341. int level = 0;
  65342. if (useNonZeroWinding)
  65343. {
  65344. while (--num > 0)
  65345. {
  65346. line += 2;
  65347. level += *line;
  65348. int corrected = abs (level);
  65349. if (corrected >> 8)
  65350. corrected = 255;
  65351. *line = corrected;
  65352. }
  65353. }
  65354. else
  65355. {
  65356. while (--num > 0)
  65357. {
  65358. line += 2;
  65359. level += *line;
  65360. int corrected = abs (level);
  65361. if (corrected >> 8)
  65362. {
  65363. corrected &= 511;
  65364. if (corrected >> 8)
  65365. corrected = 511 - corrected;
  65366. }
  65367. *line = corrected;
  65368. }
  65369. }
  65370. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65371. }
  65372. }
  65373. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65374. {
  65375. if (newNumEdgesPerLine != maxEdgesPerLine)
  65376. {
  65377. maxEdgesPerLine = newNumEdgesPerLine;
  65378. jassert (bounds.getHeight() > 0);
  65379. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65380. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65381. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65382. table.swapWith (newTable);
  65383. lineStrideElements = newLineStrideElements;
  65384. }
  65385. }
  65386. void EdgeTable::optimiseTable() throw()
  65387. {
  65388. int maxLineElements = 0;
  65389. for (int i = bounds.getHeight(); --i >= 0;)
  65390. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65391. remapTableForNumEdges (maxLineElements);
  65392. }
  65393. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  65394. {
  65395. jassert (y >= 0 && y < bounds.getHeight());
  65396. int* line = table + lineStrideElements * y;
  65397. const int numPoints = line[0];
  65398. int n = numPoints << 1;
  65399. if (n > 0)
  65400. {
  65401. while (n > 0)
  65402. {
  65403. const int cx = line [n - 1];
  65404. if (cx <= x)
  65405. {
  65406. if (cx == x)
  65407. {
  65408. line [n] += winding;
  65409. return;
  65410. }
  65411. break;
  65412. }
  65413. n -= 2;
  65414. }
  65415. if (numPoints >= maxEdgesPerLine)
  65416. {
  65417. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65418. jassert (numPoints < maxEdgesPerLine);
  65419. line = table + lineStrideElements * y;
  65420. }
  65421. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65422. }
  65423. line [n + 1] = x;
  65424. line [n + 2] = winding;
  65425. line[0]++;
  65426. }
  65427. void EdgeTable::translate (float dx, const int dy) throw()
  65428. {
  65429. bounds.translate ((int) std::floor (dx), dy);
  65430. int* lineStart = table;
  65431. const int intDx = (int) (dx * 256.0f);
  65432. for (int i = bounds.getHeight(); --i >= 0;)
  65433. {
  65434. int* line = lineStart;
  65435. lineStart += lineStrideElements;
  65436. int num = *line++;
  65437. while (--num >= 0)
  65438. {
  65439. *line += intDx;
  65440. line += 2;
  65441. }
  65442. }
  65443. }
  65444. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  65445. {
  65446. jassert (y >= 0 && y < bounds.getHeight());
  65447. int* dest = table + lineStrideElements * y;
  65448. if (dest[0] == 0)
  65449. return;
  65450. int otherNumPoints = *otherLine;
  65451. if (otherNumPoints == 0)
  65452. {
  65453. *dest = 0;
  65454. return;
  65455. }
  65456. const int right = bounds.getRight() << 8;
  65457. // optimise for the common case where our line lies entirely within a
  65458. // single pair of points, as happens when clipping to a simple rect.
  65459. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65460. {
  65461. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65462. return;
  65463. }
  65464. ++otherLine;
  65465. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65466. int* temp = (int*) alloca (lineSizeBytes);
  65467. memcpy (temp, dest, lineSizeBytes);
  65468. const int* src1 = temp;
  65469. int srcNum1 = *src1++;
  65470. int x1 = *src1++;
  65471. const int* src2 = otherLine;
  65472. int srcNum2 = otherNumPoints;
  65473. int x2 = *src2++;
  65474. int destIndex = 0, destTotal = 0;
  65475. int level1 = 0, level2 = 0;
  65476. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65477. while (srcNum1 > 0 && srcNum2 > 0)
  65478. {
  65479. int nextX;
  65480. if (x1 < x2)
  65481. {
  65482. nextX = x1;
  65483. level1 = *src1++;
  65484. x1 = *src1++;
  65485. --srcNum1;
  65486. }
  65487. else if (x1 == x2)
  65488. {
  65489. nextX = x1;
  65490. level1 = *src1++;
  65491. level2 = *src2++;
  65492. x1 = *src1++;
  65493. x2 = *src2++;
  65494. --srcNum1;
  65495. --srcNum2;
  65496. }
  65497. else
  65498. {
  65499. nextX = x2;
  65500. level2 = *src2++;
  65501. x2 = *src2++;
  65502. --srcNum2;
  65503. }
  65504. if (nextX > lastX)
  65505. {
  65506. if (nextX >= right)
  65507. break;
  65508. lastX = nextX;
  65509. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65510. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  65511. if (nextLevel != lastLevel)
  65512. {
  65513. if (destTotal >= maxEdgesPerLine)
  65514. {
  65515. dest[0] = destTotal;
  65516. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65517. dest = table + lineStrideElements * y;
  65518. }
  65519. ++destTotal;
  65520. lastLevel = nextLevel;
  65521. dest[++destIndex] = nextX;
  65522. dest[++destIndex] = nextLevel;
  65523. }
  65524. }
  65525. }
  65526. if (lastLevel > 0)
  65527. {
  65528. if (destTotal >= maxEdgesPerLine)
  65529. {
  65530. dest[0] = destTotal;
  65531. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65532. dest = table + lineStrideElements * y;
  65533. }
  65534. ++destTotal;
  65535. dest[++destIndex] = right;
  65536. dest[++destIndex] = 0;
  65537. }
  65538. dest[0] = destTotal;
  65539. #if JUCE_DEBUG
  65540. int last = std::numeric_limits<int>::min();
  65541. for (int i = 0; i < dest[0]; ++i)
  65542. {
  65543. jassert (dest[i * 2 + 1] > last);
  65544. last = dest[i * 2 + 1];
  65545. }
  65546. jassert (dest [dest[0] * 2] == 0);
  65547. #endif
  65548. }
  65549. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65550. {
  65551. int* lastItem = dest + (dest[0] * 2 - 1);
  65552. if (x2 < lastItem[0])
  65553. {
  65554. if (x2 <= dest[1])
  65555. {
  65556. dest[0] = 0;
  65557. return;
  65558. }
  65559. while (x2 < lastItem[-2])
  65560. {
  65561. --(dest[0]);
  65562. lastItem -= 2;
  65563. }
  65564. lastItem[0] = x2;
  65565. lastItem[1] = 0;
  65566. }
  65567. if (x1 > dest[1])
  65568. {
  65569. while (lastItem[0] > x1)
  65570. lastItem -= 2;
  65571. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65572. if (itemsRemoved > 0)
  65573. {
  65574. dest[0] -= itemsRemoved;
  65575. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65576. }
  65577. dest[1] = x1;
  65578. }
  65579. }
  65580. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  65581. {
  65582. const Rectangle<int> clipped (r.getIntersection (bounds));
  65583. if (clipped.isEmpty())
  65584. {
  65585. needToCheckEmptinesss = false;
  65586. bounds.setHeight (0);
  65587. }
  65588. else
  65589. {
  65590. const int top = clipped.getY() - bounds.getY();
  65591. const int bottom = clipped.getBottom() - bounds.getY();
  65592. if (bottom < bounds.getHeight())
  65593. bounds.setHeight (bottom);
  65594. if (clipped.getRight() < bounds.getRight())
  65595. bounds.setRight (clipped.getRight());
  65596. for (int i = top; --i >= 0;)
  65597. table [lineStrideElements * i] = 0;
  65598. if (clipped.getX() > bounds.getX())
  65599. {
  65600. const int x1 = clipped.getX() << 8;
  65601. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65602. int* line = table + lineStrideElements * top;
  65603. for (int i = bottom - top; --i >= 0;)
  65604. {
  65605. if (line[0] != 0)
  65606. clipEdgeTableLineToRange (line, x1, x2);
  65607. line += lineStrideElements;
  65608. }
  65609. }
  65610. needToCheckEmptinesss = true;
  65611. }
  65612. }
  65613. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  65614. {
  65615. const Rectangle<int> clipped (r.getIntersection (bounds));
  65616. if (! clipped.isEmpty())
  65617. {
  65618. const int top = clipped.getY() - bounds.getY();
  65619. const int bottom = clipped.getBottom() - bounds.getY();
  65620. //XXX optimise here by shortening the table if it fills top or bottom
  65621. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65622. clipped.getX() << 8, 0,
  65623. clipped.getRight() << 8, 255,
  65624. std::numeric_limits<int>::max(), 0 };
  65625. for (int i = top; i < bottom; ++i)
  65626. intersectWithEdgeTableLine (i, rectLine);
  65627. needToCheckEmptinesss = true;
  65628. }
  65629. }
  65630. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  65631. {
  65632. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  65633. if (clipped.isEmpty())
  65634. {
  65635. needToCheckEmptinesss = false;
  65636. bounds.setHeight (0);
  65637. }
  65638. else
  65639. {
  65640. const int top = clipped.getY() - bounds.getY();
  65641. const int bottom = clipped.getBottom() - bounds.getY();
  65642. if (bottom < bounds.getHeight())
  65643. bounds.setHeight (bottom);
  65644. if (clipped.getRight() < bounds.getRight())
  65645. bounds.setRight (clipped.getRight());
  65646. int i = 0;
  65647. for (i = top; --i >= 0;)
  65648. table [lineStrideElements * i] = 0;
  65649. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  65650. for (i = top; i < bottom; ++i)
  65651. {
  65652. intersectWithEdgeTableLine (i, otherLine);
  65653. otherLine += other.lineStrideElements;
  65654. }
  65655. needToCheckEmptinesss = true;
  65656. }
  65657. }
  65658. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  65659. {
  65660. y -= bounds.getY();
  65661. if (y < 0 || y >= bounds.getHeight())
  65662. return;
  65663. needToCheckEmptinesss = true;
  65664. if (numPixels <= 0)
  65665. {
  65666. table [lineStrideElements * y] = 0;
  65667. return;
  65668. }
  65669. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  65670. int destIndex = 0, lastLevel = 0;
  65671. while (--numPixels >= 0)
  65672. {
  65673. const int alpha = *mask;
  65674. mask += maskStride;
  65675. if (alpha != lastLevel)
  65676. {
  65677. tempLine[++destIndex] = (x << 8);
  65678. tempLine[++destIndex] = alpha;
  65679. lastLevel = alpha;
  65680. }
  65681. ++x;
  65682. }
  65683. if (lastLevel > 0)
  65684. {
  65685. tempLine[++destIndex] = (x << 8);
  65686. tempLine[++destIndex] = 0;
  65687. }
  65688. tempLine[0] = destIndex >> 1;
  65689. intersectWithEdgeTableLine (y, tempLine);
  65690. }
  65691. bool EdgeTable::isEmpty() throw()
  65692. {
  65693. if (needToCheckEmptinesss)
  65694. {
  65695. needToCheckEmptinesss = false;
  65696. int* t = table;
  65697. for (int i = bounds.getHeight(); --i >= 0;)
  65698. {
  65699. if (t[0] > 1)
  65700. return false;
  65701. t += lineStrideElements;
  65702. }
  65703. bounds.setHeight (0);
  65704. }
  65705. return bounds.getHeight() == 0;
  65706. }
  65707. END_JUCE_NAMESPACE
  65708. /*** End of inlined file: juce_EdgeTable.cpp ***/
  65709. /*** Start of inlined file: juce_FillType.cpp ***/
  65710. BEGIN_JUCE_NAMESPACE
  65711. FillType::FillType() throw()
  65712. : colour (0xff000000), image (0)
  65713. {
  65714. }
  65715. FillType::FillType (const Colour& colour_) throw()
  65716. : colour (colour_), image (0)
  65717. {
  65718. }
  65719. FillType::FillType (const ColourGradient& gradient_)
  65720. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  65721. {
  65722. }
  65723. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  65724. : colour (0xff000000), image (image_), transform (transform_)
  65725. {
  65726. }
  65727. FillType::FillType (const FillType& other)
  65728. : colour (other.colour),
  65729. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  65730. image (other.image), transform (other.transform)
  65731. {
  65732. }
  65733. FillType& FillType::operator= (const FillType& other)
  65734. {
  65735. if (this != &other)
  65736. {
  65737. colour = other.colour;
  65738. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  65739. image = other.image;
  65740. transform = other.transform;
  65741. }
  65742. return *this;
  65743. }
  65744. FillType::~FillType() throw()
  65745. {
  65746. }
  65747. bool FillType::operator== (const FillType& other) const
  65748. {
  65749. return colour == other.colour && image == other.image
  65750. && transform == other.transform
  65751. && (gradient == other.gradient
  65752. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  65753. }
  65754. bool FillType::operator!= (const FillType& other) const
  65755. {
  65756. return ! operator== (other);
  65757. }
  65758. void FillType::setColour (const Colour& newColour) throw()
  65759. {
  65760. gradient = 0;
  65761. image = Image::null;
  65762. colour = newColour;
  65763. }
  65764. void FillType::setGradient (const ColourGradient& newGradient)
  65765. {
  65766. if (gradient != 0)
  65767. {
  65768. *gradient = newGradient;
  65769. }
  65770. else
  65771. {
  65772. image = Image::null;
  65773. gradient = new ColourGradient (newGradient);
  65774. colour = Colours::black;
  65775. }
  65776. }
  65777. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  65778. {
  65779. gradient = 0;
  65780. image = image_;
  65781. transform = transform_;
  65782. colour = Colours::black;
  65783. }
  65784. void FillType::setOpacity (const float newOpacity) throw()
  65785. {
  65786. colour = colour.withAlpha (newOpacity);
  65787. }
  65788. bool FillType::isInvisible() const throw()
  65789. {
  65790. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  65791. }
  65792. END_JUCE_NAMESPACE
  65793. /*** End of inlined file: juce_FillType.cpp ***/
  65794. /*** Start of inlined file: juce_Graphics.cpp ***/
  65795. BEGIN_JUCE_NAMESPACE
  65796. template <typename Type>
  65797. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  65798. {
  65799. const int maxVal = 0x3fffffff;
  65800. return (int) x >= -maxVal && (int) x <= maxVal
  65801. && (int) y >= -maxVal && (int) y <= maxVal
  65802. && (int) w >= -maxVal && (int) w <= maxVal
  65803. && (int) h >= -maxVal && (int) h <= maxVal;
  65804. }
  65805. LowLevelGraphicsContext::LowLevelGraphicsContext()
  65806. {
  65807. }
  65808. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  65809. {
  65810. }
  65811. Graphics::Graphics (const Image& imageToDrawOnto)
  65812. : context (imageToDrawOnto.createLowLevelContext()),
  65813. contextToDelete (context),
  65814. saveStatePending (false)
  65815. {
  65816. }
  65817. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  65818. : context (internalContext),
  65819. saveStatePending (false)
  65820. {
  65821. }
  65822. Graphics::~Graphics()
  65823. {
  65824. }
  65825. void Graphics::resetToDefaultState()
  65826. {
  65827. saveStateIfPending();
  65828. context->setFill (FillType());
  65829. context->setFont (Font());
  65830. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  65831. }
  65832. bool Graphics::isVectorDevice() const
  65833. {
  65834. return context->isVectorDevice();
  65835. }
  65836. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  65837. {
  65838. saveStateIfPending();
  65839. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  65840. }
  65841. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  65842. {
  65843. saveStateIfPending();
  65844. return context->clipToRectangleList (clipRegion);
  65845. }
  65846. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  65847. {
  65848. saveStateIfPending();
  65849. context->clipToPath (path, transform);
  65850. return ! context->isClipEmpty();
  65851. }
  65852. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  65853. {
  65854. saveStateIfPending();
  65855. context->clipToImageAlpha (image, transform);
  65856. return ! context->isClipEmpty();
  65857. }
  65858. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  65859. {
  65860. saveStateIfPending();
  65861. context->excludeClipRectangle (rectangleToExclude);
  65862. }
  65863. bool Graphics::isClipEmpty() const
  65864. {
  65865. return context->isClipEmpty();
  65866. }
  65867. const Rectangle<int> Graphics::getClipBounds() const
  65868. {
  65869. return context->getClipBounds();
  65870. }
  65871. void Graphics::saveState()
  65872. {
  65873. saveStateIfPending();
  65874. saveStatePending = true;
  65875. }
  65876. void Graphics::restoreState()
  65877. {
  65878. if (saveStatePending)
  65879. saveStatePending = false;
  65880. else
  65881. context->restoreState();
  65882. }
  65883. void Graphics::saveStateIfPending()
  65884. {
  65885. if (saveStatePending)
  65886. {
  65887. saveStatePending = false;
  65888. context->saveState();
  65889. }
  65890. }
  65891. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  65892. {
  65893. saveStateIfPending();
  65894. context->setOrigin (newOriginX, newOriginY);
  65895. }
  65896. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  65897. {
  65898. return context->clipRegionIntersects (area);
  65899. }
  65900. void Graphics::setColour (const Colour& newColour)
  65901. {
  65902. saveStateIfPending();
  65903. context->setFill (newColour);
  65904. }
  65905. void Graphics::setOpacity (const float newOpacity)
  65906. {
  65907. saveStateIfPending();
  65908. context->setOpacity (newOpacity);
  65909. }
  65910. void Graphics::setGradientFill (const ColourGradient& gradient)
  65911. {
  65912. setFillType (gradient);
  65913. }
  65914. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  65915. {
  65916. saveStateIfPending();
  65917. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  65918. context->setOpacity (opacity);
  65919. }
  65920. void Graphics::setFillType (const FillType& newFill)
  65921. {
  65922. saveStateIfPending();
  65923. context->setFill (newFill);
  65924. }
  65925. void Graphics::setFont (const Font& newFont)
  65926. {
  65927. saveStateIfPending();
  65928. context->setFont (newFont);
  65929. }
  65930. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  65931. {
  65932. saveStateIfPending();
  65933. Font f (context->getFont());
  65934. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  65935. context->setFont (f);
  65936. }
  65937. const Font Graphics::getCurrentFont() const
  65938. {
  65939. return context->getFont();
  65940. }
  65941. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  65942. {
  65943. if (text.isNotEmpty()
  65944. && startX < context->getClipBounds().getRight())
  65945. {
  65946. GlyphArrangement arr;
  65947. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  65948. arr.draw (*this);
  65949. }
  65950. }
  65951. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  65952. {
  65953. if (text.isNotEmpty())
  65954. {
  65955. GlyphArrangement arr;
  65956. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  65957. arr.draw (*this, transform);
  65958. }
  65959. }
  65960. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  65961. {
  65962. if (text.isNotEmpty()
  65963. && startX < context->getClipBounds().getRight())
  65964. {
  65965. GlyphArrangement arr;
  65966. arr.addJustifiedText (context->getFont(), text,
  65967. (float) startX, (float) baselineY, (float) maximumLineWidth,
  65968. Justification::left);
  65969. arr.draw (*this);
  65970. }
  65971. }
  65972. void Graphics::drawText (const String& text,
  65973. const int x, const int y, const int width, const int height,
  65974. const Justification& justificationType,
  65975. const bool useEllipsesIfTooBig) const
  65976. {
  65977. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65978. {
  65979. GlyphArrangement arr;
  65980. arr.addCurtailedLineOfText (context->getFont(), text,
  65981. 0.0f, 0.0f, (float) width,
  65982. useEllipsesIfTooBig);
  65983. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  65984. (float) x, (float) y, (float) width, (float) height,
  65985. justificationType);
  65986. arr.draw (*this);
  65987. }
  65988. }
  65989. void Graphics::drawFittedText (const String& text,
  65990. const int x, const int y, const int width, const int height,
  65991. const Justification& justification,
  65992. const int maximumNumberOfLines,
  65993. const float minimumHorizontalScale) const
  65994. {
  65995. if (text.isNotEmpty()
  65996. && width > 0 && height > 0
  65997. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65998. {
  65999. GlyphArrangement arr;
  66000. arr.addFittedText (context->getFont(), text,
  66001. (float) x, (float) y, (float) width, (float) height,
  66002. justification,
  66003. maximumNumberOfLines,
  66004. minimumHorizontalScale);
  66005. arr.draw (*this);
  66006. }
  66007. }
  66008. void Graphics::fillRect (int x, int y, int width, int height) const
  66009. {
  66010. // passing in a silly number can cause maths problems in rendering!
  66011. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66012. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66013. }
  66014. void Graphics::fillRect (const Rectangle<int>& r) const
  66015. {
  66016. context->fillRect (r, false);
  66017. }
  66018. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66019. {
  66020. // passing in a silly number can cause maths problems in rendering!
  66021. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66022. Path p;
  66023. p.addRectangle (x, y, width, height);
  66024. fillPath (p);
  66025. }
  66026. void Graphics::setPixel (int x, int y) const
  66027. {
  66028. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66029. }
  66030. void Graphics::fillAll() const
  66031. {
  66032. fillRect (context->getClipBounds());
  66033. }
  66034. void Graphics::fillAll (const Colour& colourToUse) const
  66035. {
  66036. if (! colourToUse.isTransparent())
  66037. {
  66038. const Rectangle<int> clip (context->getClipBounds());
  66039. context->saveState();
  66040. context->setFill (colourToUse);
  66041. context->fillRect (clip, false);
  66042. context->restoreState();
  66043. }
  66044. }
  66045. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66046. {
  66047. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66048. context->fillPath (path, transform);
  66049. }
  66050. void Graphics::strokePath (const Path& path,
  66051. const PathStrokeType& strokeType,
  66052. const AffineTransform& transform) const
  66053. {
  66054. Path stroke;
  66055. strokeType.createStrokedPath (stroke, path, transform);
  66056. fillPath (stroke);
  66057. }
  66058. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66059. const int lineThickness) const
  66060. {
  66061. // passing in a silly number can cause maths problems in rendering!
  66062. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66063. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66064. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66065. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66066. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66067. }
  66068. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66069. {
  66070. // passing in a silly number can cause maths problems in rendering!
  66071. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66072. Path p;
  66073. p.addRectangle (x, y, width, lineThickness);
  66074. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66075. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66076. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66077. fillPath (p);
  66078. }
  66079. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66080. {
  66081. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66082. }
  66083. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66084. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66085. const bool useGradient, const bool sharpEdgeOnOutside) const
  66086. {
  66087. // passing in a silly number can cause maths problems in rendering!
  66088. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66089. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66090. {
  66091. context->saveState();
  66092. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66093. const float ramp = oldOpacity / bevelThickness;
  66094. for (int i = bevelThickness; --i >= 0;)
  66095. {
  66096. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66097. : oldOpacity;
  66098. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66099. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66100. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66101. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66102. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66103. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66104. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66105. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66106. }
  66107. context->restoreState();
  66108. }
  66109. }
  66110. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66111. {
  66112. // passing in a silly number can cause maths problems in rendering!
  66113. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66114. Path p;
  66115. p.addEllipse (x, y, width, height);
  66116. fillPath (p);
  66117. }
  66118. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66119. const float lineThickness) const
  66120. {
  66121. // passing in a silly number can cause maths problems in rendering!
  66122. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66123. Path p;
  66124. p.addEllipse (x, y, width, height);
  66125. strokePath (p, PathStrokeType (lineThickness));
  66126. }
  66127. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66128. {
  66129. // passing in a silly number can cause maths problems in rendering!
  66130. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66131. Path p;
  66132. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66133. fillPath (p);
  66134. }
  66135. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66136. {
  66137. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66138. }
  66139. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66140. const float cornerSize, const float lineThickness) const
  66141. {
  66142. // passing in a silly number can cause maths problems in rendering!
  66143. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66144. Path p;
  66145. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66146. strokePath (p, PathStrokeType (lineThickness));
  66147. }
  66148. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66149. {
  66150. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66151. }
  66152. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66153. {
  66154. Path p;
  66155. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66156. fillPath (p);
  66157. }
  66158. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66159. const int checkWidth, const int checkHeight,
  66160. const Colour& colour1, const Colour& colour2) const
  66161. {
  66162. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66163. if (checkWidth > 0 && checkHeight > 0)
  66164. {
  66165. context->saveState();
  66166. if (colour1 == colour2)
  66167. {
  66168. context->setFill (colour1);
  66169. context->fillRect (area, false);
  66170. }
  66171. else
  66172. {
  66173. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66174. if (! clipped.isEmpty())
  66175. {
  66176. context->clipToRectangle (clipped);
  66177. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66178. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66179. const int startX = area.getX() + checkNumX * checkWidth;
  66180. const int startY = area.getY() + checkNumY * checkHeight;
  66181. const int right = clipped.getRight();
  66182. const int bottom = clipped.getBottom();
  66183. for (int i = 0; i < 2; ++i)
  66184. {
  66185. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66186. int cy = i;
  66187. for (int y = startY; y < bottom; y += checkHeight)
  66188. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66189. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66190. }
  66191. }
  66192. }
  66193. context->restoreState();
  66194. }
  66195. }
  66196. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66197. {
  66198. context->drawVerticalLine (x, top, bottom);
  66199. }
  66200. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66201. {
  66202. context->drawHorizontalLine (y, left, right);
  66203. }
  66204. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66205. {
  66206. context->drawLine (Line<float> (x1, y1, x2, y2));
  66207. }
  66208. void Graphics::drawLine (const float startX, const float startY,
  66209. const float endX, const float endY,
  66210. const float lineThickness) const
  66211. {
  66212. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66213. }
  66214. void Graphics::drawLine (const Line<float>& line) const
  66215. {
  66216. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66217. }
  66218. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66219. {
  66220. Path p;
  66221. p.addLineSegment (line, lineThickness);
  66222. fillPath (p);
  66223. }
  66224. void Graphics::drawDashedLine (const float startX, const float startY,
  66225. const float endX, const float endY,
  66226. const float* const dashLengths,
  66227. const int numDashLengths,
  66228. const float lineThickness) const
  66229. {
  66230. const double dx = endX - startX;
  66231. const double dy = endY - startY;
  66232. const double totalLen = juce_hypot (dx, dy);
  66233. if (totalLen >= 0.5)
  66234. {
  66235. const double onePixAlpha = 1.0 / totalLen;
  66236. double alpha = 0.0;
  66237. float x = startX;
  66238. float y = startY;
  66239. int n = 0;
  66240. while (alpha < 1.0f)
  66241. {
  66242. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66243. n = n % numDashLengths;
  66244. const float oldX = x;
  66245. const float oldY = y;
  66246. x = (float) (startX + dx * alpha);
  66247. y = (float) (startY + dy * alpha);
  66248. if ((n & 1) != 0)
  66249. {
  66250. if (lineThickness != 1.0f)
  66251. drawLine (oldX, oldY, x, y, lineThickness);
  66252. else
  66253. drawLine (oldX, oldY, x, y);
  66254. }
  66255. }
  66256. }
  66257. }
  66258. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66259. {
  66260. saveStateIfPending();
  66261. context->setInterpolationQuality (newQuality);
  66262. }
  66263. void Graphics::drawImageAt (const Image& imageToDraw,
  66264. const int topLeftX, const int topLeftY,
  66265. const bool fillAlphaChannelWithCurrentBrush) const
  66266. {
  66267. const int imageW = imageToDraw.getWidth();
  66268. const int imageH = imageToDraw.getHeight();
  66269. drawImage (imageToDraw,
  66270. topLeftX, topLeftY, imageW, imageH,
  66271. 0, 0, imageW, imageH,
  66272. fillAlphaChannelWithCurrentBrush);
  66273. }
  66274. void Graphics::drawImageWithin (const Image& imageToDraw,
  66275. const int destX, const int destY,
  66276. const int destW, const int destH,
  66277. const RectanglePlacement& placementWithinTarget,
  66278. const bool fillAlphaChannelWithCurrentBrush) const
  66279. {
  66280. // passing in a silly number can cause maths problems in rendering!
  66281. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66282. if (imageToDraw.isValid())
  66283. {
  66284. const int imageW = imageToDraw.getWidth();
  66285. const int imageH = imageToDraw.getHeight();
  66286. if (imageW > 0 && imageH > 0)
  66287. {
  66288. double newX = 0.0, newY = 0.0;
  66289. double newW = imageW;
  66290. double newH = imageH;
  66291. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66292. destX, destY, destW, destH);
  66293. if (newW > 0 && newH > 0)
  66294. {
  66295. drawImage (imageToDraw,
  66296. roundToInt (newX), roundToInt (newY),
  66297. roundToInt (newW), roundToInt (newH),
  66298. 0, 0, imageW, imageH,
  66299. fillAlphaChannelWithCurrentBrush);
  66300. }
  66301. }
  66302. }
  66303. }
  66304. void Graphics::drawImage (const Image& imageToDraw,
  66305. int dx, int dy, int dw, int dh,
  66306. int sx, int sy, int sw, int sh,
  66307. const bool fillAlphaChannelWithCurrentBrush) const
  66308. {
  66309. // passing in a silly number can cause maths problems in rendering!
  66310. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66311. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66312. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66313. {
  66314. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66315. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66316. .translated ((float) dx, (float) dy),
  66317. fillAlphaChannelWithCurrentBrush);
  66318. }
  66319. }
  66320. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66321. const AffineTransform& transform,
  66322. const bool fillAlphaChannelWithCurrentBrush) const
  66323. {
  66324. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66325. {
  66326. if (fillAlphaChannelWithCurrentBrush)
  66327. {
  66328. context->saveState();
  66329. context->clipToImageAlpha (imageToDraw, transform);
  66330. fillAll();
  66331. context->restoreState();
  66332. }
  66333. else
  66334. {
  66335. context->drawImage (imageToDraw, transform, false);
  66336. }
  66337. }
  66338. }
  66339. END_JUCE_NAMESPACE
  66340. /*** End of inlined file: juce_Graphics.cpp ***/
  66341. /*** Start of inlined file: juce_Justification.cpp ***/
  66342. BEGIN_JUCE_NAMESPACE
  66343. Justification::Justification (const Justification& other) throw()
  66344. : flags (other.flags)
  66345. {
  66346. }
  66347. Justification& Justification::operator= (const Justification& other) throw()
  66348. {
  66349. flags = other.flags;
  66350. return *this;
  66351. }
  66352. int Justification::getOnlyVerticalFlags() const throw()
  66353. {
  66354. return flags & (top | bottom | verticallyCentred);
  66355. }
  66356. int Justification::getOnlyHorizontalFlags() const throw()
  66357. {
  66358. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66359. }
  66360. void Justification::applyToRectangle (int& x, int& y,
  66361. const int w, const int h,
  66362. const int spaceX, const int spaceY,
  66363. const int spaceW, const int spaceH) const throw()
  66364. {
  66365. if ((flags & horizontallyCentred) != 0)
  66366. x = spaceX + ((spaceW - w) >> 1);
  66367. else if ((flags & right) != 0)
  66368. x = spaceX + spaceW - w;
  66369. else
  66370. x = spaceX;
  66371. if ((flags & verticallyCentred) != 0)
  66372. y = spaceY + ((spaceH - h) >> 1);
  66373. else if ((flags & bottom) != 0)
  66374. y = spaceY + spaceH - h;
  66375. else
  66376. y = spaceY;
  66377. }
  66378. END_JUCE_NAMESPACE
  66379. /*** End of inlined file: juce_Justification.cpp ***/
  66380. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66381. BEGIN_JUCE_NAMESPACE
  66382. // this will throw an assertion if you try to draw something that's not
  66383. // possible in postscript
  66384. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66385. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66386. #define notPossibleInPostscriptAssert jassertfalse
  66387. #else
  66388. #define notPossibleInPostscriptAssert
  66389. #endif
  66390. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66391. const String& documentTitle,
  66392. const int totalWidth_,
  66393. const int totalHeight_)
  66394. : out (resultingPostScript),
  66395. totalWidth (totalWidth_),
  66396. totalHeight (totalHeight_),
  66397. needToClip (true)
  66398. {
  66399. stateStack.add (new SavedState());
  66400. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66401. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66402. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66403. "\n%%BoundingBox: 0 0 600 824"
  66404. "\n%%Pages: 0"
  66405. "\n%%Creator: Raw Material Software JUCE"
  66406. "\n%%Title: " << documentTitle <<
  66407. "\n%%CreationDate: none"
  66408. "\n%%LanguageLevel: 2"
  66409. "\n%%EndComments"
  66410. "\n%%BeginProlog"
  66411. "\n%%BeginResource: JRes"
  66412. "\n/bd {bind def} bind def"
  66413. "\n/c {setrgbcolor} bd"
  66414. "\n/m {moveto} bd"
  66415. "\n/l {lineto} bd"
  66416. "\n/rl {rlineto} bd"
  66417. "\n/ct {curveto} bd"
  66418. "\n/cp {closepath} bd"
  66419. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66420. "\n/doclip {initclip newpath} bd"
  66421. "\n/endclip {clip newpath} bd"
  66422. "\n%%EndResource"
  66423. "\n%%EndProlog"
  66424. "\n%%BeginSetup"
  66425. "\n%%EndSetup"
  66426. "\n%%Page: 1 1"
  66427. "\n%%BeginPageSetup"
  66428. "\n%%EndPageSetup\n\n"
  66429. << "40 800 translate\n"
  66430. << scale << ' ' << scale << " scale\n\n";
  66431. }
  66432. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66433. {
  66434. }
  66435. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66436. {
  66437. return true;
  66438. }
  66439. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66440. {
  66441. if (x != 0 || y != 0)
  66442. {
  66443. stateStack.getLast()->xOffset += x;
  66444. stateStack.getLast()->yOffset += y;
  66445. needToClip = true;
  66446. }
  66447. }
  66448. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66449. {
  66450. needToClip = true;
  66451. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66452. }
  66453. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66454. {
  66455. needToClip = true;
  66456. return stateStack.getLast()->clip.clipTo (clipRegion);
  66457. }
  66458. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66459. {
  66460. needToClip = true;
  66461. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66462. }
  66463. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66464. {
  66465. writeClip();
  66466. Path p (path);
  66467. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66468. writePath (p);
  66469. out << "clip\n";
  66470. }
  66471. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66472. {
  66473. needToClip = true;
  66474. jassertfalse; // xxx
  66475. }
  66476. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66477. {
  66478. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66479. }
  66480. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66481. {
  66482. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66483. -stateStack.getLast()->yOffset);
  66484. }
  66485. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66486. {
  66487. return stateStack.getLast()->clip.isEmpty();
  66488. }
  66489. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66490. : xOffset (0),
  66491. yOffset (0)
  66492. {
  66493. }
  66494. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66495. {
  66496. }
  66497. void LowLevelGraphicsPostScriptRenderer::saveState()
  66498. {
  66499. stateStack.add (new SavedState (*stateStack.getLast()));
  66500. }
  66501. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66502. {
  66503. jassert (stateStack.size() > 0);
  66504. if (stateStack.size() > 0)
  66505. stateStack.removeLast();
  66506. }
  66507. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66508. {
  66509. if (needToClip)
  66510. {
  66511. needToClip = false;
  66512. out << "doclip ";
  66513. int itemsOnLine = 0;
  66514. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66515. {
  66516. if (++itemsOnLine == 6)
  66517. {
  66518. itemsOnLine = 0;
  66519. out << '\n';
  66520. }
  66521. const Rectangle<int>& r = *i.getRectangle();
  66522. out << r.getX() << ' ' << -r.getY() << ' '
  66523. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66524. }
  66525. out << "endclip\n";
  66526. }
  66527. }
  66528. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66529. {
  66530. Colour c (Colours::white.overlaidWith (colour));
  66531. if (lastColour != c)
  66532. {
  66533. lastColour = c;
  66534. out << String (c.getFloatRed(), 3) << ' '
  66535. << String (c.getFloatGreen(), 3) << ' '
  66536. << String (c.getFloatBlue(), 3) << " c\n";
  66537. }
  66538. }
  66539. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66540. {
  66541. out << String (x, 2) << ' '
  66542. << String (-y, 2) << ' ';
  66543. }
  66544. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66545. {
  66546. out << "newpath ";
  66547. float lastX = 0.0f;
  66548. float lastY = 0.0f;
  66549. int itemsOnLine = 0;
  66550. Path::Iterator i (path);
  66551. while (i.next())
  66552. {
  66553. if (++itemsOnLine == 4)
  66554. {
  66555. itemsOnLine = 0;
  66556. out << '\n';
  66557. }
  66558. switch (i.elementType)
  66559. {
  66560. case Path::Iterator::startNewSubPath:
  66561. writeXY (i.x1, i.y1);
  66562. lastX = i.x1;
  66563. lastY = i.y1;
  66564. out << "m ";
  66565. break;
  66566. case Path::Iterator::lineTo:
  66567. writeXY (i.x1, i.y1);
  66568. lastX = i.x1;
  66569. lastY = i.y1;
  66570. out << "l ";
  66571. break;
  66572. case Path::Iterator::quadraticTo:
  66573. {
  66574. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66575. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66576. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66577. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66578. writeXY (cp1x, cp1y);
  66579. writeXY (cp2x, cp2y);
  66580. writeXY (i.x2, i.y2);
  66581. out << "ct ";
  66582. lastX = i.x2;
  66583. lastY = i.y2;
  66584. }
  66585. break;
  66586. case Path::Iterator::cubicTo:
  66587. writeXY (i.x1, i.y1);
  66588. writeXY (i.x2, i.y2);
  66589. writeXY (i.x3, i.y3);
  66590. out << "ct ";
  66591. lastX = i.x3;
  66592. lastY = i.y3;
  66593. break;
  66594. case Path::Iterator::closePath:
  66595. out << "cp ";
  66596. break;
  66597. default:
  66598. jassertfalse;
  66599. break;
  66600. }
  66601. }
  66602. out << '\n';
  66603. }
  66604. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66605. {
  66606. out << "[ "
  66607. << trans.mat00 << ' '
  66608. << trans.mat10 << ' '
  66609. << trans.mat01 << ' '
  66610. << trans.mat11 << ' '
  66611. << trans.mat02 << ' '
  66612. << trans.mat12 << " ] concat ";
  66613. }
  66614. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  66615. {
  66616. stateStack.getLast()->fillType = fillType;
  66617. }
  66618. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  66619. {
  66620. }
  66621. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  66622. {
  66623. }
  66624. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  66625. {
  66626. if (stateStack.getLast()->fillType.isColour())
  66627. {
  66628. writeClip();
  66629. writeColour (stateStack.getLast()->fillType.colour);
  66630. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66631. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  66632. }
  66633. else
  66634. {
  66635. Path p;
  66636. p.addRectangle (r);
  66637. fillPath (p, AffineTransform::identity);
  66638. }
  66639. }
  66640. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  66641. {
  66642. if (stateStack.getLast()->fillType.isColour())
  66643. {
  66644. writeClip();
  66645. Path p (path);
  66646. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  66647. (float) stateStack.getLast()->yOffset));
  66648. writePath (p);
  66649. writeColour (stateStack.getLast()->fillType.colour);
  66650. out << "fill\n";
  66651. }
  66652. else if (stateStack.getLast()->fillType.isGradient())
  66653. {
  66654. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  66655. // postscript can't do semi-transparent ones.
  66656. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  66657. writeClip();
  66658. out << "gsave ";
  66659. {
  66660. Path p (path);
  66661. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66662. writePath (p);
  66663. out << "clip\n";
  66664. }
  66665. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  66666. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  66667. // time-being, this just fills it with the average colour..
  66668. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  66669. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  66670. out << "grestore\n";
  66671. }
  66672. }
  66673. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  66674. const int sx, const int sy,
  66675. const int maxW, const int maxH) const
  66676. {
  66677. out << "{<\n";
  66678. const int w = jmin (maxW, im.getWidth());
  66679. const int h = jmin (maxH, im.getHeight());
  66680. int charsOnLine = 0;
  66681. const Image::BitmapData srcData (im, 0, 0, w, h);
  66682. Colour pixel;
  66683. for (int y = h; --y >= 0;)
  66684. {
  66685. for (int x = 0; x < w; ++x)
  66686. {
  66687. const uint8* pixelData = srcData.getPixelPointer (x, y);
  66688. if (x >= sx && y >= sy)
  66689. {
  66690. if (im.isARGB())
  66691. {
  66692. PixelARGB p (*(const PixelARGB*) pixelData);
  66693. p.unpremultiply();
  66694. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  66695. }
  66696. else if (im.isRGB())
  66697. {
  66698. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  66699. }
  66700. else
  66701. {
  66702. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  66703. }
  66704. }
  66705. else
  66706. {
  66707. pixel = Colours::transparentWhite;
  66708. }
  66709. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  66710. out << String::toHexString (pixelValues, 3, 0);
  66711. charsOnLine += 3;
  66712. if (charsOnLine > 100)
  66713. {
  66714. out << '\n';
  66715. charsOnLine = 0;
  66716. }
  66717. }
  66718. }
  66719. out << "\n>}\n";
  66720. }
  66721. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  66722. {
  66723. const int w = sourceImage.getWidth();
  66724. const int h = sourceImage.getHeight();
  66725. writeClip();
  66726. out << "gsave ";
  66727. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  66728. .scaled (1.0f, -1.0f));
  66729. RectangleList imageClip;
  66730. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  66731. out << "newpath ";
  66732. int itemsOnLine = 0;
  66733. for (RectangleList::Iterator i (imageClip); i.next();)
  66734. {
  66735. if (++itemsOnLine == 6)
  66736. {
  66737. out << '\n';
  66738. itemsOnLine = 0;
  66739. }
  66740. const Rectangle<int>& r = *i.getRectangle();
  66741. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  66742. }
  66743. out << " clip newpath\n";
  66744. out << w << ' ' << h << " scale\n";
  66745. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  66746. writeImage (sourceImage, 0, 0, w, h);
  66747. out << "false 3 colorimage grestore\n";
  66748. needToClip = true;
  66749. }
  66750. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  66751. {
  66752. Path p;
  66753. p.addLineSegment (line, 1.0f);
  66754. fillPath (p, AffineTransform::identity);
  66755. }
  66756. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  66757. {
  66758. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  66759. }
  66760. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  66761. {
  66762. drawLine (Line<float> (left, (float) y, right, (float) y));
  66763. }
  66764. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  66765. {
  66766. stateStack.getLast()->font = newFont;
  66767. }
  66768. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  66769. {
  66770. return stateStack.getLast()->font;
  66771. }
  66772. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66773. {
  66774. Path p;
  66775. Font& font = stateStack.getLast()->font;
  66776. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66777. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  66778. }
  66779. END_JUCE_NAMESPACE
  66780. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66781. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66782. BEGIN_JUCE_NAMESPACE
  66783. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  66784. #define JUCE_USE_SSE_INSTRUCTIONS 1
  66785. #endif
  66786. #if JUCE_MSVC
  66787. #pragma warning (push)
  66788. #pragma warning (disable: 4127) // "expression is constant" warning
  66789. #if JUCE_DEBUG
  66790. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  66791. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  66792. #endif
  66793. #endif
  66794. namespace SoftwareRendererClasses
  66795. {
  66796. template <class PixelType, bool replaceExisting = false>
  66797. class SolidColourEdgeTableRenderer
  66798. {
  66799. public:
  66800. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  66801. : data (data_),
  66802. sourceColour (colour)
  66803. {
  66804. if (sizeof (PixelType) == 3)
  66805. {
  66806. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  66807. && sourceColour.getGreen() == sourceColour.getBlue();
  66808. filler[0].set (sourceColour);
  66809. filler[1].set (sourceColour);
  66810. filler[2].set (sourceColour);
  66811. filler[3].set (sourceColour);
  66812. }
  66813. }
  66814. forcedinline void setEdgeTableYPos (const int y) throw()
  66815. {
  66816. linePixels = (PixelType*) data.getLinePointer (y);
  66817. }
  66818. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66819. {
  66820. if (replaceExisting)
  66821. linePixels[x].set (sourceColour);
  66822. else
  66823. linePixels[x].blend (sourceColour, alphaLevel);
  66824. }
  66825. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66826. {
  66827. if (replaceExisting)
  66828. linePixels[x].set (sourceColour);
  66829. else
  66830. linePixels[x].blend (sourceColour);
  66831. }
  66832. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  66833. {
  66834. PixelARGB p (sourceColour);
  66835. p.multiplyAlpha (alphaLevel);
  66836. PixelType* dest = linePixels + x;
  66837. if (replaceExisting || p.getAlpha() >= 0xff)
  66838. replaceLine (dest, p, width);
  66839. else
  66840. blendLine (dest, p, width);
  66841. }
  66842. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  66843. {
  66844. PixelType* dest = linePixels + x;
  66845. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  66846. replaceLine (dest, sourceColour, width);
  66847. else
  66848. blendLine (dest, sourceColour, width);
  66849. }
  66850. private:
  66851. const Image::BitmapData& data;
  66852. PixelType* linePixels;
  66853. PixelARGB sourceColour;
  66854. PixelRGB filler [4];
  66855. bool areRGBComponentsEqual;
  66856. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  66857. {
  66858. do
  66859. {
  66860. dest->blend (colour);
  66861. ++dest;
  66862. } while (--width > 0);
  66863. }
  66864. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  66865. {
  66866. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  66867. {
  66868. memset (dest, colour.getRed(), width * 3);
  66869. }
  66870. else
  66871. {
  66872. if (width >> 5)
  66873. {
  66874. const int* const intFiller = (const int*) filler;
  66875. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  66876. {
  66877. dest->set (colour);
  66878. ++dest;
  66879. --width;
  66880. }
  66881. while (width > 4)
  66882. {
  66883. ((int*) dest) [0] = intFiller[0];
  66884. ((int*) dest) [1] = intFiller[1];
  66885. ((int*) dest) [2] = intFiller[2];
  66886. dest = (PixelRGB*) (((uint8*) dest) + 12);
  66887. width -= 4;
  66888. }
  66889. }
  66890. while (--width >= 0)
  66891. {
  66892. dest->set (colour);
  66893. ++dest;
  66894. }
  66895. }
  66896. }
  66897. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  66898. {
  66899. memset (dest, colour.getAlpha(), width);
  66900. }
  66901. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  66902. {
  66903. do
  66904. {
  66905. dest->set (colour);
  66906. ++dest;
  66907. } while (--width > 0);
  66908. }
  66909. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  66910. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  66911. };
  66912. class LinearGradientPixelGenerator
  66913. {
  66914. public:
  66915. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  66916. : lookupTable (lookupTable_), numEntries (numEntries_)
  66917. {
  66918. jassert (numEntries_ >= 0);
  66919. Point<float> p1 (gradient.point1);
  66920. Point<float> p2 (gradient.point2);
  66921. if (! transform.isIdentity())
  66922. {
  66923. const Line<float> l (p2, p1);
  66924. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  66925. p1.applyTransform (transform);
  66926. p2.applyTransform (transform);
  66927. p3.applyTransform (transform);
  66928. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  66929. }
  66930. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  66931. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  66932. if (vertical)
  66933. {
  66934. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  66935. start = roundToInt (p1.getY() * scale);
  66936. }
  66937. else if (horizontal)
  66938. {
  66939. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  66940. start = roundToInt (p1.getX() * scale);
  66941. }
  66942. else
  66943. {
  66944. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  66945. yTerm = p1.getY() - p1.getX() / grad;
  66946. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  66947. grad *= scale;
  66948. }
  66949. }
  66950. forcedinline void setY (const int y) throw()
  66951. {
  66952. if (vertical)
  66953. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  66954. else if (! horizontal)
  66955. start = roundToInt ((y - yTerm) * grad);
  66956. }
  66957. inline const PixelARGB getPixel (const int x) const throw()
  66958. {
  66959. return vertical ? linePix
  66960. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  66961. }
  66962. private:
  66963. const PixelARGB* const lookupTable;
  66964. const int numEntries;
  66965. PixelARGB linePix;
  66966. int start, scale;
  66967. double grad, yTerm;
  66968. bool vertical, horizontal;
  66969. enum { numScaleBits = 12 };
  66970. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  66971. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  66972. };
  66973. class RadialGradientPixelGenerator
  66974. {
  66975. public:
  66976. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  66977. const PixelARGB* const lookupTable_, const int numEntries_)
  66978. : lookupTable (lookupTable_),
  66979. numEntries (numEntries_),
  66980. gx1 (gradient.point1.getX()),
  66981. gy1 (gradient.point1.getY())
  66982. {
  66983. jassert (numEntries_ >= 0);
  66984. const Point<float> diff (gradient.point1 - gradient.point2);
  66985. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  66986. invScale = numEntries / std::sqrt (maxDist);
  66987. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  66988. }
  66989. forcedinline void setY (const int y) throw()
  66990. {
  66991. dy = y - gy1;
  66992. dy *= dy;
  66993. }
  66994. inline const PixelARGB getPixel (const int px) const throw()
  66995. {
  66996. double x = px - gx1;
  66997. x *= x;
  66998. x += dy;
  66999. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67000. }
  67001. protected:
  67002. const PixelARGB* const lookupTable;
  67003. const int numEntries;
  67004. const double gx1, gy1;
  67005. double maxDist, invScale, dy;
  67006. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67007. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67008. };
  67009. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67010. {
  67011. public:
  67012. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67013. const PixelARGB* const lookupTable_, const int numEntries_)
  67014. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67015. inverseTransform (transform.inverted())
  67016. {
  67017. tM10 = inverseTransform.mat10;
  67018. tM00 = inverseTransform.mat00;
  67019. }
  67020. forcedinline void setY (const int y) throw()
  67021. {
  67022. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67023. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67024. }
  67025. inline const PixelARGB getPixel (const int px) const throw()
  67026. {
  67027. double x = px;
  67028. const double y = tM10 * x + lineYM11;
  67029. x = tM00 * x + lineYM01;
  67030. x *= x;
  67031. x += y * y;
  67032. if (x >= maxDist)
  67033. return lookupTable [numEntries];
  67034. else
  67035. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67036. }
  67037. private:
  67038. double tM10, tM00, lineYM01, lineYM11;
  67039. const AffineTransform inverseTransform;
  67040. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67041. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67042. };
  67043. template <class PixelType, class GradientType>
  67044. class GradientEdgeTableRenderer : public GradientType
  67045. {
  67046. public:
  67047. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67048. const PixelARGB* const lookupTable_, const int numEntries_)
  67049. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67050. destData (destData_)
  67051. {
  67052. }
  67053. forcedinline void setEdgeTableYPos (const int y) throw()
  67054. {
  67055. linePixels = (PixelType*) destData.getLinePointer (y);
  67056. GradientType::setY (y);
  67057. }
  67058. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67059. {
  67060. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67061. }
  67062. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67063. {
  67064. linePixels[x].blend (GradientType::getPixel (x));
  67065. }
  67066. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67067. {
  67068. PixelType* dest = linePixels + x;
  67069. if (alphaLevel < 0xff)
  67070. {
  67071. do
  67072. {
  67073. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67074. } while (--width > 0);
  67075. }
  67076. else
  67077. {
  67078. do
  67079. {
  67080. (dest++)->blend (GradientType::getPixel (x++));
  67081. } while (--width > 0);
  67082. }
  67083. }
  67084. void handleEdgeTableLineFull (int x, int width) const throw()
  67085. {
  67086. PixelType* dest = linePixels + x;
  67087. do
  67088. {
  67089. (dest++)->blend (GradientType::getPixel (x++));
  67090. } while (--width > 0);
  67091. }
  67092. private:
  67093. const Image::BitmapData& destData;
  67094. PixelType* linePixels;
  67095. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67096. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67097. };
  67098. static forcedinline int safeModulo (int n, const int divisor) throw()
  67099. {
  67100. jassert (divisor > 0);
  67101. n %= divisor;
  67102. return (n < 0) ? (n + divisor) : n;
  67103. }
  67104. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67105. class ImageFillEdgeTableRenderer
  67106. {
  67107. public:
  67108. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67109. const Image::BitmapData& srcData_,
  67110. const int extraAlpha_,
  67111. const int x, const int y)
  67112. : destData (destData_),
  67113. srcData (srcData_),
  67114. extraAlpha (extraAlpha_ + 1),
  67115. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67116. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67117. {
  67118. }
  67119. forcedinline void setEdgeTableYPos (int y) throw()
  67120. {
  67121. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67122. y -= yOffset;
  67123. if (repeatPattern)
  67124. {
  67125. jassert (y >= 0);
  67126. y %= srcData.height;
  67127. }
  67128. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67129. }
  67130. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67131. {
  67132. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67133. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67134. }
  67135. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67136. {
  67137. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67138. }
  67139. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67140. {
  67141. DestPixelType* dest = linePixels + x;
  67142. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67143. x -= xOffset;
  67144. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67145. if (alphaLevel < 0xfe)
  67146. {
  67147. do
  67148. {
  67149. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67150. } while (--width > 0);
  67151. }
  67152. else
  67153. {
  67154. if (repeatPattern)
  67155. {
  67156. do
  67157. {
  67158. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67159. } while (--width > 0);
  67160. }
  67161. else
  67162. {
  67163. copyRow (dest, sourceLineStart + x, width);
  67164. }
  67165. }
  67166. }
  67167. void handleEdgeTableLineFull (int x, int width) const throw()
  67168. {
  67169. DestPixelType* dest = linePixels + x;
  67170. x -= xOffset;
  67171. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67172. if (extraAlpha < 0xfe)
  67173. {
  67174. do
  67175. {
  67176. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67177. } while (--width > 0);
  67178. }
  67179. else
  67180. {
  67181. if (repeatPattern)
  67182. {
  67183. do
  67184. {
  67185. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67186. } while (--width > 0);
  67187. }
  67188. else
  67189. {
  67190. copyRow (dest, sourceLineStart + x, width);
  67191. }
  67192. }
  67193. }
  67194. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67195. {
  67196. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67197. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67198. uint8* mask = (uint8*) (s + x - xOffset);
  67199. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67200. mask += PixelARGB::indexA;
  67201. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67202. }
  67203. private:
  67204. const Image::BitmapData& destData;
  67205. const Image::BitmapData& srcData;
  67206. const int extraAlpha, xOffset, yOffset;
  67207. DestPixelType* linePixels;
  67208. SrcPixelType* sourceLineStart;
  67209. template <class PixelType1, class PixelType2>
  67210. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67211. {
  67212. do
  67213. {
  67214. dest++ ->blend (*src++);
  67215. } while (--width > 0);
  67216. }
  67217. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67218. {
  67219. memcpy (dest, src, width * sizeof (PixelRGB));
  67220. }
  67221. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67222. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67223. };
  67224. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67225. class TransformedImageFillEdgeTableRenderer
  67226. {
  67227. public:
  67228. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67229. const Image::BitmapData& srcData_,
  67230. const AffineTransform& transform,
  67231. const int extraAlpha_,
  67232. const bool betterQuality_)
  67233. : interpolator (transform),
  67234. destData (destData_),
  67235. srcData (srcData_),
  67236. extraAlpha (extraAlpha_ + 1),
  67237. betterQuality (betterQuality_),
  67238. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67239. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67240. maxX (srcData_.width - 1),
  67241. maxY (srcData_.height - 1),
  67242. scratchSize (2048)
  67243. {
  67244. scratchBuffer.malloc (scratchSize);
  67245. }
  67246. ~TransformedImageFillEdgeTableRenderer()
  67247. {
  67248. }
  67249. forcedinline void setEdgeTableYPos (const int newY) throw()
  67250. {
  67251. y = newY;
  67252. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67253. }
  67254. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67255. {
  67256. alphaLevel *= extraAlpha;
  67257. alphaLevel >>= 8;
  67258. SrcPixelType p;
  67259. generate (&p, x, 1);
  67260. linePixels[x].blend (p, alphaLevel);
  67261. }
  67262. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67263. {
  67264. SrcPixelType p;
  67265. generate (&p, x, 1);
  67266. linePixels[x].blend (p, extraAlpha);
  67267. }
  67268. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67269. {
  67270. if (width > scratchSize)
  67271. {
  67272. scratchSize = width;
  67273. scratchBuffer.malloc (scratchSize);
  67274. }
  67275. SrcPixelType* span = scratchBuffer;
  67276. generate (span, x, width);
  67277. DestPixelType* dest = linePixels + x;
  67278. alphaLevel *= extraAlpha;
  67279. alphaLevel >>= 8;
  67280. if (alphaLevel < 0xfe)
  67281. {
  67282. do
  67283. {
  67284. dest++ ->blend (*span++, alphaLevel);
  67285. } while (--width > 0);
  67286. }
  67287. else
  67288. {
  67289. do
  67290. {
  67291. dest++ ->blend (*span++);
  67292. } while (--width > 0);
  67293. }
  67294. }
  67295. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67296. {
  67297. handleEdgeTableLine (x, width, 255);
  67298. }
  67299. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67300. {
  67301. if (width > scratchSize)
  67302. {
  67303. scratchSize = width;
  67304. scratchBuffer.malloc (scratchSize);
  67305. }
  67306. y = y_;
  67307. generate (scratchBuffer, x, width);
  67308. et.clipLineToMask (x, y_,
  67309. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67310. sizeof (SrcPixelType), width);
  67311. }
  67312. private:
  67313. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67314. {
  67315. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67316. do
  67317. {
  67318. int hiResX, hiResY;
  67319. this->interpolator.next (hiResX, hiResY);
  67320. hiResX += pixelOffsetInt;
  67321. hiResY += pixelOffsetInt;
  67322. int loResX = hiResX >> 8;
  67323. int loResY = hiResY >> 8;
  67324. if (repeatPattern)
  67325. {
  67326. loResX = safeModulo (loResX, srcData.width);
  67327. loResY = safeModulo (loResY, srcData.height);
  67328. }
  67329. if (betterQuality
  67330. && ((unsigned int) loResX) < (unsigned int) maxX
  67331. && ((unsigned int) loResY) < (unsigned int) maxY)
  67332. {
  67333. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67334. hiResX &= 255;
  67335. hiResY &= 255;
  67336. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67337. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67338. c[0] += weight * src[0];
  67339. c[1] += weight * src[1];
  67340. c[2] += weight * src[2];
  67341. c[3] += weight * src[3];
  67342. weight = hiResX * (256 - hiResY);
  67343. c[0] += weight * src[4];
  67344. c[1] += weight * src[5];
  67345. c[2] += weight * src[6];
  67346. c[3] += weight * src[7];
  67347. src += this->srcData.lineStride;
  67348. weight = (256 - hiResX) * hiResY;
  67349. c[0] += weight * src[0];
  67350. c[1] += weight * src[1];
  67351. c[2] += weight * src[2];
  67352. c[3] += weight * src[3];
  67353. weight = hiResX * hiResY;
  67354. c[0] += weight * src[4];
  67355. c[1] += weight * src[5];
  67356. c[2] += weight * src[6];
  67357. c[3] += weight * src[7];
  67358. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67359. (uint8) (c[PixelARGB::indexR] >> 16),
  67360. (uint8) (c[PixelARGB::indexG] >> 16),
  67361. (uint8) (c[PixelARGB::indexB] >> 16));
  67362. }
  67363. else
  67364. {
  67365. if (! repeatPattern)
  67366. {
  67367. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67368. if (loResX < 0) loResX = 0;
  67369. if (loResY < 0) loResY = 0;
  67370. if (loResX > maxX) loResX = maxX;
  67371. if (loResY > maxY) loResY = maxY;
  67372. }
  67373. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67374. }
  67375. ++dest;
  67376. } while (--numPixels > 0);
  67377. }
  67378. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  67379. {
  67380. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67381. do
  67382. {
  67383. int hiResX, hiResY;
  67384. this->interpolator.next (hiResX, hiResY);
  67385. hiResX += pixelOffsetInt;
  67386. hiResY += pixelOffsetInt;
  67387. int loResX = hiResX >> 8;
  67388. int loResY = hiResY >> 8;
  67389. if (repeatPattern)
  67390. {
  67391. loResX = safeModulo (loResX, srcData.width);
  67392. loResY = safeModulo (loResY, srcData.height);
  67393. }
  67394. if (betterQuality
  67395. && ((unsigned int) loResX) < (unsigned int) maxX
  67396. && ((unsigned int) loResY) < (unsigned int) maxY)
  67397. {
  67398. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67399. hiResX &= 255;
  67400. hiResY &= 255;
  67401. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67402. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  67403. c[0] += weight * src[0];
  67404. c[1] += weight * src[1];
  67405. c[2] += weight * src[2];
  67406. weight = hiResX * (256 - hiResY);
  67407. c[0] += weight * src[3];
  67408. c[1] += weight * src[4];
  67409. c[2] += weight * src[5];
  67410. src += this->srcData.lineStride;
  67411. weight = (256 - hiResX) * hiResY;
  67412. c[0] += weight * src[0];
  67413. c[1] += weight * src[1];
  67414. c[2] += weight * src[2];
  67415. weight = hiResX * hiResY;
  67416. c[0] += weight * src[3];
  67417. c[1] += weight * src[4];
  67418. c[2] += weight * src[5];
  67419. dest->setARGB ((uint8) 255,
  67420. (uint8) (c[PixelRGB::indexR] >> 16),
  67421. (uint8) (c[PixelRGB::indexG] >> 16),
  67422. (uint8) (c[PixelRGB::indexB] >> 16));
  67423. }
  67424. else
  67425. {
  67426. if (! repeatPattern)
  67427. {
  67428. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67429. if (loResX < 0) loResX = 0;
  67430. if (loResY < 0) loResY = 0;
  67431. if (loResX > maxX) loResX = maxX;
  67432. if (loResY > maxY) loResY = maxY;
  67433. }
  67434. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  67435. }
  67436. ++dest;
  67437. } while (--numPixels > 0);
  67438. }
  67439. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  67440. {
  67441. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67442. do
  67443. {
  67444. int hiResX, hiResY;
  67445. this->interpolator.next (hiResX, hiResY);
  67446. hiResX += pixelOffsetInt;
  67447. hiResY += pixelOffsetInt;
  67448. int loResX = hiResX >> 8;
  67449. int loResY = hiResY >> 8;
  67450. if (repeatPattern)
  67451. {
  67452. loResX = safeModulo (loResX, srcData.width);
  67453. loResY = safeModulo (loResY, srcData.height);
  67454. }
  67455. if (betterQuality
  67456. && ((unsigned int) loResX) < (unsigned int) maxX
  67457. && ((unsigned int) loResY) < (unsigned int) maxY)
  67458. {
  67459. hiResX &= 255;
  67460. hiResY &= 255;
  67461. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67462. uint32 c = 256 * 128;
  67463. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  67464. c += src[1] * (hiResX * (256 - hiResY));
  67465. src += this->srcData.lineStride;
  67466. c += src[0] * ((256 - hiResX) * hiResY);
  67467. c += src[1] * (hiResX * hiResY);
  67468. *((uint8*) dest) = (uint8) c;
  67469. }
  67470. else
  67471. {
  67472. if (! repeatPattern)
  67473. {
  67474. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67475. if (loResX < 0) loResX = 0;
  67476. if (loResY < 0) loResY = 0;
  67477. if (loResX > maxX) loResX = maxX;
  67478. if (loResY > maxY) loResY = maxY;
  67479. }
  67480. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  67481. }
  67482. ++dest;
  67483. } while (--numPixels > 0);
  67484. }
  67485. class TransformedImageSpanInterpolator
  67486. {
  67487. public:
  67488. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  67489. : inverseTransform (transform.inverted())
  67490. {}
  67491. void setStartOfLine (float x, float y, const int numPixels) throw()
  67492. {
  67493. float x1 = x, y1 = y;
  67494. x += numPixels;
  67495. inverseTransform.transformPoints (x1, y1, x, y);
  67496. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  67497. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  67498. }
  67499. void next (int& x, int& y) throw()
  67500. {
  67501. x = xBresenham.n;
  67502. xBresenham.stepToNext();
  67503. y = yBresenham.n;
  67504. yBresenham.stepToNext();
  67505. }
  67506. private:
  67507. class BresenhamInterpolator
  67508. {
  67509. public:
  67510. BresenhamInterpolator() throw() {}
  67511. void set (const int n1, const int n2, const int numSteps_) throw()
  67512. {
  67513. numSteps = jmax (1, numSteps_);
  67514. step = (n2 - n1) / numSteps;
  67515. remainder = modulo = (n2 - n1) % numSteps;
  67516. n = n1;
  67517. if (modulo <= 0)
  67518. {
  67519. modulo += numSteps;
  67520. remainder += numSteps;
  67521. --step;
  67522. }
  67523. modulo -= numSteps;
  67524. }
  67525. forcedinline void stepToNext() throw()
  67526. {
  67527. modulo += remainder;
  67528. n += step;
  67529. if (modulo > 0)
  67530. {
  67531. modulo -= numSteps;
  67532. ++n;
  67533. }
  67534. }
  67535. int n;
  67536. private:
  67537. int numSteps, step, modulo, remainder;
  67538. };
  67539. const AffineTransform inverseTransform;
  67540. BresenhamInterpolator xBresenham, yBresenham;
  67541. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  67542. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  67543. };
  67544. TransformedImageSpanInterpolator interpolator;
  67545. const Image::BitmapData& destData;
  67546. const Image::BitmapData& srcData;
  67547. const int extraAlpha;
  67548. const bool betterQuality;
  67549. const float pixelOffset;
  67550. const int pixelOffsetInt, maxX, maxY;
  67551. int y;
  67552. DestPixelType* linePixels;
  67553. HeapBlock <SrcPixelType> scratchBuffer;
  67554. int scratchSize;
  67555. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  67556. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  67557. };
  67558. class ClipRegionBase : public ReferenceCountedObject
  67559. {
  67560. public:
  67561. ClipRegionBase() {}
  67562. virtual ~ClipRegionBase() {}
  67563. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67564. virtual const Ptr clone() const = 0;
  67565. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67566. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67567. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67568. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67569. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67570. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67571. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67572. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67573. virtual const Rectangle<int> getClipBounds() const = 0;
  67574. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  67575. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  67576. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  67577. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  67578. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  67579. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  67580. protected:
  67581. template <class Iterator>
  67582. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  67583. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  67584. {
  67585. switch (destData.pixelFormat)
  67586. {
  67587. case Image::ARGB:
  67588. switch (srcData.pixelFormat)
  67589. {
  67590. case Image::ARGB:
  67591. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67592. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67593. break;
  67594. case Image::RGB:
  67595. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67596. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67597. break;
  67598. default:
  67599. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67600. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67601. break;
  67602. }
  67603. break;
  67604. case Image::RGB:
  67605. switch (srcData.pixelFormat)
  67606. {
  67607. case Image::ARGB:
  67608. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67609. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67610. break;
  67611. case Image::RGB:
  67612. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67613. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67614. break;
  67615. default:
  67616. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67617. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67618. break;
  67619. }
  67620. break;
  67621. default:
  67622. switch (srcData.pixelFormat)
  67623. {
  67624. case Image::ARGB:
  67625. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67626. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67627. break;
  67628. case Image::RGB:
  67629. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67630. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67631. break;
  67632. default:
  67633. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67634. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67635. break;
  67636. }
  67637. break;
  67638. }
  67639. }
  67640. template <class Iterator>
  67641. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  67642. {
  67643. switch (destData.pixelFormat)
  67644. {
  67645. case Image::ARGB:
  67646. switch (srcData.pixelFormat)
  67647. {
  67648. case Image::ARGB:
  67649. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67650. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67651. break;
  67652. case Image::RGB:
  67653. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67654. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67655. break;
  67656. default:
  67657. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67658. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67659. break;
  67660. }
  67661. break;
  67662. case Image::RGB:
  67663. switch (srcData.pixelFormat)
  67664. {
  67665. case Image::ARGB:
  67666. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67667. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67668. break;
  67669. case Image::RGB:
  67670. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67671. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67672. break;
  67673. default:
  67674. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67675. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67676. break;
  67677. }
  67678. break;
  67679. default:
  67680. switch (srcData.pixelFormat)
  67681. {
  67682. case Image::ARGB:
  67683. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67684. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67685. break;
  67686. case Image::RGB:
  67687. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67688. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67689. break;
  67690. default:
  67691. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67692. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  67693. break;
  67694. }
  67695. break;
  67696. }
  67697. }
  67698. template <class Iterator, class DestPixelType>
  67699. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  67700. {
  67701. jassert (destData.pixelStride == sizeof (DestPixelType));
  67702. if (replaceContents)
  67703. {
  67704. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  67705. iter.iterate (r);
  67706. }
  67707. else
  67708. {
  67709. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  67710. iter.iterate (r);
  67711. }
  67712. }
  67713. template <class Iterator, class DestPixelType>
  67714. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  67715. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  67716. {
  67717. jassert (destData.pixelStride == sizeof (DestPixelType));
  67718. if (g.isRadial)
  67719. {
  67720. if (isIdentity)
  67721. {
  67722. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67723. iter.iterate (renderer);
  67724. }
  67725. else
  67726. {
  67727. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67728. iter.iterate (renderer);
  67729. }
  67730. }
  67731. else
  67732. {
  67733. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  67734. iter.iterate (renderer);
  67735. }
  67736. }
  67737. };
  67738. class ClipRegion_EdgeTable : public ClipRegionBase
  67739. {
  67740. public:
  67741. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  67742. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  67743. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  67744. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  67745. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  67746. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  67747. ~ClipRegion_EdgeTable() {}
  67748. const Ptr clone() const
  67749. {
  67750. return new ClipRegion_EdgeTable (*this);
  67751. }
  67752. const Ptr applyClipTo (const Ptr& target) const
  67753. {
  67754. return target->clipToEdgeTable (edgeTable);
  67755. }
  67756. const Ptr clipToRectangle (const Rectangle<int>& r)
  67757. {
  67758. edgeTable.clipToRectangle (r);
  67759. return edgeTable.isEmpty() ? 0 : this;
  67760. }
  67761. const Ptr clipToRectangleList (const RectangleList& r)
  67762. {
  67763. RectangleList inverse (edgeTable.getMaximumBounds());
  67764. if (inverse.subtract (r))
  67765. for (RectangleList::Iterator iter (inverse); iter.next();)
  67766. edgeTable.excludeRectangle (*iter.getRectangle());
  67767. return edgeTable.isEmpty() ? 0 : this;
  67768. }
  67769. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67770. {
  67771. edgeTable.excludeRectangle (r);
  67772. return edgeTable.isEmpty() ? 0 : this;
  67773. }
  67774. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67775. {
  67776. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  67777. edgeTable.clipToEdgeTable (et);
  67778. return edgeTable.isEmpty() ? 0 : this;
  67779. }
  67780. const Ptr clipToEdgeTable (const EdgeTable& et)
  67781. {
  67782. edgeTable.clipToEdgeTable (et);
  67783. return edgeTable.isEmpty() ? 0 : this;
  67784. }
  67785. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  67786. {
  67787. const Image::BitmapData srcData (image, false);
  67788. if (transform.isOnlyTranslation())
  67789. {
  67790. // If our translation doesn't involve any distortion, just use a simple blit..
  67791. const int tx = (int) (transform.getTranslationX() * 256.0f);
  67792. const int ty = (int) (transform.getTranslationY() * 256.0f);
  67793. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67794. {
  67795. const int imageX = ((tx + 128) >> 8);
  67796. const int imageY = ((ty + 128) >> 8);
  67797. if (image.getFormat() == Image::ARGB)
  67798. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  67799. else
  67800. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  67801. return edgeTable.isEmpty() ? 0 : this;
  67802. }
  67803. }
  67804. if (transform.isSingularity())
  67805. return 0;
  67806. {
  67807. Path p;
  67808. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  67809. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  67810. edgeTable.clipToEdgeTable (et2);
  67811. }
  67812. if (! edgeTable.isEmpty())
  67813. {
  67814. if (image.getFormat() == Image::ARGB)
  67815. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  67816. else
  67817. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  67818. }
  67819. return edgeTable.isEmpty() ? 0 : this;
  67820. }
  67821. bool clipRegionIntersects (const Rectangle<int>& r) const
  67822. {
  67823. return edgeTable.getMaximumBounds().intersects (r);
  67824. }
  67825. const Rectangle<int> getClipBounds() const
  67826. {
  67827. return edgeTable.getMaximumBounds();
  67828. }
  67829. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67830. {
  67831. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  67832. const Rectangle<int> clipped (totalClip.getIntersection (area));
  67833. if (! clipped.isEmpty())
  67834. {
  67835. ClipRegion_EdgeTable et (clipped);
  67836. et.edgeTable.clipToEdgeTable (edgeTable);
  67837. et.fillAllWithColour (destData, colour, replaceContents);
  67838. }
  67839. }
  67840. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67841. {
  67842. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  67843. const Rectangle<float> clipped (totalClip.getIntersection (area));
  67844. if (! clipped.isEmpty())
  67845. {
  67846. ClipRegion_EdgeTable et (clipped);
  67847. et.edgeTable.clipToEdgeTable (edgeTable);
  67848. et.fillAllWithColour (destData, colour, false);
  67849. }
  67850. }
  67851. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67852. {
  67853. switch (destData.pixelFormat)
  67854. {
  67855. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67856. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67857. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67858. }
  67859. }
  67860. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67861. {
  67862. HeapBlock <PixelARGB> lookupTable;
  67863. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67864. jassert (numLookupEntries > 0);
  67865. switch (destData.pixelFormat)
  67866. {
  67867. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67868. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67869. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67870. }
  67871. }
  67872. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67873. {
  67874. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67875. }
  67876. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67877. {
  67878. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  67879. }
  67880. EdgeTable edgeTable;
  67881. private:
  67882. template <class SrcPixelType>
  67883. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  67884. {
  67885. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  67886. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  67887. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  67888. edgeTable.getMaximumBounds().getWidth());
  67889. }
  67890. template <class SrcPixelType>
  67891. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  67892. {
  67893. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  67894. edgeTable.clipToRectangle (r);
  67895. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  67896. for (int y = 0; y < r.getHeight(); ++y)
  67897. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  67898. }
  67899. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  67900. };
  67901. class ClipRegion_RectangleList : public ClipRegionBase
  67902. {
  67903. public:
  67904. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  67905. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  67906. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  67907. ~ClipRegion_RectangleList() {}
  67908. const Ptr clone() const
  67909. {
  67910. return new ClipRegion_RectangleList (*this);
  67911. }
  67912. const Ptr applyClipTo (const Ptr& target) const
  67913. {
  67914. return target->clipToRectangleList (clip);
  67915. }
  67916. const Ptr clipToRectangle (const Rectangle<int>& r)
  67917. {
  67918. clip.clipTo (r);
  67919. return clip.isEmpty() ? 0 : this;
  67920. }
  67921. const Ptr clipToRectangleList (const RectangleList& r)
  67922. {
  67923. clip.clipTo (r);
  67924. return clip.isEmpty() ? 0 : this;
  67925. }
  67926. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67927. {
  67928. clip.subtract (r);
  67929. return clip.isEmpty() ? 0 : this;
  67930. }
  67931. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67932. {
  67933. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  67934. }
  67935. const Ptr clipToEdgeTable (const EdgeTable& et)
  67936. {
  67937. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  67938. }
  67939. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  67940. {
  67941. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  67942. }
  67943. bool clipRegionIntersects (const Rectangle<int>& r) const
  67944. {
  67945. return clip.intersects (r);
  67946. }
  67947. const Rectangle<int> getClipBounds() const
  67948. {
  67949. return clip.getBounds();
  67950. }
  67951. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67952. {
  67953. SubRectangleIterator iter (clip, area);
  67954. switch (destData.pixelFormat)
  67955. {
  67956. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67957. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67958. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67959. }
  67960. }
  67961. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67962. {
  67963. SubRectangleIteratorFloat iter (clip, area);
  67964. switch (destData.pixelFormat)
  67965. {
  67966. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  67967. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  67968. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  67969. }
  67970. }
  67971. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67972. {
  67973. switch (destData.pixelFormat)
  67974. {
  67975. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67976. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67977. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67978. }
  67979. }
  67980. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67981. {
  67982. HeapBlock <PixelARGB> lookupTable;
  67983. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67984. jassert (numLookupEntries > 0);
  67985. switch (destData.pixelFormat)
  67986. {
  67987. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67988. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67989. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67990. }
  67991. }
  67992. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67993. {
  67994. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67995. }
  67996. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67997. {
  67998. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  67999. }
  68000. RectangleList clip;
  68001. template <class Renderer>
  68002. void iterate (Renderer& r) const throw()
  68003. {
  68004. RectangleList::Iterator iter (clip);
  68005. while (iter.next())
  68006. {
  68007. const Rectangle<int> rect (*iter.getRectangle());
  68008. const int x = rect.getX();
  68009. const int w = rect.getWidth();
  68010. jassert (w > 0);
  68011. const int bottom = rect.getBottom();
  68012. for (int y = rect.getY(); y < bottom; ++y)
  68013. {
  68014. r.setEdgeTableYPos (y);
  68015. r.handleEdgeTableLineFull (x, w);
  68016. }
  68017. }
  68018. }
  68019. private:
  68020. class SubRectangleIterator
  68021. {
  68022. public:
  68023. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68024. : clip (clip_), area (area_)
  68025. {
  68026. }
  68027. template <class Renderer>
  68028. void iterate (Renderer& r) const throw()
  68029. {
  68030. RectangleList::Iterator iter (clip);
  68031. while (iter.next())
  68032. {
  68033. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68034. if (! rect.isEmpty())
  68035. {
  68036. const int x = rect.getX();
  68037. const int w = rect.getWidth();
  68038. const int bottom = rect.getBottom();
  68039. for (int y = rect.getY(); y < bottom; ++y)
  68040. {
  68041. r.setEdgeTableYPos (y);
  68042. r.handleEdgeTableLineFull (x, w);
  68043. }
  68044. }
  68045. }
  68046. }
  68047. private:
  68048. const RectangleList& clip;
  68049. const Rectangle<int> area;
  68050. SubRectangleIterator (const SubRectangleIterator&);
  68051. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68052. };
  68053. class SubRectangleIteratorFloat
  68054. {
  68055. public:
  68056. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68057. : clip (clip_), area (area_)
  68058. {
  68059. }
  68060. template <class Renderer>
  68061. void iterate (Renderer& r) const throw()
  68062. {
  68063. int left = roundToInt (area.getX() * 256.0f);
  68064. int top = roundToInt (area.getY() * 256.0f);
  68065. int right = roundToInt (area.getRight() * 256.0f);
  68066. int bottom = roundToInt (area.getBottom() * 256.0f);
  68067. int totalTop, totalLeft, totalBottom, totalRight;
  68068. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68069. if ((top >> 8) == (bottom >> 8))
  68070. {
  68071. topAlpha = bottom - top;
  68072. bottomAlpha = 0;
  68073. totalTop = top >> 8;
  68074. totalBottom = bottom = top = totalTop + 1;
  68075. }
  68076. else
  68077. {
  68078. if ((top & 255) == 0)
  68079. {
  68080. topAlpha = 0;
  68081. top = totalTop = (top >> 8);
  68082. }
  68083. else
  68084. {
  68085. topAlpha = 255 - (top & 255);
  68086. totalTop = (top >> 8);
  68087. top = totalTop + 1;
  68088. }
  68089. bottomAlpha = bottom & 255;
  68090. bottom >>= 8;
  68091. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68092. }
  68093. if ((left >> 8) == (right >> 8))
  68094. {
  68095. leftAlpha = right - left;
  68096. rightAlpha = 0;
  68097. totalLeft = (left >> 8);
  68098. totalRight = right = left = totalLeft + 1;
  68099. }
  68100. else
  68101. {
  68102. if ((left & 255) == 0)
  68103. {
  68104. leftAlpha = 0;
  68105. left = totalLeft = (left >> 8);
  68106. }
  68107. else
  68108. {
  68109. leftAlpha = 255 - (left & 255);
  68110. totalLeft = (left >> 8);
  68111. left = totalLeft + 1;
  68112. }
  68113. rightAlpha = right & 255;
  68114. right >>= 8;
  68115. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68116. }
  68117. RectangleList::Iterator iter (clip);
  68118. while (iter.next())
  68119. {
  68120. const int clipLeft = iter.getRectangle()->getX();
  68121. const int clipRight = iter.getRectangle()->getRight();
  68122. const int clipTop = iter.getRectangle()->getY();
  68123. const int clipBottom = iter.getRectangle()->getBottom();
  68124. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68125. {
  68126. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68127. {
  68128. if (topAlpha != 0 && totalTop >= clipTop)
  68129. {
  68130. r.setEdgeTableYPos (totalTop);
  68131. r.handleEdgeTablePixel (left, topAlpha);
  68132. }
  68133. const int endY = jmin (bottom, clipBottom);
  68134. for (int y = jmax (clipTop, top); y < endY; ++y)
  68135. {
  68136. r.setEdgeTableYPos (y);
  68137. r.handleEdgeTablePixelFull (left);
  68138. }
  68139. if (bottomAlpha != 0 && bottom < clipBottom)
  68140. {
  68141. r.setEdgeTableYPos (bottom);
  68142. r.handleEdgeTablePixel (left, bottomAlpha);
  68143. }
  68144. }
  68145. else
  68146. {
  68147. const int clippedLeft = jmax (left, clipLeft);
  68148. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68149. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68150. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68151. if (topAlpha != 0 && totalTop >= clipTop)
  68152. {
  68153. r.setEdgeTableYPos (totalTop);
  68154. if (doLeftAlpha)
  68155. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68156. if (clippedWidth > 0)
  68157. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68158. if (doRightAlpha)
  68159. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68160. }
  68161. const int endY = jmin (bottom, clipBottom);
  68162. for (int y = jmax (clipTop, top); y < endY; ++y)
  68163. {
  68164. r.setEdgeTableYPos (y);
  68165. if (doLeftAlpha)
  68166. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68167. if (clippedWidth > 0)
  68168. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68169. if (doRightAlpha)
  68170. r.handleEdgeTablePixel (right, rightAlpha);
  68171. }
  68172. if (bottomAlpha != 0 && bottom < clipBottom)
  68173. {
  68174. r.setEdgeTableYPos (bottom);
  68175. if (doLeftAlpha)
  68176. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68177. if (clippedWidth > 0)
  68178. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68179. if (doRightAlpha)
  68180. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68181. }
  68182. }
  68183. }
  68184. }
  68185. }
  68186. private:
  68187. const RectangleList& clip;
  68188. const Rectangle<float>& area;
  68189. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68190. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68191. };
  68192. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68193. };
  68194. }
  68195. class LowLevelGraphicsSoftwareRenderer::SavedState
  68196. {
  68197. public:
  68198. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68199. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68200. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68201. {
  68202. }
  68203. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68204. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68205. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68206. {
  68207. }
  68208. SavedState (const SavedState& other)
  68209. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68210. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68211. {
  68212. }
  68213. ~SavedState()
  68214. {
  68215. }
  68216. void setOrigin (const int x, const int y) throw()
  68217. {
  68218. xOffset += x;
  68219. yOffset += y;
  68220. }
  68221. bool clipToRectangle (const Rectangle<int>& r)
  68222. {
  68223. if (clip != 0)
  68224. {
  68225. cloneClipIfMultiplyReferenced();
  68226. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68227. }
  68228. return clip != 0;
  68229. }
  68230. bool clipToRectangleList (const RectangleList& r)
  68231. {
  68232. if (clip != 0)
  68233. {
  68234. cloneClipIfMultiplyReferenced();
  68235. RectangleList offsetList (r);
  68236. offsetList.offsetAll (xOffset, yOffset);
  68237. clip = clip->clipToRectangleList (offsetList);
  68238. }
  68239. return clip != 0;
  68240. }
  68241. bool excludeClipRectangle (const Rectangle<int>& r)
  68242. {
  68243. if (clip != 0)
  68244. {
  68245. cloneClipIfMultiplyReferenced();
  68246. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68247. }
  68248. return clip != 0;
  68249. }
  68250. void clipToPath (const Path& p, const AffineTransform& transform)
  68251. {
  68252. if (clip != 0)
  68253. {
  68254. cloneClipIfMultiplyReferenced();
  68255. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68256. }
  68257. }
  68258. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68259. {
  68260. if (clip != 0)
  68261. {
  68262. if (image.hasAlphaChannel())
  68263. {
  68264. cloneClipIfMultiplyReferenced();
  68265. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68266. interpolationQuality != Graphics::lowResamplingQuality);
  68267. }
  68268. else
  68269. {
  68270. Path p;
  68271. p.addRectangle (image.getBounds());
  68272. clipToPath (p, t);
  68273. }
  68274. }
  68275. }
  68276. bool clipRegionIntersects (const Rectangle<int>& r) const
  68277. {
  68278. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68279. }
  68280. const Rectangle<int> getClipBounds() const
  68281. {
  68282. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68283. }
  68284. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68285. {
  68286. if (clip != 0)
  68287. {
  68288. if (fillType.isColour())
  68289. {
  68290. Image::BitmapData destData (image, true);
  68291. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68292. }
  68293. else
  68294. {
  68295. const Rectangle<int> totalClip (clip->getClipBounds());
  68296. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68297. if (! clipped.isEmpty())
  68298. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68299. }
  68300. }
  68301. }
  68302. void fillRect (Image& image, const Rectangle<float>& r)
  68303. {
  68304. if (clip != 0)
  68305. {
  68306. if (fillType.isColour())
  68307. {
  68308. Image::BitmapData destData (image, true);
  68309. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68310. }
  68311. else
  68312. {
  68313. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68314. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68315. if (! clipped.isEmpty())
  68316. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68317. }
  68318. }
  68319. }
  68320. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68321. {
  68322. if (clip != 0)
  68323. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68324. }
  68325. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68326. {
  68327. if (clip != 0)
  68328. {
  68329. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68330. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68331. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68332. fillShape (image, shapeToFill, false);
  68333. }
  68334. }
  68335. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68336. {
  68337. jassert (clip != 0);
  68338. shapeToFill = clip->applyClipTo (shapeToFill);
  68339. if (shapeToFill != 0)
  68340. {
  68341. Image::BitmapData destData (image, true);
  68342. if (fillType.isGradient())
  68343. {
  68344. jassert (! replaceContents); // that option is just for solid colours
  68345. ColourGradient g2 (*(fillType.gradient));
  68346. g2.multiplyOpacity (fillType.getOpacity());
  68347. g2.point1.addXY (-0.5f, -0.5f);
  68348. g2.point2.addXY (-0.5f, -0.5f);
  68349. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  68350. const bool isIdentity = transform.isOnlyTranslation();
  68351. if (isIdentity)
  68352. {
  68353. // If our translation doesn't involve any distortion, we can speed it up..
  68354. g2.point1.applyTransform (transform);
  68355. g2.point2.applyTransform (transform);
  68356. transform = AffineTransform::identity;
  68357. }
  68358. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68359. }
  68360. else if (fillType.isTiledImage())
  68361. {
  68362. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68363. }
  68364. else
  68365. {
  68366. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68367. }
  68368. }
  68369. }
  68370. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68371. {
  68372. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68373. const Image::BitmapData destData (destImage, true);
  68374. const Image::BitmapData srcData (sourceImage, false);
  68375. const int alpha = fillType.colour.getAlpha();
  68376. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68377. if (transform.isOnlyTranslation())
  68378. {
  68379. // If our translation doesn't involve any distortion, just use a simple blit..
  68380. int tx = (int) (transform.getTranslationX() * 256.0f);
  68381. int ty = (int) (transform.getTranslationY() * 256.0f);
  68382. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68383. {
  68384. tx = ((tx + 128) >> 8);
  68385. ty = ((ty + 128) >> 8);
  68386. if (tiledFillClipRegion != 0)
  68387. {
  68388. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68389. }
  68390. else
  68391. {
  68392. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  68393. c = clip->applyClipTo (c);
  68394. if (c != 0)
  68395. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68396. }
  68397. return;
  68398. }
  68399. }
  68400. if (transform.isSingularity())
  68401. return;
  68402. if (tiledFillClipRegion != 0)
  68403. {
  68404. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68405. }
  68406. else
  68407. {
  68408. Path p;
  68409. p.addRectangle (sourceImage.getBounds());
  68410. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68411. c = c->clipToPath (p, transform);
  68412. if (c != 0)
  68413. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68414. }
  68415. }
  68416. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68417. int xOffset, yOffset;
  68418. Font font;
  68419. FillType fillType;
  68420. Graphics::ResamplingQuality interpolationQuality;
  68421. private:
  68422. void cloneClipIfMultiplyReferenced()
  68423. {
  68424. if (clip->getReferenceCount() > 1)
  68425. clip = clip->clone();
  68426. }
  68427. SavedState& operator= (const SavedState&);
  68428. };
  68429. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68430. : image (image_)
  68431. {
  68432. currentState = new SavedState (image_.getBounds(), 0, 0);
  68433. }
  68434. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68435. const RectangleList& initialClip)
  68436. : image (image_)
  68437. {
  68438. currentState = new SavedState (initialClip, xOffset, yOffset);
  68439. }
  68440. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68441. {
  68442. }
  68443. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68444. {
  68445. return false;
  68446. }
  68447. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68448. {
  68449. currentState->setOrigin (x, y);
  68450. }
  68451. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68452. {
  68453. return currentState->clipToRectangle (r);
  68454. }
  68455. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68456. {
  68457. return currentState->clipToRectangleList (clipRegion);
  68458. }
  68459. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68460. {
  68461. currentState->excludeClipRectangle (r);
  68462. }
  68463. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68464. {
  68465. currentState->clipToPath (path, transform);
  68466. }
  68467. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68468. {
  68469. currentState->clipToImageAlpha (sourceImage, transform);
  68470. }
  68471. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68472. {
  68473. return currentState->clipRegionIntersects (r);
  68474. }
  68475. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68476. {
  68477. return currentState->getClipBounds();
  68478. }
  68479. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68480. {
  68481. return currentState->clip == 0;
  68482. }
  68483. void LowLevelGraphicsSoftwareRenderer::saveState()
  68484. {
  68485. stateStack.add (new SavedState (*currentState));
  68486. }
  68487. void LowLevelGraphicsSoftwareRenderer::restoreState()
  68488. {
  68489. SavedState* const top = stateStack.getLast();
  68490. if (top != 0)
  68491. {
  68492. currentState = top;
  68493. stateStack.removeLast (1, false);
  68494. }
  68495. else
  68496. {
  68497. jassertfalse; // trying to pop with an empty stack!
  68498. }
  68499. }
  68500. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  68501. {
  68502. currentState->fillType = fillType;
  68503. }
  68504. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  68505. {
  68506. currentState->fillType.setOpacity (newOpacity);
  68507. }
  68508. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  68509. {
  68510. currentState->interpolationQuality = quality;
  68511. }
  68512. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  68513. {
  68514. currentState->fillRect (image, r, replaceExistingContents);
  68515. }
  68516. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  68517. {
  68518. currentState->fillPath (image, path, transform);
  68519. }
  68520. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  68521. {
  68522. currentState->renderImage (image, sourceImage, transform,
  68523. fillEntireClipAsTiles ? currentState->clip : 0);
  68524. }
  68525. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  68526. {
  68527. Path p;
  68528. p.addLineSegment (line, 1.0f);
  68529. fillPath (p, AffineTransform::identity);
  68530. }
  68531. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  68532. {
  68533. if (bottom > top)
  68534. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  68535. }
  68536. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  68537. {
  68538. if (right > left)
  68539. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  68540. }
  68541. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  68542. {
  68543. public:
  68544. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  68545. ~CachedGlyph() {}
  68546. void draw (SavedState& state, Image& image, const float x, const float y) const
  68547. {
  68548. if (edgeTable != 0)
  68549. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  68550. }
  68551. void generate (const Font& newFont, const int glyphNumber)
  68552. {
  68553. font = newFont;
  68554. glyph = glyphNumber;
  68555. edgeTable = 0;
  68556. Path glyphPath;
  68557. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  68558. if (! glyphPath.isEmpty())
  68559. {
  68560. const float fontHeight = font.getHeight();
  68561. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  68562. .translated (0.0f, -0.5f));
  68563. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  68564. glyphPath, transform);
  68565. }
  68566. }
  68567. int glyph, lastAccessCount;
  68568. Font font;
  68569. juce_UseDebuggingNewOperator
  68570. private:
  68571. ScopedPointer <EdgeTable> edgeTable;
  68572. CachedGlyph (const CachedGlyph&);
  68573. CachedGlyph& operator= (const CachedGlyph&);
  68574. };
  68575. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  68576. {
  68577. public:
  68578. GlyphCache()
  68579. : accessCounter (0), hits (0), misses (0)
  68580. {
  68581. for (int i = 120; --i >= 0;)
  68582. glyphs.add (new CachedGlyph());
  68583. }
  68584. ~GlyphCache()
  68585. {
  68586. clearSingletonInstance();
  68587. }
  68588. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  68589. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  68590. {
  68591. ++accessCounter;
  68592. int oldestCounter = std::numeric_limits<int>::max();
  68593. CachedGlyph* oldest = 0;
  68594. for (int i = glyphs.size(); --i >= 0;)
  68595. {
  68596. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  68597. if (glyph->glyph == glyphNumber && glyph->font == font)
  68598. {
  68599. ++hits;
  68600. glyph->lastAccessCount = accessCounter;
  68601. glyph->draw (state, image, x, y);
  68602. return;
  68603. }
  68604. if (glyph->lastAccessCount <= oldestCounter)
  68605. {
  68606. oldestCounter = glyph->lastAccessCount;
  68607. oldest = glyph;
  68608. }
  68609. }
  68610. if (hits + ++misses > (glyphs.size() << 4))
  68611. {
  68612. if (misses * 2 > hits)
  68613. {
  68614. for (int i = 32; --i >= 0;)
  68615. glyphs.add (new CachedGlyph());
  68616. }
  68617. hits = misses = 0;
  68618. oldest = glyphs.getLast();
  68619. }
  68620. jassert (oldest != 0);
  68621. oldest->lastAccessCount = accessCounter;
  68622. oldest->generate (font, glyphNumber);
  68623. oldest->draw (state, image, x, y);
  68624. }
  68625. juce_UseDebuggingNewOperator
  68626. private:
  68627. friend class OwnedArray <CachedGlyph>;
  68628. OwnedArray <CachedGlyph> glyphs;
  68629. int accessCounter, hits, misses;
  68630. GlyphCache (const GlyphCache&);
  68631. GlyphCache& operator= (const GlyphCache&);
  68632. };
  68633. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  68634. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  68635. {
  68636. currentState->font = newFont;
  68637. }
  68638. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  68639. {
  68640. return currentState->font;
  68641. }
  68642. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  68643. {
  68644. Font& f = currentState->font;
  68645. if (transform.isOnlyTranslation())
  68646. {
  68647. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  68648. transform.getTranslationX(),
  68649. transform.getTranslationY());
  68650. }
  68651. else
  68652. {
  68653. Path p;
  68654. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  68655. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  68656. }
  68657. }
  68658. #if JUCE_MSVC
  68659. #pragma warning (pop)
  68660. #if JUCE_DEBUG
  68661. #pragma optimize ("", on) // resets optimisations to the project defaults
  68662. #endif
  68663. #endif
  68664. END_JUCE_NAMESPACE
  68665. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  68666. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  68667. BEGIN_JUCE_NAMESPACE
  68668. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  68669. : flags (other.flags)
  68670. {
  68671. }
  68672. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  68673. {
  68674. flags = other.flags;
  68675. return *this;
  68676. }
  68677. void RectanglePlacement::applyTo (double& x, double& y,
  68678. double& w, double& h,
  68679. const double dx, const double dy,
  68680. const double dw, const double dh) const throw()
  68681. {
  68682. if (w == 0 || h == 0)
  68683. return;
  68684. if ((flags & stretchToFit) != 0)
  68685. {
  68686. x = dx;
  68687. y = dy;
  68688. w = dw;
  68689. h = dh;
  68690. }
  68691. else
  68692. {
  68693. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  68694. : jmin (dw / w, dh / h);
  68695. if ((flags & onlyReduceInSize) != 0)
  68696. scale = jmin (scale, 1.0);
  68697. if ((flags & onlyIncreaseInSize) != 0)
  68698. scale = jmax (scale, 1.0);
  68699. w *= scale;
  68700. h *= scale;
  68701. if ((flags & xLeft) != 0)
  68702. x = dx;
  68703. else if ((flags & xRight) != 0)
  68704. x = dx + dw - w;
  68705. else
  68706. x = dx + (dw - w) * 0.5;
  68707. if ((flags & yTop) != 0)
  68708. y = dy;
  68709. else if ((flags & yBottom) != 0)
  68710. y = dy + dh - h;
  68711. else
  68712. y = dy + (dh - h) * 0.5;
  68713. }
  68714. }
  68715. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  68716. float w, float h,
  68717. const float dx, const float dy,
  68718. const float dw, const float dh) const throw()
  68719. {
  68720. if (w == 0 || h == 0)
  68721. return AffineTransform::identity;
  68722. const float scaleX = dw / w;
  68723. const float scaleY = dh / h;
  68724. if ((flags & stretchToFit) != 0)
  68725. return AffineTransform::translation (-x, -y)
  68726. .scaled (scaleX, scaleY)
  68727. .translated (dx, dy);
  68728. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  68729. : jmin (scaleX, scaleY);
  68730. if ((flags & onlyReduceInSize) != 0)
  68731. scale = jmin (scale, 1.0f);
  68732. if ((flags & onlyIncreaseInSize) != 0)
  68733. scale = jmax (scale, 1.0f);
  68734. w *= scale;
  68735. h *= scale;
  68736. float newX = dx;
  68737. if ((flags & xRight) != 0)
  68738. newX += dw - w; // right
  68739. else if ((flags & xLeft) == 0)
  68740. newX += (dw - w) / 2.0f; // centre
  68741. float newY = dy;
  68742. if ((flags & yBottom) != 0)
  68743. newY += dh - h; // bottom
  68744. else if ((flags & yTop) == 0)
  68745. newY += (dh - h) / 2.0f; // centre
  68746. return AffineTransform::translation (-x, -y)
  68747. .scaled (scale, scale)
  68748. .translated (newX, newY);
  68749. }
  68750. END_JUCE_NAMESPACE
  68751. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  68752. /*** Start of inlined file: juce_Drawable.cpp ***/
  68753. BEGIN_JUCE_NAMESPACE
  68754. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  68755. const AffineTransform& transform_,
  68756. const float opacity_) throw()
  68757. : g (g_),
  68758. transform (transform_),
  68759. opacity (opacity_)
  68760. {
  68761. }
  68762. Drawable::Drawable()
  68763. : parent (0)
  68764. {
  68765. }
  68766. Drawable::~Drawable()
  68767. {
  68768. }
  68769. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  68770. {
  68771. render (RenderingContext (g, transform, opacity));
  68772. }
  68773. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  68774. {
  68775. draw (g, opacity, AffineTransform::translation (x, y));
  68776. }
  68777. void Drawable::drawWithin (Graphics& g,
  68778. const int destX,
  68779. const int destY,
  68780. const int destW,
  68781. const int destH,
  68782. const RectanglePlacement& placement,
  68783. const float opacity) const
  68784. {
  68785. if (destW > 0 && destH > 0)
  68786. {
  68787. Rectangle<float> bounds (getBounds());
  68788. draw (g, opacity,
  68789. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  68790. (float) destX, (float) destY,
  68791. (float) destW, (float) destH));
  68792. }
  68793. }
  68794. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  68795. {
  68796. Drawable* result = 0;
  68797. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  68798. if (image.isValid())
  68799. {
  68800. DrawableImage* const di = new DrawableImage();
  68801. di->setImage (image);
  68802. result = di;
  68803. }
  68804. else
  68805. {
  68806. const String asString (String::createStringFromData (data, (int) numBytes));
  68807. XmlDocument doc (asString);
  68808. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  68809. if (outer != 0 && outer->hasTagName ("svg"))
  68810. {
  68811. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  68812. if (svg != 0)
  68813. result = Drawable::createFromSVG (*svg);
  68814. }
  68815. }
  68816. return result;
  68817. }
  68818. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  68819. {
  68820. MemoryOutputStream mo;
  68821. mo.writeFromInputStream (dataSource, -1);
  68822. return createFromImageData (mo.getData(), mo.getDataSize());
  68823. }
  68824. Drawable* Drawable::createFromImageFile (const File& file)
  68825. {
  68826. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  68827. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  68828. }
  68829. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68830. {
  68831. return createChildFromValueTree (0, tree, imageProvider);
  68832. }
  68833. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  68834. {
  68835. const Identifier type (tree.getType());
  68836. Drawable* d = 0;
  68837. if (type == DrawablePath::valueTreeType)
  68838. d = new DrawablePath();
  68839. else if (type == DrawableComposite::valueTreeType)
  68840. d = new DrawableComposite();
  68841. else if (type == DrawableImage::valueTreeType)
  68842. d = new DrawableImage();
  68843. else if (type == DrawableText::valueTreeType)
  68844. d = new DrawableText();
  68845. if (d != 0)
  68846. {
  68847. d->parent = parent;
  68848. d->refreshFromValueTree (tree, imageProvider);
  68849. }
  68850. return d;
  68851. }
  68852. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  68853. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  68854. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  68855. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  68856. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  68857. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  68858. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  68859. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  68860. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  68861. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  68862. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  68863. : state (state_)
  68864. {
  68865. }
  68866. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  68867. {
  68868. }
  68869. const String Drawable::ValueTreeWrapperBase::getID() const
  68870. {
  68871. return state [idProperty];
  68872. }
  68873. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  68874. {
  68875. if (newID.isEmpty())
  68876. state.removeProperty (idProperty, undoManager);
  68877. else
  68878. state.setProperty (idProperty, newID, undoManager);
  68879. }
  68880. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  68881. RelativeCoordinate::NamedCoordinateFinder* const nameFinder, ImageProvider* imageProvider)
  68882. {
  68883. const String newType (v[type].toString());
  68884. if (newType == "solid")
  68885. {
  68886. const String colourString (v [colour].toString());
  68887. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  68888. : (uint32) colourString.getHexValue32()));
  68889. }
  68890. else if (newType == "gradient")
  68891. {
  68892. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  68893. ColourGradient g;
  68894. if (gp1 != 0) *gp1 = p1;
  68895. if (gp2 != 0) *gp2 = p2;
  68896. if (gp3 != 0) *gp3 = p3;
  68897. g.point1 = p1.resolve (nameFinder);
  68898. g.point2 = p2.resolve (nameFinder);
  68899. g.isRadial = v[radial];
  68900. StringArray colourSteps;
  68901. colourSteps.addTokens (v[colours].toString(), false);
  68902. for (int i = 0; i < colourSteps.size() / 2; ++i)
  68903. g.addColour (colourSteps[i * 2].getDoubleValue(),
  68904. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  68905. FillType fillType (g);
  68906. if (g.isRadial)
  68907. {
  68908. const Point<float> point3 (p3.resolve (nameFinder));
  68909. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  68910. g.point1.getY() + g.point1.getX() - g.point2.getX());
  68911. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  68912. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  68913. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  68914. }
  68915. return fillType;
  68916. }
  68917. else if (newType == "image")
  68918. {
  68919. Image im;
  68920. if (imageProvider != 0)
  68921. im = imageProvider->getImageForIdentifier (v[imageId]);
  68922. FillType f (im, AffineTransform::identity);
  68923. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  68924. return f;
  68925. }
  68926. jassertfalse;
  68927. return FillType();
  68928. }
  68929. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  68930. {
  68931. const ColourGradient& g = *fillType.gradient;
  68932. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  68933. g.point1.getY() + g.point1.getX() - g.point2.getX());
  68934. return point3Source.transformedBy (fillType.transform);
  68935. }
  68936. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  68937. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  68938. ImageProvider* imageProvider, UndoManager* const undoManager)
  68939. {
  68940. if (fillType.isColour())
  68941. {
  68942. v.setProperty (type, "solid", undoManager);
  68943. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  68944. }
  68945. else if (fillType.isGradient())
  68946. {
  68947. v.setProperty (type, "gradient", undoManager);
  68948. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  68949. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  68950. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  68951. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  68952. String s;
  68953. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68954. s << ' ' << fillType.gradient->getColourPosition (i)
  68955. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68956. v.setProperty (colours, s.trimStart(), undoManager);
  68957. }
  68958. else if (fillType.isTiledImage())
  68959. {
  68960. v.setProperty (type, "image", undoManager);
  68961. if (imageProvider != 0)
  68962. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  68963. if (fillType.getOpacity() < 1.0f)
  68964. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  68965. else
  68966. v.removeProperty (imageOpacity, undoManager);
  68967. }
  68968. else
  68969. {
  68970. jassertfalse;
  68971. }
  68972. }
  68973. END_JUCE_NAMESPACE
  68974. /*** End of inlined file: juce_Drawable.cpp ***/
  68975. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  68976. BEGIN_JUCE_NAMESPACE
  68977. DrawableComposite::DrawableComposite()
  68978. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  68979. {
  68980. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  68981. RelativeCoordinate (100.0),
  68982. RelativeCoordinate (0.0),
  68983. RelativeCoordinate (100.0)));
  68984. }
  68985. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  68986. {
  68987. bounds = other.bounds;
  68988. for (int i = 0; i < other.drawables.size(); ++i)
  68989. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  68990. markersX.addCopiesOf (other.markersX);
  68991. markersY.addCopiesOf (other.markersY);
  68992. }
  68993. DrawableComposite::~DrawableComposite()
  68994. {
  68995. }
  68996. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  68997. {
  68998. if (drawable != 0)
  68999. {
  69000. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69001. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69002. drawables.insert (index, drawable);
  69003. drawable->parent = this;
  69004. }
  69005. }
  69006. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69007. {
  69008. insertDrawable (drawable.createCopy(), index);
  69009. }
  69010. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69011. {
  69012. drawables.remove (index, deleteDrawable);
  69013. }
  69014. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69015. {
  69016. for (int i = drawables.size(); --i >= 0;)
  69017. if (drawables.getUnchecked(i)->getName() == name)
  69018. return drawables.getUnchecked(i);
  69019. return 0;
  69020. }
  69021. void DrawableComposite::bringToFront (const int index)
  69022. {
  69023. if (index >= 0 && index < drawables.size() - 1)
  69024. drawables.move (index, -1);
  69025. }
  69026. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69027. {
  69028. bounds = newBoundingBox;
  69029. }
  69030. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69031. : name (other.name), position (other.position)
  69032. {
  69033. }
  69034. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69035. : name (name_), position (position_)
  69036. {
  69037. }
  69038. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69039. {
  69040. return name != other.name || position != other.position;
  69041. }
  69042. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69043. const char* const DrawableComposite::contentRightMarkerName ("right");
  69044. const char* const DrawableComposite::contentTopMarkerName ("top");
  69045. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69046. const RelativeRectangle DrawableComposite::getContentArea() const
  69047. {
  69048. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69049. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69050. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69051. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69052. }
  69053. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69054. {
  69055. setMarker (contentLeftMarkerName, true, newArea.left);
  69056. setMarker (contentRightMarkerName, true, newArea.right);
  69057. setMarker (contentTopMarkerName, false, newArea.top);
  69058. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69059. }
  69060. void DrawableComposite::resetBoundingBoxToContentArea()
  69061. {
  69062. const RelativeRectangle content (getContentArea());
  69063. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69064. RelativePoint (content.right, content.top),
  69065. RelativePoint (content.left, content.bottom)));
  69066. }
  69067. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69068. {
  69069. const Rectangle<float> bounds (getUntransformedBounds (false));
  69070. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69071. RelativeCoordinate (bounds.getRight()),
  69072. RelativeCoordinate (bounds.getY()),
  69073. RelativeCoordinate (bounds.getBottom())));
  69074. resetBoundingBoxToContentArea();
  69075. }
  69076. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69077. {
  69078. return (xAxis ? markersX : markersY).size();
  69079. }
  69080. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69081. {
  69082. return (xAxis ? markersX : markersY) [index];
  69083. }
  69084. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69085. {
  69086. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69087. for (int i = 0; i < markers.size(); ++i)
  69088. {
  69089. Marker* const m = markers.getUnchecked(i);
  69090. if (m->name == name)
  69091. {
  69092. if (m->position != position)
  69093. {
  69094. m->position = position;
  69095. invalidatePoints();
  69096. }
  69097. return;
  69098. }
  69099. }
  69100. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69101. invalidatePoints();
  69102. }
  69103. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69104. {
  69105. jassert (index >= 2);
  69106. if (index >= 2)
  69107. (xAxis ? markersX : markersY).remove (index);
  69108. }
  69109. const AffineTransform DrawableComposite::calculateTransform() const
  69110. {
  69111. Point<float> resolved[3];
  69112. bounds.resolveThreePoints (resolved, parent);
  69113. const Rectangle<float> content (getContentArea().resolve (parent));
  69114. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69115. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69116. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69117. }
  69118. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69119. {
  69120. if (drawables.size() > 0 && context.opacity > 0)
  69121. {
  69122. if (context.opacity >= 1.0f || drawables.size() == 1)
  69123. {
  69124. Drawable::RenderingContext contextCopy (context);
  69125. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69126. for (int i = 0; i < drawables.size(); ++i)
  69127. drawables.getUnchecked(i)->render (contextCopy);
  69128. }
  69129. else
  69130. {
  69131. // To correctly render a whole composite layer with an overall transparency,
  69132. // we need to render everything opaquely into a temp buffer, then blend that
  69133. // with the target opacity...
  69134. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69135. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69136. {
  69137. Graphics tempG (tempImage);
  69138. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69139. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69140. render (tempContext);
  69141. }
  69142. context.g.setOpacity (context.opacity);
  69143. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69144. }
  69145. }
  69146. }
  69147. const RelativeCoordinate DrawableComposite::findNamedCoordinate (const String& objectName, const String& edge) const
  69148. {
  69149. if (objectName == RelativeCoordinate::Strings::parent)
  69150. {
  69151. if (edge == RelativeCoordinate::Strings::right || edge == RelativeCoordinate::Strings::bottom)
  69152. {
  69153. jassertfalse; // a Drawable doesn't have a fixed right-hand or bottom edge - use a marker instead if you need a point of reference.
  69154. return RelativeCoordinate (100.0);
  69155. }
  69156. }
  69157. int i;
  69158. for (i = 0; i < markersX.size(); ++i)
  69159. {
  69160. Marker* const m = markersX.getUnchecked(i);
  69161. if (m->name == objectName)
  69162. return m->position;
  69163. }
  69164. for (i = 0; i < markersY.size(); ++i)
  69165. {
  69166. Marker* const m = markersY.getUnchecked(i);
  69167. if (m->name == objectName)
  69168. return m->position;
  69169. }
  69170. return RelativeCoordinate();
  69171. }
  69172. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69173. {
  69174. Rectangle<float> bounds;
  69175. int i;
  69176. for (i = 0; i < drawables.size(); ++i)
  69177. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69178. if (includeMarkers)
  69179. {
  69180. if (markersX.size() > 0)
  69181. {
  69182. float minX = std::numeric_limits<float>::max();
  69183. float maxX = std::numeric_limits<float>::min();
  69184. for (i = markersX.size(); --i >= 0;)
  69185. {
  69186. const Marker* m = markersX.getUnchecked(i);
  69187. const float pos = (float) m->position.resolve (this);
  69188. minX = jmin (minX, pos);
  69189. maxX = jmax (maxX, pos);
  69190. }
  69191. if (minX <= maxX)
  69192. {
  69193. if (bounds.getHeight() > 0)
  69194. {
  69195. minX = jmin (minX, bounds.getX());
  69196. maxX = jmax (maxX, bounds.getRight());
  69197. }
  69198. bounds.setLeft (minX);
  69199. bounds.setWidth (maxX - minX);
  69200. }
  69201. }
  69202. if (markersY.size() > 0)
  69203. {
  69204. float minY = std::numeric_limits<float>::max();
  69205. float maxY = std::numeric_limits<float>::min();
  69206. for (i = markersY.size(); --i >= 0;)
  69207. {
  69208. const Marker* m = markersY.getUnchecked(i);
  69209. const float pos = (float) m->position.resolve (this);
  69210. minY = jmin (minY, pos);
  69211. maxY = jmax (maxY, pos);
  69212. }
  69213. if (minY <= maxY)
  69214. {
  69215. if (bounds.getHeight() > 0)
  69216. {
  69217. minY = jmin (minY, bounds.getY());
  69218. maxY = jmax (maxY, bounds.getBottom());
  69219. }
  69220. bounds.setTop (minY);
  69221. bounds.setHeight (maxY - minY);
  69222. }
  69223. }
  69224. }
  69225. return bounds;
  69226. }
  69227. const Rectangle<float> DrawableComposite::getBounds() const
  69228. {
  69229. return getUntransformedBounds (true).transformed (calculateTransform());
  69230. }
  69231. bool DrawableComposite::hitTest (float x, float y) const
  69232. {
  69233. calculateTransform().inverted().transformPoint (x, y);
  69234. for (int i = 0; i < drawables.size(); ++i)
  69235. if (drawables.getUnchecked(i)->hitTest (x, y))
  69236. return true;
  69237. return false;
  69238. }
  69239. Drawable* DrawableComposite::createCopy() const
  69240. {
  69241. return new DrawableComposite (*this);
  69242. }
  69243. void DrawableComposite::invalidatePoints()
  69244. {
  69245. for (int i = 0; i < drawables.size(); ++i)
  69246. drawables.getUnchecked(i)->invalidatePoints();
  69247. }
  69248. const Identifier DrawableComposite::valueTreeType ("Group");
  69249. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69250. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69251. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69252. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69253. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69254. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69255. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69256. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69257. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69258. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69259. : ValueTreeWrapperBase (state_)
  69260. {
  69261. jassert (state.hasType (valueTreeType));
  69262. }
  69263. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69264. {
  69265. return state.getChildWithName (childGroupTag);
  69266. }
  69267. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69268. {
  69269. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69270. }
  69271. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69272. {
  69273. return getChildList().getNumChildren();
  69274. }
  69275. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69276. {
  69277. return getChildList().getChild (index);
  69278. }
  69279. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69280. {
  69281. if (getID() == objectId)
  69282. return state;
  69283. if (! recursive)
  69284. {
  69285. return getChildList().getChildWithProperty (idProperty, objectId);
  69286. }
  69287. else
  69288. {
  69289. const ValueTree childList (getChildList());
  69290. for (int i = getNumDrawables(); --i >= 0;)
  69291. {
  69292. const ValueTree& child = childList.getChild (i);
  69293. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69294. return child;
  69295. if (child.hasType (DrawableComposite::valueTreeType))
  69296. {
  69297. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69298. if (v.isValid())
  69299. return v;
  69300. }
  69301. }
  69302. return ValueTree::invalid;
  69303. }
  69304. }
  69305. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69306. {
  69307. return getChildList().indexOf (item);
  69308. }
  69309. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69310. {
  69311. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69312. }
  69313. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69314. {
  69315. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69316. }
  69317. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69318. {
  69319. getChildList().removeChild (child, undoManager);
  69320. }
  69321. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69322. {
  69323. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69324. state.getProperty (topRight, "100, 0"),
  69325. state.getProperty (bottomLeft, "0, 100"));
  69326. }
  69327. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69328. {
  69329. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69330. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69331. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69332. }
  69333. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69334. {
  69335. const RelativeRectangle content (getContentArea());
  69336. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69337. RelativePoint (content.right, content.top),
  69338. RelativePoint (content.left, content.bottom)), undoManager);
  69339. }
  69340. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69341. {
  69342. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69343. getMarker (true, getMarkerState (true, 1)).position,
  69344. getMarker (false, getMarkerState (false, 0)).position,
  69345. getMarker (false, getMarkerState (false, 1)).position);
  69346. }
  69347. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69348. {
  69349. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69350. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69351. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69352. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69353. }
  69354. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69355. {
  69356. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69357. }
  69358. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69359. {
  69360. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69361. }
  69362. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69363. {
  69364. return getMarkerList (xAxis).getNumChildren();
  69365. }
  69366. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69367. {
  69368. return getMarkerList (xAxis).getChild (index);
  69369. }
  69370. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69371. {
  69372. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69373. }
  69374. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69375. {
  69376. return state.isAChildOf (getMarkerList (xAxis));
  69377. }
  69378. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  69379. {
  69380. jassert (containsMarker (xAxis, state));
  69381. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString(), xAxis));
  69382. }
  69383. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  69384. {
  69385. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  69386. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  69387. if (marker.isValid())
  69388. {
  69389. marker.setProperty (posProperty, m.position.toString(), undoManager);
  69390. }
  69391. else
  69392. {
  69393. marker = ValueTree (markerTag);
  69394. marker.setProperty (nameProperty, m.name, 0);
  69395. marker.setProperty (posProperty, m.position.toString(), 0);
  69396. markerList.addChild (marker, -1, undoManager);
  69397. }
  69398. }
  69399. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  69400. {
  69401. if (state [nameProperty].toString() != contentLeftMarkerName
  69402. && state [nameProperty].toString() != contentRightMarkerName
  69403. && state [nameProperty].toString() != contentTopMarkerName
  69404. && state [nameProperty].toString() != contentBottomMarkerName)
  69405. return getMarkerList (xAxis).removeChild (state, undoManager);
  69406. }
  69407. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69408. {
  69409. const ValueTreeWrapper wrapper (tree);
  69410. setName (wrapper.getID());
  69411. Rectangle<float> damage;
  69412. bool redrawAll = false;
  69413. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  69414. if (bounds != newBounds)
  69415. {
  69416. redrawAll = true;
  69417. damage = getBounds();
  69418. bounds = newBounds;
  69419. }
  69420. const int numMarkersX = wrapper.getNumMarkers (true);
  69421. const int numMarkersY = wrapper.getNumMarkers (false);
  69422. // Remove deleted markers...
  69423. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  69424. {
  69425. if (! redrawAll)
  69426. {
  69427. redrawAll = true;
  69428. damage = getBounds();
  69429. }
  69430. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  69431. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  69432. }
  69433. // Update markers and add new ones..
  69434. int i;
  69435. for (i = 0; i < numMarkersX; ++i)
  69436. {
  69437. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  69438. Marker* m = markersX[i];
  69439. if (m == 0 || newMarker != *m)
  69440. {
  69441. if (! redrawAll)
  69442. {
  69443. redrawAll = true;
  69444. damage = getBounds();
  69445. }
  69446. if (m == 0)
  69447. markersX.add (new Marker (newMarker));
  69448. else
  69449. *m = newMarker;
  69450. }
  69451. }
  69452. for (i = 0; i < numMarkersY; ++i)
  69453. {
  69454. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  69455. Marker* m = markersY[i];
  69456. if (m == 0 || newMarker != *m)
  69457. {
  69458. if (! redrawAll)
  69459. {
  69460. redrawAll = true;
  69461. damage = getBounds();
  69462. }
  69463. if (m == 0)
  69464. markersY.add (new Marker (newMarker));
  69465. else
  69466. *m = newMarker;
  69467. }
  69468. }
  69469. // Remove deleted drawables..
  69470. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  69471. {
  69472. Drawable* const d = drawables.getUnchecked(i);
  69473. if (! redrawAll)
  69474. damage = damage.getUnion (d->getBounds());
  69475. d->parent = 0;
  69476. drawables.remove (i);
  69477. }
  69478. // Update drawables and add new ones..
  69479. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  69480. {
  69481. const ValueTree newDrawable (wrapper.getDrawableState (i));
  69482. Drawable* d = drawables[i];
  69483. if (d != 0)
  69484. {
  69485. if (newDrawable.hasType (d->getValueTreeType()))
  69486. {
  69487. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  69488. if (! redrawAll)
  69489. damage = damage.getUnion (area);
  69490. }
  69491. else
  69492. {
  69493. if (! redrawAll)
  69494. damage = damage.getUnion (d->getBounds());
  69495. d = createChildFromValueTree (this, newDrawable, imageProvider);
  69496. drawables.set (i, d);
  69497. if (! redrawAll)
  69498. damage = damage.getUnion (d->getBounds());
  69499. }
  69500. }
  69501. else
  69502. {
  69503. d = createChildFromValueTree (this, newDrawable, imageProvider);
  69504. drawables.set (i, d);
  69505. if (! redrawAll)
  69506. damage = damage.getUnion (d->getBounds());
  69507. }
  69508. }
  69509. if (redrawAll)
  69510. damage = damage.getUnion (getBounds());
  69511. else if (! damage.isEmpty())
  69512. damage = damage.transformed (calculateTransform());
  69513. return damage;
  69514. }
  69515. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  69516. {
  69517. ValueTree tree (valueTreeType);
  69518. ValueTreeWrapper v (tree);
  69519. v.setID (getName(), 0);
  69520. v.setBoundingBox (bounds, 0);
  69521. int i;
  69522. for (i = 0; i < drawables.size(); ++i)
  69523. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  69524. for (i = 0; i < markersX.size(); ++i)
  69525. v.setMarker (true, *markersX.getUnchecked(i), 0);
  69526. for (i = 0; i < markersY.size(); ++i)
  69527. v.setMarker (false, *markersY.getUnchecked(i), 0);
  69528. return tree;
  69529. }
  69530. END_JUCE_NAMESPACE
  69531. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  69532. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  69533. BEGIN_JUCE_NAMESPACE
  69534. DrawableImage::DrawableImage()
  69535. : image (0),
  69536. opacity (1.0f),
  69537. overlayColour (0x00000000)
  69538. {
  69539. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  69540. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  69541. }
  69542. DrawableImage::DrawableImage (const DrawableImage& other)
  69543. : image (other.image),
  69544. opacity (other.opacity),
  69545. overlayColour (other.overlayColour),
  69546. bounds (other.bounds)
  69547. {
  69548. }
  69549. DrawableImage::~DrawableImage()
  69550. {
  69551. }
  69552. void DrawableImage::setImage (const Image& imageToUse)
  69553. {
  69554. image = imageToUse;
  69555. if (image.isValid())
  69556. {
  69557. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  69558. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  69559. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  69560. }
  69561. }
  69562. void DrawableImage::setOpacity (const float newOpacity)
  69563. {
  69564. opacity = newOpacity;
  69565. }
  69566. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  69567. {
  69568. overlayColour = newOverlayColour;
  69569. }
  69570. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  69571. {
  69572. bounds = newBounds;
  69573. }
  69574. const AffineTransform DrawableImage::calculateTransform() const
  69575. {
  69576. if (image.isNull())
  69577. return AffineTransform::identity;
  69578. Point<float> resolved[3];
  69579. bounds.resolveThreePoints (resolved, parent);
  69580. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  69581. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  69582. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  69583. tr.getX(), tr.getY(),
  69584. bl.getX(), bl.getY());
  69585. }
  69586. void DrawableImage::render (const Drawable::RenderingContext& context) const
  69587. {
  69588. if (image.isValid())
  69589. {
  69590. const AffineTransform t (calculateTransform().followedBy (context.transform));
  69591. if (opacity > 0.0f && ! overlayColour.isOpaque())
  69592. {
  69593. context.g.setOpacity (context.opacity * opacity);
  69594. context.g.drawImageTransformed (image, t, false);
  69595. }
  69596. if (! overlayColour.isTransparent())
  69597. {
  69598. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  69599. context.g.drawImageTransformed (image, t, true);
  69600. }
  69601. }
  69602. }
  69603. const Rectangle<float> DrawableImage::getBounds() const
  69604. {
  69605. if (image.isNull())
  69606. return Rectangle<float>();
  69607. return bounds.getBounds (parent);
  69608. }
  69609. bool DrawableImage::hitTest (float x, float y) const
  69610. {
  69611. if (image.isNull())
  69612. return false;
  69613. calculateTransform().inverted().transformPoint (x, y);
  69614. const int ix = roundToInt (x);
  69615. const int iy = roundToInt (y);
  69616. return ix >= 0
  69617. && iy >= 0
  69618. && ix < image.getWidth()
  69619. && iy < image.getHeight()
  69620. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  69621. }
  69622. Drawable* DrawableImage::createCopy() const
  69623. {
  69624. return new DrawableImage (*this);
  69625. }
  69626. void DrawableImage::invalidatePoints()
  69627. {
  69628. }
  69629. const Identifier DrawableImage::valueTreeType ("Image");
  69630. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  69631. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  69632. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  69633. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  69634. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  69635. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69636. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69637. : ValueTreeWrapperBase (state_)
  69638. {
  69639. jassert (state.hasType (valueTreeType));
  69640. }
  69641. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  69642. {
  69643. return state [image];
  69644. }
  69645. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  69646. {
  69647. return state.getPropertyAsValue (image, undoManager);
  69648. }
  69649. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  69650. {
  69651. state.setProperty (image, newIdentifier, undoManager);
  69652. }
  69653. float DrawableImage::ValueTreeWrapper::getOpacity() const
  69654. {
  69655. return (float) state.getProperty (opacity, 1.0);
  69656. }
  69657. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  69658. {
  69659. if (! state.hasProperty (opacity))
  69660. state.setProperty (opacity, 1.0, undoManager);
  69661. return state.getPropertyAsValue (opacity, undoManager);
  69662. }
  69663. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  69664. {
  69665. state.setProperty (opacity, newOpacity, undoManager);
  69666. }
  69667. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  69668. {
  69669. return Colour (state [overlay].toString().getHexValue32());
  69670. }
  69671. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  69672. {
  69673. if (newColour.isTransparent())
  69674. state.removeProperty (overlay, undoManager);
  69675. else
  69676. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  69677. }
  69678. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  69679. {
  69680. return state.getPropertyAsValue (overlay, undoManager);
  69681. }
  69682. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  69683. {
  69684. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69685. state.getProperty (topRight, "100, 0"),
  69686. state.getProperty (bottomLeft, "0, 100"));
  69687. }
  69688. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69689. {
  69690. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69691. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69692. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69693. }
  69694. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69695. {
  69696. const ValueTreeWrapper controller (tree);
  69697. setName (controller.getID());
  69698. const float newOpacity = controller.getOpacity();
  69699. const Colour newOverlayColour (controller.getOverlayColour());
  69700. Image newImage;
  69701. const var imageIdentifier (controller.getImageIdentifier());
  69702. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  69703. if (imageProvider != 0)
  69704. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  69705. const RelativeParallelogram newBounds (controller.getBoundingBox());
  69706. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  69707. {
  69708. const Rectangle<float> damage (getBounds());
  69709. opacity = newOpacity;
  69710. overlayColour = newOverlayColour;
  69711. bounds = newBounds;
  69712. image = newImage;
  69713. return damage.getUnion (getBounds());
  69714. }
  69715. return Rectangle<float>();
  69716. }
  69717. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  69718. {
  69719. ValueTree tree (valueTreeType);
  69720. ValueTreeWrapper v (tree);
  69721. v.setID (getName(), 0);
  69722. v.setOpacity (opacity, 0);
  69723. v.setOverlayColour (overlayColour, 0);
  69724. v.setBoundingBox (bounds, 0);
  69725. if (image.isValid())
  69726. {
  69727. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  69728. if (imageProvider != 0)
  69729. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  69730. }
  69731. return tree;
  69732. }
  69733. END_JUCE_NAMESPACE
  69734. /*** End of inlined file: juce_DrawableImage.cpp ***/
  69735. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  69736. BEGIN_JUCE_NAMESPACE
  69737. DrawablePath::DrawablePath()
  69738. : mainFill (Colours::black),
  69739. strokeFill (Colours::black),
  69740. strokeType (0.0f),
  69741. pathNeedsUpdating (true),
  69742. strokeNeedsUpdating (true)
  69743. {
  69744. }
  69745. DrawablePath::DrawablePath (const DrawablePath& other)
  69746. : mainFill (other.mainFill),
  69747. strokeFill (other.strokeFill),
  69748. strokeType (other.strokeType),
  69749. pathNeedsUpdating (true),
  69750. strokeNeedsUpdating (true)
  69751. {
  69752. if (other.relativePath != 0)
  69753. relativePath = new RelativePointPath (*other.relativePath);
  69754. else
  69755. path = other.path;
  69756. }
  69757. DrawablePath::~DrawablePath()
  69758. {
  69759. }
  69760. void DrawablePath::setPath (const Path& newPath)
  69761. {
  69762. path = newPath;
  69763. strokeNeedsUpdating = true;
  69764. }
  69765. void DrawablePath::setFill (const FillType& newFill)
  69766. {
  69767. mainFill = newFill;
  69768. }
  69769. void DrawablePath::setStrokeFill (const FillType& newFill)
  69770. {
  69771. strokeFill = newFill;
  69772. }
  69773. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  69774. {
  69775. strokeType = newStrokeType;
  69776. strokeNeedsUpdating = true;
  69777. }
  69778. void DrawablePath::setStrokeThickness (const float newThickness)
  69779. {
  69780. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69781. }
  69782. void DrawablePath::updatePath() const
  69783. {
  69784. if (pathNeedsUpdating)
  69785. {
  69786. pathNeedsUpdating = false;
  69787. if (relativePath != 0)
  69788. {
  69789. path.clear();
  69790. relativePath->createPath (path, parent);
  69791. strokeNeedsUpdating = true;
  69792. }
  69793. }
  69794. }
  69795. void DrawablePath::updateStroke() const
  69796. {
  69797. if (strokeNeedsUpdating)
  69798. {
  69799. strokeNeedsUpdating = false;
  69800. updatePath();
  69801. stroke.clear();
  69802. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  69803. }
  69804. }
  69805. const Path& DrawablePath::getPath() const
  69806. {
  69807. updatePath();
  69808. return path;
  69809. }
  69810. const Path& DrawablePath::getStrokePath() const
  69811. {
  69812. updateStroke();
  69813. return stroke;
  69814. }
  69815. bool DrawablePath::isStrokeVisible() const throw()
  69816. {
  69817. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69818. }
  69819. void DrawablePath::invalidatePoints()
  69820. {
  69821. pathNeedsUpdating = true;
  69822. strokeNeedsUpdating = true;
  69823. }
  69824. void DrawablePath::render (const Drawable::RenderingContext& context) const
  69825. {
  69826. {
  69827. FillType f (mainFill);
  69828. if (f.isGradient())
  69829. f.gradient->multiplyOpacity (context.opacity);
  69830. f.transform = f.transform.followedBy (context.transform);
  69831. context.g.setFillType (f);
  69832. context.g.fillPath (getPath(), context.transform);
  69833. }
  69834. if (isStrokeVisible())
  69835. {
  69836. FillType f (strokeFill);
  69837. if (f.isGradient())
  69838. f.gradient->multiplyOpacity (context.opacity);
  69839. f.transform = f.transform.followedBy (context.transform);
  69840. context.g.setFillType (f);
  69841. context.g.fillPath (getStrokePath(), context.transform);
  69842. }
  69843. }
  69844. const Rectangle<float> DrawablePath::getBounds() const
  69845. {
  69846. if (isStrokeVisible())
  69847. return getStrokePath().getBounds();
  69848. else
  69849. return getPath().getBounds();
  69850. }
  69851. bool DrawablePath::hitTest (float x, float y) const
  69852. {
  69853. return getPath().contains (x, y)
  69854. || (isStrokeVisible() && getStrokePath().contains (x, y));
  69855. }
  69856. Drawable* DrawablePath::createCopy() const
  69857. {
  69858. return new DrawablePath (*this);
  69859. }
  69860. const Identifier DrawablePath::valueTreeType ("Path");
  69861. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  69862. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  69863. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  69864. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  69865. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  69866. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  69867. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  69868. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  69869. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  69870. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  69871. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69872. : ValueTreeWrapperBase (state_)
  69873. {
  69874. jassert (state.hasType (valueTreeType));
  69875. }
  69876. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  69877. {
  69878. return state.getOrCreateChildWithName (path, 0);
  69879. }
  69880. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  69881. {
  69882. ValueTree v (state.getChildWithName (fill));
  69883. if (v.isValid())
  69884. return v;
  69885. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69886. return getMainFillState();
  69887. }
  69888. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  69889. {
  69890. ValueTree v (state.getChildWithName (stroke));
  69891. if (v.isValid())
  69892. return v;
  69893. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69894. return getStrokeFillState();
  69895. }
  69896. const FillType DrawablePath::ValueTreeWrapper::getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69897. ImageProvider* imageProvider) const
  69898. {
  69899. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69900. }
  69901. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  69902. const RelativePoint* gp2, const RelativePoint* gp3,
  69903. ImageProvider* imageProvider, UndoManager* undoManager)
  69904. {
  69905. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69906. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69907. }
  69908. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69909. ImageProvider* imageProvider) const
  69910. {
  69911. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69912. }
  69913. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  69914. const RelativePoint* gp2, const RelativePoint* gp3,
  69915. ImageProvider* imageProvider, UndoManager* undoManager)
  69916. {
  69917. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69918. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69919. }
  69920. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  69921. {
  69922. const String jointStyleString (state [jointStyle].toString());
  69923. const String capStyleString (state [capStyle].toString());
  69924. return PathStrokeType (state [strokeWidth],
  69925. jointStyleString == "curved" ? PathStrokeType::curved
  69926. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69927. : PathStrokeType::mitered),
  69928. capStyleString == "square" ? PathStrokeType::square
  69929. : (capStyleString == "round" ? PathStrokeType::rounded
  69930. : PathStrokeType::butt));
  69931. }
  69932. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69933. {
  69934. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69935. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69936. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69937. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69938. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69939. }
  69940. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  69941. {
  69942. return state [nonZeroWinding];
  69943. }
  69944. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  69945. {
  69946. state.setProperty (nonZeroWinding, b, undoManager);
  69947. }
  69948. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  69949. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  69950. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  69951. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  69952. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  69953. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  69954. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  69955. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  69956. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  69957. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  69958. : state (state_)
  69959. {
  69960. }
  69961. DrawablePath::ValueTreeWrapper::Element::~Element()
  69962. {
  69963. }
  69964. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  69965. {
  69966. return ValueTreeWrapper (state.getParent().getParent());
  69967. }
  69968. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  69969. {
  69970. return Element (state.getSibling (-1));
  69971. }
  69972. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  69973. {
  69974. const Identifier i (state.getType());
  69975. if (i == startSubPathElement || i == lineToElement) return 1;
  69976. if (i == quadraticToElement) return 2;
  69977. if (i == cubicToElement) return 3;
  69978. return 0;
  69979. }
  69980. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  69981. {
  69982. jassert (index >= 0 && index < getNumControlPoints());
  69983. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  69984. }
  69985. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  69986. {
  69987. jassert (index >= 0 && index < getNumControlPoints());
  69988. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  69989. }
  69990. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  69991. {
  69992. jassert (index >= 0 && index < getNumControlPoints());
  69993. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  69994. }
  69995. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  69996. {
  69997. const Identifier i (state.getType());
  69998. if (i == startSubPathElement)
  69999. return getControlPoint (0);
  70000. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70001. return getPreviousElement().getEndPoint();
  70002. }
  70003. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70004. {
  70005. const Identifier i (state.getType());
  70006. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70007. if (i == quadraticToElement) return getControlPoint (1);
  70008. if (i == cubicToElement) return getControlPoint (2);
  70009. jassert (i == closeSubPathElement);
  70010. return RelativePoint();
  70011. }
  70012. float DrawablePath::ValueTreeWrapper::Element::getLength (RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  70013. {
  70014. const Identifier i (state.getType());
  70015. if (i == lineToElement || i == closeSubPathElement)
  70016. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70017. if (i == cubicToElement)
  70018. {
  70019. Path p;
  70020. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70021. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70022. return p.getLength();
  70023. }
  70024. if (i == quadraticToElement)
  70025. {
  70026. Path p;
  70027. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70028. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70029. return p.getLength();
  70030. }
  70031. jassert (i == startSubPathElement);
  70032. return 0;
  70033. }
  70034. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70035. {
  70036. return state [mode].toString();
  70037. }
  70038. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70039. {
  70040. if (state.hasType (cubicToElement))
  70041. state.setProperty (mode, newMode, undoManager);
  70042. }
  70043. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70044. {
  70045. const Identifier i (state.getType());
  70046. if (i == quadraticToElement || i == cubicToElement)
  70047. {
  70048. ValueTree newState (lineToElement);
  70049. Element e (newState);
  70050. e.setControlPoint (0, getEndPoint(), undoManager);
  70051. state = newState;
  70052. }
  70053. }
  70054. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager)
  70055. {
  70056. const Identifier i (state.getType());
  70057. if (i == lineToElement || i == quadraticToElement)
  70058. {
  70059. ValueTree newState (cubicToElement);
  70060. Element e (newState);
  70061. const RelativePoint start (getStartPoint());
  70062. const RelativePoint end (getEndPoint());
  70063. const Point<float> startResolved (start.resolve (nameFinder));
  70064. const Point<float> endResolved (end.resolve (nameFinder));
  70065. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70066. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70067. e.setControlPoint (2, end, undoManager);
  70068. state = newState;
  70069. }
  70070. }
  70071. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70072. {
  70073. const Identifier i (state.getType());
  70074. if (i != startSubPathElement)
  70075. {
  70076. ValueTree newState (startSubPathElement);
  70077. Element e (newState);
  70078. e.setControlPoint (0, getEndPoint(), undoManager);
  70079. state = newState;
  70080. }
  70081. }
  70082. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70083. {
  70084. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70085. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70086. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70087. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70088. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70089. return newCp1 + (newCp2 - newCp1) * proportion;
  70090. }
  70091. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70092. {
  70093. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70094. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70095. return mid1 + (mid2 - mid1) * proportion;
  70096. }
  70097. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  70098. {
  70099. const Identifier i (state.getType());
  70100. float bestProp = 0;
  70101. if (i == cubicToElement)
  70102. {
  70103. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70104. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70105. float bestDistance = std::numeric_limits<float>::max();
  70106. for (int i = 110; --i >= 0;)
  70107. {
  70108. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70109. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70110. const float distance = centre.getDistanceFrom (targetPoint);
  70111. if (distance < bestDistance)
  70112. {
  70113. bestProp = prop;
  70114. bestDistance = distance;
  70115. }
  70116. }
  70117. }
  70118. else if (i == quadraticToElement)
  70119. {
  70120. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70121. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70122. float bestDistance = std::numeric_limits<float>::max();
  70123. for (int i = 110; --i >= 0;)
  70124. {
  70125. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70126. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70127. const float distance = centre.getDistanceFrom (targetPoint);
  70128. if (distance < bestDistance)
  70129. {
  70130. bestProp = prop;
  70131. bestDistance = distance;
  70132. }
  70133. }
  70134. }
  70135. else if (i == lineToElement)
  70136. {
  70137. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70138. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70139. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70140. }
  70141. return bestProp;
  70142. }
  70143. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager)
  70144. {
  70145. ValueTree newTree;
  70146. const Identifier i (state.getType());
  70147. if (i == cubicToElement)
  70148. {
  70149. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70150. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70151. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70152. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70153. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70154. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70155. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70156. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70157. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70158. setControlPoint (0, mid1, undoManager);
  70159. setControlPoint (1, newCp1, undoManager);
  70160. setControlPoint (2, newCentre, undoManager);
  70161. setModeOfEndPoint (roundedMode, undoManager);
  70162. Element newElement (newTree = ValueTree (cubicToElement));
  70163. newElement.setControlPoint (0, newCp2, 0);
  70164. newElement.setControlPoint (1, mid3, 0);
  70165. newElement.setControlPoint (2, rp4, 0);
  70166. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70167. }
  70168. else if (i == quadraticToElement)
  70169. {
  70170. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70171. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70172. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70173. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70174. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70175. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70176. setControlPoint (0, mid1, undoManager);
  70177. setControlPoint (1, newCentre, undoManager);
  70178. setModeOfEndPoint (roundedMode, undoManager);
  70179. Element newElement (newTree = ValueTree (quadraticToElement));
  70180. newElement.setControlPoint (0, mid2, 0);
  70181. newElement.setControlPoint (1, rp3, 0);
  70182. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70183. }
  70184. else if (i == lineToElement)
  70185. {
  70186. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70187. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70188. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70189. setControlPoint (0, newPoint, undoManager);
  70190. Element newElement (newTree = ValueTree (lineToElement));
  70191. newElement.setControlPoint (0, rp2, 0);
  70192. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70193. }
  70194. else if (i == closeSubPathElement)
  70195. {
  70196. }
  70197. return newTree;
  70198. }
  70199. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70200. {
  70201. state.getParent().removeChild (state, undoManager);
  70202. }
  70203. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70204. {
  70205. Rectangle<float> damageRect;
  70206. ValueTreeWrapper v (tree);
  70207. setName (v.getID());
  70208. bool needsRedraw = false;
  70209. const FillType newFill (v.getMainFill (parent, imageProvider));
  70210. if (mainFill != newFill)
  70211. {
  70212. needsRedraw = true;
  70213. mainFill = newFill;
  70214. }
  70215. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70216. if (strokeFill != newStrokeFill)
  70217. {
  70218. needsRedraw = true;
  70219. strokeFill = newStrokeFill;
  70220. }
  70221. const PathStrokeType newStroke (v.getStrokeType());
  70222. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70223. Path newPath;
  70224. newRelativePath->createPath (newPath, parent);
  70225. if (! newRelativePath->containsAnyDynamicPoints())
  70226. newRelativePath = 0;
  70227. if (strokeType != newStroke || path != newPath)
  70228. {
  70229. damageRect = getBounds();
  70230. path.swapWithPath (newPath);
  70231. strokeNeedsUpdating = true;
  70232. strokeType = newStroke;
  70233. needsRedraw = true;
  70234. }
  70235. relativePath = newRelativePath;
  70236. if (needsRedraw)
  70237. damageRect = damageRect.getUnion (getBounds());
  70238. return damageRect;
  70239. }
  70240. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70241. {
  70242. ValueTree tree (valueTreeType);
  70243. ValueTreeWrapper v (tree);
  70244. v.setID (getName(), 0);
  70245. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70246. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70247. v.setStrokeType (strokeType, 0);
  70248. if (relativePath != 0)
  70249. {
  70250. relativePath->writeTo (tree, 0);
  70251. }
  70252. else
  70253. {
  70254. RelativePointPath rp (path);
  70255. rp.writeTo (tree, 0);
  70256. }
  70257. return tree;
  70258. }
  70259. END_JUCE_NAMESPACE
  70260. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70261. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70262. BEGIN_JUCE_NAMESPACE
  70263. DrawableText::DrawableText()
  70264. : colour (Colours::black),
  70265. justification (Justification::centredLeft)
  70266. {
  70267. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70268. RelativePoint (50.0f, 0.0f),
  70269. RelativePoint (0.0f, 20.0f)));
  70270. setFont (Font (15.0f), true);
  70271. }
  70272. DrawableText::DrawableText (const DrawableText& other)
  70273. : text (other.text),
  70274. font (other.font),
  70275. colour (other.colour),
  70276. justification (other.justification),
  70277. bounds (other.bounds),
  70278. fontSizeControlPoint (other.fontSizeControlPoint)
  70279. {
  70280. }
  70281. DrawableText::~DrawableText()
  70282. {
  70283. }
  70284. void DrawableText::setText (const String& newText)
  70285. {
  70286. text = newText;
  70287. }
  70288. void DrawableText::setColour (const Colour& newColour)
  70289. {
  70290. colour = newColour;
  70291. }
  70292. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70293. {
  70294. font = newFont;
  70295. if (applySizeAndScale)
  70296. {
  70297. Point<float> corners[3];
  70298. bounds.resolveThreePoints (corners, parent);
  70299. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70300. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70301. }
  70302. }
  70303. void DrawableText::setJustification (const Justification& newJustification)
  70304. {
  70305. justification = newJustification;
  70306. }
  70307. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70308. {
  70309. bounds = newBounds;
  70310. }
  70311. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70312. {
  70313. fontSizeControlPoint = newPoint;
  70314. }
  70315. void DrawableText::render (const Drawable::RenderingContext& context) const
  70316. {
  70317. Point<float> points[3];
  70318. bounds.resolveThreePoints (points, parent);
  70319. const float w = Line<float> (points[0], points[1]).getLength();
  70320. const float h = Line<float> (points[0], points[2]).getLength();
  70321. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70322. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70323. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70324. Font f (font);
  70325. f.setHeight (fontHeight);
  70326. f.setHorizontalScale (fontWidth / fontHeight);
  70327. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70328. GlyphArrangement ga;
  70329. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70330. ga.draw (context.g,
  70331. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70332. w, 0, points[1].getX(), points[1].getY(),
  70333. 0, h, points[2].getX(), points[2].getY())
  70334. .followedBy (context.transform));
  70335. }
  70336. const Rectangle<float> DrawableText::getBounds() const
  70337. {
  70338. return bounds.getBounds (parent);
  70339. }
  70340. bool DrawableText::hitTest (float x, float y) const
  70341. {
  70342. Path p;
  70343. bounds.getPath (p, parent);
  70344. return p.contains (x, y);
  70345. }
  70346. Drawable* DrawableText::createCopy() const
  70347. {
  70348. return new DrawableText (*this);
  70349. }
  70350. void DrawableText::invalidatePoints()
  70351. {
  70352. }
  70353. const Identifier DrawableText::valueTreeType ("Text");
  70354. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70355. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70356. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70357. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70358. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70359. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70360. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70361. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70362. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70363. : ValueTreeWrapperBase (state_)
  70364. {
  70365. jassert (state.hasType (valueTreeType));
  70366. }
  70367. const String DrawableText::ValueTreeWrapper::getText() const
  70368. {
  70369. return state [text].toString();
  70370. }
  70371. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70372. {
  70373. state.setProperty (text, newText, undoManager);
  70374. }
  70375. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70376. {
  70377. return state.getPropertyAsValue (text, undoManager);
  70378. }
  70379. const Colour DrawableText::ValueTreeWrapper::getColour() const
  70380. {
  70381. return Colour::fromString (state [colour].toString());
  70382. }
  70383. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  70384. {
  70385. state.setProperty (colour, newColour.toString(), undoManager);
  70386. }
  70387. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  70388. {
  70389. return Justification ((int) state [justification]);
  70390. }
  70391. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  70392. {
  70393. state.setProperty (justification, newJustification.getFlags(), undoManager);
  70394. }
  70395. const Font DrawableText::ValueTreeWrapper::getFont() const
  70396. {
  70397. return Font::fromString (state [font]);
  70398. }
  70399. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  70400. {
  70401. state.setProperty (font, newFont.toString(), undoManager);
  70402. }
  70403. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  70404. {
  70405. return state.getPropertyAsValue (font, undoManager);
  70406. }
  70407. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  70408. {
  70409. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  70410. }
  70411. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70412. {
  70413. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70414. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70415. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70416. }
  70417. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  70418. {
  70419. return state [fontSizeAnchor].toString();
  70420. }
  70421. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  70422. {
  70423. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  70424. }
  70425. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  70426. {
  70427. ValueTreeWrapper v (tree);
  70428. setName (v.getID());
  70429. const RelativeParallelogram newBounds (v.getBoundingBox());
  70430. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  70431. const Colour newColour (v.getColour());
  70432. const Justification newJustification (v.getJustification());
  70433. const String newText (v.getText());
  70434. const Font newFont (v.getFont());
  70435. if (text != newText || font != newFont || justification != newJustification
  70436. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  70437. {
  70438. const Rectangle<float> damage (getBounds());
  70439. setBoundingBox (newBounds);
  70440. setFontSizeControlPoint (newFontPoint);
  70441. setColour (newColour);
  70442. setFont (newFont, false);
  70443. setJustification (newJustification);
  70444. setText (newText);
  70445. return damage.getUnion (getBounds());
  70446. }
  70447. return Rectangle<float>();
  70448. }
  70449. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  70450. {
  70451. ValueTree tree (valueTreeType);
  70452. ValueTreeWrapper v (tree);
  70453. v.setID (getName(), 0);
  70454. v.setText (text, 0);
  70455. v.setFont (font, 0);
  70456. v.setJustification (justification, 0);
  70457. v.setColour (colour, 0);
  70458. v.setBoundingBox (bounds, 0);
  70459. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  70460. return tree;
  70461. }
  70462. END_JUCE_NAMESPACE
  70463. /*** End of inlined file: juce_DrawableText.cpp ***/
  70464. /*** Start of inlined file: juce_SVGParser.cpp ***/
  70465. BEGIN_JUCE_NAMESPACE
  70466. class SVGState
  70467. {
  70468. public:
  70469. SVGState (const XmlElement* const topLevel)
  70470. : topLevelXml (topLevel),
  70471. elementX (0), elementY (0),
  70472. width (512), height (512),
  70473. viewBoxW (0), viewBoxH (0)
  70474. {
  70475. }
  70476. ~SVGState()
  70477. {
  70478. }
  70479. Drawable* parseSVGElement (const XmlElement& xml)
  70480. {
  70481. if (! xml.hasTagName ("svg"))
  70482. return 0;
  70483. DrawableComposite* const drawable = new DrawableComposite();
  70484. drawable->setName (xml.getStringAttribute ("id"));
  70485. SVGState newState (*this);
  70486. if (xml.hasAttribute ("transform"))
  70487. newState.addTransform (xml);
  70488. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  70489. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  70490. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  70491. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  70492. if (xml.hasAttribute ("viewBox"))
  70493. {
  70494. const String viewParams (xml.getStringAttribute ("viewBox"));
  70495. int i = 0;
  70496. float vx, vy, vw, vh;
  70497. if (parseCoords (viewParams, vx, vy, i, true)
  70498. && parseCoords (viewParams, vw, vh, i, true)
  70499. && vw > 0
  70500. && vh > 0)
  70501. {
  70502. newState.viewBoxW = vw;
  70503. newState.viewBoxH = vh;
  70504. int placementFlags = 0;
  70505. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  70506. if (aspect.containsIgnoreCase ("none"))
  70507. {
  70508. placementFlags = RectanglePlacement::stretchToFit;
  70509. }
  70510. else
  70511. {
  70512. if (aspect.containsIgnoreCase ("slice"))
  70513. placementFlags |= RectanglePlacement::fillDestination;
  70514. if (aspect.containsIgnoreCase ("xMin"))
  70515. placementFlags |= RectanglePlacement::xLeft;
  70516. else if (aspect.containsIgnoreCase ("xMax"))
  70517. placementFlags |= RectanglePlacement::xRight;
  70518. else
  70519. placementFlags |= RectanglePlacement::xMid;
  70520. if (aspect.containsIgnoreCase ("yMin"))
  70521. placementFlags |= RectanglePlacement::yTop;
  70522. else if (aspect.containsIgnoreCase ("yMax"))
  70523. placementFlags |= RectanglePlacement::yBottom;
  70524. else
  70525. placementFlags |= RectanglePlacement::yMid;
  70526. }
  70527. const RectanglePlacement placement (placementFlags);
  70528. newState.transform
  70529. = placement.getTransformToFit (vx, vy, vw, vh,
  70530. 0.0f, 0.0f, newState.width, newState.height)
  70531. .followedBy (newState.transform);
  70532. }
  70533. }
  70534. else
  70535. {
  70536. if (viewBoxW == 0)
  70537. newState.viewBoxW = newState.width;
  70538. if (viewBoxH == 0)
  70539. newState.viewBoxH = newState.height;
  70540. }
  70541. newState.parseSubElements (xml, drawable);
  70542. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  70543. return drawable;
  70544. }
  70545. private:
  70546. const XmlElement* const topLevelXml;
  70547. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  70548. AffineTransform transform;
  70549. String cssStyleText;
  70550. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  70551. {
  70552. forEachXmlChildElement (xml, e)
  70553. {
  70554. Drawable* d = 0;
  70555. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  70556. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  70557. else if (e->hasTagName ("path")) d = parsePath (*e);
  70558. else if (e->hasTagName ("rect")) d = parseRect (*e);
  70559. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  70560. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  70561. else if (e->hasTagName ("line")) d = parseLine (*e);
  70562. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  70563. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  70564. else if (e->hasTagName ("text")) d = parseText (*e);
  70565. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  70566. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  70567. parentDrawable->insertDrawable (d);
  70568. }
  70569. }
  70570. DrawableComposite* parseSwitch (const XmlElement& xml)
  70571. {
  70572. const XmlElement* const group = xml.getChildByName ("g");
  70573. if (group != 0)
  70574. return parseGroupElement (*group);
  70575. return 0;
  70576. }
  70577. DrawableComposite* parseGroupElement (const XmlElement& xml)
  70578. {
  70579. DrawableComposite* const drawable = new DrawableComposite();
  70580. drawable->setName (xml.getStringAttribute ("id"));
  70581. if (xml.hasAttribute ("transform"))
  70582. {
  70583. SVGState newState (*this);
  70584. newState.addTransform (xml);
  70585. newState.parseSubElements (xml, drawable);
  70586. }
  70587. else
  70588. {
  70589. parseSubElements (xml, drawable);
  70590. }
  70591. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  70592. return drawable;
  70593. }
  70594. Drawable* parsePath (const XmlElement& xml) const
  70595. {
  70596. const String d (xml.getStringAttribute ("d").trimStart());
  70597. Path path;
  70598. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  70599. path.setUsingNonZeroWinding (false);
  70600. int index = 0;
  70601. float lastX = 0, lastY = 0;
  70602. float lastX2 = 0, lastY2 = 0;
  70603. juce_wchar lastCommandChar = 0;
  70604. bool isRelative = true;
  70605. bool carryOn = true;
  70606. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  70607. while (d[index] != 0)
  70608. {
  70609. float x, y, x2, y2, x3, y3;
  70610. if (validCommandChars.containsChar (d[index]))
  70611. {
  70612. lastCommandChar = d [index++];
  70613. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  70614. }
  70615. switch (lastCommandChar)
  70616. {
  70617. case 'M':
  70618. case 'm':
  70619. case 'L':
  70620. case 'l':
  70621. if (parseCoords (d, x, y, index, false))
  70622. {
  70623. if (isRelative)
  70624. {
  70625. x += lastX;
  70626. y += lastY;
  70627. }
  70628. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  70629. {
  70630. path.startNewSubPath (x, y);
  70631. lastCommandChar = 'l';
  70632. }
  70633. else
  70634. path.lineTo (x, y);
  70635. lastX2 = lastX;
  70636. lastY2 = lastY;
  70637. lastX = x;
  70638. lastY = y;
  70639. }
  70640. else
  70641. {
  70642. ++index;
  70643. }
  70644. break;
  70645. case 'H':
  70646. case 'h':
  70647. if (parseCoord (d, x, index, false, true))
  70648. {
  70649. if (isRelative)
  70650. x += lastX;
  70651. path.lineTo (x, lastY);
  70652. lastX2 = lastX;
  70653. lastX = x;
  70654. }
  70655. else
  70656. {
  70657. ++index;
  70658. }
  70659. break;
  70660. case 'V':
  70661. case 'v':
  70662. if (parseCoord (d, y, index, false, false))
  70663. {
  70664. if (isRelative)
  70665. y += lastY;
  70666. path.lineTo (lastX, y);
  70667. lastY2 = lastY;
  70668. lastY = y;
  70669. }
  70670. else
  70671. {
  70672. ++index;
  70673. }
  70674. break;
  70675. case 'C':
  70676. case 'c':
  70677. if (parseCoords (d, x, y, index, false)
  70678. && parseCoords (d, x2, y2, index, false)
  70679. && parseCoords (d, x3, y3, index, false))
  70680. {
  70681. if (isRelative)
  70682. {
  70683. x += lastX;
  70684. y += lastY;
  70685. x2 += lastX;
  70686. y2 += lastY;
  70687. x3 += lastX;
  70688. y3 += lastY;
  70689. }
  70690. path.cubicTo (x, y, x2, y2, x3, y3);
  70691. lastX2 = x2;
  70692. lastY2 = y2;
  70693. lastX = x3;
  70694. lastY = y3;
  70695. }
  70696. else
  70697. {
  70698. ++index;
  70699. }
  70700. break;
  70701. case 'S':
  70702. case 's':
  70703. if (parseCoords (d, x, y, index, false)
  70704. && parseCoords (d, x3, y3, index, false))
  70705. {
  70706. if (isRelative)
  70707. {
  70708. x += lastX;
  70709. y += lastY;
  70710. x3 += lastX;
  70711. y3 += lastY;
  70712. }
  70713. x2 = lastX + (lastX - lastX2);
  70714. y2 = lastY + (lastY - lastY2);
  70715. path.cubicTo (x2, y2, x, y, x3, y3);
  70716. lastX2 = x;
  70717. lastY2 = y;
  70718. lastX = x3;
  70719. lastY = y3;
  70720. }
  70721. else
  70722. {
  70723. ++index;
  70724. }
  70725. break;
  70726. case 'Q':
  70727. case 'q':
  70728. if (parseCoords (d, x, y, index, false)
  70729. && parseCoords (d, x2, y2, index, false))
  70730. {
  70731. if (isRelative)
  70732. {
  70733. x += lastX;
  70734. y += lastY;
  70735. x2 += lastX;
  70736. y2 += lastY;
  70737. }
  70738. path.quadraticTo (x, y, x2, y2);
  70739. lastX2 = x;
  70740. lastY2 = y;
  70741. lastX = x2;
  70742. lastY = y2;
  70743. }
  70744. else
  70745. {
  70746. ++index;
  70747. }
  70748. break;
  70749. case 'T':
  70750. case 't':
  70751. if (parseCoords (d, x, y, index, false))
  70752. {
  70753. if (isRelative)
  70754. {
  70755. x += lastX;
  70756. y += lastY;
  70757. }
  70758. x2 = lastX + (lastX - lastX2);
  70759. y2 = lastY + (lastY - lastY2);
  70760. path.quadraticTo (x2, y2, x, y);
  70761. lastX2 = x2;
  70762. lastY2 = y2;
  70763. lastX = x;
  70764. lastY = y;
  70765. }
  70766. else
  70767. {
  70768. ++index;
  70769. }
  70770. break;
  70771. case 'A':
  70772. case 'a':
  70773. if (parseCoords (d, x, y, index, false))
  70774. {
  70775. String num;
  70776. if (parseNextNumber (d, num, index, false))
  70777. {
  70778. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  70779. if (parseNextNumber (d, num, index, false))
  70780. {
  70781. const bool largeArc = num.getIntValue() != 0;
  70782. if (parseNextNumber (d, num, index, false))
  70783. {
  70784. const bool sweep = num.getIntValue() != 0;
  70785. if (parseCoords (d, x2, y2, index, false))
  70786. {
  70787. if (isRelative)
  70788. {
  70789. x2 += lastX;
  70790. y2 += lastY;
  70791. }
  70792. if (lastX != x2 || lastY != y2)
  70793. {
  70794. double centreX, centreY, startAngle, deltaAngle;
  70795. double rx = x, ry = y;
  70796. endpointToCentreParameters (lastX, lastY, x2, y2,
  70797. angle, largeArc, sweep,
  70798. rx, ry, centreX, centreY,
  70799. startAngle, deltaAngle);
  70800. path.addCentredArc ((float) centreX, (float) centreY,
  70801. (float) rx, (float) ry,
  70802. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  70803. false);
  70804. path.lineTo (x2, y2);
  70805. }
  70806. lastX2 = lastX;
  70807. lastY2 = lastY;
  70808. lastX = x2;
  70809. lastY = y2;
  70810. }
  70811. }
  70812. }
  70813. }
  70814. }
  70815. else
  70816. {
  70817. ++index;
  70818. }
  70819. break;
  70820. case 'Z':
  70821. case 'z':
  70822. path.closeSubPath();
  70823. while (CharacterFunctions::isWhitespace (d [index]))
  70824. ++index;
  70825. break;
  70826. default:
  70827. carryOn = false;
  70828. break;
  70829. }
  70830. if (! carryOn)
  70831. break;
  70832. }
  70833. return parseShape (xml, path);
  70834. }
  70835. Drawable* parseRect (const XmlElement& xml) const
  70836. {
  70837. Path rect;
  70838. const bool hasRX = xml.hasAttribute ("rx");
  70839. const bool hasRY = xml.hasAttribute ("ry");
  70840. if (hasRX || hasRY)
  70841. {
  70842. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  70843. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  70844. if (! hasRX)
  70845. rx = ry;
  70846. else if (! hasRY)
  70847. ry = rx;
  70848. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  70849. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  70850. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  70851. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  70852. rx, ry);
  70853. }
  70854. else
  70855. {
  70856. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  70857. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  70858. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  70859. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  70860. }
  70861. return parseShape (xml, rect);
  70862. }
  70863. Drawable* parseCircle (const XmlElement& xml) const
  70864. {
  70865. Path circle;
  70866. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  70867. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  70868. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  70869. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  70870. return parseShape (xml, circle);
  70871. }
  70872. Drawable* parseEllipse (const XmlElement& xml) const
  70873. {
  70874. Path ellipse;
  70875. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  70876. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  70877. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  70878. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  70879. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  70880. return parseShape (xml, ellipse);
  70881. }
  70882. Drawable* parseLine (const XmlElement& xml) const
  70883. {
  70884. Path line;
  70885. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  70886. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  70887. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  70888. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  70889. line.startNewSubPath (x1, y1);
  70890. line.lineTo (x2, y2);
  70891. return parseShape (xml, line);
  70892. }
  70893. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  70894. {
  70895. const String points (xml.getStringAttribute ("points"));
  70896. Path path;
  70897. int index = 0;
  70898. float x, y;
  70899. if (parseCoords (points, x, y, index, true))
  70900. {
  70901. float firstX = x;
  70902. float firstY = y;
  70903. float lastX = 0, lastY = 0;
  70904. path.startNewSubPath (x, y);
  70905. while (parseCoords (points, x, y, index, true))
  70906. {
  70907. lastX = x;
  70908. lastY = y;
  70909. path.lineTo (x, y);
  70910. }
  70911. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  70912. path.closeSubPath();
  70913. }
  70914. return parseShape (xml, path);
  70915. }
  70916. Drawable* parseShape (const XmlElement& xml, Path& path,
  70917. const bool shouldParseTransform = true) const
  70918. {
  70919. if (shouldParseTransform && xml.hasAttribute ("transform"))
  70920. {
  70921. SVGState newState (*this);
  70922. newState.addTransform (xml);
  70923. return newState.parseShape (xml, path, false);
  70924. }
  70925. DrawablePath* dp = new DrawablePath();
  70926. dp->setName (xml.getStringAttribute ("id"));
  70927. dp->setFill (Colours::transparentBlack);
  70928. path.applyTransform (transform);
  70929. dp->setPath (path);
  70930. Path::Iterator iter (path);
  70931. bool containsClosedSubPath = false;
  70932. while (iter.next())
  70933. {
  70934. if (iter.elementType == Path::Iterator::closePath)
  70935. {
  70936. containsClosedSubPath = true;
  70937. break;
  70938. }
  70939. }
  70940. dp->setFill (getPathFillType (path,
  70941. getStyleAttribute (&xml, "fill"),
  70942. getStyleAttribute (&xml, "fill-opacity"),
  70943. getStyleAttribute (&xml, "opacity"),
  70944. containsClosedSubPath ? Colours::black
  70945. : Colours::transparentBlack));
  70946. const String strokeType (getStyleAttribute (&xml, "stroke"));
  70947. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  70948. {
  70949. dp->setStrokeFill (getPathFillType (path, strokeType,
  70950. getStyleAttribute (&xml, "stroke-opacity"),
  70951. getStyleAttribute (&xml, "opacity"),
  70952. Colours::transparentBlack));
  70953. dp->setStrokeType (getStrokeFor (&xml));
  70954. }
  70955. return dp;
  70956. }
  70957. const XmlElement* findLinkedElement (const XmlElement* e) const
  70958. {
  70959. const String id (e->getStringAttribute ("xlink:href"));
  70960. if (! id.startsWithChar ('#'))
  70961. return 0;
  70962. return findElementForId (topLevelXml, id.substring (1));
  70963. }
  70964. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  70965. {
  70966. if (fillXml == 0)
  70967. return;
  70968. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  70969. {
  70970. int index = 0;
  70971. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  70972. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  70973. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  70974. double offset = e->getDoubleAttribute ("offset");
  70975. if (e->getStringAttribute ("offset").containsChar ('%'))
  70976. offset *= 0.01;
  70977. cg.addColour (jlimit (0.0, 1.0, offset), col);
  70978. }
  70979. }
  70980. const FillType getPathFillType (const Path& path,
  70981. const String& fill,
  70982. const String& fillOpacity,
  70983. const String& overallOpacity,
  70984. const Colour& defaultColour) const
  70985. {
  70986. float opacity = 1.0f;
  70987. if (overallOpacity.isNotEmpty())
  70988. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  70989. if (fillOpacity.isNotEmpty())
  70990. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  70991. if (fill.startsWithIgnoreCase ("url"))
  70992. {
  70993. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  70994. .upToLastOccurrenceOf (")", false, false).trim());
  70995. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  70996. if (fillXml != 0
  70997. && (fillXml->hasTagName ("linearGradient")
  70998. || fillXml->hasTagName ("radialGradient")))
  70999. {
  71000. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71001. ColourGradient gradient;
  71002. addGradientStopsIn (gradient, inheritedFrom);
  71003. addGradientStopsIn (gradient, fillXml);
  71004. if (gradient.getNumColours() > 0)
  71005. {
  71006. gradient.addColour (0.0, gradient.getColour (0));
  71007. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71008. }
  71009. else
  71010. {
  71011. gradient.addColour (0.0, Colours::black);
  71012. gradient.addColour (1.0, Colours::black);
  71013. }
  71014. if (overallOpacity.isNotEmpty())
  71015. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71016. jassert (gradient.getNumColours() > 0);
  71017. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71018. float gradientWidth = viewBoxW;
  71019. float gradientHeight = viewBoxH;
  71020. float dx = 0.0f;
  71021. float dy = 0.0f;
  71022. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71023. if (! userSpace)
  71024. {
  71025. const Rectangle<float> bounds (path.getBounds());
  71026. dx = bounds.getX();
  71027. dy = bounds.getY();
  71028. gradientWidth = bounds.getWidth();
  71029. gradientHeight = bounds.getHeight();
  71030. }
  71031. if (gradient.isRadial)
  71032. {
  71033. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71034. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71035. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71036. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71037. //xxx (the fx, fy focal point isn't handled properly here..)
  71038. }
  71039. else
  71040. {
  71041. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71042. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71043. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71044. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71045. if (gradient.point1 == gradient.point2)
  71046. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71047. }
  71048. FillType type (gradient);
  71049. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71050. .followedBy (transform);
  71051. return type;
  71052. }
  71053. }
  71054. if (fill.equalsIgnoreCase ("none"))
  71055. return Colours::transparentBlack;
  71056. int i = 0;
  71057. const Colour colour (parseColour (fill, i, defaultColour));
  71058. return colour.withMultipliedAlpha (opacity);
  71059. }
  71060. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71061. {
  71062. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71063. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71064. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71065. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71066. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71067. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71068. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71069. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71070. if (join.equalsIgnoreCase ("round"))
  71071. joinStyle = PathStrokeType::curved;
  71072. else if (join.equalsIgnoreCase ("bevel"))
  71073. joinStyle = PathStrokeType::beveled;
  71074. if (cap.equalsIgnoreCase ("round"))
  71075. capStyle = PathStrokeType::rounded;
  71076. else if (cap.equalsIgnoreCase ("square"))
  71077. capStyle = PathStrokeType::square;
  71078. float ox = 0.0f, oy = 0.0f;
  71079. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71080. transform.transformPoints (ox, oy, x, y);
  71081. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71082. joinStyle, capStyle);
  71083. }
  71084. Drawable* parseText (const XmlElement& xml)
  71085. {
  71086. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71087. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71088. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71089. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71090. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71091. //xxx not done text yet!
  71092. forEachXmlChildElement (xml, e)
  71093. {
  71094. if (e->isTextElement())
  71095. {
  71096. const String text (e->getText());
  71097. Path path;
  71098. Drawable* s = parseShape (*e, path);
  71099. delete s;
  71100. }
  71101. else if (e->hasTagName ("tspan"))
  71102. {
  71103. Drawable* s = parseText (*e);
  71104. delete s;
  71105. }
  71106. }
  71107. return 0;
  71108. }
  71109. void addTransform (const XmlElement& xml)
  71110. {
  71111. transform = parseTransform (xml.getStringAttribute ("transform"))
  71112. .followedBy (transform);
  71113. }
  71114. bool parseCoord (const String& s, float& value, int& index,
  71115. const bool allowUnits, const bool isX) const
  71116. {
  71117. String number;
  71118. if (! parseNextNumber (s, number, index, allowUnits))
  71119. {
  71120. value = 0;
  71121. return false;
  71122. }
  71123. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71124. return true;
  71125. }
  71126. bool parseCoords (const String& s, float& x, float& y,
  71127. int& index, const bool allowUnits) const
  71128. {
  71129. return parseCoord (s, x, index, allowUnits, true)
  71130. && parseCoord (s, y, index, allowUnits, false);
  71131. }
  71132. float getCoordLength (const String& s, const float sizeForProportions) const
  71133. {
  71134. float n = s.getFloatValue();
  71135. const int len = s.length();
  71136. if (len > 2)
  71137. {
  71138. const float dpi = 96.0f;
  71139. const juce_wchar n1 = s [len - 2];
  71140. const juce_wchar n2 = s [len - 1];
  71141. if (n1 == 'i' && n2 == 'n')
  71142. n *= dpi;
  71143. else if (n1 == 'm' && n2 == 'm')
  71144. n *= dpi / 25.4f;
  71145. else if (n1 == 'c' && n2 == 'm')
  71146. n *= dpi / 2.54f;
  71147. else if (n1 == 'p' && n2 == 'c')
  71148. n *= 15.0f;
  71149. else if (n2 == '%')
  71150. n *= 0.01f * sizeForProportions;
  71151. }
  71152. return n;
  71153. }
  71154. void getCoordList (Array <float>& coords, const String& list,
  71155. const bool allowUnits, const bool isX) const
  71156. {
  71157. int index = 0;
  71158. float value;
  71159. while (parseCoord (list, value, index, allowUnits, isX))
  71160. coords.add (value);
  71161. }
  71162. void parseCSSStyle (const XmlElement& xml)
  71163. {
  71164. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71165. }
  71166. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71167. const String& defaultValue = String::empty) const
  71168. {
  71169. if (xml->hasAttribute (attributeName))
  71170. return xml->getStringAttribute (attributeName, defaultValue);
  71171. const String styleAtt (xml->getStringAttribute ("style"));
  71172. if (styleAtt.isNotEmpty())
  71173. {
  71174. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71175. if (value.isNotEmpty())
  71176. return value;
  71177. }
  71178. else if (xml->hasAttribute ("class"))
  71179. {
  71180. const String className ("." + xml->getStringAttribute ("class"));
  71181. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71182. if (index < 0)
  71183. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71184. if (index >= 0)
  71185. {
  71186. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71187. if (openBracket > index)
  71188. {
  71189. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71190. if (closeBracket > openBracket)
  71191. {
  71192. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71193. if (value.isNotEmpty())
  71194. return value;
  71195. }
  71196. }
  71197. }
  71198. }
  71199. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71200. if (xml != 0)
  71201. return getStyleAttribute (xml, attributeName, defaultValue);
  71202. return defaultValue;
  71203. }
  71204. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71205. {
  71206. if (xml->hasAttribute (attributeName))
  71207. return xml->getStringAttribute (attributeName);
  71208. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71209. if (xml != 0)
  71210. return getInheritedAttribute (xml, attributeName);
  71211. return String::empty;
  71212. }
  71213. static bool isIdentifierChar (const juce_wchar c)
  71214. {
  71215. return CharacterFunctions::isLetter (c) || c == '-';
  71216. }
  71217. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71218. {
  71219. int i = 0;
  71220. for (;;)
  71221. {
  71222. i = list.indexOf (i, attributeName);
  71223. if (i < 0)
  71224. break;
  71225. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71226. && ! isIdentifierChar (list [i + attributeName.length()]))
  71227. {
  71228. i = list.indexOfChar (i, ':');
  71229. if (i < 0)
  71230. break;
  71231. int end = list.indexOfChar (i, ';');
  71232. if (end < 0)
  71233. end = 0x7ffff;
  71234. return list.substring (i + 1, end).trim();
  71235. }
  71236. ++i;
  71237. }
  71238. return defaultValue;
  71239. }
  71240. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71241. {
  71242. const juce_wchar* const s = source;
  71243. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71244. ++index;
  71245. int start = index;
  71246. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71247. ++index;
  71248. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71249. ++index;
  71250. if ((s[index] == 'e' || s[index] == 'E')
  71251. && (CharacterFunctions::isDigit (s[index + 1])
  71252. || s[index + 1] == '-'
  71253. || s[index + 1] == '+'))
  71254. {
  71255. index += 2;
  71256. while (CharacterFunctions::isDigit (s[index]))
  71257. ++index;
  71258. }
  71259. if (allowUnits)
  71260. {
  71261. while (CharacterFunctions::isLetter (s[index]))
  71262. ++index;
  71263. }
  71264. if (index == start)
  71265. return false;
  71266. value = String (s + start, index - start);
  71267. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71268. ++index;
  71269. return true;
  71270. }
  71271. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71272. {
  71273. if (s [index] == '#')
  71274. {
  71275. uint32 hex [6];
  71276. zeromem (hex, sizeof (hex));
  71277. int numChars = 0;
  71278. for (int i = 6; --i >= 0;)
  71279. {
  71280. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71281. if (hexValue >= 0)
  71282. hex [numChars++] = hexValue;
  71283. else
  71284. break;
  71285. }
  71286. if (numChars <= 3)
  71287. return Colour ((uint8) (hex [0] * 0x11),
  71288. (uint8) (hex [1] * 0x11),
  71289. (uint8) (hex [2] * 0x11));
  71290. else
  71291. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71292. (uint8) ((hex [2] << 4) + hex [3]),
  71293. (uint8) ((hex [4] << 4) + hex [5]));
  71294. }
  71295. else if (s [index] == 'r'
  71296. && s [index + 1] == 'g'
  71297. && s [index + 2] == 'b')
  71298. {
  71299. const int openBracket = s.indexOfChar (index, '(');
  71300. const int closeBracket = s.indexOfChar (openBracket, ')');
  71301. if (openBracket >= 3 && closeBracket > openBracket)
  71302. {
  71303. index = closeBracket;
  71304. StringArray tokens;
  71305. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71306. tokens.trim();
  71307. tokens.removeEmptyStrings();
  71308. if (tokens[0].containsChar ('%'))
  71309. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71310. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71311. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71312. else
  71313. return Colour ((uint8) tokens[0].getIntValue(),
  71314. (uint8) tokens[1].getIntValue(),
  71315. (uint8) tokens[2].getIntValue());
  71316. }
  71317. }
  71318. return Colours::findColourForName (s, defaultColour);
  71319. }
  71320. static const AffineTransform parseTransform (String t)
  71321. {
  71322. AffineTransform result;
  71323. while (t.isNotEmpty())
  71324. {
  71325. StringArray tokens;
  71326. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71327. .upToFirstOccurrenceOf (")", false, false),
  71328. ", ", String::empty);
  71329. tokens.removeEmptyStrings (true);
  71330. float numbers [6];
  71331. for (int i = 0; i < 6; ++i)
  71332. numbers[i] = tokens[i].getFloatValue();
  71333. AffineTransform trans;
  71334. if (t.startsWithIgnoreCase ("matrix"))
  71335. {
  71336. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71337. numbers[1], numbers[3], numbers[5]);
  71338. }
  71339. else if (t.startsWithIgnoreCase ("translate"))
  71340. {
  71341. jassert (tokens.size() == 2);
  71342. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71343. }
  71344. else if (t.startsWithIgnoreCase ("scale"))
  71345. {
  71346. if (tokens.size() == 1)
  71347. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71348. else
  71349. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71350. }
  71351. else if (t.startsWithIgnoreCase ("rotate"))
  71352. {
  71353. if (tokens.size() != 3)
  71354. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71355. else
  71356. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71357. numbers[1], numbers[2]);
  71358. }
  71359. else if (t.startsWithIgnoreCase ("skewX"))
  71360. {
  71361. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71362. 0.0f, 1.0f, 0.0f);
  71363. }
  71364. else if (t.startsWithIgnoreCase ("skewY"))
  71365. {
  71366. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71367. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71368. }
  71369. result = trans.followedBy (result);
  71370. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  71371. }
  71372. return result;
  71373. }
  71374. static void endpointToCentreParameters (const double x1, const double y1,
  71375. const double x2, const double y2,
  71376. const double angle,
  71377. const bool largeArc, const bool sweep,
  71378. double& rx, double& ry,
  71379. double& centreX, double& centreY,
  71380. double& startAngle, double& deltaAngle)
  71381. {
  71382. const double midX = (x1 - x2) * 0.5;
  71383. const double midY = (y1 - y2) * 0.5;
  71384. const double cosAngle = cos (angle);
  71385. const double sinAngle = sin (angle);
  71386. const double xp = cosAngle * midX + sinAngle * midY;
  71387. const double yp = cosAngle * midY - sinAngle * midX;
  71388. const double xp2 = xp * xp;
  71389. const double yp2 = yp * yp;
  71390. double rx2 = rx * rx;
  71391. double ry2 = ry * ry;
  71392. const double s = (xp2 / rx2) + (yp2 / ry2);
  71393. double c;
  71394. if (s <= 1.0)
  71395. {
  71396. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  71397. / (( rx2 * yp2) + (ry2 * xp2))));
  71398. if (largeArc == sweep)
  71399. c = -c;
  71400. }
  71401. else
  71402. {
  71403. const double s2 = std::sqrt (s);
  71404. rx *= s2;
  71405. ry *= s2;
  71406. rx2 = rx * rx;
  71407. ry2 = ry * ry;
  71408. c = 0;
  71409. }
  71410. const double cpx = ((rx * yp) / ry) * c;
  71411. const double cpy = ((-ry * xp) / rx) * c;
  71412. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  71413. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  71414. const double ux = (xp - cpx) / rx;
  71415. const double uy = (yp - cpy) / ry;
  71416. const double vx = (-xp - cpx) / rx;
  71417. const double vy = (-yp - cpy) / ry;
  71418. const double length = juce_hypot (ux, uy);
  71419. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  71420. if (uy < 0)
  71421. startAngle = -startAngle;
  71422. startAngle += double_Pi * 0.5;
  71423. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  71424. / (length * juce_hypot (vx, vy))));
  71425. if ((ux * vy) - (uy * vx) < 0)
  71426. deltaAngle = -deltaAngle;
  71427. if (sweep)
  71428. {
  71429. if (deltaAngle < 0)
  71430. deltaAngle += double_Pi * 2.0;
  71431. }
  71432. else
  71433. {
  71434. if (deltaAngle > 0)
  71435. deltaAngle -= double_Pi * 2.0;
  71436. }
  71437. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  71438. }
  71439. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  71440. {
  71441. forEachXmlChildElement (*parent, e)
  71442. {
  71443. if (e->compareAttribute ("id", id))
  71444. return e;
  71445. const XmlElement* const found = findElementForId (e, id);
  71446. if (found != 0)
  71447. return found;
  71448. }
  71449. return 0;
  71450. }
  71451. SVGState& operator= (const SVGState&);
  71452. };
  71453. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  71454. {
  71455. SVGState state (&svgDocument);
  71456. return state.parseSVGElement (svgDocument);
  71457. }
  71458. END_JUCE_NAMESPACE
  71459. /*** End of inlined file: juce_SVGParser.cpp ***/
  71460. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  71461. BEGIN_JUCE_NAMESPACE
  71462. #if JUCE_MSVC && JUCE_DEBUG
  71463. #pragma optimize ("t", on)
  71464. #endif
  71465. DropShadowEffect::DropShadowEffect()
  71466. : offsetX (0),
  71467. offsetY (0),
  71468. radius (4),
  71469. opacity (0.6f)
  71470. {
  71471. }
  71472. DropShadowEffect::~DropShadowEffect()
  71473. {
  71474. }
  71475. void DropShadowEffect::setShadowProperties (const float newRadius,
  71476. const float newOpacity,
  71477. const int newShadowOffsetX,
  71478. const int newShadowOffsetY)
  71479. {
  71480. radius = jmax (1.1f, newRadius);
  71481. offsetX = newShadowOffsetX;
  71482. offsetY = newShadowOffsetY;
  71483. opacity = newOpacity;
  71484. }
  71485. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  71486. {
  71487. const int w = image.getWidth();
  71488. const int h = image.getHeight();
  71489. Image shadowImage (Image::SingleChannel, w, h, false);
  71490. const Image::BitmapData srcData (image, false);
  71491. const Image::BitmapData destData (shadowImage, true);
  71492. const int filter = roundToInt (63.0f / radius);
  71493. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  71494. for (int x = w; --x >= 0;)
  71495. {
  71496. int shadowAlpha = 0;
  71497. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  71498. uint8* shadowPix = destData.data + x;
  71499. for (int y = h; --y >= 0;)
  71500. {
  71501. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  71502. *shadowPix = (uint8) shadowAlpha;
  71503. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  71504. shadowPix += destData.lineStride;
  71505. }
  71506. }
  71507. for (int y = h; --y >= 0;)
  71508. {
  71509. int shadowAlpha = 0;
  71510. uint8* shadowPix = destData.getLinePointer (y);
  71511. for (int x = w; --x >= 0;)
  71512. {
  71513. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  71514. *shadowPix++ = (uint8) shadowAlpha;
  71515. }
  71516. }
  71517. g.setColour (Colours::black.withAlpha (opacity));
  71518. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  71519. g.setOpacity (1.0f);
  71520. g.drawImageAt (image, 0, 0);
  71521. }
  71522. #if JUCE_MSVC && JUCE_DEBUG
  71523. #pragma optimize ("", on) // resets optimisations to the project defaults
  71524. #endif
  71525. END_JUCE_NAMESPACE
  71526. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  71527. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  71528. BEGIN_JUCE_NAMESPACE
  71529. GlowEffect::GlowEffect()
  71530. : radius (2.0f),
  71531. colour (Colours::white)
  71532. {
  71533. }
  71534. GlowEffect::~GlowEffect()
  71535. {
  71536. }
  71537. void GlowEffect::setGlowProperties (const float newRadius,
  71538. const Colour& newColour)
  71539. {
  71540. radius = newRadius;
  71541. colour = newColour;
  71542. }
  71543. void GlowEffect::applyEffect (Image& image, Graphics& g)
  71544. {
  71545. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  71546. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  71547. blurKernel.createGaussianBlur (radius);
  71548. blurKernel.rescaleAllValues (radius);
  71549. blurKernel.applyToImage (temp, image, image.getBounds());
  71550. g.setColour (colour);
  71551. g.drawImageAt (temp, 0, 0, true);
  71552. g.setOpacity (1.0f);
  71553. g.drawImageAt (image, 0, 0, false);
  71554. }
  71555. END_JUCE_NAMESPACE
  71556. /*** End of inlined file: juce_GlowEffect.cpp ***/
  71557. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  71558. BEGIN_JUCE_NAMESPACE
  71559. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  71560. : opacity (opacity_)
  71561. {
  71562. }
  71563. ReduceOpacityEffect::~ReduceOpacityEffect()
  71564. {
  71565. }
  71566. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  71567. {
  71568. opacity = jlimit (0.0f, 1.0f, newOpacity);
  71569. }
  71570. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  71571. {
  71572. g.setOpacity (opacity);
  71573. g.drawImageAt (image, 0, 0);
  71574. }
  71575. END_JUCE_NAMESPACE
  71576. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  71577. /*** Start of inlined file: juce_Font.cpp ***/
  71578. BEGIN_JUCE_NAMESPACE
  71579. namespace FontValues
  71580. {
  71581. static float limitFontHeight (const float height) throw()
  71582. {
  71583. return jlimit (0.1f, 10000.0f, height);
  71584. }
  71585. static const float defaultFontHeight = 14.0f;
  71586. static String fallbackFont;
  71587. }
  71588. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  71589. const float kerning_, const float ascent_, const int styleFlags_,
  71590. Typeface* const typeface_) throw()
  71591. : typefaceName (typefaceName_),
  71592. height (height_),
  71593. horizontalScale (horizontalScale_),
  71594. kerning (kerning_),
  71595. ascent (ascent_),
  71596. styleFlags (styleFlags_),
  71597. typeface (typeface_)
  71598. {
  71599. }
  71600. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  71601. : typefaceName (other.typefaceName),
  71602. height (other.height),
  71603. horizontalScale (other.horizontalScale),
  71604. kerning (other.kerning),
  71605. ascent (other.ascent),
  71606. styleFlags (other.styleFlags),
  71607. typeface (other.typeface)
  71608. {
  71609. }
  71610. Font::Font() throw()
  71611. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  71612. 1.0f, 0, 0, Font::plain, 0))
  71613. {
  71614. }
  71615. Font::Font (const float fontHeight, const int styleFlags_) throw()
  71616. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  71617. 1.0f, 0, 0, styleFlags_, 0))
  71618. {
  71619. }
  71620. Font::Font (const String& typefaceName_,
  71621. const float fontHeight,
  71622. const int styleFlags_) throw()
  71623. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  71624. 1.0f, 0, 0, styleFlags_, 0))
  71625. {
  71626. }
  71627. Font::Font (const Font& other) throw()
  71628. : font (other.font)
  71629. {
  71630. }
  71631. Font& Font::operator= (const Font& other) throw()
  71632. {
  71633. font = other.font;
  71634. return *this;
  71635. }
  71636. Font::~Font() throw()
  71637. {
  71638. }
  71639. Font::Font (const Typeface::Ptr& typeface) throw()
  71640. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  71641. 1.0f, 0, 0, Font::plain, typeface))
  71642. {
  71643. }
  71644. bool Font::operator== (const Font& other) const throw()
  71645. {
  71646. return font == other.font
  71647. || (font->height == other.font->height
  71648. && font->styleFlags == other.font->styleFlags
  71649. && font->horizontalScale == other.font->horizontalScale
  71650. && font->kerning == other.font->kerning
  71651. && font->typefaceName == other.font->typefaceName);
  71652. }
  71653. bool Font::operator!= (const Font& other) const throw()
  71654. {
  71655. return ! operator== (other);
  71656. }
  71657. void Font::dupeInternalIfShared() throw()
  71658. {
  71659. if (font->getReferenceCount() > 1)
  71660. font = new SharedFontInternal (*font);
  71661. }
  71662. const String Font::getDefaultSansSerifFontName() throw()
  71663. {
  71664. static const String name ("<Sans-Serif>");
  71665. return name;
  71666. }
  71667. const String Font::getDefaultSerifFontName() throw()
  71668. {
  71669. static const String name ("<Serif>");
  71670. return name;
  71671. }
  71672. const String Font::getDefaultMonospacedFontName() throw()
  71673. {
  71674. static const String name ("<Monospaced>");
  71675. return name;
  71676. }
  71677. void Font::setTypefaceName (const String& faceName) throw()
  71678. {
  71679. if (faceName != font->typefaceName)
  71680. {
  71681. dupeInternalIfShared();
  71682. font->typefaceName = faceName;
  71683. font->typeface = 0;
  71684. font->ascent = 0;
  71685. }
  71686. }
  71687. const String Font::getFallbackFontName() throw()
  71688. {
  71689. return FontValues::fallbackFont;
  71690. }
  71691. void Font::setFallbackFontName (const String& name) throw()
  71692. {
  71693. FontValues::fallbackFont = name;
  71694. }
  71695. void Font::setHeight (float newHeight) throw()
  71696. {
  71697. newHeight = FontValues::limitFontHeight (newHeight);
  71698. if (font->height != newHeight)
  71699. {
  71700. dupeInternalIfShared();
  71701. font->height = newHeight;
  71702. }
  71703. }
  71704. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  71705. {
  71706. newHeight = FontValues::limitFontHeight (newHeight);
  71707. if (font->height != newHeight)
  71708. {
  71709. dupeInternalIfShared();
  71710. font->horizontalScale *= (font->height / newHeight);
  71711. font->height = newHeight;
  71712. }
  71713. }
  71714. void Font::setStyleFlags (const int newFlags) throw()
  71715. {
  71716. if (font->styleFlags != newFlags)
  71717. {
  71718. dupeInternalIfShared();
  71719. font->styleFlags = newFlags;
  71720. font->typeface = 0;
  71721. font->ascent = 0;
  71722. }
  71723. }
  71724. void Font::setSizeAndStyle (float newHeight,
  71725. const int newStyleFlags,
  71726. const float newHorizontalScale,
  71727. const float newKerningAmount) throw()
  71728. {
  71729. newHeight = FontValues::limitFontHeight (newHeight);
  71730. if (font->height != newHeight
  71731. || font->horizontalScale != newHorizontalScale
  71732. || font->kerning != newKerningAmount)
  71733. {
  71734. dupeInternalIfShared();
  71735. font->height = newHeight;
  71736. font->horizontalScale = newHorizontalScale;
  71737. font->kerning = newKerningAmount;
  71738. }
  71739. setStyleFlags (newStyleFlags);
  71740. }
  71741. void Font::setHorizontalScale (const float scaleFactor) throw()
  71742. {
  71743. dupeInternalIfShared();
  71744. font->horizontalScale = scaleFactor;
  71745. }
  71746. void Font::setExtraKerningFactor (const float extraKerning) throw()
  71747. {
  71748. dupeInternalIfShared();
  71749. font->kerning = extraKerning;
  71750. }
  71751. void Font::setBold (const bool shouldBeBold) throw()
  71752. {
  71753. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  71754. : (font->styleFlags & ~bold));
  71755. }
  71756. bool Font::isBold() const throw()
  71757. {
  71758. return (font->styleFlags & bold) != 0;
  71759. }
  71760. void Font::setItalic (const bool shouldBeItalic) throw()
  71761. {
  71762. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  71763. : (font->styleFlags & ~italic));
  71764. }
  71765. bool Font::isItalic() const throw()
  71766. {
  71767. return (font->styleFlags & italic) != 0;
  71768. }
  71769. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  71770. {
  71771. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  71772. : (font->styleFlags & ~underlined));
  71773. }
  71774. bool Font::isUnderlined() const throw()
  71775. {
  71776. return (font->styleFlags & underlined) != 0;
  71777. }
  71778. float Font::getAscent() const throw()
  71779. {
  71780. if (font->ascent == 0)
  71781. font->ascent = getTypeface()->getAscent();
  71782. return font->height * font->ascent;
  71783. }
  71784. float Font::getDescent() const throw()
  71785. {
  71786. return font->height - getAscent();
  71787. }
  71788. int Font::getStringWidth (const String& text) const throw()
  71789. {
  71790. return roundToInt (getStringWidthFloat (text));
  71791. }
  71792. float Font::getStringWidthFloat (const String& text) const throw()
  71793. {
  71794. float w = getTypeface()->getStringWidth (text);
  71795. if (font->kerning != 0)
  71796. w += font->kerning * text.length();
  71797. return w * font->height * font->horizontalScale;
  71798. }
  71799. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  71800. {
  71801. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  71802. const float scale = font->height * font->horizontalScale;
  71803. const int num = xOffsets.size();
  71804. if (num > 0)
  71805. {
  71806. float* const x = &(xOffsets.getReference(0));
  71807. if (font->kerning != 0)
  71808. {
  71809. for (int i = 0; i < num; ++i)
  71810. x[i] = (x[i] + i * font->kerning) * scale;
  71811. }
  71812. else
  71813. {
  71814. for (int i = 0; i < num; ++i)
  71815. x[i] *= scale;
  71816. }
  71817. }
  71818. }
  71819. void Font::findFonts (Array<Font>& destArray) throw()
  71820. {
  71821. const StringArray names (findAllTypefaceNames());
  71822. for (int i = 0; i < names.size(); ++i)
  71823. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  71824. }
  71825. const String Font::toString() const
  71826. {
  71827. String s (getTypefaceName());
  71828. if (s == getDefaultSansSerifFontName())
  71829. s = String::empty;
  71830. else
  71831. s += "; ";
  71832. s += String (getHeight(), 1);
  71833. if (isBold())
  71834. s += " bold";
  71835. if (isItalic())
  71836. s += " italic";
  71837. return s;
  71838. }
  71839. const Font Font::fromString (const String& fontDescription)
  71840. {
  71841. String name;
  71842. const int separator = fontDescription.indexOfChar (';');
  71843. if (separator > 0)
  71844. name = fontDescription.substring (0, separator).trim();
  71845. if (name.isEmpty())
  71846. name = getDefaultSansSerifFontName();
  71847. String sizeAndStyle (fontDescription.substring (separator + 1));
  71848. float height = sizeAndStyle.getFloatValue();
  71849. if (height <= 0)
  71850. height = 10.0f;
  71851. int flags = Font::plain;
  71852. if (sizeAndStyle.containsIgnoreCase ("bold"))
  71853. flags |= Font::bold;
  71854. if (sizeAndStyle.containsIgnoreCase ("italic"))
  71855. flags |= Font::italic;
  71856. return Font (name, height, flags);
  71857. }
  71858. class TypefaceCache : public DeletedAtShutdown
  71859. {
  71860. public:
  71861. TypefaceCache (int numToCache = 10) throw()
  71862. : counter (1)
  71863. {
  71864. while (--numToCache >= 0)
  71865. faces.add (new CachedFace());
  71866. }
  71867. ~TypefaceCache()
  71868. {
  71869. clearSingletonInstance();
  71870. }
  71871. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  71872. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  71873. {
  71874. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  71875. const String faceName (font.getTypefaceName());
  71876. int i;
  71877. for (i = faces.size(); --i >= 0;)
  71878. {
  71879. CachedFace* const face = faces.getUnchecked(i);
  71880. if (face->flags == flags
  71881. && face->typefaceName == faceName)
  71882. {
  71883. face->lastUsageCount = ++counter;
  71884. return face->typeFace;
  71885. }
  71886. }
  71887. int replaceIndex = 0;
  71888. int bestLastUsageCount = std::numeric_limits<int>::max();
  71889. for (i = faces.size(); --i >= 0;)
  71890. {
  71891. const int lu = faces.getUnchecked(i)->lastUsageCount;
  71892. if (bestLastUsageCount > lu)
  71893. {
  71894. bestLastUsageCount = lu;
  71895. replaceIndex = i;
  71896. }
  71897. }
  71898. CachedFace* const face = faces.getUnchecked (replaceIndex);
  71899. face->typefaceName = faceName;
  71900. face->flags = flags;
  71901. face->lastUsageCount = ++counter;
  71902. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  71903. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  71904. return face->typeFace;
  71905. }
  71906. juce_UseDebuggingNewOperator
  71907. private:
  71908. struct CachedFace
  71909. {
  71910. CachedFace() throw()
  71911. : lastUsageCount (0), flags (-1)
  71912. {
  71913. }
  71914. String typefaceName;
  71915. int lastUsageCount;
  71916. int flags;
  71917. Typeface::Ptr typeFace;
  71918. };
  71919. int counter;
  71920. OwnedArray <CachedFace> faces;
  71921. TypefaceCache (const TypefaceCache&);
  71922. TypefaceCache& operator= (const TypefaceCache&);
  71923. };
  71924. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  71925. Typeface* Font::getTypeface() const throw()
  71926. {
  71927. if (font->typeface == 0)
  71928. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  71929. return font->typeface;
  71930. }
  71931. END_JUCE_NAMESPACE
  71932. /*** End of inlined file: juce_Font.cpp ***/
  71933. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  71934. BEGIN_JUCE_NAMESPACE
  71935. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  71936. const juce_wchar character_, const int glyph_)
  71937. : x (x_),
  71938. y (y_),
  71939. w (w_),
  71940. font (font_),
  71941. character (character_),
  71942. glyph (glyph_)
  71943. {
  71944. }
  71945. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  71946. : x (other.x),
  71947. y (other.y),
  71948. w (other.w),
  71949. font (other.font),
  71950. character (other.character),
  71951. glyph (other.glyph)
  71952. {
  71953. }
  71954. void PositionedGlyph::draw (const Graphics& g) const
  71955. {
  71956. if (! isWhitespace())
  71957. {
  71958. g.getInternalContext()->setFont (font);
  71959. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  71960. }
  71961. }
  71962. void PositionedGlyph::draw (const Graphics& g,
  71963. const AffineTransform& transform) const
  71964. {
  71965. if (! isWhitespace())
  71966. {
  71967. g.getInternalContext()->setFont (font);
  71968. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  71969. .followedBy (transform));
  71970. }
  71971. }
  71972. void PositionedGlyph::createPath (Path& path) const
  71973. {
  71974. if (! isWhitespace())
  71975. {
  71976. Typeface* const t = font.getTypeface();
  71977. if (t != 0)
  71978. {
  71979. Path p;
  71980. t->getOutlineForGlyph (glyph, p);
  71981. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  71982. .translated (x, y));
  71983. }
  71984. }
  71985. }
  71986. bool PositionedGlyph::hitTest (float px, float py) const
  71987. {
  71988. if (getBounds().contains (px, py) && ! isWhitespace())
  71989. {
  71990. Typeface* const t = font.getTypeface();
  71991. if (t != 0)
  71992. {
  71993. Path p;
  71994. t->getOutlineForGlyph (glyph, p);
  71995. AffineTransform::translation (-x, -y)
  71996. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  71997. .transformPoint (px, py);
  71998. return p.contains (px, py);
  71999. }
  72000. }
  72001. return false;
  72002. }
  72003. void PositionedGlyph::moveBy (const float deltaX,
  72004. const float deltaY)
  72005. {
  72006. x += deltaX;
  72007. y += deltaY;
  72008. }
  72009. GlyphArrangement::GlyphArrangement()
  72010. {
  72011. glyphs.ensureStorageAllocated (128);
  72012. }
  72013. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72014. {
  72015. addGlyphArrangement (other);
  72016. }
  72017. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72018. {
  72019. if (this != &other)
  72020. {
  72021. clear();
  72022. addGlyphArrangement (other);
  72023. }
  72024. return *this;
  72025. }
  72026. GlyphArrangement::~GlyphArrangement()
  72027. {
  72028. }
  72029. void GlyphArrangement::clear()
  72030. {
  72031. glyphs.clear();
  72032. }
  72033. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72034. {
  72035. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72036. return *glyphs [index];
  72037. }
  72038. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72039. {
  72040. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72041. glyphs.addCopiesOf (other.glyphs);
  72042. }
  72043. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72044. {
  72045. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72046. }
  72047. void GlyphArrangement::addLineOfText (const Font& font,
  72048. const String& text,
  72049. const float xOffset,
  72050. const float yOffset)
  72051. {
  72052. addCurtailedLineOfText (font, text,
  72053. xOffset, yOffset,
  72054. 1.0e10f, false);
  72055. }
  72056. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72057. const String& text,
  72058. float xOffset,
  72059. const float yOffset,
  72060. const float maxWidthPixels,
  72061. const bool useEllipsis)
  72062. {
  72063. if (text.isNotEmpty())
  72064. {
  72065. Array <int> newGlyphs;
  72066. Array <float> xOffsets;
  72067. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72068. const int textLen = newGlyphs.size();
  72069. const juce_wchar* const unicodeText = text;
  72070. for (int i = 0; i < textLen; ++i)
  72071. {
  72072. const float thisX = xOffsets.getUnchecked (i);
  72073. const float nextX = xOffsets.getUnchecked (i + 1);
  72074. if (nextX > maxWidthPixels + 1.0f)
  72075. {
  72076. // curtail the string if it's too wide..
  72077. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72078. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72079. break;
  72080. }
  72081. else
  72082. {
  72083. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72084. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72085. }
  72086. }
  72087. }
  72088. }
  72089. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72090. const int startIndex, int endIndex)
  72091. {
  72092. int numDeleted = 0;
  72093. if (glyphs.size() > 0)
  72094. {
  72095. Array<int> dotGlyphs;
  72096. Array<float> dotXs;
  72097. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72098. const float dx = dotXs[1];
  72099. float xOffset = 0.0f, yOffset = 0.0f;
  72100. while (endIndex > startIndex)
  72101. {
  72102. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72103. xOffset = pg->x;
  72104. yOffset = pg->y;
  72105. glyphs.remove (endIndex);
  72106. ++numDeleted;
  72107. if (xOffset + dx * 3 <= maxXPos)
  72108. break;
  72109. }
  72110. for (int i = 3; --i >= 0;)
  72111. {
  72112. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72113. font, '.', dotGlyphs.getFirst()));
  72114. --numDeleted;
  72115. xOffset += dx;
  72116. if (xOffset > maxXPos)
  72117. break;
  72118. }
  72119. }
  72120. return numDeleted;
  72121. }
  72122. void GlyphArrangement::addJustifiedText (const Font& font,
  72123. const String& text,
  72124. float x, float y,
  72125. const float maxLineWidth,
  72126. const Justification& horizontalLayout)
  72127. {
  72128. int lineStartIndex = glyphs.size();
  72129. addLineOfText (font, text, x, y);
  72130. const float originalY = y;
  72131. while (lineStartIndex < glyphs.size())
  72132. {
  72133. int i = lineStartIndex;
  72134. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72135. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72136. ++i;
  72137. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72138. int lastWordBreakIndex = -1;
  72139. while (i < glyphs.size())
  72140. {
  72141. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72142. const juce_wchar c = pg->getCharacter();
  72143. if (c == '\r' || c == '\n')
  72144. {
  72145. ++i;
  72146. if (c == '\r' && i < glyphs.size()
  72147. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72148. ++i;
  72149. break;
  72150. }
  72151. else if (pg->isWhitespace())
  72152. {
  72153. lastWordBreakIndex = i + 1;
  72154. }
  72155. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72156. {
  72157. if (lastWordBreakIndex >= 0)
  72158. i = lastWordBreakIndex;
  72159. break;
  72160. }
  72161. ++i;
  72162. }
  72163. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72164. float currentLineEndX = currentLineStartX;
  72165. for (int j = i; --j >= lineStartIndex;)
  72166. {
  72167. if (! glyphs.getUnchecked (j)->isWhitespace())
  72168. {
  72169. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72170. break;
  72171. }
  72172. }
  72173. float deltaX = 0.0f;
  72174. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72175. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72176. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72177. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72178. else if (horizontalLayout.testFlags (Justification::right))
  72179. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72180. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72181. x + deltaX - currentLineStartX, y - originalY);
  72182. lineStartIndex = i;
  72183. y += font.getHeight();
  72184. }
  72185. }
  72186. void GlyphArrangement::addFittedText (const Font& f,
  72187. const String& text,
  72188. const float x, const float y,
  72189. const float width, const float height,
  72190. const Justification& layout,
  72191. int maximumLines,
  72192. const float minimumHorizontalScale)
  72193. {
  72194. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72195. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72196. if (text.containsAnyOf ("\r\n"))
  72197. {
  72198. GlyphArrangement ga;
  72199. ga.addJustifiedText (f, text, x, y, width, layout);
  72200. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72201. float dy = y - bb.getY();
  72202. if (layout.testFlags (Justification::verticallyCentred))
  72203. dy += (height - bb.getHeight()) * 0.5f;
  72204. else if (layout.testFlags (Justification::bottom))
  72205. dy += height - bb.getHeight();
  72206. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72207. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72208. for (int i = 0; i < ga.glyphs.size(); ++i)
  72209. glyphs.add (ga.glyphs.getUnchecked (i));
  72210. ga.glyphs.clear (false);
  72211. return;
  72212. }
  72213. int startIndex = glyphs.size();
  72214. addLineOfText (f, text.trim(), x, y);
  72215. if (glyphs.size() > startIndex)
  72216. {
  72217. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72218. - glyphs.getUnchecked (startIndex)->getLeft();
  72219. if (lineWidth <= 0)
  72220. return;
  72221. if (lineWidth * minimumHorizontalScale < width)
  72222. {
  72223. if (lineWidth > width)
  72224. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72225. width / lineWidth);
  72226. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72227. x, y, width, height, layout);
  72228. }
  72229. else if (maximumLines <= 1)
  72230. {
  72231. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72232. x, y, width, height, f, layout, minimumHorizontalScale);
  72233. }
  72234. else
  72235. {
  72236. Font font (f);
  72237. String txt (text.trim());
  72238. const int length = txt.length();
  72239. const int originalStartIndex = startIndex;
  72240. int numLines = 1;
  72241. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72242. maximumLines = 1;
  72243. maximumLines = jmin (maximumLines, length);
  72244. while (numLines < maximumLines)
  72245. {
  72246. ++numLines;
  72247. const float newFontHeight = height / (float) numLines;
  72248. if (newFontHeight < font.getHeight())
  72249. {
  72250. font.setHeight (jmax (8.0f, newFontHeight));
  72251. removeRangeOfGlyphs (startIndex, -1);
  72252. addLineOfText (font, txt, x, y);
  72253. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72254. - glyphs.getUnchecked (startIndex)->getLeft();
  72255. }
  72256. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72257. break;
  72258. }
  72259. if (numLines < 1)
  72260. numLines = 1;
  72261. float lineY = y;
  72262. float widthPerLine = lineWidth / numLines;
  72263. int lastLineStartIndex = 0;
  72264. for (int line = 0; line < numLines; ++line)
  72265. {
  72266. int i = startIndex;
  72267. lastLineStartIndex = i;
  72268. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72269. if (line == numLines - 1)
  72270. {
  72271. widthPerLine = width;
  72272. i = glyphs.size();
  72273. }
  72274. else
  72275. {
  72276. while (i < glyphs.size())
  72277. {
  72278. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72279. if (lineWidth > widthPerLine)
  72280. {
  72281. // got to a point where the line's too long, so skip forward to find a
  72282. // good place to break it..
  72283. const int searchStartIndex = i;
  72284. while (i < glyphs.size())
  72285. {
  72286. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72287. {
  72288. if (glyphs.getUnchecked (i)->isWhitespace()
  72289. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72290. {
  72291. ++i;
  72292. break;
  72293. }
  72294. }
  72295. else
  72296. {
  72297. // can't find a suitable break, so try looking backwards..
  72298. i = searchStartIndex;
  72299. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72300. {
  72301. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72302. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72303. {
  72304. i -= back - 1;
  72305. break;
  72306. }
  72307. }
  72308. break;
  72309. }
  72310. ++i;
  72311. }
  72312. break;
  72313. }
  72314. ++i;
  72315. }
  72316. int wsStart = i;
  72317. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72318. --wsStart;
  72319. int wsEnd = i;
  72320. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72321. ++wsEnd;
  72322. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72323. i = jmax (wsStart, startIndex + 1);
  72324. }
  72325. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72326. x, lineY, width, font.getHeight(), font,
  72327. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72328. minimumHorizontalScale);
  72329. startIndex = i;
  72330. lineY += font.getHeight();
  72331. if (startIndex >= glyphs.size())
  72332. break;
  72333. }
  72334. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72335. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72336. }
  72337. }
  72338. }
  72339. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72340. const float dx, const float dy)
  72341. {
  72342. jassert (startIndex >= 0);
  72343. if (dx != 0.0f || dy != 0.0f)
  72344. {
  72345. if (num < 0 || startIndex + num > glyphs.size())
  72346. num = glyphs.size() - startIndex;
  72347. while (--num >= 0)
  72348. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72349. }
  72350. }
  72351. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72352. const Justification& justification, float minimumHorizontalScale)
  72353. {
  72354. int numDeleted = 0;
  72355. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72356. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72357. if (lineWidth > w)
  72358. {
  72359. if (minimumHorizontalScale < 1.0f)
  72360. {
  72361. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72362. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72363. }
  72364. if (lineWidth > w)
  72365. {
  72366. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72367. numGlyphs -= numDeleted;
  72368. }
  72369. }
  72370. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72371. return numDeleted;
  72372. }
  72373. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  72374. const float horizontalScaleFactor)
  72375. {
  72376. jassert (startIndex >= 0);
  72377. if (num < 0 || startIndex + num > glyphs.size())
  72378. num = glyphs.size() - startIndex;
  72379. if (num > 0)
  72380. {
  72381. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  72382. while (--num >= 0)
  72383. {
  72384. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72385. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  72386. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  72387. pg->w *= horizontalScaleFactor;
  72388. }
  72389. }
  72390. }
  72391. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  72392. {
  72393. jassert (startIndex >= 0);
  72394. if (num < 0 || startIndex + num > glyphs.size())
  72395. num = glyphs.size() - startIndex;
  72396. Rectangle<float> result;
  72397. while (--num >= 0)
  72398. {
  72399. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  72400. if (includeWhitespace || ! pg->isWhitespace())
  72401. result = result.getUnion (pg->getBounds());
  72402. }
  72403. return result;
  72404. }
  72405. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  72406. const float x, const float y, const float width, const float height,
  72407. const Justification& justification)
  72408. {
  72409. jassert (num >= 0 && startIndex >= 0);
  72410. if (glyphs.size() > 0 && num > 0)
  72411. {
  72412. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  72413. | Justification::horizontallyCentred)));
  72414. float deltaX = 0.0f;
  72415. if (justification.testFlags (Justification::horizontallyJustified))
  72416. deltaX = x - bb.getX();
  72417. else if (justification.testFlags (Justification::horizontallyCentred))
  72418. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  72419. else if (justification.testFlags (Justification::right))
  72420. deltaX = (x + width) - bb.getRight();
  72421. else
  72422. deltaX = x - bb.getX();
  72423. float deltaY = 0.0f;
  72424. if (justification.testFlags (Justification::top))
  72425. deltaY = y - bb.getY();
  72426. else if (justification.testFlags (Justification::bottom))
  72427. deltaY = (y + height) - bb.getBottom();
  72428. else
  72429. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  72430. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  72431. if (justification.testFlags (Justification::horizontallyJustified))
  72432. {
  72433. int lineStart = 0;
  72434. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  72435. int i;
  72436. for (i = 0; i < num; ++i)
  72437. {
  72438. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  72439. if (glyphY != baseY)
  72440. {
  72441. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72442. lineStart = i;
  72443. baseY = glyphY;
  72444. }
  72445. }
  72446. if (i > lineStart)
  72447. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  72448. }
  72449. }
  72450. }
  72451. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  72452. {
  72453. if (start + num < glyphs.size()
  72454. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  72455. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  72456. {
  72457. int numSpaces = 0;
  72458. int spacesAtEnd = 0;
  72459. for (int i = 0; i < num; ++i)
  72460. {
  72461. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72462. {
  72463. ++spacesAtEnd;
  72464. ++numSpaces;
  72465. }
  72466. else
  72467. {
  72468. spacesAtEnd = 0;
  72469. }
  72470. }
  72471. numSpaces -= spacesAtEnd;
  72472. if (numSpaces > 0)
  72473. {
  72474. const float startX = glyphs.getUnchecked (start)->getLeft();
  72475. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  72476. const float extraPaddingBetweenWords
  72477. = (targetWidth - (endX - startX)) / (float) numSpaces;
  72478. float deltaX = 0.0f;
  72479. for (int i = 0; i < num; ++i)
  72480. {
  72481. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  72482. if (glyphs.getUnchecked (start + i)->isWhitespace())
  72483. deltaX += extraPaddingBetweenWords;
  72484. }
  72485. }
  72486. }
  72487. }
  72488. void GlyphArrangement::draw (const Graphics& g) const
  72489. {
  72490. for (int i = 0; i < glyphs.size(); ++i)
  72491. {
  72492. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  72493. if (pg->font.isUnderlined())
  72494. {
  72495. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  72496. float nextX = pg->x + pg->w;
  72497. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  72498. nextX = glyphs.getUnchecked (i + 1)->x;
  72499. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  72500. nextX - pg->x, lineThickness);
  72501. }
  72502. pg->draw (g);
  72503. }
  72504. }
  72505. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  72506. {
  72507. for (int i = 0; i < glyphs.size(); ++i)
  72508. {
  72509. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  72510. if (pg->font.isUnderlined())
  72511. {
  72512. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  72513. float nextX = pg->x + pg->w;
  72514. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  72515. nextX = glyphs.getUnchecked (i + 1)->x;
  72516. Path p;
  72517. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  72518. nextX, pg->y + lineThickness * 2.0f),
  72519. lineThickness);
  72520. g.fillPath (p, transform);
  72521. }
  72522. pg->draw (g, transform);
  72523. }
  72524. }
  72525. void GlyphArrangement::createPath (Path& path) const
  72526. {
  72527. for (int i = 0; i < glyphs.size(); ++i)
  72528. glyphs.getUnchecked (i)->createPath (path);
  72529. }
  72530. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  72531. {
  72532. for (int i = 0; i < glyphs.size(); ++i)
  72533. if (glyphs.getUnchecked (i)->hitTest (x, y))
  72534. return i;
  72535. return -1;
  72536. }
  72537. END_JUCE_NAMESPACE
  72538. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  72539. /*** Start of inlined file: juce_TextLayout.cpp ***/
  72540. BEGIN_JUCE_NAMESPACE
  72541. class TextLayout::Token
  72542. {
  72543. public:
  72544. String text;
  72545. Font font;
  72546. int x, y, w, h;
  72547. int line, lineHeight;
  72548. bool isWhitespace, isNewLine;
  72549. Token (const String& t,
  72550. const Font& f,
  72551. const bool isWhitespace_)
  72552. : text (t),
  72553. font (f),
  72554. x(0),
  72555. y(0),
  72556. isWhitespace (isWhitespace_)
  72557. {
  72558. w = font.getStringWidth (t);
  72559. h = roundToInt (f.getHeight());
  72560. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  72561. }
  72562. Token (const Token& other)
  72563. : text (other.text),
  72564. font (other.font),
  72565. x (other.x),
  72566. y (other.y),
  72567. w (other.w),
  72568. h (other.h),
  72569. line (other.line),
  72570. lineHeight (other.lineHeight),
  72571. isWhitespace (other.isWhitespace),
  72572. isNewLine (other.isNewLine)
  72573. {
  72574. }
  72575. ~Token()
  72576. {
  72577. }
  72578. void draw (Graphics& g,
  72579. const int xOffset,
  72580. const int yOffset)
  72581. {
  72582. if (! isWhitespace)
  72583. {
  72584. g.setFont (font);
  72585. g.drawSingleLineText (text.trimEnd(),
  72586. xOffset + x,
  72587. yOffset + y + (lineHeight - h)
  72588. + roundToInt (font.getAscent()));
  72589. }
  72590. }
  72591. juce_UseDebuggingNewOperator
  72592. };
  72593. TextLayout::TextLayout()
  72594. : totalLines (0)
  72595. {
  72596. tokens.ensureStorageAllocated (64);
  72597. }
  72598. TextLayout::TextLayout (const String& text, const Font& font)
  72599. : totalLines (0)
  72600. {
  72601. tokens.ensureStorageAllocated (64);
  72602. appendText (text, font);
  72603. }
  72604. TextLayout::TextLayout (const TextLayout& other)
  72605. : totalLines (0)
  72606. {
  72607. *this = other;
  72608. }
  72609. TextLayout& TextLayout::operator= (const TextLayout& other)
  72610. {
  72611. if (this != &other)
  72612. {
  72613. clear();
  72614. totalLines = other.totalLines;
  72615. tokens.addCopiesOf (other.tokens);
  72616. }
  72617. return *this;
  72618. }
  72619. TextLayout::~TextLayout()
  72620. {
  72621. clear();
  72622. }
  72623. void TextLayout::clear()
  72624. {
  72625. tokens.clear();
  72626. totalLines = 0;
  72627. }
  72628. void TextLayout::appendText (const String& text, const Font& font)
  72629. {
  72630. const juce_wchar* t = text;
  72631. String currentString;
  72632. int lastCharType = 0;
  72633. for (;;)
  72634. {
  72635. const juce_wchar c = *t++;
  72636. if (c == 0)
  72637. break;
  72638. int charType;
  72639. if (c == '\r' || c == '\n')
  72640. {
  72641. charType = 0;
  72642. }
  72643. else if (CharacterFunctions::isWhitespace (c))
  72644. {
  72645. charType = 2;
  72646. }
  72647. else
  72648. {
  72649. charType = 1;
  72650. }
  72651. if (charType == 0 || charType != lastCharType)
  72652. {
  72653. if (currentString.isNotEmpty())
  72654. {
  72655. tokens.add (new Token (currentString, font,
  72656. lastCharType == 2 || lastCharType == 0));
  72657. }
  72658. currentString = String::charToString (c);
  72659. if (c == '\r' && *t == '\n')
  72660. currentString += *t++;
  72661. }
  72662. else
  72663. {
  72664. currentString += c;
  72665. }
  72666. lastCharType = charType;
  72667. }
  72668. if (currentString.isNotEmpty())
  72669. tokens.add (new Token (currentString, font, lastCharType == 2));
  72670. }
  72671. void TextLayout::setText (const String& text, const Font& font)
  72672. {
  72673. clear();
  72674. appendText (text, font);
  72675. }
  72676. void TextLayout::layout (int maxWidth,
  72677. const Justification& justification,
  72678. const bool attemptToBalanceLineLengths)
  72679. {
  72680. if (attemptToBalanceLineLengths)
  72681. {
  72682. const int originalW = maxWidth;
  72683. int bestWidth = maxWidth;
  72684. float bestLineProportion = 0.0f;
  72685. while (maxWidth > originalW / 2)
  72686. {
  72687. layout (maxWidth, justification, false);
  72688. if (getNumLines() <= 1)
  72689. return;
  72690. const int lastLineW = getLineWidth (getNumLines() - 1);
  72691. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  72692. const float prop = lastLineW / (float) lastButOneLineW;
  72693. if (prop > 0.9f)
  72694. return;
  72695. if (prop > bestLineProportion)
  72696. {
  72697. bestLineProportion = prop;
  72698. bestWidth = maxWidth;
  72699. }
  72700. maxWidth -= 10;
  72701. }
  72702. layout (bestWidth, justification, false);
  72703. }
  72704. else
  72705. {
  72706. int x = 0;
  72707. int y = 0;
  72708. int h = 0;
  72709. totalLines = 0;
  72710. int i;
  72711. for (i = 0; i < tokens.size(); ++i)
  72712. {
  72713. Token* const t = tokens.getUnchecked(i);
  72714. t->x = x;
  72715. t->y = y;
  72716. t->line = totalLines;
  72717. x += t->w;
  72718. h = jmax (h, t->h);
  72719. const Token* nextTok = tokens [i + 1];
  72720. if (nextTok == 0)
  72721. break;
  72722. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  72723. {
  72724. // finished a line, so go back and update the heights of the things on it
  72725. for (int j = i; j >= 0; --j)
  72726. {
  72727. Token* const tok = tokens.getUnchecked(j);
  72728. if (tok->line == totalLines)
  72729. tok->lineHeight = h;
  72730. else
  72731. break;
  72732. }
  72733. x = 0;
  72734. y += h;
  72735. h = 0;
  72736. ++totalLines;
  72737. }
  72738. }
  72739. // finished a line, so go back and update the heights of the things on it
  72740. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  72741. {
  72742. Token* const t = tokens.getUnchecked(j);
  72743. if (t->line == totalLines)
  72744. t->lineHeight = h;
  72745. else
  72746. break;
  72747. }
  72748. ++totalLines;
  72749. if (! justification.testFlags (Justification::left))
  72750. {
  72751. int totalW = getWidth();
  72752. for (i = totalLines; --i >= 0;)
  72753. {
  72754. const int lineW = getLineWidth (i);
  72755. int dx = 0;
  72756. if (justification.testFlags (Justification::horizontallyCentred))
  72757. dx = (totalW - lineW) / 2;
  72758. else if (justification.testFlags (Justification::right))
  72759. dx = totalW - lineW;
  72760. for (int j = tokens.size(); --j >= 0;)
  72761. {
  72762. Token* const t = tokens.getUnchecked(j);
  72763. if (t->line == i)
  72764. t->x += dx;
  72765. }
  72766. }
  72767. }
  72768. }
  72769. }
  72770. int TextLayout::getLineWidth (const int lineNumber) const
  72771. {
  72772. int maxW = 0;
  72773. for (int i = tokens.size(); --i >= 0;)
  72774. {
  72775. const Token* const t = tokens.getUnchecked(i);
  72776. if (t->line == lineNumber && ! t->isWhitespace)
  72777. maxW = jmax (maxW, t->x + t->w);
  72778. }
  72779. return maxW;
  72780. }
  72781. int TextLayout::getWidth() const
  72782. {
  72783. int maxW = 0;
  72784. for (int i = tokens.size(); --i >= 0;)
  72785. {
  72786. const Token* const t = tokens.getUnchecked(i);
  72787. if (! t->isWhitespace)
  72788. maxW = jmax (maxW, t->x + t->w);
  72789. }
  72790. return maxW;
  72791. }
  72792. int TextLayout::getHeight() const
  72793. {
  72794. int maxH = 0;
  72795. for (int i = tokens.size(); --i >= 0;)
  72796. {
  72797. const Token* const t = tokens.getUnchecked(i);
  72798. if (! t->isWhitespace)
  72799. maxH = jmax (maxH, t->y + t->h);
  72800. }
  72801. return maxH;
  72802. }
  72803. void TextLayout::draw (Graphics& g,
  72804. const int xOffset,
  72805. const int yOffset) const
  72806. {
  72807. for (int i = tokens.size(); --i >= 0;)
  72808. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  72809. }
  72810. void TextLayout::drawWithin (Graphics& g,
  72811. int x, int y, int w, int h,
  72812. const Justification& justification) const
  72813. {
  72814. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  72815. x, y, w, h);
  72816. draw (g, x, y);
  72817. }
  72818. END_JUCE_NAMESPACE
  72819. /*** End of inlined file: juce_TextLayout.cpp ***/
  72820. /*** Start of inlined file: juce_Typeface.cpp ***/
  72821. BEGIN_JUCE_NAMESPACE
  72822. Typeface::Typeface (const String& name_) throw()
  72823. : name (name_)
  72824. {
  72825. }
  72826. Typeface::~Typeface()
  72827. {
  72828. }
  72829. class CustomTypeface::GlyphInfo
  72830. {
  72831. public:
  72832. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  72833. : character (character_), path (path_), width (width_)
  72834. {
  72835. }
  72836. ~GlyphInfo() throw()
  72837. {
  72838. }
  72839. struct KerningPair
  72840. {
  72841. juce_wchar character2;
  72842. float kerningAmount;
  72843. };
  72844. void addKerningPair (const juce_wchar subsequentCharacter,
  72845. const float extraKerningAmount) throw()
  72846. {
  72847. KerningPair kp;
  72848. kp.character2 = subsequentCharacter;
  72849. kp.kerningAmount = extraKerningAmount;
  72850. kerningPairs.add (kp);
  72851. }
  72852. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  72853. {
  72854. if (subsequentCharacter != 0)
  72855. {
  72856. for (int i = kerningPairs.size(); --i >= 0;)
  72857. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  72858. return width + kerningPairs.getReference(i).kerningAmount;
  72859. }
  72860. return width;
  72861. }
  72862. const juce_wchar character;
  72863. const Path path;
  72864. float width;
  72865. Array <KerningPair> kerningPairs;
  72866. juce_UseDebuggingNewOperator
  72867. private:
  72868. GlyphInfo (const GlyphInfo&);
  72869. GlyphInfo& operator= (const GlyphInfo&);
  72870. };
  72871. CustomTypeface::CustomTypeface()
  72872. : Typeface (String::empty)
  72873. {
  72874. clear();
  72875. }
  72876. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  72877. : Typeface (String::empty)
  72878. {
  72879. clear();
  72880. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  72881. BufferedInputStream in (&gzin, 32768, false);
  72882. name = in.readString();
  72883. isBold = in.readBool();
  72884. isItalic = in.readBool();
  72885. ascent = in.readFloat();
  72886. defaultCharacter = (juce_wchar) in.readShort();
  72887. int i, numChars = in.readInt();
  72888. for (i = 0; i < numChars; ++i)
  72889. {
  72890. const juce_wchar c = (juce_wchar) in.readShort();
  72891. const float width = in.readFloat();
  72892. Path p;
  72893. p.loadPathFromStream (in);
  72894. addGlyph (c, p, width);
  72895. }
  72896. const int numKerningPairs = in.readInt();
  72897. for (i = 0; i < numKerningPairs; ++i)
  72898. {
  72899. const juce_wchar char1 = (juce_wchar) in.readShort();
  72900. const juce_wchar char2 = (juce_wchar) in.readShort();
  72901. addKerningPair (char1, char2, in.readFloat());
  72902. }
  72903. }
  72904. CustomTypeface::~CustomTypeface()
  72905. {
  72906. }
  72907. void CustomTypeface::clear()
  72908. {
  72909. defaultCharacter = 0;
  72910. ascent = 1.0f;
  72911. isBold = isItalic = false;
  72912. zeromem (lookupTable, sizeof (lookupTable));
  72913. glyphs.clear();
  72914. }
  72915. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  72916. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  72917. {
  72918. name = name_;
  72919. defaultCharacter = defaultCharacter_;
  72920. ascent = ascent_;
  72921. isBold = isBold_;
  72922. isItalic = isItalic_;
  72923. }
  72924. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  72925. {
  72926. // Check that you're not trying to add the same character twice..
  72927. jassert (findGlyph (character, false) == 0);
  72928. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  72929. lookupTable [character] = (short) glyphs.size();
  72930. glyphs.add (new GlyphInfo (character, path, width));
  72931. }
  72932. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  72933. {
  72934. if (extraAmount != 0)
  72935. {
  72936. GlyphInfo* const g = findGlyph (char1, true);
  72937. jassert (g != 0); // can only add kerning pairs for characters that exist!
  72938. if (g != 0)
  72939. g->addKerningPair (char2, extraAmount);
  72940. }
  72941. }
  72942. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  72943. {
  72944. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  72945. return glyphs [(int) lookupTable [(int) character]];
  72946. for (int i = 0; i < glyphs.size(); ++i)
  72947. {
  72948. GlyphInfo* const g = glyphs.getUnchecked(i);
  72949. if (g->character == character)
  72950. return g;
  72951. }
  72952. if (loadIfNeeded && loadGlyphIfPossible (character))
  72953. return findGlyph (character, false);
  72954. return 0;
  72955. }
  72956. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  72957. {
  72958. GlyphInfo* glyph = findGlyph (character, true);
  72959. if (glyph == 0)
  72960. {
  72961. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  72962. glyph = findGlyph (L' ', true);
  72963. if (glyph == 0)
  72964. {
  72965. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  72966. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  72967. if (fallbackTypeface != 0 && fallbackTypeface != this)
  72968. {
  72969. //xxx
  72970. }
  72971. if (glyph == 0)
  72972. glyph = findGlyph (defaultCharacter, true);
  72973. }
  72974. }
  72975. return glyph;
  72976. }
  72977. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  72978. {
  72979. return false;
  72980. }
  72981. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  72982. {
  72983. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  72984. for (int i = 0; i < numCharacters; ++i)
  72985. {
  72986. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  72987. Array <int> glyphIndexes;
  72988. Array <float> offsets;
  72989. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  72990. const int glyphIndex = glyphIndexes.getFirst();
  72991. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  72992. {
  72993. const float glyphWidth = offsets[1];
  72994. Path p;
  72995. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  72996. addGlyph (c, p, glyphWidth);
  72997. for (int j = glyphs.size() - 1; --j >= 0;)
  72998. {
  72999. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73000. glyphIndexes.clearQuick();
  73001. offsets.clearQuick();
  73002. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73003. if (offsets.size() > 1)
  73004. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73005. }
  73006. }
  73007. }
  73008. }
  73009. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73010. {
  73011. GZIPCompressorOutputStream out (&outputStream);
  73012. out.writeString (name);
  73013. out.writeBool (isBold);
  73014. out.writeBool (isItalic);
  73015. out.writeFloat (ascent);
  73016. out.writeShort ((short) (unsigned short) defaultCharacter);
  73017. out.writeInt (glyphs.size());
  73018. int i, numKerningPairs = 0;
  73019. for (i = 0; i < glyphs.size(); ++i)
  73020. {
  73021. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73022. out.writeShort ((short) (unsigned short) g->character);
  73023. out.writeFloat (g->width);
  73024. g->path.writePathToStream (out);
  73025. numKerningPairs += g->kerningPairs.size();
  73026. }
  73027. out.writeInt (numKerningPairs);
  73028. for (i = 0; i < glyphs.size(); ++i)
  73029. {
  73030. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73031. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73032. {
  73033. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73034. out.writeShort ((short) (unsigned short) g->character);
  73035. out.writeShort ((short) (unsigned short) p.character2);
  73036. out.writeFloat (p.kerningAmount);
  73037. }
  73038. }
  73039. return true;
  73040. }
  73041. float CustomTypeface::getAscent() const
  73042. {
  73043. return ascent;
  73044. }
  73045. float CustomTypeface::getDescent() const
  73046. {
  73047. return 1.0f - ascent;
  73048. }
  73049. float CustomTypeface::getStringWidth (const String& text)
  73050. {
  73051. float x = 0;
  73052. const juce_wchar* t = text;
  73053. while (*t != 0)
  73054. {
  73055. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73056. if (glyph != 0)
  73057. x += glyph->getHorizontalSpacing (*t);
  73058. }
  73059. return x;
  73060. }
  73061. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73062. {
  73063. xOffsets.add (0);
  73064. float x = 0;
  73065. const juce_wchar* t = text;
  73066. while (*t != 0)
  73067. {
  73068. const juce_wchar c = *t++;
  73069. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73070. if (glyph != 0)
  73071. {
  73072. x += glyph->getHorizontalSpacing (*t);
  73073. resultGlyphs.add ((int) glyph->character);
  73074. xOffsets.add (x);
  73075. }
  73076. }
  73077. }
  73078. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73079. {
  73080. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73081. if (glyph != 0)
  73082. {
  73083. path = glyph->path;
  73084. return true;
  73085. }
  73086. return false;
  73087. }
  73088. END_JUCE_NAMESPACE
  73089. /*** End of inlined file: juce_Typeface.cpp ***/
  73090. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73091. BEGIN_JUCE_NAMESPACE
  73092. AffineTransform::AffineTransform() throw()
  73093. : mat00 (1.0f),
  73094. mat01 (0),
  73095. mat02 (0),
  73096. mat10 (0),
  73097. mat11 (1.0f),
  73098. mat12 (0)
  73099. {
  73100. }
  73101. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73102. : mat00 (other.mat00),
  73103. mat01 (other.mat01),
  73104. mat02 (other.mat02),
  73105. mat10 (other.mat10),
  73106. mat11 (other.mat11),
  73107. mat12 (other.mat12)
  73108. {
  73109. }
  73110. AffineTransform::AffineTransform (const float mat00_,
  73111. const float mat01_,
  73112. const float mat02_,
  73113. const float mat10_,
  73114. const float mat11_,
  73115. const float mat12_) throw()
  73116. : mat00 (mat00_),
  73117. mat01 (mat01_),
  73118. mat02 (mat02_),
  73119. mat10 (mat10_),
  73120. mat11 (mat11_),
  73121. mat12 (mat12_)
  73122. {
  73123. }
  73124. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73125. {
  73126. mat00 = other.mat00;
  73127. mat01 = other.mat01;
  73128. mat02 = other.mat02;
  73129. mat10 = other.mat10;
  73130. mat11 = other.mat11;
  73131. mat12 = other.mat12;
  73132. return *this;
  73133. }
  73134. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73135. {
  73136. return mat00 == other.mat00
  73137. && mat01 == other.mat01
  73138. && mat02 == other.mat02
  73139. && mat10 == other.mat10
  73140. && mat11 == other.mat11
  73141. && mat12 == other.mat12;
  73142. }
  73143. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73144. {
  73145. return ! operator== (other);
  73146. }
  73147. bool AffineTransform::isIdentity() const throw()
  73148. {
  73149. return (mat01 == 0)
  73150. && (mat02 == 0)
  73151. && (mat10 == 0)
  73152. && (mat12 == 0)
  73153. && (mat00 == 1.0f)
  73154. && (mat11 == 1.0f);
  73155. }
  73156. const AffineTransform AffineTransform::identity;
  73157. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73158. {
  73159. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73160. other.mat00 * mat01 + other.mat01 * mat11,
  73161. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73162. other.mat10 * mat00 + other.mat11 * mat10,
  73163. other.mat10 * mat01 + other.mat11 * mat11,
  73164. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73165. }
  73166. const AffineTransform AffineTransform::followedBy (const float omat00,
  73167. const float omat01,
  73168. const float omat02,
  73169. const float omat10,
  73170. const float omat11,
  73171. const float omat12) const throw()
  73172. {
  73173. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73174. omat00 * mat01 + omat01 * mat11,
  73175. omat00 * mat02 + omat01 * mat12 + omat02,
  73176. omat10 * mat00 + omat11 * mat10,
  73177. omat10 * mat01 + omat11 * mat11,
  73178. omat10 * mat02 + omat11 * mat12 + omat12);
  73179. }
  73180. const AffineTransform AffineTransform::translated (const float dx,
  73181. const float dy) const throw()
  73182. {
  73183. return AffineTransform (mat00, mat01, mat02 + dx,
  73184. mat10, mat11, mat12 + dy);
  73185. }
  73186. const AffineTransform AffineTransform::translation (const float dx,
  73187. const float dy) throw()
  73188. {
  73189. return AffineTransform (1.0f, 0, dx,
  73190. 0, 1.0f, dy);
  73191. }
  73192. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73193. {
  73194. const float cosRad = std::cos (rad);
  73195. const float sinRad = std::sin (rad);
  73196. return followedBy (cosRad, -sinRad, 0,
  73197. sinRad, cosRad, 0);
  73198. }
  73199. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73200. {
  73201. const float cosRad = std::cos (rad);
  73202. const float sinRad = std::sin (rad);
  73203. return AffineTransform (cosRad, -sinRad, 0,
  73204. sinRad, cosRad, 0);
  73205. }
  73206. const AffineTransform AffineTransform::rotated (const float angle,
  73207. const float pivotX,
  73208. const float pivotY) const throw()
  73209. {
  73210. return translated (-pivotX, -pivotY)
  73211. .rotated (angle)
  73212. .translated (pivotX, pivotY);
  73213. }
  73214. const AffineTransform AffineTransform::rotation (const float angle,
  73215. const float pivotX,
  73216. const float pivotY) throw()
  73217. {
  73218. return translation (-pivotX, -pivotY)
  73219. .rotated (angle)
  73220. .translated (pivotX, pivotY);
  73221. }
  73222. const AffineTransform AffineTransform::scaled (const float factorX,
  73223. const float factorY) const throw()
  73224. {
  73225. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73226. factorY * mat10, factorY * mat11, factorY * mat12);
  73227. }
  73228. const AffineTransform AffineTransform::scale (const float factorX,
  73229. const float factorY) throw()
  73230. {
  73231. return AffineTransform (factorX, 0, 0,
  73232. 0, factorY, 0);
  73233. }
  73234. const AffineTransform AffineTransform::sheared (const float shearX,
  73235. const float shearY) const throw()
  73236. {
  73237. return followedBy (1.0f, shearX, 0,
  73238. shearY, 1.0f, 0);
  73239. }
  73240. const AffineTransform AffineTransform::inverted() const throw()
  73241. {
  73242. double determinant = (mat00 * mat11 - mat10 * mat01);
  73243. if (determinant != 0.0)
  73244. {
  73245. determinant = 1.0 / determinant;
  73246. const float dst00 = (float) (mat11 * determinant);
  73247. const float dst10 = (float) (-mat10 * determinant);
  73248. const float dst01 = (float) (-mat01 * determinant);
  73249. const float dst11 = (float) (mat00 * determinant);
  73250. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73251. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73252. }
  73253. else
  73254. {
  73255. // singularity..
  73256. return *this;
  73257. }
  73258. }
  73259. bool AffineTransform::isSingularity() const throw()
  73260. {
  73261. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73262. }
  73263. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73264. const float x10, const float y10,
  73265. const float x01, const float y01) throw()
  73266. {
  73267. return AffineTransform (x10 - x00, x01 - x00, x00,
  73268. y10 - y00, y01 - y00, y00);
  73269. }
  73270. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73271. const float sx2, const float sy2, const float tx2, const float ty2,
  73272. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73273. {
  73274. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73275. .inverted()
  73276. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73277. }
  73278. bool AffineTransform::isOnlyTranslation() const throw()
  73279. {
  73280. return (mat01 == 0)
  73281. && (mat10 == 0)
  73282. && (mat00 == 1.0f)
  73283. && (mat11 == 1.0f);
  73284. }
  73285. END_JUCE_NAMESPACE
  73286. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73287. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73288. BEGIN_JUCE_NAMESPACE
  73289. BorderSize::BorderSize() throw()
  73290. : top (0),
  73291. left (0),
  73292. bottom (0),
  73293. right (0)
  73294. {
  73295. }
  73296. BorderSize::BorderSize (const BorderSize& other) throw()
  73297. : top (other.top),
  73298. left (other.left),
  73299. bottom (other.bottom),
  73300. right (other.right)
  73301. {
  73302. }
  73303. BorderSize::BorderSize (const int topGap,
  73304. const int leftGap,
  73305. const int bottomGap,
  73306. const int rightGap) throw()
  73307. : top (topGap),
  73308. left (leftGap),
  73309. bottom (bottomGap),
  73310. right (rightGap)
  73311. {
  73312. }
  73313. BorderSize::BorderSize (const int allGaps) throw()
  73314. : top (allGaps),
  73315. left (allGaps),
  73316. bottom (allGaps),
  73317. right (allGaps)
  73318. {
  73319. }
  73320. BorderSize::~BorderSize() throw()
  73321. {
  73322. }
  73323. void BorderSize::setTop (const int newTopGap) throw()
  73324. {
  73325. top = newTopGap;
  73326. }
  73327. void BorderSize::setLeft (const int newLeftGap) throw()
  73328. {
  73329. left = newLeftGap;
  73330. }
  73331. void BorderSize::setBottom (const int newBottomGap) throw()
  73332. {
  73333. bottom = newBottomGap;
  73334. }
  73335. void BorderSize::setRight (const int newRightGap) throw()
  73336. {
  73337. right = newRightGap;
  73338. }
  73339. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73340. {
  73341. return Rectangle<int> (r.getX() + left,
  73342. r.getY() + top,
  73343. r.getWidth() - (left + right),
  73344. r.getHeight() - (top + bottom));
  73345. }
  73346. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73347. {
  73348. r.setBounds (r.getX() + left,
  73349. r.getY() + top,
  73350. r.getWidth() - (left + right),
  73351. r.getHeight() - (top + bottom));
  73352. }
  73353. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73354. {
  73355. return Rectangle<int> (r.getX() - left,
  73356. r.getY() - top,
  73357. r.getWidth() + (left + right),
  73358. r.getHeight() + (top + bottom));
  73359. }
  73360. void BorderSize::addTo (Rectangle<int>& r) const throw()
  73361. {
  73362. r.setBounds (r.getX() - left,
  73363. r.getY() - top,
  73364. r.getWidth() + (left + right),
  73365. r.getHeight() + (top + bottom));
  73366. }
  73367. bool BorderSize::operator== (const BorderSize& other) const throw()
  73368. {
  73369. return top == other.top
  73370. && left == other.left
  73371. && bottom == other.bottom
  73372. && right == other.right;
  73373. }
  73374. bool BorderSize::operator!= (const BorderSize& other) const throw()
  73375. {
  73376. return ! operator== (other);
  73377. }
  73378. END_JUCE_NAMESPACE
  73379. /*** End of inlined file: juce_BorderSize.cpp ***/
  73380. /*** Start of inlined file: juce_Path.cpp ***/
  73381. BEGIN_JUCE_NAMESPACE
  73382. // tests that some co-ords aren't NaNs
  73383. #define CHECK_COORDS_ARE_VALID(x, y) \
  73384. jassert (x == x && y == y);
  73385. namespace PathHelpers
  73386. {
  73387. static const float ellipseAngularIncrement = 0.05f;
  73388. static const String nextToken (const juce_wchar*& t)
  73389. {
  73390. while (CharacterFunctions::isWhitespace (*t))
  73391. ++t;
  73392. const juce_wchar* const start = t;
  73393. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  73394. ++t;
  73395. return String (start, (int) (t - start));
  73396. }
  73397. }
  73398. const float Path::lineMarker = 100001.0f;
  73399. const float Path::moveMarker = 100002.0f;
  73400. const float Path::quadMarker = 100003.0f;
  73401. const float Path::cubicMarker = 100004.0f;
  73402. const float Path::closeSubPathMarker = 100005.0f;
  73403. Path::Path()
  73404. : numElements (0),
  73405. pathXMin (0),
  73406. pathXMax (0),
  73407. pathYMin (0),
  73408. pathYMax (0),
  73409. useNonZeroWinding (true)
  73410. {
  73411. }
  73412. Path::~Path()
  73413. {
  73414. }
  73415. Path::Path (const Path& other)
  73416. : numElements (other.numElements),
  73417. pathXMin (other.pathXMin),
  73418. pathXMax (other.pathXMax),
  73419. pathYMin (other.pathYMin),
  73420. pathYMax (other.pathYMax),
  73421. useNonZeroWinding (other.useNonZeroWinding)
  73422. {
  73423. if (numElements > 0)
  73424. {
  73425. data.setAllocatedSize ((int) numElements);
  73426. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73427. }
  73428. }
  73429. Path& Path::operator= (const Path& other)
  73430. {
  73431. if (this != &other)
  73432. {
  73433. data.ensureAllocatedSize ((int) other.numElements);
  73434. numElements = other.numElements;
  73435. pathXMin = other.pathXMin;
  73436. pathXMax = other.pathXMax;
  73437. pathYMin = other.pathYMin;
  73438. pathYMax = other.pathYMax;
  73439. useNonZeroWinding = other.useNonZeroWinding;
  73440. if (numElements > 0)
  73441. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  73442. }
  73443. return *this;
  73444. }
  73445. bool Path::operator== (const Path& other) const throw()
  73446. {
  73447. return ! operator!= (other);
  73448. }
  73449. bool Path::operator!= (const Path& other) const throw()
  73450. {
  73451. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  73452. return true;
  73453. for (size_t i = 0; i < numElements; ++i)
  73454. if (data.elements[i] != other.data.elements[i])
  73455. return true;
  73456. return false;
  73457. }
  73458. void Path::clear() throw()
  73459. {
  73460. numElements = 0;
  73461. pathXMin = 0;
  73462. pathYMin = 0;
  73463. pathYMax = 0;
  73464. pathXMax = 0;
  73465. }
  73466. void Path::swapWithPath (Path& other) throw()
  73467. {
  73468. data.swapWith (other.data);
  73469. swapVariables <size_t> (numElements, other.numElements);
  73470. swapVariables <float> (pathXMin, other.pathXMin);
  73471. swapVariables <float> (pathXMax, other.pathXMax);
  73472. swapVariables <float> (pathYMin, other.pathYMin);
  73473. swapVariables <float> (pathYMax, other.pathYMax);
  73474. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  73475. }
  73476. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  73477. {
  73478. useNonZeroWinding = isNonZero;
  73479. }
  73480. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  73481. const bool preserveProportions) throw()
  73482. {
  73483. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  73484. }
  73485. bool Path::isEmpty() const throw()
  73486. {
  73487. size_t i = 0;
  73488. while (i < numElements)
  73489. {
  73490. const float type = data.elements [i++];
  73491. if (type == moveMarker)
  73492. {
  73493. i += 2;
  73494. }
  73495. else if (type == lineMarker
  73496. || type == quadMarker
  73497. || type == cubicMarker)
  73498. {
  73499. return false;
  73500. }
  73501. }
  73502. return true;
  73503. }
  73504. const Rectangle<float> Path::getBounds() const throw()
  73505. {
  73506. return Rectangle<float> (pathXMin, pathYMin,
  73507. pathXMax - pathXMin,
  73508. pathYMax - pathYMin);
  73509. }
  73510. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  73511. {
  73512. return getBounds().transformed (transform);
  73513. }
  73514. void Path::startNewSubPath (const float x, const float y)
  73515. {
  73516. CHECK_COORDS_ARE_VALID (x, y);
  73517. if (numElements == 0)
  73518. {
  73519. pathXMin = pathXMax = x;
  73520. pathYMin = pathYMax = y;
  73521. }
  73522. else
  73523. {
  73524. pathXMin = jmin (pathXMin, x);
  73525. pathXMax = jmax (pathXMax, x);
  73526. pathYMin = jmin (pathYMin, y);
  73527. pathYMax = jmax (pathYMax, y);
  73528. }
  73529. data.ensureAllocatedSize ((int) numElements + 3);
  73530. data.elements [numElements++] = moveMarker;
  73531. data.elements [numElements++] = x;
  73532. data.elements [numElements++] = y;
  73533. }
  73534. void Path::startNewSubPath (const Point<float>& start)
  73535. {
  73536. startNewSubPath (start.getX(), start.getY());
  73537. }
  73538. void Path::lineTo (const float x, const float y)
  73539. {
  73540. CHECK_COORDS_ARE_VALID (x, y);
  73541. if (numElements == 0)
  73542. startNewSubPath (0, 0);
  73543. data.ensureAllocatedSize ((int) numElements + 3);
  73544. data.elements [numElements++] = lineMarker;
  73545. data.elements [numElements++] = x;
  73546. data.elements [numElements++] = y;
  73547. pathXMin = jmin (pathXMin, x);
  73548. pathXMax = jmax (pathXMax, x);
  73549. pathYMin = jmin (pathYMin, y);
  73550. pathYMax = jmax (pathYMax, y);
  73551. }
  73552. void Path::lineTo (const Point<float>& end)
  73553. {
  73554. lineTo (end.getX(), end.getY());
  73555. }
  73556. void Path::quadraticTo (const float x1, const float y1,
  73557. const float x2, const float y2)
  73558. {
  73559. CHECK_COORDS_ARE_VALID (x1, y1);
  73560. CHECK_COORDS_ARE_VALID (x2, y2);
  73561. if (numElements == 0)
  73562. startNewSubPath (0, 0);
  73563. data.ensureAllocatedSize ((int) numElements + 5);
  73564. data.elements [numElements++] = quadMarker;
  73565. data.elements [numElements++] = x1;
  73566. data.elements [numElements++] = y1;
  73567. data.elements [numElements++] = x2;
  73568. data.elements [numElements++] = y2;
  73569. pathXMin = jmin (pathXMin, x1, x2);
  73570. pathXMax = jmax (pathXMax, x1, x2);
  73571. pathYMin = jmin (pathYMin, y1, y2);
  73572. pathYMax = jmax (pathYMax, y1, y2);
  73573. }
  73574. void Path::quadraticTo (const Point<float>& controlPoint,
  73575. const Point<float>& endPoint)
  73576. {
  73577. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  73578. endPoint.getX(), endPoint.getY());
  73579. }
  73580. void Path::cubicTo (const float x1, const float y1,
  73581. const float x2, const float y2,
  73582. const float x3, const float y3)
  73583. {
  73584. CHECK_COORDS_ARE_VALID (x1, y1);
  73585. CHECK_COORDS_ARE_VALID (x2, y2);
  73586. CHECK_COORDS_ARE_VALID (x3, y3);
  73587. if (numElements == 0)
  73588. startNewSubPath (0, 0);
  73589. data.ensureAllocatedSize ((int) numElements + 7);
  73590. data.elements [numElements++] = cubicMarker;
  73591. data.elements [numElements++] = x1;
  73592. data.elements [numElements++] = y1;
  73593. data.elements [numElements++] = x2;
  73594. data.elements [numElements++] = y2;
  73595. data.elements [numElements++] = x3;
  73596. data.elements [numElements++] = y3;
  73597. pathXMin = jmin (pathXMin, x1, x2, x3);
  73598. pathXMax = jmax (pathXMax, x1, x2, x3);
  73599. pathYMin = jmin (pathYMin, y1, y2, y3);
  73600. pathYMax = jmax (pathYMax, y1, y2, y3);
  73601. }
  73602. void Path::cubicTo (const Point<float>& controlPoint1,
  73603. const Point<float>& controlPoint2,
  73604. const Point<float>& endPoint)
  73605. {
  73606. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  73607. controlPoint2.getX(), controlPoint2.getY(),
  73608. endPoint.getX(), endPoint.getY());
  73609. }
  73610. void Path::closeSubPath()
  73611. {
  73612. if (numElements > 0
  73613. && data.elements [numElements - 1] != closeSubPathMarker)
  73614. {
  73615. data.ensureAllocatedSize ((int) numElements + 1);
  73616. data.elements [numElements++] = closeSubPathMarker;
  73617. }
  73618. }
  73619. const Point<float> Path::getCurrentPosition() const
  73620. {
  73621. size_t i = numElements - 1;
  73622. if (i > 0 && data.elements[i] == closeSubPathMarker)
  73623. {
  73624. while (i >= 0)
  73625. {
  73626. if (data.elements[i] == moveMarker)
  73627. {
  73628. i += 2;
  73629. break;
  73630. }
  73631. --i;
  73632. }
  73633. }
  73634. if (i > 0)
  73635. return Point<float> (data.elements [i - 1], data.elements [i]);
  73636. return Point<float>();
  73637. }
  73638. void Path::addRectangle (const float x, const float y,
  73639. const float w, const float h)
  73640. {
  73641. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  73642. if (w < 0)
  73643. swapVariables (x1, x2);
  73644. if (h < 0)
  73645. swapVariables (y1, y2);
  73646. data.ensureAllocatedSize ((int) numElements + 13);
  73647. if (numElements == 0)
  73648. {
  73649. pathXMin = x1;
  73650. pathXMax = x2;
  73651. pathYMin = y1;
  73652. pathYMax = y2;
  73653. }
  73654. else
  73655. {
  73656. pathXMin = jmin (pathXMin, x1);
  73657. pathXMax = jmax (pathXMax, x2);
  73658. pathYMin = jmin (pathYMin, y1);
  73659. pathYMax = jmax (pathYMax, y2);
  73660. }
  73661. data.elements [numElements++] = moveMarker;
  73662. data.elements [numElements++] = x1;
  73663. data.elements [numElements++] = y2;
  73664. data.elements [numElements++] = lineMarker;
  73665. data.elements [numElements++] = x1;
  73666. data.elements [numElements++] = y1;
  73667. data.elements [numElements++] = lineMarker;
  73668. data.elements [numElements++] = x2;
  73669. data.elements [numElements++] = y1;
  73670. data.elements [numElements++] = lineMarker;
  73671. data.elements [numElements++] = x2;
  73672. data.elements [numElements++] = y2;
  73673. data.elements [numElements++] = closeSubPathMarker;
  73674. }
  73675. void Path::addRectangle (const Rectangle<int>& rectangle)
  73676. {
  73677. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  73678. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  73679. }
  73680. void Path::addRoundedRectangle (const float x, const float y,
  73681. const float w, const float h,
  73682. float csx,
  73683. float csy)
  73684. {
  73685. csx = jmin (csx, w * 0.5f);
  73686. csy = jmin (csy, h * 0.5f);
  73687. const float cs45x = csx * 0.45f;
  73688. const float cs45y = csy * 0.45f;
  73689. const float x2 = x + w;
  73690. const float y2 = y + h;
  73691. startNewSubPath (x + csx, y);
  73692. lineTo (x2 - csx, y);
  73693. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  73694. lineTo (x2, y2 - csy);
  73695. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  73696. lineTo (x + csx, y2);
  73697. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  73698. lineTo (x, y + csy);
  73699. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  73700. closeSubPath();
  73701. }
  73702. void Path::addRoundedRectangle (const float x, const float y,
  73703. const float w, const float h,
  73704. float cs)
  73705. {
  73706. addRoundedRectangle (x, y, w, h, cs, cs);
  73707. }
  73708. void Path::addTriangle (const float x1, const float y1,
  73709. const float x2, const float y2,
  73710. const float x3, const float y3)
  73711. {
  73712. startNewSubPath (x1, y1);
  73713. lineTo (x2, y2);
  73714. lineTo (x3, y3);
  73715. closeSubPath();
  73716. }
  73717. void Path::addQuadrilateral (const float x1, const float y1,
  73718. const float x2, const float y2,
  73719. const float x3, const float y3,
  73720. const float x4, const float y4)
  73721. {
  73722. startNewSubPath (x1, y1);
  73723. lineTo (x2, y2);
  73724. lineTo (x3, y3);
  73725. lineTo (x4, y4);
  73726. closeSubPath();
  73727. }
  73728. void Path::addEllipse (const float x, const float y,
  73729. const float w, const float h)
  73730. {
  73731. const float hw = w * 0.5f;
  73732. const float hw55 = hw * 0.55f;
  73733. const float hh = h * 0.5f;
  73734. const float hh45 = hh * 0.55f;
  73735. const float cx = x + hw;
  73736. const float cy = y + hh;
  73737. startNewSubPath (cx, cy - hh);
  73738. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  73739. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  73740. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  73741. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  73742. closeSubPath();
  73743. }
  73744. void Path::addArc (const float x, const float y,
  73745. const float w, const float h,
  73746. const float fromRadians,
  73747. const float toRadians,
  73748. const bool startAsNewSubPath)
  73749. {
  73750. const float radiusX = w / 2.0f;
  73751. const float radiusY = h / 2.0f;
  73752. addCentredArc (x + radiusX,
  73753. y + radiusY,
  73754. radiusX, radiusY,
  73755. 0.0f,
  73756. fromRadians, toRadians,
  73757. startAsNewSubPath);
  73758. }
  73759. void Path::addCentredArc (const float centreX, const float centreY,
  73760. const float radiusX, const float radiusY,
  73761. const float rotationOfEllipse,
  73762. const float fromRadians,
  73763. const float toRadians,
  73764. const bool startAsNewSubPath)
  73765. {
  73766. if (radiusX > 0.0f && radiusY > 0.0f)
  73767. {
  73768. const Point<float> centre (centreX, centreY);
  73769. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  73770. float angle = fromRadians;
  73771. if (startAsNewSubPath)
  73772. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73773. if (fromRadians < toRadians)
  73774. {
  73775. if (startAsNewSubPath)
  73776. angle += PathHelpers::ellipseAngularIncrement;
  73777. while (angle < toRadians)
  73778. {
  73779. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73780. angle += PathHelpers::ellipseAngularIncrement;
  73781. }
  73782. }
  73783. else
  73784. {
  73785. if (startAsNewSubPath)
  73786. angle -= PathHelpers::ellipseAngularIncrement;
  73787. while (angle > toRadians)
  73788. {
  73789. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  73790. angle -= PathHelpers::ellipseAngularIncrement;
  73791. }
  73792. }
  73793. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  73794. }
  73795. }
  73796. void Path::addPieSegment (const float x, const float y,
  73797. const float width, const float height,
  73798. const float fromRadians,
  73799. const float toRadians,
  73800. const float innerCircleProportionalSize)
  73801. {
  73802. float radiusX = width * 0.5f;
  73803. float radiusY = height * 0.5f;
  73804. const Point<float> centre (x + radiusX, y + radiusY);
  73805. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  73806. addArc (x, y, width, height, fromRadians, toRadians);
  73807. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  73808. {
  73809. closeSubPath();
  73810. if (innerCircleProportionalSize > 0)
  73811. {
  73812. radiusX *= innerCircleProportionalSize;
  73813. radiusY *= innerCircleProportionalSize;
  73814. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  73815. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  73816. }
  73817. }
  73818. else
  73819. {
  73820. if (innerCircleProportionalSize > 0)
  73821. {
  73822. radiusX *= innerCircleProportionalSize;
  73823. radiusY *= innerCircleProportionalSize;
  73824. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  73825. }
  73826. else
  73827. {
  73828. lineTo (centre);
  73829. }
  73830. }
  73831. closeSubPath();
  73832. }
  73833. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  73834. {
  73835. const Line<float> reversed (line.reversed());
  73836. lineThickness *= 0.5f;
  73837. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  73838. lineTo (line.getPointAlongLine (0, -lineThickness));
  73839. lineTo (reversed.getPointAlongLine (0, lineThickness));
  73840. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  73841. closeSubPath();
  73842. }
  73843. void Path::addArrow (const Line<float>& line, float lineThickness,
  73844. float arrowheadWidth, float arrowheadLength)
  73845. {
  73846. const Line<float> reversed (line.reversed());
  73847. lineThickness *= 0.5f;
  73848. arrowheadWidth *= 0.5f;
  73849. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  73850. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  73851. lineTo (line.getPointAlongLine (0, -lineThickness));
  73852. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  73853. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  73854. lineTo (line.getEnd());
  73855. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  73856. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  73857. closeSubPath();
  73858. }
  73859. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  73860. const float radius, const float startAngle)
  73861. {
  73862. jassert (numberOfSides > 1); // this would be silly.
  73863. if (numberOfSides > 1)
  73864. {
  73865. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  73866. for (int i = 0; i < numberOfSides; ++i)
  73867. {
  73868. const float angle = startAngle + i * angleBetweenPoints;
  73869. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  73870. if (i == 0)
  73871. startNewSubPath (p);
  73872. else
  73873. lineTo (p);
  73874. }
  73875. closeSubPath();
  73876. }
  73877. }
  73878. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  73879. const float innerRadius, const float outerRadius, const float startAngle)
  73880. {
  73881. jassert (numberOfPoints > 1); // this would be silly.
  73882. if (numberOfPoints > 1)
  73883. {
  73884. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  73885. for (int i = 0; i < numberOfPoints; ++i)
  73886. {
  73887. const float angle = startAngle + i * angleBetweenPoints;
  73888. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  73889. if (i == 0)
  73890. startNewSubPath (p);
  73891. else
  73892. lineTo (p);
  73893. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  73894. }
  73895. closeSubPath();
  73896. }
  73897. }
  73898. void Path::addBubble (float x, float y,
  73899. float w, float h,
  73900. float cs,
  73901. float tipX,
  73902. float tipY,
  73903. int whichSide,
  73904. float arrowPos,
  73905. float arrowWidth)
  73906. {
  73907. if (w > 1.0f && h > 1.0f)
  73908. {
  73909. cs = jmin (cs, w * 0.5f, h * 0.5f);
  73910. const float cs2 = 2.0f * cs;
  73911. startNewSubPath (x + cs, y);
  73912. if (whichSide == 0)
  73913. {
  73914. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  73915. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  73916. lineTo (arrowX1, y);
  73917. lineTo (tipX, tipY);
  73918. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  73919. }
  73920. lineTo (x + w - cs, y);
  73921. if (cs > 0.0f)
  73922. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  73923. if (whichSide == 3)
  73924. {
  73925. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  73926. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  73927. lineTo (x + w, arrowY1);
  73928. lineTo (tipX, tipY);
  73929. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  73930. }
  73931. lineTo (x + w, y + h - cs);
  73932. if (cs > 0.0f)
  73933. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  73934. if (whichSide == 2)
  73935. {
  73936. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  73937. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  73938. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  73939. lineTo (tipX, tipY);
  73940. lineTo (arrowX1, y + h);
  73941. }
  73942. lineTo (x + cs, y + h);
  73943. if (cs > 0.0f)
  73944. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  73945. if (whichSide == 1)
  73946. {
  73947. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  73948. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  73949. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  73950. lineTo (tipX, tipY);
  73951. lineTo (x, arrowY1);
  73952. }
  73953. lineTo (x, y + cs);
  73954. if (cs > 0.0f)
  73955. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  73956. closeSubPath();
  73957. }
  73958. }
  73959. void Path::addPath (const Path& other)
  73960. {
  73961. size_t i = 0;
  73962. while (i < other.numElements)
  73963. {
  73964. const float type = other.data.elements [i++];
  73965. if (type == moveMarker)
  73966. {
  73967. startNewSubPath (other.data.elements [i],
  73968. other.data.elements [i + 1]);
  73969. i += 2;
  73970. }
  73971. else if (type == lineMarker)
  73972. {
  73973. lineTo (other.data.elements [i],
  73974. other.data.elements [i + 1]);
  73975. i += 2;
  73976. }
  73977. else if (type == quadMarker)
  73978. {
  73979. quadraticTo (other.data.elements [i],
  73980. other.data.elements [i + 1],
  73981. other.data.elements [i + 2],
  73982. other.data.elements [i + 3]);
  73983. i += 4;
  73984. }
  73985. else if (type == cubicMarker)
  73986. {
  73987. cubicTo (other.data.elements [i],
  73988. other.data.elements [i + 1],
  73989. other.data.elements [i + 2],
  73990. other.data.elements [i + 3],
  73991. other.data.elements [i + 4],
  73992. other.data.elements [i + 5]);
  73993. i += 6;
  73994. }
  73995. else if (type == closeSubPathMarker)
  73996. {
  73997. closeSubPath();
  73998. }
  73999. else
  74000. {
  74001. // something's gone wrong with the element list!
  74002. jassertfalse;
  74003. }
  74004. }
  74005. }
  74006. void Path::addPath (const Path& other,
  74007. const AffineTransform& transformToApply)
  74008. {
  74009. size_t i = 0;
  74010. while (i < other.numElements)
  74011. {
  74012. const float type = other.data.elements [i++];
  74013. if (type == closeSubPathMarker)
  74014. {
  74015. closeSubPath();
  74016. }
  74017. else
  74018. {
  74019. float x = other.data.elements [i++];
  74020. float y = other.data.elements [i++];
  74021. transformToApply.transformPoint (x, y);
  74022. if (type == moveMarker)
  74023. {
  74024. startNewSubPath (x, y);
  74025. }
  74026. else if (type == lineMarker)
  74027. {
  74028. lineTo (x, y);
  74029. }
  74030. else if (type == quadMarker)
  74031. {
  74032. float x2 = other.data.elements [i++];
  74033. float y2 = other.data.elements [i++];
  74034. transformToApply.transformPoint (x2, y2);
  74035. quadraticTo (x, y, x2, y2);
  74036. }
  74037. else if (type == cubicMarker)
  74038. {
  74039. float x2 = other.data.elements [i++];
  74040. float y2 = other.data.elements [i++];
  74041. float x3 = other.data.elements [i++];
  74042. float y3 = other.data.elements [i++];
  74043. transformToApply.transformPoints (x2, y2, x3, y3);
  74044. cubicTo (x, y, x2, y2, x3, y3);
  74045. }
  74046. else
  74047. {
  74048. // something's gone wrong with the element list!
  74049. jassertfalse;
  74050. }
  74051. }
  74052. }
  74053. }
  74054. void Path::applyTransform (const AffineTransform& transform) throw()
  74055. {
  74056. size_t i = 0;
  74057. pathYMin = pathXMin = 0;
  74058. pathYMax = pathXMax = 0;
  74059. bool setMaxMin = false;
  74060. while (i < numElements)
  74061. {
  74062. const float type = data.elements [i++];
  74063. if (type == moveMarker)
  74064. {
  74065. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74066. if (setMaxMin)
  74067. {
  74068. pathXMin = jmin (pathXMin, data.elements [i]);
  74069. pathXMax = jmax (pathXMax, data.elements [i]);
  74070. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74071. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74072. }
  74073. else
  74074. {
  74075. pathXMin = pathXMax = data.elements [i];
  74076. pathYMin = pathYMax = data.elements [i + 1];
  74077. setMaxMin = true;
  74078. }
  74079. i += 2;
  74080. }
  74081. else if (type == lineMarker)
  74082. {
  74083. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74084. pathXMin = jmin (pathXMin, data.elements [i]);
  74085. pathXMax = jmax (pathXMax, data.elements [i]);
  74086. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74087. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74088. i += 2;
  74089. }
  74090. else if (type == quadMarker)
  74091. {
  74092. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74093. data.elements [i + 2], data.elements [i + 3]);
  74094. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74095. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74096. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74097. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74098. i += 4;
  74099. }
  74100. else if (type == cubicMarker)
  74101. {
  74102. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74103. data.elements [i + 2], data.elements [i + 3],
  74104. data.elements [i + 4], data.elements [i + 5]);
  74105. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74106. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74107. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74108. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74109. i += 6;
  74110. }
  74111. }
  74112. }
  74113. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74114. const float w, const float h,
  74115. const bool preserveProportions,
  74116. const Justification& justification) const
  74117. {
  74118. Rectangle<float> bounds (getBounds());
  74119. if (preserveProportions)
  74120. {
  74121. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74122. return AffineTransform::identity;
  74123. float newW, newH;
  74124. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74125. if (srcRatio > h / w)
  74126. {
  74127. newW = h / srcRatio;
  74128. newH = h;
  74129. }
  74130. else
  74131. {
  74132. newW = w;
  74133. newH = w * srcRatio;
  74134. }
  74135. float newXCentre = x;
  74136. float newYCentre = y;
  74137. if (justification.testFlags (Justification::left))
  74138. newXCentre += newW * 0.5f;
  74139. else if (justification.testFlags (Justification::right))
  74140. newXCentre += w - newW * 0.5f;
  74141. else
  74142. newXCentre += w * 0.5f;
  74143. if (justification.testFlags (Justification::top))
  74144. newYCentre += newH * 0.5f;
  74145. else if (justification.testFlags (Justification::bottom))
  74146. newYCentre += h - newH * 0.5f;
  74147. else
  74148. newYCentre += h * 0.5f;
  74149. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74150. bounds.getHeight() * -0.5f - bounds.getY())
  74151. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74152. .translated (newXCentre, newYCentre);
  74153. }
  74154. else
  74155. {
  74156. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74157. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74158. .translated (x, y);
  74159. }
  74160. }
  74161. bool Path::contains (const float x, const float y, const float tolerence) const
  74162. {
  74163. if (x <= pathXMin || x >= pathXMax
  74164. || y <= pathYMin || y >= pathYMax)
  74165. return false;
  74166. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74167. int positiveCrossings = 0;
  74168. int negativeCrossings = 0;
  74169. while (i.next())
  74170. {
  74171. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74172. {
  74173. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74174. if (intersectX <= x)
  74175. {
  74176. if (i.y1 < i.y2)
  74177. ++positiveCrossings;
  74178. else
  74179. ++negativeCrossings;
  74180. }
  74181. }
  74182. }
  74183. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74184. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74185. }
  74186. bool Path::contains (const Point<float>& point, const float tolerence) const
  74187. {
  74188. return contains (point.getX(), point.getY(), tolerence);
  74189. }
  74190. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74191. {
  74192. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74193. Point<float> intersection;
  74194. while (i.next())
  74195. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74196. return true;
  74197. return false;
  74198. }
  74199. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74200. {
  74201. Line<float> result (line);
  74202. const bool startInside = contains (line.getStart());
  74203. const bool endInside = contains (line.getEnd());
  74204. if (startInside == endInside)
  74205. {
  74206. if (keepSectionOutsidePath == startInside)
  74207. result = Line<float>();
  74208. }
  74209. else
  74210. {
  74211. PathFlatteningIterator i (*this, AffineTransform::identity);
  74212. Point<float> intersection;
  74213. while (i.next())
  74214. {
  74215. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74216. {
  74217. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74218. result.setStart (intersection);
  74219. else
  74220. result.setEnd (intersection);
  74221. }
  74222. }
  74223. }
  74224. return result;
  74225. }
  74226. float Path::getLength (const AffineTransform& transform) const
  74227. {
  74228. float length = 0;
  74229. PathFlatteningIterator i (*this, transform);
  74230. while (i.next())
  74231. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74232. return length;
  74233. }
  74234. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74235. {
  74236. PathFlatteningIterator i (*this, transform);
  74237. while (i.next())
  74238. {
  74239. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74240. const float lineLength = line.getLength();
  74241. if (distanceFromStart <= lineLength)
  74242. return line.getPointAlongLine (distanceFromStart);
  74243. distanceFromStart -= lineLength;
  74244. }
  74245. return Point<float> (i.x2, i.y2);
  74246. }
  74247. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74248. const AffineTransform& transform) const
  74249. {
  74250. PathFlatteningIterator i (*this, transform);
  74251. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74252. float length = 0;
  74253. Point<float> pointOnLine;
  74254. while (i.next())
  74255. {
  74256. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74257. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74258. if (distance < bestDistance)
  74259. {
  74260. bestDistance = distance;
  74261. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74262. pointOnPath = pointOnLine;
  74263. }
  74264. length += line.getLength();
  74265. }
  74266. return bestPosition;
  74267. }
  74268. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74269. {
  74270. if (cornerRadius <= 0.01f)
  74271. return *this;
  74272. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74273. size_t n = 0;
  74274. bool lastWasLine = false, firstWasLine = false;
  74275. Path p;
  74276. while (n < numElements)
  74277. {
  74278. const float type = data.elements [n++];
  74279. if (type == moveMarker)
  74280. {
  74281. indexOfPathStart = p.numElements;
  74282. indexOfPathStartThis = n - 1;
  74283. const float x = data.elements [n++];
  74284. const float y = data.elements [n++];
  74285. p.startNewSubPath (x, y);
  74286. lastWasLine = false;
  74287. firstWasLine = (data.elements [n] == lineMarker);
  74288. }
  74289. else if (type == lineMarker || type == closeSubPathMarker)
  74290. {
  74291. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74292. if (type == lineMarker)
  74293. {
  74294. endX = data.elements [n++];
  74295. endY = data.elements [n++];
  74296. if (n > 8)
  74297. {
  74298. startX = data.elements [n - 8];
  74299. startY = data.elements [n - 7];
  74300. joinX = data.elements [n - 5];
  74301. joinY = data.elements [n - 4];
  74302. }
  74303. }
  74304. else
  74305. {
  74306. endX = data.elements [indexOfPathStartThis + 1];
  74307. endY = data.elements [indexOfPathStartThis + 2];
  74308. if (n > 6)
  74309. {
  74310. startX = data.elements [n - 6];
  74311. startY = data.elements [n - 5];
  74312. joinX = data.elements [n - 3];
  74313. joinY = data.elements [n - 2];
  74314. }
  74315. }
  74316. if (lastWasLine)
  74317. {
  74318. const double len1 = juce_hypot (startX - joinX,
  74319. startY - joinY);
  74320. if (len1 > 0)
  74321. {
  74322. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74323. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74324. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74325. }
  74326. const double len2 = juce_hypot (endX - joinX,
  74327. endY - joinY);
  74328. if (len2 > 0)
  74329. {
  74330. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74331. p.quadraticTo (joinX, joinY,
  74332. (float) (joinX + (endX - joinX) * propNeeded),
  74333. (float) (joinY + (endY - joinY) * propNeeded));
  74334. }
  74335. p.lineTo (endX, endY);
  74336. }
  74337. else if (type == lineMarker)
  74338. {
  74339. p.lineTo (endX, endY);
  74340. lastWasLine = true;
  74341. }
  74342. if (type == closeSubPathMarker)
  74343. {
  74344. if (firstWasLine)
  74345. {
  74346. startX = data.elements [n - 3];
  74347. startY = data.elements [n - 2];
  74348. joinX = endX;
  74349. joinY = endY;
  74350. endX = data.elements [indexOfPathStartThis + 4];
  74351. endY = data.elements [indexOfPathStartThis + 5];
  74352. const double len1 = juce_hypot (startX - joinX,
  74353. startY - joinY);
  74354. if (len1 > 0)
  74355. {
  74356. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74357. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74358. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74359. }
  74360. const double len2 = juce_hypot (endX - joinX,
  74361. endY - joinY);
  74362. if (len2 > 0)
  74363. {
  74364. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74365. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74366. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74367. p.quadraticTo (joinX, joinY, endX, endY);
  74368. p.data.elements [indexOfPathStart + 1] = endX;
  74369. p.data.elements [indexOfPathStart + 2] = endY;
  74370. }
  74371. }
  74372. p.closeSubPath();
  74373. }
  74374. }
  74375. else if (type == quadMarker)
  74376. {
  74377. lastWasLine = false;
  74378. const float x1 = data.elements [n++];
  74379. const float y1 = data.elements [n++];
  74380. const float x2 = data.elements [n++];
  74381. const float y2 = data.elements [n++];
  74382. p.quadraticTo (x1, y1, x2, y2);
  74383. }
  74384. else if (type == cubicMarker)
  74385. {
  74386. lastWasLine = false;
  74387. const float x1 = data.elements [n++];
  74388. const float y1 = data.elements [n++];
  74389. const float x2 = data.elements [n++];
  74390. const float y2 = data.elements [n++];
  74391. const float x3 = data.elements [n++];
  74392. const float y3 = data.elements [n++];
  74393. p.cubicTo (x1, y1, x2, y2, x3, y3);
  74394. }
  74395. }
  74396. return p;
  74397. }
  74398. void Path::loadPathFromStream (InputStream& source)
  74399. {
  74400. while (! source.isExhausted())
  74401. {
  74402. switch (source.readByte())
  74403. {
  74404. case 'm':
  74405. {
  74406. const float x = source.readFloat();
  74407. const float y = source.readFloat();
  74408. startNewSubPath (x, y);
  74409. break;
  74410. }
  74411. case 'l':
  74412. {
  74413. const float x = source.readFloat();
  74414. const float y = source.readFloat();
  74415. lineTo (x, y);
  74416. break;
  74417. }
  74418. case 'q':
  74419. {
  74420. const float x1 = source.readFloat();
  74421. const float y1 = source.readFloat();
  74422. const float x2 = source.readFloat();
  74423. const float y2 = source.readFloat();
  74424. quadraticTo (x1, y1, x2, y2);
  74425. break;
  74426. }
  74427. case 'b':
  74428. {
  74429. const float x1 = source.readFloat();
  74430. const float y1 = source.readFloat();
  74431. const float x2 = source.readFloat();
  74432. const float y2 = source.readFloat();
  74433. const float x3 = source.readFloat();
  74434. const float y3 = source.readFloat();
  74435. cubicTo (x1, y1, x2, y2, x3, y3);
  74436. break;
  74437. }
  74438. case 'c':
  74439. closeSubPath();
  74440. break;
  74441. case 'n':
  74442. useNonZeroWinding = true;
  74443. break;
  74444. case 'z':
  74445. useNonZeroWinding = false;
  74446. break;
  74447. case 'e':
  74448. return; // end of path marker
  74449. default:
  74450. jassertfalse; // illegal char in the stream
  74451. break;
  74452. }
  74453. }
  74454. }
  74455. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  74456. {
  74457. MemoryInputStream in (pathData, numberOfBytes, false);
  74458. loadPathFromStream (in);
  74459. }
  74460. void Path::writePathToStream (OutputStream& dest) const
  74461. {
  74462. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  74463. size_t i = 0;
  74464. while (i < numElements)
  74465. {
  74466. const float type = data.elements [i++];
  74467. if (type == moveMarker)
  74468. {
  74469. dest.writeByte ('m');
  74470. dest.writeFloat (data.elements [i++]);
  74471. dest.writeFloat (data.elements [i++]);
  74472. }
  74473. else if (type == lineMarker)
  74474. {
  74475. dest.writeByte ('l');
  74476. dest.writeFloat (data.elements [i++]);
  74477. dest.writeFloat (data.elements [i++]);
  74478. }
  74479. else if (type == quadMarker)
  74480. {
  74481. dest.writeByte ('q');
  74482. dest.writeFloat (data.elements [i++]);
  74483. dest.writeFloat (data.elements [i++]);
  74484. dest.writeFloat (data.elements [i++]);
  74485. dest.writeFloat (data.elements [i++]);
  74486. }
  74487. else if (type == cubicMarker)
  74488. {
  74489. dest.writeByte ('b');
  74490. dest.writeFloat (data.elements [i++]);
  74491. dest.writeFloat (data.elements [i++]);
  74492. dest.writeFloat (data.elements [i++]);
  74493. dest.writeFloat (data.elements [i++]);
  74494. dest.writeFloat (data.elements [i++]);
  74495. dest.writeFloat (data.elements [i++]);
  74496. }
  74497. else if (type == closeSubPathMarker)
  74498. {
  74499. dest.writeByte ('c');
  74500. }
  74501. }
  74502. dest.writeByte ('e'); // marks the end-of-path
  74503. }
  74504. const String Path::toString() const
  74505. {
  74506. MemoryOutputStream s (2048);
  74507. if (! useNonZeroWinding)
  74508. s << 'a';
  74509. size_t i = 0;
  74510. float lastMarker = 0.0f;
  74511. while (i < numElements)
  74512. {
  74513. const float marker = data.elements [i++];
  74514. char markerChar = 0;
  74515. int numCoords = 0;
  74516. if (marker == moveMarker)
  74517. {
  74518. markerChar = 'm';
  74519. numCoords = 2;
  74520. }
  74521. else if (marker == lineMarker)
  74522. {
  74523. markerChar = 'l';
  74524. numCoords = 2;
  74525. }
  74526. else if (marker == quadMarker)
  74527. {
  74528. markerChar = 'q';
  74529. numCoords = 4;
  74530. }
  74531. else if (marker == cubicMarker)
  74532. {
  74533. markerChar = 'c';
  74534. numCoords = 6;
  74535. }
  74536. else
  74537. {
  74538. jassert (marker == closeSubPathMarker);
  74539. markerChar = 'z';
  74540. }
  74541. if (marker != lastMarker)
  74542. {
  74543. if (s.getDataSize() != 0)
  74544. s << ' ';
  74545. s << markerChar;
  74546. lastMarker = marker;
  74547. }
  74548. while (--numCoords >= 0 && i < numElements)
  74549. {
  74550. String coord (data.elements [i++], 3);
  74551. while (coord.endsWithChar ('0') && coord != "0")
  74552. coord = coord.dropLastCharacters (1);
  74553. if (coord.endsWithChar ('.'))
  74554. coord = coord.dropLastCharacters (1);
  74555. if (s.getDataSize() != 0)
  74556. s << ' ';
  74557. s << coord;
  74558. }
  74559. }
  74560. return s.toUTF8();
  74561. }
  74562. void Path::restoreFromString (const String& stringVersion)
  74563. {
  74564. clear();
  74565. setUsingNonZeroWinding (true);
  74566. const juce_wchar* t = stringVersion;
  74567. juce_wchar marker = 'm';
  74568. int numValues = 2;
  74569. float values [6];
  74570. for (;;)
  74571. {
  74572. const String token (PathHelpers::nextToken (t));
  74573. const juce_wchar firstChar = token[0];
  74574. int startNum = 0;
  74575. if (firstChar == 0)
  74576. break;
  74577. if (firstChar == 'm' || firstChar == 'l')
  74578. {
  74579. marker = firstChar;
  74580. numValues = 2;
  74581. }
  74582. else if (firstChar == 'q')
  74583. {
  74584. marker = firstChar;
  74585. numValues = 4;
  74586. }
  74587. else if (firstChar == 'c')
  74588. {
  74589. marker = firstChar;
  74590. numValues = 6;
  74591. }
  74592. else if (firstChar == 'z')
  74593. {
  74594. marker = firstChar;
  74595. numValues = 0;
  74596. }
  74597. else if (firstChar == 'a')
  74598. {
  74599. setUsingNonZeroWinding (false);
  74600. continue;
  74601. }
  74602. else
  74603. {
  74604. ++startNum;
  74605. values [0] = token.getFloatValue();
  74606. }
  74607. for (int i = startNum; i < numValues; ++i)
  74608. values [i] = PathHelpers::nextToken (t).getFloatValue();
  74609. switch (marker)
  74610. {
  74611. case 'm':
  74612. startNewSubPath (values[0], values[1]);
  74613. break;
  74614. case 'l':
  74615. lineTo (values[0], values[1]);
  74616. break;
  74617. case 'q':
  74618. quadraticTo (values[0], values[1],
  74619. values[2], values[3]);
  74620. break;
  74621. case 'c':
  74622. cubicTo (values[0], values[1],
  74623. values[2], values[3],
  74624. values[4], values[5]);
  74625. break;
  74626. case 'z':
  74627. closeSubPath();
  74628. break;
  74629. default:
  74630. jassertfalse; // illegal string format?
  74631. break;
  74632. }
  74633. }
  74634. }
  74635. Path::Iterator::Iterator (const Path& path_)
  74636. : path (path_),
  74637. index (0)
  74638. {
  74639. }
  74640. Path::Iterator::~Iterator()
  74641. {
  74642. }
  74643. bool Path::Iterator::next()
  74644. {
  74645. const float* const elements = path.data.elements;
  74646. if (index < path.numElements)
  74647. {
  74648. const float type = elements [index++];
  74649. if (type == moveMarker)
  74650. {
  74651. elementType = startNewSubPath;
  74652. x1 = elements [index++];
  74653. y1 = elements [index++];
  74654. }
  74655. else if (type == lineMarker)
  74656. {
  74657. elementType = lineTo;
  74658. x1 = elements [index++];
  74659. y1 = elements [index++];
  74660. }
  74661. else if (type == quadMarker)
  74662. {
  74663. elementType = quadraticTo;
  74664. x1 = elements [index++];
  74665. y1 = elements [index++];
  74666. x2 = elements [index++];
  74667. y2 = elements [index++];
  74668. }
  74669. else if (type == cubicMarker)
  74670. {
  74671. elementType = cubicTo;
  74672. x1 = elements [index++];
  74673. y1 = elements [index++];
  74674. x2 = elements [index++];
  74675. y2 = elements [index++];
  74676. x3 = elements [index++];
  74677. y3 = elements [index++];
  74678. }
  74679. else if (type == closeSubPathMarker)
  74680. {
  74681. elementType = closePath;
  74682. }
  74683. return true;
  74684. }
  74685. return false;
  74686. }
  74687. END_JUCE_NAMESPACE
  74688. /*** End of inlined file: juce_Path.cpp ***/
  74689. /*** Start of inlined file: juce_PathIterator.cpp ***/
  74690. BEGIN_JUCE_NAMESPACE
  74691. #if JUCE_MSVC && JUCE_DEBUG
  74692. #pragma optimize ("t", on)
  74693. #endif
  74694. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  74695. const AffineTransform& transform_,
  74696. float tolerence_)
  74697. : x2 (0),
  74698. y2 (0),
  74699. closesSubPath (false),
  74700. subPathIndex (-1),
  74701. path (path_),
  74702. transform (transform_),
  74703. points (path_.data.elements),
  74704. tolerence (tolerence_ * tolerence_),
  74705. subPathCloseX (0),
  74706. subPathCloseY (0),
  74707. isIdentityTransform (transform_.isIdentity()),
  74708. stackBase (32),
  74709. index (0),
  74710. stackSize (32)
  74711. {
  74712. stackPos = stackBase;
  74713. }
  74714. PathFlatteningIterator::~PathFlatteningIterator()
  74715. {
  74716. }
  74717. bool PathFlatteningIterator::next()
  74718. {
  74719. x1 = x2;
  74720. y1 = y2;
  74721. float x3 = 0;
  74722. float y3 = 0;
  74723. float x4 = 0;
  74724. float y4 = 0;
  74725. float type;
  74726. for (;;)
  74727. {
  74728. if (stackPos == stackBase)
  74729. {
  74730. if (index >= path.numElements)
  74731. {
  74732. return false;
  74733. }
  74734. else
  74735. {
  74736. type = points [index++];
  74737. if (type != Path::closeSubPathMarker)
  74738. {
  74739. x2 = points [index++];
  74740. y2 = points [index++];
  74741. if (type == Path::quadMarker)
  74742. {
  74743. x3 = points [index++];
  74744. y3 = points [index++];
  74745. if (! isIdentityTransform)
  74746. transform.transformPoints (x2, y2, x3, y3);
  74747. }
  74748. else if (type == Path::cubicMarker)
  74749. {
  74750. x3 = points [index++];
  74751. y3 = points [index++];
  74752. x4 = points [index++];
  74753. y4 = points [index++];
  74754. if (! isIdentityTransform)
  74755. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  74756. }
  74757. else
  74758. {
  74759. if (! isIdentityTransform)
  74760. transform.transformPoint (x2, y2);
  74761. }
  74762. }
  74763. }
  74764. }
  74765. else
  74766. {
  74767. type = *--stackPos;
  74768. if (type != Path::closeSubPathMarker)
  74769. {
  74770. x2 = *--stackPos;
  74771. y2 = *--stackPos;
  74772. if (type == Path::quadMarker)
  74773. {
  74774. x3 = *--stackPos;
  74775. y3 = *--stackPos;
  74776. }
  74777. else if (type == Path::cubicMarker)
  74778. {
  74779. x3 = *--stackPos;
  74780. y3 = *--stackPos;
  74781. x4 = *--stackPos;
  74782. y4 = *--stackPos;
  74783. }
  74784. }
  74785. }
  74786. if (type == Path::lineMarker)
  74787. {
  74788. ++subPathIndex;
  74789. closesSubPath = (stackPos == stackBase)
  74790. && (index < path.numElements)
  74791. && (points [index] == Path::closeSubPathMarker)
  74792. && x2 == subPathCloseX
  74793. && y2 == subPathCloseY;
  74794. return true;
  74795. }
  74796. else if (type == Path::quadMarker)
  74797. {
  74798. const size_t offset = (size_t) (stackPos - stackBase);
  74799. if (offset >= stackSize - 10)
  74800. {
  74801. stackSize <<= 1;
  74802. stackBase.realloc (stackSize);
  74803. stackPos = stackBase + offset;
  74804. }
  74805. const float dx1 = x1 - x2;
  74806. const float dy1 = y1 - y2;
  74807. const float dx2 = x2 - x3;
  74808. const float dy2 = y2 - y3;
  74809. const float m1x = (x1 + x2) * 0.5f;
  74810. const float m1y = (y1 + y2) * 0.5f;
  74811. const float m2x = (x2 + x3) * 0.5f;
  74812. const float m2y = (y2 + y3) * 0.5f;
  74813. const float m3x = (m1x + m2x) * 0.5f;
  74814. const float m3y = (m1y + m2y) * 0.5f;
  74815. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  74816. {
  74817. *stackPos++ = y3;
  74818. *stackPos++ = x3;
  74819. *stackPos++ = m2y;
  74820. *stackPos++ = m2x;
  74821. *stackPos++ = Path::quadMarker;
  74822. *stackPos++ = m3y;
  74823. *stackPos++ = m3x;
  74824. *stackPos++ = m1y;
  74825. *stackPos++ = m1x;
  74826. *stackPos++ = Path::quadMarker;
  74827. }
  74828. else
  74829. {
  74830. *stackPos++ = y3;
  74831. *stackPos++ = x3;
  74832. *stackPos++ = Path::lineMarker;
  74833. *stackPos++ = m3y;
  74834. *stackPos++ = m3x;
  74835. *stackPos++ = Path::lineMarker;
  74836. }
  74837. jassert (stackPos < stackBase + stackSize);
  74838. }
  74839. else if (type == Path::cubicMarker)
  74840. {
  74841. const size_t offset = (size_t) (stackPos - stackBase);
  74842. if (offset >= stackSize - 16)
  74843. {
  74844. stackSize <<= 1;
  74845. stackBase.realloc (stackSize);
  74846. stackPos = stackBase + offset;
  74847. }
  74848. const float dx1 = x1 - x2;
  74849. const float dy1 = y1 - y2;
  74850. const float dx2 = x2 - x3;
  74851. const float dy2 = y2 - y3;
  74852. const float dx3 = x3 - x4;
  74853. const float dy3 = y3 - y4;
  74854. const float m1x = (x1 + x2) * 0.5f;
  74855. const float m1y = (y1 + y2) * 0.5f;
  74856. const float m2x = (x3 + x2) * 0.5f;
  74857. const float m2y = (y3 + y2) * 0.5f;
  74858. const float m3x = (x3 + x4) * 0.5f;
  74859. const float m3y = (y3 + y4) * 0.5f;
  74860. const float m4x = (m1x + m2x) * 0.5f;
  74861. const float m4y = (m1y + m2y) * 0.5f;
  74862. const float m5x = (m3x + m2x) * 0.5f;
  74863. const float m5y = (m3y + m2y) * 0.5f;
  74864. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  74865. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  74866. {
  74867. *stackPos++ = y4;
  74868. *stackPos++ = x4;
  74869. *stackPos++ = m3y;
  74870. *stackPos++ = m3x;
  74871. *stackPos++ = m5y;
  74872. *stackPos++ = m5x;
  74873. *stackPos++ = Path::cubicMarker;
  74874. *stackPos++ = (m4y + m5y) * 0.5f;
  74875. *stackPos++ = (m4x + m5x) * 0.5f;
  74876. *stackPos++ = m4y;
  74877. *stackPos++ = m4x;
  74878. *stackPos++ = m1y;
  74879. *stackPos++ = m1x;
  74880. *stackPos++ = Path::cubicMarker;
  74881. }
  74882. else
  74883. {
  74884. *stackPos++ = y4;
  74885. *stackPos++ = x4;
  74886. *stackPos++ = Path::lineMarker;
  74887. *stackPos++ = m5y;
  74888. *stackPos++ = m5x;
  74889. *stackPos++ = Path::lineMarker;
  74890. *stackPos++ = m4y;
  74891. *stackPos++ = m4x;
  74892. *stackPos++ = Path::lineMarker;
  74893. }
  74894. }
  74895. else if (type == Path::closeSubPathMarker)
  74896. {
  74897. if (x2 != subPathCloseX || y2 != subPathCloseY)
  74898. {
  74899. x1 = x2;
  74900. y1 = y2;
  74901. x2 = subPathCloseX;
  74902. y2 = subPathCloseY;
  74903. closesSubPath = true;
  74904. return true;
  74905. }
  74906. }
  74907. else
  74908. {
  74909. jassert (type == Path::moveMarker);
  74910. subPathIndex = -1;
  74911. subPathCloseX = x1 = x2;
  74912. subPathCloseY = y1 = y2;
  74913. }
  74914. }
  74915. }
  74916. #if JUCE_MSVC && JUCE_DEBUG
  74917. #pragma optimize ("", on) // resets optimisations to the project defaults
  74918. #endif
  74919. END_JUCE_NAMESPACE
  74920. /*** End of inlined file: juce_PathIterator.cpp ***/
  74921. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  74922. BEGIN_JUCE_NAMESPACE
  74923. PathStrokeType::PathStrokeType (const float strokeThickness,
  74924. const JointStyle jointStyle_,
  74925. const EndCapStyle endStyle_) throw()
  74926. : thickness (strokeThickness),
  74927. jointStyle (jointStyle_),
  74928. endStyle (endStyle_)
  74929. {
  74930. }
  74931. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  74932. : thickness (other.thickness),
  74933. jointStyle (other.jointStyle),
  74934. endStyle (other.endStyle)
  74935. {
  74936. }
  74937. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  74938. {
  74939. thickness = other.thickness;
  74940. jointStyle = other.jointStyle;
  74941. endStyle = other.endStyle;
  74942. return *this;
  74943. }
  74944. PathStrokeType::~PathStrokeType() throw()
  74945. {
  74946. }
  74947. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  74948. {
  74949. return thickness == other.thickness
  74950. && jointStyle == other.jointStyle
  74951. && endStyle == other.endStyle;
  74952. }
  74953. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  74954. {
  74955. return ! operator== (other);
  74956. }
  74957. namespace PathStrokeHelpers
  74958. {
  74959. static bool lineIntersection (const float x1, const float y1,
  74960. const float x2, const float y2,
  74961. const float x3, const float y3,
  74962. const float x4, const float y4,
  74963. float& intersectionX,
  74964. float& intersectionY,
  74965. float& distanceBeyondLine1EndSquared) throw()
  74966. {
  74967. if (x2 != x3 || y2 != y3)
  74968. {
  74969. const float dx1 = x2 - x1;
  74970. const float dy1 = y2 - y1;
  74971. const float dx2 = x4 - x3;
  74972. const float dy2 = y4 - y3;
  74973. const float divisor = dx1 * dy2 - dx2 * dy1;
  74974. if (divisor == 0)
  74975. {
  74976. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  74977. {
  74978. if (dy1 == 0 && dy2 != 0)
  74979. {
  74980. const float along = (y1 - y3) / dy2;
  74981. intersectionX = x3 + along * dx2;
  74982. intersectionY = y1;
  74983. distanceBeyondLine1EndSquared = intersectionX - x2;
  74984. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74985. if ((x2 > x1) == (intersectionX < x2))
  74986. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74987. return along >= 0 && along <= 1.0f;
  74988. }
  74989. else if (dy2 == 0 && dy1 != 0)
  74990. {
  74991. const float along = (y3 - y1) / dy1;
  74992. intersectionX = x1 + along * dx1;
  74993. intersectionY = y3;
  74994. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  74995. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74996. if (along < 1.0f)
  74997. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74998. return along >= 0 && along <= 1.0f;
  74999. }
  75000. else if (dx1 == 0 && dx2 != 0)
  75001. {
  75002. const float along = (x1 - x3) / dx2;
  75003. intersectionX = x1;
  75004. intersectionY = y3 + along * dy2;
  75005. distanceBeyondLine1EndSquared = intersectionY - y2;
  75006. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75007. if ((y2 > y1) == (intersectionY < y2))
  75008. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75009. return along >= 0 && along <= 1.0f;
  75010. }
  75011. else if (dx2 == 0 && dx1 != 0)
  75012. {
  75013. const float along = (x3 - x1) / dx1;
  75014. intersectionX = x3;
  75015. intersectionY = y1 + along * dy1;
  75016. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75017. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75018. if (along < 1.0f)
  75019. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75020. return along >= 0 && along <= 1.0f;
  75021. }
  75022. }
  75023. intersectionX = 0.5f * (x2 + x3);
  75024. intersectionY = 0.5f * (y2 + y3);
  75025. distanceBeyondLine1EndSquared = 0.0f;
  75026. return false;
  75027. }
  75028. else
  75029. {
  75030. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75031. intersectionX = x1 + along1 * dx1;
  75032. intersectionY = y1 + along1 * dy1;
  75033. if (along1 >= 0 && along1 <= 1.0f)
  75034. {
  75035. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75036. if (along2 >= 0 && along2 <= divisor)
  75037. {
  75038. distanceBeyondLine1EndSquared = 0.0f;
  75039. return true;
  75040. }
  75041. }
  75042. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75043. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75044. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75045. if (along1 < 1.0f)
  75046. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75047. return false;
  75048. }
  75049. }
  75050. intersectionX = x2;
  75051. intersectionY = y2;
  75052. distanceBeyondLine1EndSquared = 0.0f;
  75053. return true;
  75054. }
  75055. static void addEdgeAndJoint (Path& destPath,
  75056. const PathStrokeType::JointStyle style,
  75057. const float maxMiterExtensionSquared, const float width,
  75058. const float x1, const float y1,
  75059. const float x2, const float y2,
  75060. const float x3, const float y3,
  75061. const float x4, const float y4,
  75062. const float midX, const float midY)
  75063. {
  75064. if (style == PathStrokeType::beveled
  75065. || (x3 == x4 && y3 == y4)
  75066. || (x1 == x2 && y1 == y2))
  75067. {
  75068. destPath.lineTo (x2, y2);
  75069. destPath.lineTo (x3, y3);
  75070. }
  75071. else
  75072. {
  75073. float jx, jy, distanceBeyondLine1EndSquared;
  75074. // if they intersect, use this point..
  75075. if (lineIntersection (x1, y1, x2, y2,
  75076. x3, y3, x4, y4,
  75077. jx, jy, distanceBeyondLine1EndSquared))
  75078. {
  75079. destPath.lineTo (jx, jy);
  75080. }
  75081. else
  75082. {
  75083. if (style == PathStrokeType::mitered)
  75084. {
  75085. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75086. && distanceBeyondLine1EndSquared > 0.0f)
  75087. {
  75088. destPath.lineTo (jx, jy);
  75089. }
  75090. else
  75091. {
  75092. // the end sticks out too far, so just use a blunt joint
  75093. destPath.lineTo (x2, y2);
  75094. destPath.lineTo (x3, y3);
  75095. }
  75096. }
  75097. else
  75098. {
  75099. // curved joints
  75100. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75101. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75102. const float angleIncrement = 0.1f;
  75103. destPath.lineTo (x2, y2);
  75104. if (std::abs (angle1 - angle2) > angleIncrement)
  75105. {
  75106. if (angle2 > angle1 + float_Pi
  75107. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75108. {
  75109. if (angle2 > angle1)
  75110. angle2 -= float_Pi * 2.0f;
  75111. jassert (angle1 <= angle2 + float_Pi);
  75112. angle1 -= angleIncrement;
  75113. while (angle1 > angle2)
  75114. {
  75115. destPath.lineTo (midX + width * std::sin (angle1),
  75116. midY + width * std::cos (angle1));
  75117. angle1 -= angleIncrement;
  75118. }
  75119. }
  75120. else
  75121. {
  75122. if (angle1 > angle2)
  75123. angle1 -= float_Pi * 2.0f;
  75124. jassert (angle1 >= angle2 - float_Pi);
  75125. angle1 += angleIncrement;
  75126. while (angle1 < angle2)
  75127. {
  75128. destPath.lineTo (midX + width * std::sin (angle1),
  75129. midY + width * std::cos (angle1));
  75130. angle1 += angleIncrement;
  75131. }
  75132. }
  75133. }
  75134. destPath.lineTo (x3, y3);
  75135. }
  75136. }
  75137. }
  75138. }
  75139. static void addLineEnd (Path& destPath,
  75140. const PathStrokeType::EndCapStyle style,
  75141. const float x1, const float y1,
  75142. const float x2, const float y2,
  75143. const float width)
  75144. {
  75145. if (style == PathStrokeType::butt)
  75146. {
  75147. destPath.lineTo (x2, y2);
  75148. }
  75149. else
  75150. {
  75151. float offx1, offy1, offx2, offy2;
  75152. float dx = x2 - x1;
  75153. float dy = y2 - y1;
  75154. const float len = juce_hypotf (dx, dy);
  75155. if (len == 0)
  75156. {
  75157. offx1 = offx2 = x1;
  75158. offy1 = offy2 = y1;
  75159. }
  75160. else
  75161. {
  75162. const float offset = width / len;
  75163. dx *= offset;
  75164. dy *= offset;
  75165. offx1 = x1 + dy;
  75166. offy1 = y1 - dx;
  75167. offx2 = x2 + dy;
  75168. offy2 = y2 - dx;
  75169. }
  75170. if (style == PathStrokeType::square)
  75171. {
  75172. // sqaure ends
  75173. destPath.lineTo (offx1, offy1);
  75174. destPath.lineTo (offx2, offy2);
  75175. destPath.lineTo (x2, y2);
  75176. }
  75177. else
  75178. {
  75179. // rounded ends
  75180. const float midx = (offx1 + offx2) * 0.5f;
  75181. const float midy = (offy1 + offy2) * 0.5f;
  75182. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75183. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75184. midx, midy);
  75185. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75186. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75187. x2, y2);
  75188. }
  75189. }
  75190. }
  75191. struct Arrowhead
  75192. {
  75193. float startWidth, startLength;
  75194. float endWidth, endLength;
  75195. };
  75196. static void addArrowhead (Path& destPath,
  75197. const float x1, const float y1,
  75198. const float x2, const float y2,
  75199. const float tipX, const float tipY,
  75200. const float width,
  75201. const float arrowheadWidth)
  75202. {
  75203. Line<float> line (x1, y1, x2, y2);
  75204. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75205. destPath.lineTo (tipX, tipY);
  75206. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75207. destPath.lineTo (x2, y2);
  75208. }
  75209. struct LineSection
  75210. {
  75211. float x1, y1, x2, y2; // original line
  75212. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75213. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75214. };
  75215. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75216. {
  75217. while (amountAtEnd > 0 && subPath.size() > 0)
  75218. {
  75219. LineSection& l = subPath.getReference (subPath.size() - 1);
  75220. float dx = l.rx2 - l.rx1;
  75221. float dy = l.ry2 - l.ry1;
  75222. const float len = juce_hypotf (dx, dy);
  75223. if (len <= amountAtEnd && subPath.size() > 1)
  75224. {
  75225. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75226. prev.x2 = l.x2;
  75227. prev.y2 = l.y2;
  75228. subPath.removeLast();
  75229. amountAtEnd -= len;
  75230. }
  75231. else
  75232. {
  75233. const float prop = jmin (0.9999f, amountAtEnd / len);
  75234. dx *= prop;
  75235. dy *= prop;
  75236. l.rx1 += dx;
  75237. l.ry1 += dy;
  75238. l.lx2 += dx;
  75239. l.ly2 += dy;
  75240. break;
  75241. }
  75242. }
  75243. while (amountAtStart > 0 && subPath.size() > 0)
  75244. {
  75245. LineSection& l = subPath.getReference (0);
  75246. float dx = l.rx2 - l.rx1;
  75247. float dy = l.ry2 - l.ry1;
  75248. const float len = juce_hypotf (dx, dy);
  75249. if (len <= amountAtStart && subPath.size() > 1)
  75250. {
  75251. LineSection& next = subPath.getReference (1);
  75252. next.x1 = l.x1;
  75253. next.y1 = l.y1;
  75254. subPath.remove (0);
  75255. amountAtStart -= len;
  75256. }
  75257. else
  75258. {
  75259. const float prop = jmin (0.9999f, amountAtStart / len);
  75260. dx *= prop;
  75261. dy *= prop;
  75262. l.rx2 -= dx;
  75263. l.ry2 -= dy;
  75264. l.lx1 -= dx;
  75265. l.ly1 -= dy;
  75266. break;
  75267. }
  75268. }
  75269. }
  75270. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75271. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75272. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75273. const Arrowhead* const arrowhead)
  75274. {
  75275. jassert (subPath.size() > 0);
  75276. if (arrowhead != 0)
  75277. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75278. const LineSection& firstLine = subPath.getReference (0);
  75279. float lastX1 = firstLine.lx1;
  75280. float lastY1 = firstLine.ly1;
  75281. float lastX2 = firstLine.lx2;
  75282. float lastY2 = firstLine.ly2;
  75283. if (isClosed)
  75284. {
  75285. destPath.startNewSubPath (lastX1, lastY1);
  75286. }
  75287. else
  75288. {
  75289. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75290. if (arrowhead != 0)
  75291. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75292. width, arrowhead->startWidth);
  75293. else
  75294. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75295. }
  75296. int i;
  75297. for (i = 1; i < subPath.size(); ++i)
  75298. {
  75299. const LineSection& l = subPath.getReference (i);
  75300. addEdgeAndJoint (destPath, jointStyle,
  75301. maxMiterExtensionSquared, width,
  75302. lastX1, lastY1, lastX2, lastY2,
  75303. l.lx1, l.ly1, l.lx2, l.ly2,
  75304. l.x1, l.y1);
  75305. lastX1 = l.lx1;
  75306. lastY1 = l.ly1;
  75307. lastX2 = l.lx2;
  75308. lastY2 = l.ly2;
  75309. }
  75310. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75311. if (isClosed)
  75312. {
  75313. const LineSection& l = subPath.getReference (0);
  75314. addEdgeAndJoint (destPath, jointStyle,
  75315. maxMiterExtensionSquared, width,
  75316. lastX1, lastY1, lastX2, lastY2,
  75317. l.lx1, l.ly1, l.lx2, l.ly2,
  75318. l.x1, l.y1);
  75319. destPath.closeSubPath();
  75320. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75321. }
  75322. else
  75323. {
  75324. destPath.lineTo (lastX2, lastY2);
  75325. if (arrowhead != 0)
  75326. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75327. width, arrowhead->endWidth);
  75328. else
  75329. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75330. }
  75331. lastX1 = lastLine.rx1;
  75332. lastY1 = lastLine.ry1;
  75333. lastX2 = lastLine.rx2;
  75334. lastY2 = lastLine.ry2;
  75335. for (i = subPath.size() - 1; --i >= 0;)
  75336. {
  75337. const LineSection& l = subPath.getReference (i);
  75338. addEdgeAndJoint (destPath, jointStyle,
  75339. maxMiterExtensionSquared, width,
  75340. lastX1, lastY1, lastX2, lastY2,
  75341. l.rx1, l.ry1, l.rx2, l.ry2,
  75342. l.x2, l.y2);
  75343. lastX1 = l.rx1;
  75344. lastY1 = l.ry1;
  75345. lastX2 = l.rx2;
  75346. lastY2 = l.ry2;
  75347. }
  75348. if (isClosed)
  75349. {
  75350. addEdgeAndJoint (destPath, jointStyle,
  75351. maxMiterExtensionSquared, width,
  75352. lastX1, lastY1, lastX2, lastY2,
  75353. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75354. lastLine.x2, lastLine.y2);
  75355. }
  75356. else
  75357. {
  75358. // do the last line
  75359. destPath.lineTo (lastX2, lastY2);
  75360. }
  75361. destPath.closeSubPath();
  75362. }
  75363. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75364. const PathStrokeType::EndCapStyle endStyle,
  75365. Path& destPath, const Path& source,
  75366. const AffineTransform& transform,
  75367. const float extraAccuracy, const Arrowhead* const arrowhead)
  75368. {
  75369. if (thickness <= 0)
  75370. {
  75371. destPath.clear();
  75372. return;
  75373. }
  75374. const Path* sourcePath = &source;
  75375. Path temp;
  75376. if (sourcePath == &destPath)
  75377. {
  75378. destPath.swapWithPath (temp);
  75379. sourcePath = &temp;
  75380. }
  75381. else
  75382. {
  75383. destPath.clear();
  75384. }
  75385. destPath.setUsingNonZeroWinding (true);
  75386. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  75387. const float width = 0.5f * thickness;
  75388. // Iterate the path, creating a list of the
  75389. // left/right-hand lines along either side of it...
  75390. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  75391. Array <LineSection> subPath;
  75392. subPath.ensureStorageAllocated (512);
  75393. LineSection l;
  75394. l.x1 = 0;
  75395. l.y1 = 0;
  75396. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  75397. while (it.next())
  75398. {
  75399. if (it.subPathIndex == 0)
  75400. {
  75401. if (subPath.size() > 0)
  75402. {
  75403. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75404. subPath.clearQuick();
  75405. }
  75406. l.x1 = it.x1;
  75407. l.y1 = it.y1;
  75408. }
  75409. l.x2 = it.x2;
  75410. l.y2 = it.y2;
  75411. float dx = l.x2 - l.x1;
  75412. float dy = l.y2 - l.y1;
  75413. const float hypotSquared = dx*dx + dy*dy;
  75414. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  75415. {
  75416. const float len = std::sqrt (hypotSquared);
  75417. if (len == 0)
  75418. {
  75419. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  75420. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  75421. }
  75422. else
  75423. {
  75424. const float offset = width / len;
  75425. dx *= offset;
  75426. dy *= offset;
  75427. l.rx2 = l.x1 - dy;
  75428. l.ry2 = l.y1 + dx;
  75429. l.lx1 = l.x1 + dy;
  75430. l.ly1 = l.y1 - dx;
  75431. l.lx2 = l.x2 + dy;
  75432. l.ly2 = l.y2 - dx;
  75433. l.rx1 = l.x2 - dy;
  75434. l.ry1 = l.y2 + dx;
  75435. }
  75436. subPath.add (l);
  75437. if (it.closesSubPath)
  75438. {
  75439. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75440. subPath.clearQuick();
  75441. }
  75442. else
  75443. {
  75444. l.x1 = it.x2;
  75445. l.y1 = it.y2;
  75446. }
  75447. }
  75448. }
  75449. if (subPath.size() > 0)
  75450. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  75451. }
  75452. }
  75453. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  75454. const AffineTransform& transform, const float extraAccuracy) const
  75455. {
  75456. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  75457. transform, extraAccuracy, 0);
  75458. }
  75459. void PathStrokeType::createDashedStroke (Path& destPath,
  75460. const Path& sourcePath,
  75461. const float* dashLengths,
  75462. int numDashLengths,
  75463. const AffineTransform& transform,
  75464. const float extraAccuracy) const
  75465. {
  75466. if (thickness <= 0)
  75467. return;
  75468. // this should really be an even number..
  75469. jassert ((numDashLengths & 1) == 0);
  75470. Path newDestPath;
  75471. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  75472. bool first = true;
  75473. int dashNum = 0;
  75474. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  75475. float dx = 0.0f, dy = 0.0f;
  75476. for (;;)
  75477. {
  75478. const bool isSolid = ((dashNum & 1) == 0);
  75479. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  75480. jassert (dashLen > 0); // must be a positive increment!
  75481. if (dashLen <= 0)
  75482. break;
  75483. pos += dashLen;
  75484. while (pos > lineEndPos)
  75485. {
  75486. if (! it.next())
  75487. {
  75488. if (isSolid && ! first)
  75489. newDestPath.lineTo (it.x2, it.y2);
  75490. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  75491. return;
  75492. }
  75493. if (isSolid && ! first)
  75494. newDestPath.lineTo (it.x1, it.y1);
  75495. else
  75496. newDestPath.startNewSubPath (it.x1, it.y1);
  75497. dx = it.x2 - it.x1;
  75498. dy = it.y2 - it.y1;
  75499. lineLen = juce_hypotf (dx, dy);
  75500. lineEndPos += lineLen;
  75501. first = it.closesSubPath;
  75502. }
  75503. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  75504. if (isSolid)
  75505. newDestPath.lineTo (it.x1 + dx * alpha,
  75506. it.y1 + dy * alpha);
  75507. else
  75508. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  75509. it.y1 + dy * alpha);
  75510. }
  75511. }
  75512. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  75513. const Path& sourcePath,
  75514. const float arrowheadStartWidth, const float arrowheadStartLength,
  75515. const float arrowheadEndWidth, const float arrowheadEndLength,
  75516. const AffineTransform& transform,
  75517. const float extraAccuracy) const
  75518. {
  75519. PathStrokeHelpers::Arrowhead head;
  75520. head.startWidth = arrowheadStartWidth;
  75521. head.startLength = arrowheadStartLength;
  75522. head.endWidth = arrowheadEndWidth;
  75523. head.endLength = arrowheadEndLength;
  75524. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  75525. destPath, sourcePath, transform, extraAccuracy, &head);
  75526. }
  75527. END_JUCE_NAMESPACE
  75528. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  75529. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  75530. BEGIN_JUCE_NAMESPACE
  75531. PositionedRectangle::PositionedRectangle() throw()
  75532. : x (0.0),
  75533. y (0.0),
  75534. w (0.0),
  75535. h (0.0),
  75536. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  75537. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  75538. wMode (absoluteSize),
  75539. hMode (absoluteSize)
  75540. {
  75541. }
  75542. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  75543. : x (other.x),
  75544. y (other.y),
  75545. w (other.w),
  75546. h (other.h),
  75547. xMode (other.xMode),
  75548. yMode (other.yMode),
  75549. wMode (other.wMode),
  75550. hMode (other.hMode)
  75551. {
  75552. }
  75553. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  75554. {
  75555. x = other.x;
  75556. y = other.y;
  75557. w = other.w;
  75558. h = other.h;
  75559. xMode = other.xMode;
  75560. yMode = other.yMode;
  75561. wMode = other.wMode;
  75562. hMode = other.hMode;
  75563. return *this;
  75564. }
  75565. PositionedRectangle::~PositionedRectangle() throw()
  75566. {
  75567. }
  75568. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  75569. {
  75570. return x == other.x
  75571. && y == other.y
  75572. && w == other.w
  75573. && h == other.h
  75574. && xMode == other.xMode
  75575. && yMode == other.yMode
  75576. && wMode == other.wMode
  75577. && hMode == other.hMode;
  75578. }
  75579. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  75580. {
  75581. return ! operator== (other);
  75582. }
  75583. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  75584. {
  75585. StringArray tokens;
  75586. tokens.addTokens (stringVersion, false);
  75587. decodePosString (tokens [0], xMode, x);
  75588. decodePosString (tokens [1], yMode, y);
  75589. decodeSizeString (tokens [2], wMode, w);
  75590. decodeSizeString (tokens [3], hMode, h);
  75591. }
  75592. const String PositionedRectangle::toString() const throw()
  75593. {
  75594. String s;
  75595. s.preallocateStorage (12);
  75596. addPosDescription (s, xMode, x);
  75597. s << ' ';
  75598. addPosDescription (s, yMode, y);
  75599. s << ' ';
  75600. addSizeDescription (s, wMode, w);
  75601. s << ' ';
  75602. addSizeDescription (s, hMode, h);
  75603. return s;
  75604. }
  75605. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  75606. {
  75607. jassert (! target.isEmpty());
  75608. double x_, y_, w_, h_;
  75609. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  75610. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  75611. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  75612. roundToInt (w_), roundToInt (h_));
  75613. }
  75614. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  75615. double& x_, double& y_,
  75616. double& w_, double& h_) const throw()
  75617. {
  75618. jassert (! target.isEmpty());
  75619. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  75620. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  75621. }
  75622. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  75623. {
  75624. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  75625. }
  75626. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  75627. const Rectangle<int>& target) throw()
  75628. {
  75629. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  75630. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  75631. }
  75632. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  75633. const double newW, const double newH,
  75634. const Rectangle<int>& target) throw()
  75635. {
  75636. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  75637. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  75638. }
  75639. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  75640. {
  75641. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  75642. updateFrom (comp.getBounds(), Rectangle<int>());
  75643. else
  75644. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  75645. }
  75646. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  75647. {
  75648. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  75649. }
  75650. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  75651. {
  75652. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  75653. | absoluteFromParentBottomRight
  75654. | absoluteFromParentCentre
  75655. | proportionOfParentSize));
  75656. }
  75657. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  75658. {
  75659. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  75660. }
  75661. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  75662. {
  75663. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  75664. | absoluteFromParentBottomRight
  75665. | absoluteFromParentCentre
  75666. | proportionOfParentSize));
  75667. }
  75668. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  75669. {
  75670. return (SizeMode) wMode;
  75671. }
  75672. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  75673. {
  75674. return (SizeMode) hMode;
  75675. }
  75676. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  75677. const PositionMode xMode_,
  75678. const AnchorPoint yAnchor,
  75679. const PositionMode yMode_,
  75680. const SizeMode widthMode,
  75681. const SizeMode heightMode,
  75682. const Rectangle<int>& target) throw()
  75683. {
  75684. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  75685. {
  75686. double tx, tw;
  75687. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  75688. xMode = (uint8) (xAnchor | xMode_);
  75689. wMode = (uint8) widthMode;
  75690. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  75691. }
  75692. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  75693. {
  75694. double ty, th;
  75695. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  75696. yMode = (uint8) (yAnchor | yMode_);
  75697. hMode = (uint8) heightMode;
  75698. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  75699. }
  75700. }
  75701. bool PositionedRectangle::isPositionAbsolute() const throw()
  75702. {
  75703. return xMode == absoluteFromParentTopLeft
  75704. && yMode == absoluteFromParentTopLeft
  75705. && wMode == absoluteSize
  75706. && hMode == absoluteSize;
  75707. }
  75708. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  75709. {
  75710. if ((mode & proportionOfParentSize) != 0)
  75711. {
  75712. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  75713. }
  75714. else
  75715. {
  75716. s << (roundToInt (value * 100.0) / 100.0);
  75717. if ((mode & absoluteFromParentBottomRight) != 0)
  75718. s << 'R';
  75719. else if ((mode & absoluteFromParentCentre) != 0)
  75720. s << 'C';
  75721. }
  75722. if ((mode & anchorAtRightOrBottom) != 0)
  75723. s << 'r';
  75724. else if ((mode & anchorAtCentre) != 0)
  75725. s << 'c';
  75726. }
  75727. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  75728. {
  75729. if (mode == proportionalSize)
  75730. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  75731. else if (mode == parentSizeMinusAbsolute)
  75732. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  75733. else
  75734. s << (roundToInt (value * 100.0) / 100.0);
  75735. }
  75736. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  75737. {
  75738. if (s.containsChar ('r'))
  75739. mode = anchorAtRightOrBottom;
  75740. else if (s.containsChar ('c'))
  75741. mode = anchorAtCentre;
  75742. else
  75743. mode = anchorAtLeftOrTop;
  75744. if (s.containsChar ('%'))
  75745. {
  75746. mode |= proportionOfParentSize;
  75747. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  75748. }
  75749. else
  75750. {
  75751. if (s.containsChar ('R'))
  75752. mode |= absoluteFromParentBottomRight;
  75753. else if (s.containsChar ('C'))
  75754. mode |= absoluteFromParentCentre;
  75755. else
  75756. mode |= absoluteFromParentTopLeft;
  75757. value = s.removeCharacters ("rcRC").getDoubleValue();
  75758. }
  75759. }
  75760. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  75761. {
  75762. if (s.containsChar ('%'))
  75763. {
  75764. mode = proportionalSize;
  75765. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  75766. }
  75767. else if (s.containsChar ('M'))
  75768. {
  75769. mode = parentSizeMinusAbsolute;
  75770. value = s.getDoubleValue();
  75771. }
  75772. else
  75773. {
  75774. mode = absoluteSize;
  75775. value = s.getDoubleValue();
  75776. }
  75777. }
  75778. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  75779. const double x_, const double w_,
  75780. const uint8 xMode_, const uint8 wMode_,
  75781. const int parentPos,
  75782. const int parentSize) const throw()
  75783. {
  75784. if (wMode_ == proportionalSize)
  75785. wOut = roundToInt (w_ * parentSize);
  75786. else if (wMode_ == parentSizeMinusAbsolute)
  75787. wOut = jmax (0, parentSize - roundToInt (w_));
  75788. else
  75789. wOut = roundToInt (w_);
  75790. if ((xMode_ & proportionOfParentSize) != 0)
  75791. xOut = parentPos + x_ * parentSize;
  75792. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  75793. xOut = (parentPos + parentSize) - x_;
  75794. else if ((xMode_ & absoluteFromParentCentre) != 0)
  75795. xOut = x_ + (parentPos + parentSize / 2);
  75796. else
  75797. xOut = x_ + parentPos;
  75798. if ((xMode_ & anchorAtRightOrBottom) != 0)
  75799. xOut -= wOut;
  75800. else if ((xMode_ & anchorAtCentre) != 0)
  75801. xOut -= wOut / 2;
  75802. }
  75803. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  75804. double x_, const double w_,
  75805. const uint8 xMode_, const uint8 wMode_,
  75806. const int parentPos,
  75807. const int parentSize) const throw()
  75808. {
  75809. if (wMode_ == proportionalSize)
  75810. {
  75811. if (parentSize > 0)
  75812. wOut = w_ / parentSize;
  75813. }
  75814. else if (wMode_ == parentSizeMinusAbsolute)
  75815. wOut = parentSize - w_;
  75816. else
  75817. wOut = w_;
  75818. if ((xMode_ & anchorAtRightOrBottom) != 0)
  75819. x_ += w_;
  75820. else if ((xMode_ & anchorAtCentre) != 0)
  75821. x_ += w_ / 2;
  75822. if ((xMode_ & proportionOfParentSize) != 0)
  75823. {
  75824. if (parentSize > 0)
  75825. xOut = (x_ - parentPos) / parentSize;
  75826. }
  75827. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  75828. xOut = (parentPos + parentSize) - x_;
  75829. else if ((xMode_ & absoluteFromParentCentre) != 0)
  75830. xOut = x_ - (parentPos + parentSize / 2);
  75831. else
  75832. xOut = x_ - parentPos;
  75833. }
  75834. END_JUCE_NAMESPACE
  75835. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  75836. /*** Start of inlined file: juce_RectangleList.cpp ***/
  75837. BEGIN_JUCE_NAMESPACE
  75838. RectangleList::RectangleList() throw()
  75839. {
  75840. }
  75841. RectangleList::RectangleList (const Rectangle<int>& rect)
  75842. {
  75843. if (! rect.isEmpty())
  75844. rects.add (rect);
  75845. }
  75846. RectangleList::RectangleList (const RectangleList& other)
  75847. : rects (other.rects)
  75848. {
  75849. }
  75850. RectangleList& RectangleList::operator= (const RectangleList& other)
  75851. {
  75852. rects = other.rects;
  75853. return *this;
  75854. }
  75855. RectangleList::~RectangleList()
  75856. {
  75857. }
  75858. void RectangleList::clear()
  75859. {
  75860. rects.clearQuick();
  75861. }
  75862. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  75863. {
  75864. if (((unsigned int) index) < (unsigned int) rects.size())
  75865. return rects.getReference (index);
  75866. return Rectangle<int>();
  75867. }
  75868. bool RectangleList::isEmpty() const throw()
  75869. {
  75870. return rects.size() == 0;
  75871. }
  75872. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  75873. : current (0),
  75874. owner (list),
  75875. index (list.rects.size())
  75876. {
  75877. }
  75878. RectangleList::Iterator::~Iterator()
  75879. {
  75880. }
  75881. bool RectangleList::Iterator::next() throw()
  75882. {
  75883. if (--index >= 0)
  75884. {
  75885. current = & (owner.rects.getReference (index));
  75886. return true;
  75887. }
  75888. return false;
  75889. }
  75890. void RectangleList::add (const Rectangle<int>& rect)
  75891. {
  75892. if (! rect.isEmpty())
  75893. {
  75894. if (rects.size() == 0)
  75895. {
  75896. rects.add (rect);
  75897. }
  75898. else
  75899. {
  75900. bool anyOverlaps = false;
  75901. int i;
  75902. for (i = rects.size(); --i >= 0;)
  75903. {
  75904. Rectangle<int>& ourRect = rects.getReference (i);
  75905. if (rect.intersects (ourRect))
  75906. {
  75907. if (rect.contains (ourRect))
  75908. rects.remove (i);
  75909. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  75910. anyOverlaps = true;
  75911. }
  75912. }
  75913. if (anyOverlaps && rects.size() > 0)
  75914. {
  75915. RectangleList r (rect);
  75916. for (i = rects.size(); --i >= 0;)
  75917. {
  75918. const Rectangle<int>& ourRect = rects.getReference (i);
  75919. if (rect.intersects (ourRect))
  75920. {
  75921. r.subtract (ourRect);
  75922. if (r.rects.size() == 0)
  75923. return;
  75924. }
  75925. }
  75926. for (i = r.getNumRectangles(); --i >= 0;)
  75927. rects.add (r.rects.getReference (i));
  75928. }
  75929. else
  75930. {
  75931. rects.add (rect);
  75932. }
  75933. }
  75934. }
  75935. }
  75936. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  75937. {
  75938. if (! rect.isEmpty())
  75939. rects.add (rect);
  75940. }
  75941. void RectangleList::add (const int x, const int y, const int w, const int h)
  75942. {
  75943. if (rects.size() == 0)
  75944. {
  75945. if (w > 0 && h > 0)
  75946. rects.add (Rectangle<int> (x, y, w, h));
  75947. }
  75948. else
  75949. {
  75950. add (Rectangle<int> (x, y, w, h));
  75951. }
  75952. }
  75953. void RectangleList::add (const RectangleList& other)
  75954. {
  75955. for (int i = 0; i < other.rects.size(); ++i)
  75956. add (other.rects.getReference (i));
  75957. }
  75958. void RectangleList::subtract (const Rectangle<int>& rect)
  75959. {
  75960. const int originalNumRects = rects.size();
  75961. if (originalNumRects > 0)
  75962. {
  75963. const int x1 = rect.x;
  75964. const int y1 = rect.y;
  75965. const int x2 = x1 + rect.w;
  75966. const int y2 = y1 + rect.h;
  75967. for (int i = getNumRectangles(); --i >= 0;)
  75968. {
  75969. Rectangle<int>& r = rects.getReference (i);
  75970. const int rx1 = r.x;
  75971. const int ry1 = r.y;
  75972. const int rx2 = rx1 + r.w;
  75973. const int ry2 = ry1 + r.h;
  75974. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  75975. {
  75976. if (x1 > rx1 && x1 < rx2)
  75977. {
  75978. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  75979. {
  75980. r.w = x1 - rx1;
  75981. }
  75982. else
  75983. {
  75984. r.x = x1;
  75985. r.w = rx2 - x1;
  75986. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  75987. i += 2;
  75988. }
  75989. }
  75990. else if (x2 > rx1 && x2 < rx2)
  75991. {
  75992. r.x = x2;
  75993. r.w = rx2 - x2;
  75994. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  75995. {
  75996. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  75997. i += 2;
  75998. }
  75999. }
  76000. else if (y1 > ry1 && y1 < ry2)
  76001. {
  76002. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76003. {
  76004. r.h = y1 - ry1;
  76005. }
  76006. else
  76007. {
  76008. r.y = y1;
  76009. r.h = ry2 - y1;
  76010. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76011. i += 2;
  76012. }
  76013. }
  76014. else if (y2 > ry1 && y2 < ry2)
  76015. {
  76016. r.y = y2;
  76017. r.h = ry2 - y2;
  76018. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76019. {
  76020. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76021. i += 2;
  76022. }
  76023. }
  76024. else
  76025. {
  76026. rects.remove (i);
  76027. }
  76028. }
  76029. }
  76030. }
  76031. }
  76032. bool RectangleList::subtract (const RectangleList& otherList)
  76033. {
  76034. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76035. subtract (otherList.rects.getReference (i));
  76036. return rects.size() > 0;
  76037. }
  76038. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76039. {
  76040. bool notEmpty = false;
  76041. if (rect.isEmpty())
  76042. {
  76043. clear();
  76044. }
  76045. else
  76046. {
  76047. for (int i = rects.size(); --i >= 0;)
  76048. {
  76049. Rectangle<int>& r = rects.getReference (i);
  76050. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76051. rects.remove (i);
  76052. else
  76053. notEmpty = true;
  76054. }
  76055. }
  76056. return notEmpty;
  76057. }
  76058. bool RectangleList::clipTo (const RectangleList& other)
  76059. {
  76060. if (rects.size() == 0)
  76061. return false;
  76062. RectangleList result;
  76063. for (int j = 0; j < rects.size(); ++j)
  76064. {
  76065. const Rectangle<int>& rect = rects.getReference (j);
  76066. for (int i = other.rects.size(); --i >= 0;)
  76067. {
  76068. Rectangle<int> r (other.rects.getReference (i));
  76069. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76070. result.rects.add (r);
  76071. }
  76072. }
  76073. swapWith (result);
  76074. return ! isEmpty();
  76075. }
  76076. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76077. {
  76078. destRegion.clear();
  76079. if (! rect.isEmpty())
  76080. {
  76081. for (int i = rects.size(); --i >= 0;)
  76082. {
  76083. Rectangle<int> r (rects.getReference (i));
  76084. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76085. destRegion.rects.add (r);
  76086. }
  76087. }
  76088. return destRegion.rects.size() > 0;
  76089. }
  76090. void RectangleList::swapWith (RectangleList& otherList) throw()
  76091. {
  76092. rects.swapWithArray (otherList.rects);
  76093. }
  76094. void RectangleList::consolidate()
  76095. {
  76096. int i;
  76097. for (i = 0; i < getNumRectangles() - 1; ++i)
  76098. {
  76099. Rectangle<int>& r = rects.getReference (i);
  76100. const int rx1 = r.x;
  76101. const int ry1 = r.y;
  76102. const int rx2 = rx1 + r.w;
  76103. const int ry2 = ry1 + r.h;
  76104. for (int j = rects.size(); --j > i;)
  76105. {
  76106. Rectangle<int>& r2 = rects.getReference (j);
  76107. const int jrx1 = r2.x;
  76108. const int jry1 = r2.y;
  76109. const int jrx2 = jrx1 + r2.w;
  76110. const int jry2 = jry1 + r2.h;
  76111. // if the vertical edges of any blocks are touching and their horizontals don't
  76112. // line up, split them horizontally..
  76113. if (jrx1 == rx2 || jrx2 == rx1)
  76114. {
  76115. if (jry1 > ry1 && jry1 < ry2)
  76116. {
  76117. r.h = jry1 - ry1;
  76118. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76119. i = -1;
  76120. break;
  76121. }
  76122. if (jry2 > ry1 && jry2 < ry2)
  76123. {
  76124. r.h = jry2 - ry1;
  76125. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76126. i = -1;
  76127. break;
  76128. }
  76129. else if (ry1 > jry1 && ry1 < jry2)
  76130. {
  76131. r2.h = ry1 - jry1;
  76132. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76133. i = -1;
  76134. break;
  76135. }
  76136. else if (ry2 > jry1 && ry2 < jry2)
  76137. {
  76138. r2.h = ry2 - jry1;
  76139. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76140. i = -1;
  76141. break;
  76142. }
  76143. }
  76144. }
  76145. }
  76146. for (i = 0; i < rects.size() - 1; ++i)
  76147. {
  76148. Rectangle<int>& r = rects.getReference (i);
  76149. for (int j = rects.size(); --j > i;)
  76150. {
  76151. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76152. {
  76153. rects.remove (j);
  76154. i = -1;
  76155. break;
  76156. }
  76157. }
  76158. }
  76159. }
  76160. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76161. {
  76162. for (int i = getNumRectangles(); --i >= 0;)
  76163. if (rects.getReference (i).contains (x, y))
  76164. return true;
  76165. return false;
  76166. }
  76167. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76168. {
  76169. if (rects.size() > 1)
  76170. {
  76171. RectangleList r (rectangleToCheck);
  76172. for (int i = rects.size(); --i >= 0;)
  76173. {
  76174. r.subtract (rects.getReference (i));
  76175. if (r.rects.size() == 0)
  76176. return true;
  76177. }
  76178. }
  76179. else if (rects.size() > 0)
  76180. {
  76181. return rects.getReference (0).contains (rectangleToCheck);
  76182. }
  76183. return false;
  76184. }
  76185. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76186. {
  76187. for (int i = rects.size(); --i >= 0;)
  76188. if (rects.getReference (i).intersects (rectangleToCheck))
  76189. return true;
  76190. return false;
  76191. }
  76192. bool RectangleList::intersects (const RectangleList& other) const throw()
  76193. {
  76194. for (int i = rects.size(); --i >= 0;)
  76195. if (other.intersectsRectangle (rects.getReference (i)))
  76196. return true;
  76197. return false;
  76198. }
  76199. const Rectangle<int> RectangleList::getBounds() const throw()
  76200. {
  76201. if (rects.size() <= 1)
  76202. {
  76203. if (rects.size() == 0)
  76204. return Rectangle<int>();
  76205. else
  76206. return rects.getReference (0);
  76207. }
  76208. else
  76209. {
  76210. const Rectangle<int>& r = rects.getReference (0);
  76211. int minX = r.x;
  76212. int minY = r.y;
  76213. int maxX = minX + r.w;
  76214. int maxY = minY + r.h;
  76215. for (int i = rects.size(); --i > 0;)
  76216. {
  76217. const Rectangle<int>& r2 = rects.getReference (i);
  76218. minX = jmin (minX, r2.x);
  76219. minY = jmin (minY, r2.y);
  76220. maxX = jmax (maxX, r2.getRight());
  76221. maxY = jmax (maxY, r2.getBottom());
  76222. }
  76223. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76224. }
  76225. }
  76226. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76227. {
  76228. for (int i = rects.size(); --i >= 0;)
  76229. {
  76230. Rectangle<int>& r = rects.getReference (i);
  76231. r.x += dx;
  76232. r.y += dy;
  76233. }
  76234. }
  76235. const Path RectangleList::toPath() const
  76236. {
  76237. Path p;
  76238. for (int i = rects.size(); --i >= 0;)
  76239. {
  76240. const Rectangle<int>& r = rects.getReference (i);
  76241. p.addRectangle ((float) r.x,
  76242. (float) r.y,
  76243. (float) r.w,
  76244. (float) r.h);
  76245. }
  76246. return p;
  76247. }
  76248. END_JUCE_NAMESPACE
  76249. /*** End of inlined file: juce_RectangleList.cpp ***/
  76250. /*** Start of inlined file: juce_Image.cpp ***/
  76251. BEGIN_JUCE_NAMESPACE
  76252. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76253. : format (format_), width (width_), height (height_)
  76254. {
  76255. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76256. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76257. }
  76258. Image::SharedImage::~SharedImage()
  76259. {
  76260. }
  76261. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76262. {
  76263. return imageData + lineStride * y + pixelStride * x;
  76264. }
  76265. class SoftwareSharedImage : public Image::SharedImage
  76266. {
  76267. public:
  76268. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76269. : Image::SharedImage (format_, width_, height_)
  76270. {
  76271. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76272. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76273. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76274. imageData = imageDataAllocated;
  76275. }
  76276. ~SoftwareSharedImage()
  76277. {
  76278. }
  76279. Image::ImageType getType() const
  76280. {
  76281. return Image::SoftwareImage;
  76282. }
  76283. LowLevelGraphicsContext* createLowLevelContext()
  76284. {
  76285. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76286. }
  76287. SharedImage* clone()
  76288. {
  76289. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76290. memcpy (s->imageData, imageData, lineStride * height);
  76291. return s;
  76292. }
  76293. private:
  76294. HeapBlock<uint8> imageDataAllocated;
  76295. };
  76296. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76297. {
  76298. return new SoftwareSharedImage (format, width, height, clearImage);
  76299. }
  76300. class SubsectionSharedImage : public Image::SharedImage
  76301. {
  76302. public:
  76303. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76304. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76305. image (image_), area (area_)
  76306. {
  76307. pixelStride = image_->getPixelStride();
  76308. lineStride = image_->getLineStride();
  76309. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76310. }
  76311. ~SubsectionSharedImage() {}
  76312. Image::ImageType getType() const
  76313. {
  76314. return Image::SoftwareImage;
  76315. }
  76316. LowLevelGraphicsContext* createLowLevelContext()
  76317. {
  76318. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76319. g->clipToRectangle (area);
  76320. g->setOrigin (area.getX(), area.getY());
  76321. return g;
  76322. }
  76323. SharedImage* clone()
  76324. {
  76325. return new SubsectionSharedImage (image->clone(), area);
  76326. }
  76327. private:
  76328. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76329. const Rectangle<int> area;
  76330. SubsectionSharedImage (const SubsectionSharedImage&);
  76331. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76332. };
  76333. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76334. {
  76335. if (area.contains (getBounds()))
  76336. return *this;
  76337. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76338. if (validArea.isEmpty())
  76339. return Image::null;
  76340. return Image (new SubsectionSharedImage (image, validArea));
  76341. }
  76342. Image::Image()
  76343. {
  76344. }
  76345. Image::Image (SharedImage* const instance)
  76346. : image (instance)
  76347. {
  76348. }
  76349. Image::Image (const PixelFormat format,
  76350. const int width, const int height,
  76351. const bool clearImage, const ImageType type)
  76352. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76353. : new SoftwareSharedImage (format, width, height, clearImage))
  76354. {
  76355. }
  76356. Image::Image (const Image& other)
  76357. : image (other.image)
  76358. {
  76359. }
  76360. Image& Image::operator= (const Image& other)
  76361. {
  76362. image = other.image;
  76363. return *this;
  76364. }
  76365. Image::~Image()
  76366. {
  76367. }
  76368. const Image Image::null;
  76369. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76370. {
  76371. return image == 0 ? 0 : image->createLowLevelContext();
  76372. }
  76373. void Image::duplicateIfShared()
  76374. {
  76375. if (image != 0 && image->getReferenceCount() > 1)
  76376. image = image->clone();
  76377. }
  76378. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76379. {
  76380. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76381. return *this;
  76382. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76383. Graphics g (newImage);
  76384. g.setImageResamplingQuality (quality);
  76385. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76386. return newImage;
  76387. }
  76388. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76389. {
  76390. if (image == 0 || newFormat == image->format)
  76391. return *this;
  76392. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76393. if (newFormat == SingleChannel)
  76394. {
  76395. if (! hasAlphaChannel())
  76396. {
  76397. newImage.clear (getBounds(), Colours::black);
  76398. }
  76399. else
  76400. {
  76401. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76402. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76403. for (int y = 0; y < image->height; ++y)
  76404. {
  76405. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76406. uint8* dst = destData.getLinePointer (y);
  76407. for (int x = image->width; --x >= 0;)
  76408. {
  76409. *dst++ = src->getAlpha();
  76410. ++src;
  76411. }
  76412. }
  76413. }
  76414. }
  76415. else
  76416. {
  76417. if (hasAlphaChannel())
  76418. newImage.clear (getBounds());
  76419. Graphics g (newImage);
  76420. g.drawImageAt (*this, 0, 0);
  76421. }
  76422. return newImage;
  76423. }
  76424. const var Image::getTag() const
  76425. {
  76426. return image == 0 ? var::null : image->userTag;
  76427. }
  76428. void Image::setTag (const var& newTag)
  76429. {
  76430. if (image != 0)
  76431. image->userTag = newTag;
  76432. }
  76433. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76434. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76435. pixelFormat (image.getFormat()),
  76436. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76437. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76438. width (w),
  76439. height (h)
  76440. {
  76441. jassert (data != 0);
  76442. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76443. }
  76444. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76445. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76446. pixelFormat (image.getFormat()),
  76447. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76448. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76449. width (w),
  76450. height (h)
  76451. {
  76452. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76453. }
  76454. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76455. : data (image.image == 0 ? 0 : image.image->imageData),
  76456. pixelFormat (image.getFormat()),
  76457. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76458. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76459. width (image.getWidth()),
  76460. height (image.getHeight())
  76461. {
  76462. }
  76463. Image::BitmapData::~BitmapData()
  76464. {
  76465. }
  76466. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76467. {
  76468. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76469. const uint8* const pixel = getPixelPointer (x, y);
  76470. switch (pixelFormat)
  76471. {
  76472. case Image::ARGB:
  76473. {
  76474. PixelARGB p (*(const PixelARGB*) pixel);
  76475. p.unpremultiply();
  76476. return Colour (p.getARGB());
  76477. }
  76478. case Image::RGB:
  76479. return Colour (((const PixelRGB*) pixel)->getARGB());
  76480. case Image::SingleChannel:
  76481. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76482. default:
  76483. jassertfalse;
  76484. break;
  76485. }
  76486. return Colour();
  76487. }
  76488. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76489. {
  76490. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76491. uint8* const pixel = getPixelPointer (x, y);
  76492. const PixelARGB col (colour.getPixelARGB());
  76493. switch (pixelFormat)
  76494. {
  76495. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76496. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76497. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76498. default: jassertfalse; break;
  76499. }
  76500. }
  76501. void Image::setPixelData (int x, int y, int w, int h,
  76502. const uint8* const sourcePixelData, const int sourceLineStride)
  76503. {
  76504. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76505. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76506. {
  76507. const BitmapData dest (*this, x, y, w, h, true);
  76508. for (int i = 0; i < h; ++i)
  76509. {
  76510. memcpy (dest.getLinePointer(i),
  76511. sourcePixelData + sourceLineStride * i,
  76512. w * dest.pixelStride);
  76513. }
  76514. }
  76515. }
  76516. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76517. {
  76518. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76519. if (! clipped.isEmpty())
  76520. {
  76521. const PixelARGB col (colourToClearTo.getPixelARGB());
  76522. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76523. uint8* dest = destData.data;
  76524. int dh = clipped.getHeight();
  76525. while (--dh >= 0)
  76526. {
  76527. uint8* line = dest;
  76528. dest += destData.lineStride;
  76529. if (isARGB())
  76530. {
  76531. for (int x = clipped.getWidth(); --x >= 0;)
  76532. {
  76533. ((PixelARGB*) line)->set (col);
  76534. line += destData.pixelStride;
  76535. }
  76536. }
  76537. else if (isRGB())
  76538. {
  76539. for (int x = clipped.getWidth(); --x >= 0;)
  76540. {
  76541. ((PixelRGB*) line)->set (col);
  76542. line += destData.pixelStride;
  76543. }
  76544. }
  76545. else
  76546. {
  76547. for (int x = clipped.getWidth(); --x >= 0;)
  76548. {
  76549. *line = col.getAlpha();
  76550. line += destData.pixelStride;
  76551. }
  76552. }
  76553. }
  76554. }
  76555. }
  76556. const Colour Image::getPixelAt (const int x, const int y) const
  76557. {
  76558. if (((unsigned int) x) < (unsigned int) getWidth()
  76559. && ((unsigned int) y) < (unsigned int) getHeight())
  76560. {
  76561. const BitmapData srcData (*this, x, y, 1, 1);
  76562. return srcData.getPixelColour (0, 0);
  76563. }
  76564. return Colour();
  76565. }
  76566. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76567. {
  76568. if (((unsigned int) x) < (unsigned int) getWidth()
  76569. && ((unsigned int) y) < (unsigned int) getHeight())
  76570. {
  76571. const BitmapData destData (*this, x, y, 1, 1, true);
  76572. destData.setPixelColour (0, 0, colour);
  76573. }
  76574. }
  76575. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76576. {
  76577. if (((unsigned int) x) < (unsigned int) getWidth()
  76578. && ((unsigned int) y) < (unsigned int) getHeight()
  76579. && hasAlphaChannel())
  76580. {
  76581. const BitmapData destData (*this, x, y, 1, 1, true);
  76582. if (isARGB())
  76583. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76584. else
  76585. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76586. }
  76587. }
  76588. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76589. {
  76590. if (hasAlphaChannel())
  76591. {
  76592. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76593. if (isARGB())
  76594. {
  76595. for (int y = 0; y < destData.height; ++y)
  76596. {
  76597. uint8* p = destData.getLinePointer (y);
  76598. for (int x = 0; x < destData.width; ++x)
  76599. {
  76600. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76601. p += destData.pixelStride;
  76602. }
  76603. }
  76604. }
  76605. else
  76606. {
  76607. for (int y = 0; y < destData.height; ++y)
  76608. {
  76609. uint8* p = destData.getLinePointer (y);
  76610. for (int x = 0; x < destData.width; ++x)
  76611. {
  76612. *p = (uint8) (*p * amountToMultiplyBy);
  76613. p += destData.pixelStride;
  76614. }
  76615. }
  76616. }
  76617. }
  76618. else
  76619. {
  76620. jassertfalse; // can't do this without an alpha-channel!
  76621. }
  76622. }
  76623. void Image::desaturate()
  76624. {
  76625. if (isARGB() || isRGB())
  76626. {
  76627. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76628. if (isARGB())
  76629. {
  76630. for (int y = 0; y < destData.height; ++y)
  76631. {
  76632. uint8* p = destData.getLinePointer (y);
  76633. for (int x = 0; x < destData.width; ++x)
  76634. {
  76635. ((PixelARGB*) p)->desaturate();
  76636. p += destData.pixelStride;
  76637. }
  76638. }
  76639. }
  76640. else
  76641. {
  76642. for (int y = 0; y < destData.height; ++y)
  76643. {
  76644. uint8* p = destData.getLinePointer (y);
  76645. for (int x = 0; x < destData.width; ++x)
  76646. {
  76647. ((PixelRGB*) p)->desaturate();
  76648. p += destData.pixelStride;
  76649. }
  76650. }
  76651. }
  76652. }
  76653. }
  76654. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76655. {
  76656. if (hasAlphaChannel())
  76657. {
  76658. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76659. SparseSet<int> pixelsOnRow;
  76660. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76661. for (int y = 0; y < srcData.height; ++y)
  76662. {
  76663. pixelsOnRow.clear();
  76664. const uint8* lineData = srcData.getLinePointer (y);
  76665. if (isARGB())
  76666. {
  76667. for (int x = 0; x < srcData.width; ++x)
  76668. {
  76669. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76670. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76671. lineData += srcData.pixelStride;
  76672. }
  76673. }
  76674. else
  76675. {
  76676. for (int x = 0; x < srcData.width; ++x)
  76677. {
  76678. if (*lineData >= threshold)
  76679. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76680. lineData += srcData.pixelStride;
  76681. }
  76682. }
  76683. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76684. {
  76685. const Range<int> range (pixelsOnRow.getRange (i));
  76686. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76687. }
  76688. result.consolidate();
  76689. }
  76690. }
  76691. else
  76692. {
  76693. result.add (0, 0, getWidth(), getHeight());
  76694. }
  76695. }
  76696. void Image::moveImageSection (int dx, int dy,
  76697. int sx, int sy,
  76698. int w, int h)
  76699. {
  76700. if (dx < 0)
  76701. {
  76702. w += dx;
  76703. sx -= dx;
  76704. dx = 0;
  76705. }
  76706. if (dy < 0)
  76707. {
  76708. h += dy;
  76709. sy -= dy;
  76710. dy = 0;
  76711. }
  76712. if (sx < 0)
  76713. {
  76714. w += sx;
  76715. dx -= sx;
  76716. sx = 0;
  76717. }
  76718. if (sy < 0)
  76719. {
  76720. h += sy;
  76721. dy -= sy;
  76722. sy = 0;
  76723. }
  76724. const int minX = jmin (dx, sx);
  76725. const int minY = jmin (dy, sy);
  76726. w = jmin (w, getWidth() - jmax (sx, dx));
  76727. h = jmin (h, getHeight() - jmax (sy, dy));
  76728. if (w > 0 && h > 0)
  76729. {
  76730. const int maxX = jmax (dx, sx) + w;
  76731. const int maxY = jmax (dy, sy) + h;
  76732. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76733. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76734. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76735. const int lineSize = destData.pixelStride * w;
  76736. if (dy > sy)
  76737. {
  76738. while (--h >= 0)
  76739. {
  76740. const int offset = h * destData.lineStride;
  76741. memmove (dst + offset, src + offset, lineSize);
  76742. }
  76743. }
  76744. else if (dst != src)
  76745. {
  76746. while (--h >= 0)
  76747. {
  76748. memmove (dst, src, lineSize);
  76749. dst += destData.lineStride;
  76750. src += destData.lineStride;
  76751. }
  76752. }
  76753. }
  76754. }
  76755. END_JUCE_NAMESPACE
  76756. /*** End of inlined file: juce_Image.cpp ***/
  76757. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76758. BEGIN_JUCE_NAMESPACE
  76759. class ImageCache::Pimpl : public Timer,
  76760. public DeletedAtShutdown
  76761. {
  76762. public:
  76763. Pimpl()
  76764. : cacheTimeout (5000)
  76765. {
  76766. }
  76767. ~Pimpl()
  76768. {
  76769. clearSingletonInstance();
  76770. }
  76771. const Image getFromHashCode (const int64 hashCode)
  76772. {
  76773. const ScopedLock sl (lock);
  76774. for (int i = images.size(); --i >= 0;)
  76775. {
  76776. Item* const item = images.getUnchecked(i);
  76777. if (item->hashCode == hashCode)
  76778. return item->image;
  76779. }
  76780. return Image::null;
  76781. }
  76782. void addImageToCache (const Image& image, const int64 hashCode)
  76783. {
  76784. if (image.isValid())
  76785. {
  76786. if (! isTimerRunning())
  76787. startTimer (2000);
  76788. Item* const item = new Item();
  76789. item->hashCode = hashCode;
  76790. item->image = image;
  76791. item->lastUseTime = Time::getApproximateMillisecondCounter();
  76792. const ScopedLock sl (lock);
  76793. images.add (item);
  76794. }
  76795. }
  76796. void timerCallback()
  76797. {
  76798. const uint32 now = Time::getApproximateMillisecondCounter();
  76799. const ScopedLock sl (lock);
  76800. for (int i = images.size(); --i >= 0;)
  76801. {
  76802. Item* const item = images.getUnchecked(i);
  76803. if (item->image.getReferenceCount() <= 1)
  76804. {
  76805. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  76806. images.remove (i);
  76807. }
  76808. else
  76809. {
  76810. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  76811. }
  76812. }
  76813. if (images.size() == 0)
  76814. stopTimer();
  76815. }
  76816. struct Item
  76817. {
  76818. Image image;
  76819. int64 hashCode;
  76820. uint32 lastUseTime;
  76821. };
  76822. int cacheTimeout;
  76823. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  76824. private:
  76825. OwnedArray<Item> images;
  76826. CriticalSection lock;
  76827. Pimpl (const Pimpl&);
  76828. Pimpl& operator= (const Pimpl&);
  76829. };
  76830. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  76831. const Image ImageCache::getFromHashCode (const int64 hashCode)
  76832. {
  76833. if (Pimpl::getInstanceWithoutCreating() != 0)
  76834. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  76835. return Image::null;
  76836. }
  76837. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  76838. {
  76839. Pimpl::getInstance()->addImageToCache (image, hashCode);
  76840. }
  76841. const Image ImageCache::getFromFile (const File& file)
  76842. {
  76843. const int64 hashCode = file.hashCode64();
  76844. Image image (getFromHashCode (hashCode));
  76845. if (image.isNull())
  76846. {
  76847. image = ImageFileFormat::loadFrom (file);
  76848. addImageToCache (image, hashCode);
  76849. }
  76850. return image;
  76851. }
  76852. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  76853. {
  76854. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  76855. Image image (getFromHashCode (hashCode));
  76856. if (image.isNull())
  76857. {
  76858. image = ImageFileFormat::loadFrom (imageData, dataSize);
  76859. addImageToCache (image, hashCode);
  76860. }
  76861. return image;
  76862. }
  76863. void ImageCache::setCacheTimeout (const int millisecs)
  76864. {
  76865. Pimpl::getInstance()->cacheTimeout = millisecs;
  76866. }
  76867. END_JUCE_NAMESPACE
  76868. /*** End of inlined file: juce_ImageCache.cpp ***/
  76869. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76870. BEGIN_JUCE_NAMESPACE
  76871. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  76872. : values (size_ * size_),
  76873. size (size_)
  76874. {
  76875. clear();
  76876. }
  76877. ImageConvolutionKernel::~ImageConvolutionKernel()
  76878. {
  76879. }
  76880. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  76881. {
  76882. if (((unsigned int) x) < (unsigned int) size
  76883. && ((unsigned int) y) < (unsigned int) size)
  76884. {
  76885. return values [x + y * size];
  76886. }
  76887. else
  76888. {
  76889. jassertfalse;
  76890. return 0;
  76891. }
  76892. }
  76893. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  76894. {
  76895. if (((unsigned int) x) < (unsigned int) size
  76896. && ((unsigned int) y) < (unsigned int) size)
  76897. {
  76898. values [x + y * size] = value;
  76899. }
  76900. else
  76901. {
  76902. jassertfalse;
  76903. }
  76904. }
  76905. void ImageConvolutionKernel::clear()
  76906. {
  76907. for (int i = size * size; --i >= 0;)
  76908. values[i] = 0;
  76909. }
  76910. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  76911. {
  76912. double currentTotal = 0.0;
  76913. for (int i = size * size; --i >= 0;)
  76914. currentTotal += values[i];
  76915. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  76916. }
  76917. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  76918. {
  76919. for (int i = size * size; --i >= 0;)
  76920. values[i] *= multiplier;
  76921. }
  76922. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  76923. {
  76924. const double radiusFactor = -1.0 / (radius * radius * 2);
  76925. const int centre = size >> 1;
  76926. for (int y = size; --y >= 0;)
  76927. {
  76928. for (int x = size; --x >= 0;)
  76929. {
  76930. const int cx = x - centre;
  76931. const int cy = y - centre;
  76932. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  76933. }
  76934. }
  76935. setOverallSum (1.0f);
  76936. }
  76937. void ImageConvolutionKernel::applyToImage (Image& destImage,
  76938. const Image& sourceImage,
  76939. const Rectangle<int>& destinationArea) const
  76940. {
  76941. if (sourceImage == destImage)
  76942. {
  76943. destImage.duplicateIfShared();
  76944. }
  76945. else
  76946. {
  76947. if (sourceImage.getWidth() != destImage.getWidth()
  76948. || sourceImage.getHeight() != destImage.getHeight()
  76949. || sourceImage.getFormat() != destImage.getFormat())
  76950. {
  76951. jassertfalse;
  76952. return;
  76953. }
  76954. }
  76955. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  76956. if (area.isEmpty())
  76957. return;
  76958. const int right = area.getRight();
  76959. const int bottom = area.getBottom();
  76960. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  76961. uint8* line = destData.data;
  76962. const Image::BitmapData srcData (sourceImage, false);
  76963. if (destData.pixelStride == 4)
  76964. {
  76965. for (int y = area.getY(); y < bottom; ++y)
  76966. {
  76967. uint8* dest = line;
  76968. line += destData.lineStride;
  76969. for (int x = area.getX(); x < right; ++x)
  76970. {
  76971. float c1 = 0;
  76972. float c2 = 0;
  76973. float c3 = 0;
  76974. float c4 = 0;
  76975. for (int yy = 0; yy < size; ++yy)
  76976. {
  76977. const int sy = y + yy - (size >> 1);
  76978. if (sy >= srcData.height)
  76979. break;
  76980. if (sy >= 0)
  76981. {
  76982. int sx = x - (size >> 1);
  76983. const uint8* src = srcData.getPixelPointer (sx, sy);
  76984. for (int xx = 0; xx < size; ++xx)
  76985. {
  76986. if (sx >= srcData.width)
  76987. break;
  76988. if (sx >= 0)
  76989. {
  76990. const float kernelMult = values [xx + yy * size];
  76991. c1 += kernelMult * *src++;
  76992. c2 += kernelMult * *src++;
  76993. c3 += kernelMult * *src++;
  76994. c4 += kernelMult * *src++;
  76995. }
  76996. else
  76997. {
  76998. src += 4;
  76999. }
  77000. ++sx;
  77001. }
  77002. }
  77003. }
  77004. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77005. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77006. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77007. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77008. }
  77009. }
  77010. }
  77011. else if (destData.pixelStride == 3)
  77012. {
  77013. for (int y = area.getY(); y < bottom; ++y)
  77014. {
  77015. uint8* dest = line;
  77016. line += destData.lineStride;
  77017. for (int x = area.getX(); x < right; ++x)
  77018. {
  77019. float c1 = 0;
  77020. float c2 = 0;
  77021. float c3 = 0;
  77022. for (int yy = 0; yy < size; ++yy)
  77023. {
  77024. const int sy = y + yy - (size >> 1);
  77025. if (sy >= srcData.height)
  77026. break;
  77027. if (sy >= 0)
  77028. {
  77029. int sx = x - (size >> 1);
  77030. const uint8* src = srcData.getPixelPointer (sx, sy);
  77031. for (int xx = 0; xx < size; ++xx)
  77032. {
  77033. if (sx >= srcData.width)
  77034. break;
  77035. if (sx >= 0)
  77036. {
  77037. const float kernelMult = values [xx + yy * size];
  77038. c1 += kernelMult * *src++;
  77039. c2 += kernelMult * *src++;
  77040. c3 += kernelMult * *src++;
  77041. }
  77042. else
  77043. {
  77044. src += 3;
  77045. }
  77046. ++sx;
  77047. }
  77048. }
  77049. }
  77050. *dest++ = (uint8) roundToInt (c1);
  77051. *dest++ = (uint8) roundToInt (c2);
  77052. *dest++ = (uint8) roundToInt (c3);
  77053. }
  77054. }
  77055. }
  77056. }
  77057. END_JUCE_NAMESPACE
  77058. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77059. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77060. BEGIN_JUCE_NAMESPACE
  77061. /*** Start of inlined file: juce_GIFLoader.h ***/
  77062. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  77063. #define __JUCE_GIFLOADER_JUCEHEADER__
  77064. #ifndef DOXYGEN
  77065. /**
  77066. Used internally by ImageFileFormat - don't use this class directly in your
  77067. application.
  77068. @see ImageFileFormat
  77069. */
  77070. class GIFLoader
  77071. {
  77072. public:
  77073. GIFLoader (InputStream& in);
  77074. ~GIFLoader();
  77075. const Image& getImage() const { return image; }
  77076. private:
  77077. Image image;
  77078. InputStream& input;
  77079. uint8 buffer [300];
  77080. uint8 palette [256][4];
  77081. bool dataBlockIsZero, fresh, finished;
  77082. int currentBit, lastBit, lastByteIndex;
  77083. int codeSize, setCodeSize;
  77084. int maxCode, maxCodeSize;
  77085. int firstcode, oldcode;
  77086. int clearCode, end_code;
  77087. enum { maxGifCode = 1 << 12 };
  77088. int table [2] [maxGifCode];
  77089. int stack [2 * maxGifCode];
  77090. int *sp;
  77091. bool getSizeFromHeader (int& width, int& height);
  77092. bool readPalette (const int numCols);
  77093. int readDataBlock (unsigned char* dest);
  77094. int processExtension (int type, int& transparent);
  77095. int readLZWByte (bool initialise, int input_code_size);
  77096. int getCode (int code_size, bool initialise);
  77097. bool readImage (int interlace, int transparent);
  77098. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77099. GIFLoader (const GIFLoader&);
  77100. GIFLoader& operator= (const GIFLoader&);
  77101. };
  77102. #endif // DOXYGEN
  77103. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  77104. /*** End of inlined file: juce_GIFLoader.h ***/
  77105. class GIFImageFormat : public ImageFileFormat
  77106. {
  77107. public:
  77108. GIFImageFormat() {}
  77109. ~GIFImageFormat() {}
  77110. const String getFormatName()
  77111. {
  77112. return "GIF";
  77113. }
  77114. bool canUnderstand (InputStream& in)
  77115. {
  77116. const int bytesNeeded = 4;
  77117. char header [bytesNeeded];
  77118. return (in.read (header, bytesNeeded) == bytesNeeded)
  77119. && header[0] == 'G'
  77120. && header[1] == 'I'
  77121. && header[2] == 'F';
  77122. }
  77123. const Image decodeImage (InputStream& in)
  77124. {
  77125. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77126. return loader->getImage();
  77127. }
  77128. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77129. {
  77130. return false;
  77131. }
  77132. };
  77133. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77134. {
  77135. static PNGImageFormat png;
  77136. static JPEGImageFormat jpg;
  77137. static GIFImageFormat gif;
  77138. ImageFileFormat* formats[4];
  77139. int numFormats = 0;
  77140. formats [numFormats++] = &png;
  77141. formats [numFormats++] = &jpg;
  77142. formats [numFormats++] = &gif;
  77143. const int64 streamPos = input.getPosition();
  77144. for (int i = 0; i < numFormats; ++i)
  77145. {
  77146. const bool found = formats[i]->canUnderstand (input);
  77147. input.setPosition (streamPos);
  77148. if (found)
  77149. return formats[i];
  77150. }
  77151. return 0;
  77152. }
  77153. const Image ImageFileFormat::loadFrom (InputStream& input)
  77154. {
  77155. ImageFileFormat* const format = findImageFormatForStream (input);
  77156. if (format != 0)
  77157. return format->decodeImage (input);
  77158. return Image::null;
  77159. }
  77160. const Image ImageFileFormat::loadFrom (const File& file)
  77161. {
  77162. InputStream* const in = file.createInputStream();
  77163. if (in != 0)
  77164. {
  77165. BufferedInputStream b (in, 8192, true);
  77166. return loadFrom (b);
  77167. }
  77168. return Image::null;
  77169. }
  77170. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77171. {
  77172. if (rawData != 0 && numBytes > 4)
  77173. {
  77174. MemoryInputStream stream (rawData, numBytes, false);
  77175. return loadFrom (stream);
  77176. }
  77177. return Image::null;
  77178. }
  77179. END_JUCE_NAMESPACE
  77180. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77181. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77182. BEGIN_JUCE_NAMESPACE
  77183. GIFLoader::GIFLoader (InputStream& in)
  77184. : input (in),
  77185. dataBlockIsZero (false),
  77186. fresh (false),
  77187. finished (false)
  77188. {
  77189. currentBit = lastBit = lastByteIndex = 0;
  77190. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77191. firstcode = oldcode = 0;
  77192. clearCode = end_code = 0;
  77193. int imageWidth, imageHeight;
  77194. int transparent = -1;
  77195. if (! getSizeFromHeader (imageWidth, imageHeight))
  77196. return;
  77197. if ((imageWidth <= 0) || (imageHeight <= 0))
  77198. return;
  77199. unsigned char buf [16];
  77200. if (in.read (buf, 3) != 3)
  77201. return;
  77202. int numColours = 2 << (buf[0] & 7);
  77203. if ((buf[0] & 0x80) != 0)
  77204. readPalette (numColours);
  77205. for (;;)
  77206. {
  77207. if (input.read (buf, 1) != 1)
  77208. break;
  77209. if (buf[0] == ';')
  77210. break;
  77211. if (buf[0] == '!')
  77212. {
  77213. if (input.read (buf, 1) != 1)
  77214. break;
  77215. if (processExtension (buf[0], transparent) < 0)
  77216. break;
  77217. continue;
  77218. }
  77219. if (buf[0] != ',')
  77220. continue;
  77221. if (input.read (buf, 9) != 9)
  77222. break;
  77223. imageWidth = makeWord (buf[4], buf[5]);
  77224. imageHeight = makeWord (buf[6], buf[7]);
  77225. numColours = 2 << (buf[8] & 7);
  77226. if ((buf[8] & 0x80) != 0)
  77227. if (! readPalette (numColours))
  77228. break;
  77229. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77230. imageWidth, imageHeight, (transparent >= 0));
  77231. readImage ((buf[8] & 0x40) != 0, transparent);
  77232. break;
  77233. }
  77234. }
  77235. GIFLoader::~GIFLoader()
  77236. {
  77237. }
  77238. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  77239. {
  77240. char b[8];
  77241. if (input.read (b, 6) == 6)
  77242. {
  77243. if ((strncmp ("GIF87a", b, 6) == 0)
  77244. || (strncmp ("GIF89a", b, 6) == 0))
  77245. {
  77246. if (input.read (b, 4) == 4)
  77247. {
  77248. w = makeWord (b[0], b[1]);
  77249. h = makeWord (b[2], b[3]);
  77250. return true;
  77251. }
  77252. }
  77253. }
  77254. return false;
  77255. }
  77256. bool GIFLoader::readPalette (const int numCols)
  77257. {
  77258. unsigned char rgb[4];
  77259. for (int i = 0; i < numCols; ++i)
  77260. {
  77261. input.read (rgb, 3);
  77262. palette [i][0] = rgb[0];
  77263. palette [i][1] = rgb[1];
  77264. palette [i][2] = rgb[2];
  77265. palette [i][3] = 0xff;
  77266. }
  77267. return true;
  77268. }
  77269. int GIFLoader::readDataBlock (unsigned char* const dest)
  77270. {
  77271. unsigned char n;
  77272. if (input.read (&n, 1) == 1)
  77273. {
  77274. dataBlockIsZero = (n == 0);
  77275. if (dataBlockIsZero || (input.read (dest, n) == n))
  77276. return n;
  77277. }
  77278. return -1;
  77279. }
  77280. int GIFLoader::processExtension (const int type, int& transparent)
  77281. {
  77282. unsigned char b [300];
  77283. int n = 0;
  77284. if (type == 0xf9)
  77285. {
  77286. n = readDataBlock (b);
  77287. if (n < 0)
  77288. return 1;
  77289. if ((b[0] & 0x1) != 0)
  77290. transparent = b[3];
  77291. }
  77292. do
  77293. {
  77294. n = readDataBlock (b);
  77295. }
  77296. while (n > 0);
  77297. return n;
  77298. }
  77299. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  77300. {
  77301. if (initialise)
  77302. {
  77303. currentBit = 0;
  77304. lastBit = 0;
  77305. finished = false;
  77306. return 0;
  77307. }
  77308. if ((currentBit + codeSize_) >= lastBit)
  77309. {
  77310. if (finished)
  77311. return -1;
  77312. buffer[0] = buffer [lastByteIndex - 2];
  77313. buffer[1] = buffer [lastByteIndex - 1];
  77314. const int n = readDataBlock (&buffer[2]);
  77315. if (n == 0)
  77316. finished = true;
  77317. lastByteIndex = 2 + n;
  77318. currentBit = (currentBit - lastBit) + 16;
  77319. lastBit = (2 + n) * 8 ;
  77320. }
  77321. int result = 0;
  77322. int i = currentBit;
  77323. for (int j = 0; j < codeSize_; ++j)
  77324. {
  77325. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77326. ++i;
  77327. }
  77328. currentBit += codeSize_;
  77329. return result;
  77330. }
  77331. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  77332. {
  77333. int code, incode, i;
  77334. if (initialise)
  77335. {
  77336. setCodeSize = inputCodeSize;
  77337. codeSize = setCodeSize + 1;
  77338. clearCode = 1 << setCodeSize;
  77339. end_code = clearCode + 1;
  77340. maxCodeSize = 2 * clearCode;
  77341. maxCode = clearCode + 2;
  77342. getCode (0, true);
  77343. fresh = true;
  77344. for (i = 0; i < clearCode; ++i)
  77345. {
  77346. table[0][i] = 0;
  77347. table[1][i] = i;
  77348. }
  77349. for (; i < maxGifCode; ++i)
  77350. {
  77351. table[0][i] = 0;
  77352. table[1][i] = 0;
  77353. }
  77354. sp = stack;
  77355. return 0;
  77356. }
  77357. else if (fresh)
  77358. {
  77359. fresh = false;
  77360. do
  77361. {
  77362. firstcode = oldcode
  77363. = getCode (codeSize, false);
  77364. }
  77365. while (firstcode == clearCode);
  77366. return firstcode;
  77367. }
  77368. if (sp > stack)
  77369. return *--sp;
  77370. while ((code = getCode (codeSize, false)) >= 0)
  77371. {
  77372. if (code == clearCode)
  77373. {
  77374. for (i = 0; i < clearCode; ++i)
  77375. {
  77376. table[0][i] = 0;
  77377. table[1][i] = i;
  77378. }
  77379. for (; i < maxGifCode; ++i)
  77380. {
  77381. table[0][i] = 0;
  77382. table[1][i] = 0;
  77383. }
  77384. codeSize = setCodeSize + 1;
  77385. maxCodeSize = 2 * clearCode;
  77386. maxCode = clearCode + 2;
  77387. sp = stack;
  77388. firstcode = oldcode = getCode (codeSize, false);
  77389. return firstcode;
  77390. }
  77391. else if (code == end_code)
  77392. {
  77393. if (dataBlockIsZero)
  77394. return -2;
  77395. unsigned char buf [260];
  77396. int n;
  77397. while ((n = readDataBlock (buf)) > 0)
  77398. {}
  77399. if (n != 0)
  77400. return -2;
  77401. }
  77402. incode = code;
  77403. if (code >= maxCode)
  77404. {
  77405. *sp++ = firstcode;
  77406. code = oldcode;
  77407. }
  77408. while (code >= clearCode)
  77409. {
  77410. *sp++ = table[1][code];
  77411. if (code == table[0][code])
  77412. return -2;
  77413. code = table[0][code];
  77414. }
  77415. *sp++ = firstcode = table[1][code];
  77416. if ((code = maxCode) < maxGifCode)
  77417. {
  77418. table[0][code] = oldcode;
  77419. table[1][code] = firstcode;
  77420. ++maxCode;
  77421. if ((maxCode >= maxCodeSize)
  77422. && (maxCodeSize < maxGifCode))
  77423. {
  77424. maxCodeSize <<= 1;
  77425. ++codeSize;
  77426. }
  77427. }
  77428. oldcode = incode;
  77429. if (sp > stack)
  77430. return *--sp;
  77431. }
  77432. return code;
  77433. }
  77434. bool GIFLoader::readImage (const int interlace, const int transparent)
  77435. {
  77436. unsigned char c;
  77437. if (input.read (&c, 1) != 1
  77438. || readLZWByte (true, c) < 0)
  77439. return false;
  77440. if (transparent >= 0)
  77441. {
  77442. palette [transparent][0] = 0;
  77443. palette [transparent][1] = 0;
  77444. palette [transparent][2] = 0;
  77445. palette [transparent][3] = 0;
  77446. }
  77447. int index;
  77448. int xpos = 0, ypos = 0, pass = 0;
  77449. const Image::BitmapData destData (image, true);
  77450. uint8* p = destData.data;
  77451. const bool hasAlpha = image.hasAlphaChannel();
  77452. while ((index = readLZWByte (false, c)) >= 0)
  77453. {
  77454. const uint8* const paletteEntry = palette [index];
  77455. if (hasAlpha)
  77456. {
  77457. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77458. paletteEntry[0],
  77459. paletteEntry[1],
  77460. paletteEntry[2]);
  77461. ((PixelARGB*) p)->premultiply();
  77462. }
  77463. else
  77464. {
  77465. ((PixelRGB*) p)->setARGB (0,
  77466. paletteEntry[0],
  77467. paletteEntry[1],
  77468. paletteEntry[2]);
  77469. }
  77470. p += destData.pixelStride;
  77471. ++xpos;
  77472. if (xpos == destData.width)
  77473. {
  77474. xpos = 0;
  77475. if (interlace)
  77476. {
  77477. switch (pass)
  77478. {
  77479. case 0:
  77480. case 1: ypos += 8; break;
  77481. case 2: ypos += 4; break;
  77482. case 3: ypos += 2; break;
  77483. }
  77484. while (ypos >= destData.height)
  77485. {
  77486. ++pass;
  77487. switch (pass)
  77488. {
  77489. case 1: ypos = 4; break;
  77490. case 2: ypos = 2; break;
  77491. case 3: ypos = 1; break;
  77492. default: return true;
  77493. }
  77494. }
  77495. }
  77496. else
  77497. {
  77498. ++ypos;
  77499. }
  77500. p = destData.getPixelPointer (xpos, ypos);
  77501. }
  77502. if (ypos >= destData.height)
  77503. break;
  77504. }
  77505. return true;
  77506. }
  77507. END_JUCE_NAMESPACE
  77508. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77509. #endif
  77510. //==============================================================================
  77511. // some files include lots of library code, so leave them to the end to avoid cluttering
  77512. // up the build for the clean files.
  77513. #if JUCE_BUILD_CORE
  77514. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77515. namespace zlibNamespace
  77516. {
  77517. #if JUCE_INCLUDE_ZLIB_CODE
  77518. #undef OS_CODE
  77519. #undef fdopen
  77520. /*** Start of inlined file: zlib.h ***/
  77521. #ifndef ZLIB_H
  77522. #define ZLIB_H
  77523. /*** Start of inlined file: zconf.h ***/
  77524. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77525. #ifndef ZCONF_H
  77526. #define ZCONF_H
  77527. // *** Just a few hacks here to make it compile nicely with Juce..
  77528. #define Z_PREFIX 1
  77529. #undef __MACTYPES__
  77530. #ifdef _MSC_VER
  77531. #pragma warning (disable : 4131 4127 4244 4267)
  77532. #endif
  77533. /*
  77534. * If you *really* need a unique prefix for all types and library functions,
  77535. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77536. */
  77537. #ifdef Z_PREFIX
  77538. # define deflateInit_ z_deflateInit_
  77539. # define deflate z_deflate
  77540. # define deflateEnd z_deflateEnd
  77541. # define inflateInit_ z_inflateInit_
  77542. # define inflate z_inflate
  77543. # define inflateEnd z_inflateEnd
  77544. # define inflatePrime z_inflatePrime
  77545. # define inflateGetHeader z_inflateGetHeader
  77546. # define adler32_combine z_adler32_combine
  77547. # define crc32_combine z_crc32_combine
  77548. # define deflateInit2_ z_deflateInit2_
  77549. # define deflateSetDictionary z_deflateSetDictionary
  77550. # define deflateCopy z_deflateCopy
  77551. # define deflateReset z_deflateReset
  77552. # define deflateParams z_deflateParams
  77553. # define deflateBound z_deflateBound
  77554. # define deflatePrime z_deflatePrime
  77555. # define inflateInit2_ z_inflateInit2_
  77556. # define inflateSetDictionary z_inflateSetDictionary
  77557. # define inflateSync z_inflateSync
  77558. # define inflateSyncPoint z_inflateSyncPoint
  77559. # define inflateCopy z_inflateCopy
  77560. # define inflateReset z_inflateReset
  77561. # define inflateBack z_inflateBack
  77562. # define inflateBackEnd z_inflateBackEnd
  77563. # define compress z_compress
  77564. # define compress2 z_compress2
  77565. # define compressBound z_compressBound
  77566. # define uncompress z_uncompress
  77567. # define adler32 z_adler32
  77568. # define crc32 z_crc32
  77569. # define get_crc_table z_get_crc_table
  77570. # define zError z_zError
  77571. # define alloc_func z_alloc_func
  77572. # define free_func z_free_func
  77573. # define in_func z_in_func
  77574. # define out_func z_out_func
  77575. # define Byte z_Byte
  77576. # define uInt z_uInt
  77577. # define uLong z_uLong
  77578. # define Bytef z_Bytef
  77579. # define charf z_charf
  77580. # define intf z_intf
  77581. # define uIntf z_uIntf
  77582. # define uLongf z_uLongf
  77583. # define voidpf z_voidpf
  77584. # define voidp z_voidp
  77585. #endif
  77586. #if defined(__MSDOS__) && !defined(MSDOS)
  77587. # define MSDOS
  77588. #endif
  77589. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77590. # define OS2
  77591. #endif
  77592. #if defined(_WINDOWS) && !defined(WINDOWS)
  77593. # define WINDOWS
  77594. #endif
  77595. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77596. # ifndef WIN32
  77597. # define WIN32
  77598. # endif
  77599. #endif
  77600. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77601. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77602. # ifndef SYS16BIT
  77603. # define SYS16BIT
  77604. # endif
  77605. # endif
  77606. #endif
  77607. /*
  77608. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77609. * than 64k bytes at a time (needed on systems with 16-bit int).
  77610. */
  77611. #ifdef SYS16BIT
  77612. # define MAXSEG_64K
  77613. #endif
  77614. #ifdef MSDOS
  77615. # define UNALIGNED_OK
  77616. #endif
  77617. #ifdef __STDC_VERSION__
  77618. # ifndef STDC
  77619. # define STDC
  77620. # endif
  77621. # if __STDC_VERSION__ >= 199901L
  77622. # ifndef STDC99
  77623. # define STDC99
  77624. # endif
  77625. # endif
  77626. #endif
  77627. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77628. # define STDC
  77629. #endif
  77630. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77631. # define STDC
  77632. #endif
  77633. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77634. # define STDC
  77635. #endif
  77636. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77637. # define STDC
  77638. #endif
  77639. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77640. # define STDC
  77641. #endif
  77642. #ifndef STDC
  77643. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77644. # define const /* note: need a more gentle solution here */
  77645. # endif
  77646. #endif
  77647. /* Some Mac compilers merge all .h files incorrectly: */
  77648. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77649. # define NO_DUMMY_DECL
  77650. #endif
  77651. /* Maximum value for memLevel in deflateInit2 */
  77652. #ifndef MAX_MEM_LEVEL
  77653. # ifdef MAXSEG_64K
  77654. # define MAX_MEM_LEVEL 8
  77655. # else
  77656. # define MAX_MEM_LEVEL 9
  77657. # endif
  77658. #endif
  77659. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77660. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77661. * created by gzip. (Files created by minigzip can still be extracted by
  77662. * gzip.)
  77663. */
  77664. #ifndef MAX_WBITS
  77665. # define MAX_WBITS 15 /* 32K LZ77 window */
  77666. #endif
  77667. /* The memory requirements for deflate are (in bytes):
  77668. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77669. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77670. plus a few kilobytes for small objects. For example, if you want to reduce
  77671. the default memory requirements from 256K to 128K, compile with
  77672. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77673. Of course this will generally degrade compression (there's no free lunch).
  77674. The memory requirements for inflate are (in bytes) 1 << windowBits
  77675. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77676. for small objects.
  77677. */
  77678. /* Type declarations */
  77679. #ifndef OF /* function prototypes */
  77680. # ifdef STDC
  77681. # define OF(args) args
  77682. # else
  77683. # define OF(args) ()
  77684. # endif
  77685. #endif
  77686. /* The following definitions for FAR are needed only for MSDOS mixed
  77687. * model programming (small or medium model with some far allocations).
  77688. * This was tested only with MSC; for other MSDOS compilers you may have
  77689. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77690. * just define FAR to be empty.
  77691. */
  77692. #ifdef SYS16BIT
  77693. # if defined(M_I86SM) || defined(M_I86MM)
  77694. /* MSC small or medium model */
  77695. # define SMALL_MEDIUM
  77696. # ifdef _MSC_VER
  77697. # define FAR _far
  77698. # else
  77699. # define FAR far
  77700. # endif
  77701. # endif
  77702. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77703. /* Turbo C small or medium model */
  77704. # define SMALL_MEDIUM
  77705. # ifdef __BORLANDC__
  77706. # define FAR _far
  77707. # else
  77708. # define FAR far
  77709. # endif
  77710. # endif
  77711. #endif
  77712. #if defined(WINDOWS) || defined(WIN32)
  77713. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77714. * This is not mandatory, but it offers a little performance increase.
  77715. */
  77716. # ifdef ZLIB_DLL
  77717. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77718. # ifdef ZLIB_INTERNAL
  77719. # define ZEXTERN extern __declspec(dllexport)
  77720. # else
  77721. # define ZEXTERN extern __declspec(dllimport)
  77722. # endif
  77723. # endif
  77724. # endif /* ZLIB_DLL */
  77725. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77726. * define ZLIB_WINAPI.
  77727. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77728. */
  77729. # ifdef ZLIB_WINAPI
  77730. # ifdef FAR
  77731. # undef FAR
  77732. # endif
  77733. # include <windows.h>
  77734. /* No need for _export, use ZLIB.DEF instead. */
  77735. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77736. # define ZEXPORT WINAPI
  77737. # ifdef WIN32
  77738. # define ZEXPORTVA WINAPIV
  77739. # else
  77740. # define ZEXPORTVA FAR CDECL
  77741. # endif
  77742. # endif
  77743. #endif
  77744. #if defined (__BEOS__)
  77745. # ifdef ZLIB_DLL
  77746. # ifdef ZLIB_INTERNAL
  77747. # define ZEXPORT __declspec(dllexport)
  77748. # define ZEXPORTVA __declspec(dllexport)
  77749. # else
  77750. # define ZEXPORT __declspec(dllimport)
  77751. # define ZEXPORTVA __declspec(dllimport)
  77752. # endif
  77753. # endif
  77754. #endif
  77755. #ifndef ZEXTERN
  77756. # define ZEXTERN extern
  77757. #endif
  77758. #ifndef ZEXPORT
  77759. # define ZEXPORT
  77760. #endif
  77761. #ifndef ZEXPORTVA
  77762. # define ZEXPORTVA
  77763. #endif
  77764. #ifndef FAR
  77765. # define FAR
  77766. #endif
  77767. #if !defined(__MACTYPES__)
  77768. typedef unsigned char Byte; /* 8 bits */
  77769. #endif
  77770. typedef unsigned int uInt; /* 16 bits or more */
  77771. typedef unsigned long uLong; /* 32 bits or more */
  77772. #ifdef SMALL_MEDIUM
  77773. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77774. # define Bytef Byte FAR
  77775. #else
  77776. typedef Byte FAR Bytef;
  77777. #endif
  77778. typedef char FAR charf;
  77779. typedef int FAR intf;
  77780. typedef uInt FAR uIntf;
  77781. typedef uLong FAR uLongf;
  77782. #ifdef STDC
  77783. typedef void const *voidpc;
  77784. typedef void FAR *voidpf;
  77785. typedef void *voidp;
  77786. #else
  77787. typedef Byte const *voidpc;
  77788. typedef Byte FAR *voidpf;
  77789. typedef Byte *voidp;
  77790. #endif
  77791. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77792. # include <sys/types.h> /* for off_t */
  77793. # include <unistd.h> /* for SEEK_* and off_t */
  77794. # ifdef VMS
  77795. # include <unixio.h> /* for off_t */
  77796. # endif
  77797. # define z_off_t off_t
  77798. #endif
  77799. #ifndef SEEK_SET
  77800. # define SEEK_SET 0 /* Seek from beginning of file. */
  77801. # define SEEK_CUR 1 /* Seek from current position. */
  77802. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  77803. #endif
  77804. #ifndef z_off_t
  77805. # define z_off_t long
  77806. #endif
  77807. #if defined(__OS400__)
  77808. # define NO_vsnprintf
  77809. #endif
  77810. #if defined(__MVS__)
  77811. # define NO_vsnprintf
  77812. # ifdef FAR
  77813. # undef FAR
  77814. # endif
  77815. #endif
  77816. /* MVS linker does not support external names larger than 8 bytes */
  77817. #if defined(__MVS__)
  77818. # pragma map(deflateInit_,"DEIN")
  77819. # pragma map(deflateInit2_,"DEIN2")
  77820. # pragma map(deflateEnd,"DEEND")
  77821. # pragma map(deflateBound,"DEBND")
  77822. # pragma map(inflateInit_,"ININ")
  77823. # pragma map(inflateInit2_,"ININ2")
  77824. # pragma map(inflateEnd,"INEND")
  77825. # pragma map(inflateSync,"INSY")
  77826. # pragma map(inflateSetDictionary,"INSEDI")
  77827. # pragma map(compressBound,"CMBND")
  77828. # pragma map(inflate_table,"INTABL")
  77829. # pragma map(inflate_fast,"INFA")
  77830. # pragma map(inflate_copyright,"INCOPY")
  77831. #endif
  77832. #endif /* ZCONF_H */
  77833. /*** End of inlined file: zconf.h ***/
  77834. #ifdef __cplusplus
  77835. extern "C" {
  77836. #endif
  77837. #define ZLIB_VERSION "1.2.3"
  77838. #define ZLIB_VERNUM 0x1230
  77839. /*
  77840. The 'zlib' compression library provides in-memory compression and
  77841. decompression functions, including integrity checks of the uncompressed
  77842. data. This version of the library supports only one compression method
  77843. (deflation) but other algorithms will be added later and will have the same
  77844. stream interface.
  77845. Compression can be done in a single step if the buffers are large
  77846. enough (for example if an input file is mmap'ed), or can be done by
  77847. repeated calls of the compression function. In the latter case, the
  77848. application must provide more input and/or consume the output
  77849. (providing more output space) before each call.
  77850. The compressed data format used by default by the in-memory functions is
  77851. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  77852. around a deflate stream, which is itself documented in RFC 1951.
  77853. The library also supports reading and writing files in gzip (.gz) format
  77854. with an interface similar to that of stdio using the functions that start
  77855. with "gz". The gzip format is different from the zlib format. gzip is a
  77856. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  77857. This library can optionally read and write gzip streams in memory as well.
  77858. The zlib format was designed to be compact and fast for use in memory
  77859. and on communications channels. The gzip format was designed for single-
  77860. file compression on file systems, has a larger header than zlib to maintain
  77861. directory information, and uses a different, slower check method than zlib.
  77862. The library does not install any signal handler. The decoder checks
  77863. the consistency of the compressed data, so the library should never
  77864. crash even in case of corrupted input.
  77865. */
  77866. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  77867. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  77868. struct internal_state;
  77869. typedef struct z_stream_s {
  77870. Bytef *next_in; /* next input byte */
  77871. uInt avail_in; /* number of bytes available at next_in */
  77872. uLong total_in; /* total nb of input bytes read so far */
  77873. Bytef *next_out; /* next output byte should be put there */
  77874. uInt avail_out; /* remaining free space at next_out */
  77875. uLong total_out; /* total nb of bytes output so far */
  77876. char *msg; /* last error message, NULL if no error */
  77877. struct internal_state FAR *state; /* not visible by applications */
  77878. alloc_func zalloc; /* used to allocate the internal state */
  77879. free_func zfree; /* used to free the internal state */
  77880. voidpf opaque; /* private data object passed to zalloc and zfree */
  77881. int data_type; /* best guess about the data type: binary or text */
  77882. uLong adler; /* adler32 value of the uncompressed data */
  77883. uLong reserved; /* reserved for future use */
  77884. } z_stream;
  77885. typedef z_stream FAR *z_streamp;
  77886. /*
  77887. gzip header information passed to and from zlib routines. See RFC 1952
  77888. for more details on the meanings of these fields.
  77889. */
  77890. typedef struct gz_header_s {
  77891. int text; /* true if compressed data believed to be text */
  77892. uLong time; /* modification time */
  77893. int xflags; /* extra flags (not used when writing a gzip file) */
  77894. int os; /* operating system */
  77895. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  77896. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  77897. uInt extra_max; /* space at extra (only when reading header) */
  77898. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  77899. uInt name_max; /* space at name (only when reading header) */
  77900. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  77901. uInt comm_max; /* space at comment (only when reading header) */
  77902. int hcrc; /* true if there was or will be a header crc */
  77903. int done; /* true when done reading gzip header (not used
  77904. when writing a gzip file) */
  77905. } gz_header;
  77906. typedef gz_header FAR *gz_headerp;
  77907. /*
  77908. The application must update next_in and avail_in when avail_in has
  77909. dropped to zero. It must update next_out and avail_out when avail_out
  77910. has dropped to zero. The application must initialize zalloc, zfree and
  77911. opaque before calling the init function. All other fields are set by the
  77912. compression library and must not be updated by the application.
  77913. The opaque value provided by the application will be passed as the first
  77914. parameter for calls of zalloc and zfree. This can be useful for custom
  77915. memory management. The compression library attaches no meaning to the
  77916. opaque value.
  77917. zalloc must return Z_NULL if there is not enough memory for the object.
  77918. If zlib is used in a multi-threaded application, zalloc and zfree must be
  77919. thread safe.
  77920. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  77921. exactly 65536 bytes, but will not be required to allocate more than this
  77922. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  77923. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  77924. have their offset normalized to zero. The default allocation function
  77925. provided by this library ensures this (see zutil.c). To reduce memory
  77926. requirements and avoid any allocation of 64K objects, at the expense of
  77927. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  77928. The fields total_in and total_out can be used for statistics or
  77929. progress reports. After compression, total_in holds the total size of
  77930. the uncompressed data and may be saved for use in the decompressor
  77931. (particularly if the decompressor wants to decompress everything in
  77932. a single step).
  77933. */
  77934. /* constants */
  77935. #define Z_NO_FLUSH 0
  77936. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  77937. #define Z_SYNC_FLUSH 2
  77938. #define Z_FULL_FLUSH 3
  77939. #define Z_FINISH 4
  77940. #define Z_BLOCK 5
  77941. /* Allowed flush values; see deflate() and inflate() below for details */
  77942. #define Z_OK 0
  77943. #define Z_STREAM_END 1
  77944. #define Z_NEED_DICT 2
  77945. #define Z_ERRNO (-1)
  77946. #define Z_STREAM_ERROR (-2)
  77947. #define Z_DATA_ERROR (-3)
  77948. #define Z_MEM_ERROR (-4)
  77949. #define Z_BUF_ERROR (-5)
  77950. #define Z_VERSION_ERROR (-6)
  77951. /* Return codes for the compression/decompression functions. Negative
  77952. * values are errors, positive values are used for special but normal events.
  77953. */
  77954. #define Z_NO_COMPRESSION 0
  77955. #define Z_BEST_SPEED 1
  77956. #define Z_BEST_COMPRESSION 9
  77957. #define Z_DEFAULT_COMPRESSION (-1)
  77958. /* compression levels */
  77959. #define Z_FILTERED 1
  77960. #define Z_HUFFMAN_ONLY 2
  77961. #define Z_RLE 3
  77962. #define Z_FIXED 4
  77963. #define Z_DEFAULT_STRATEGY 0
  77964. /* compression strategy; see deflateInit2() below for details */
  77965. #define Z_BINARY 0
  77966. #define Z_TEXT 1
  77967. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  77968. #define Z_UNKNOWN 2
  77969. /* Possible values of the data_type field (though see inflate()) */
  77970. #define Z_DEFLATED 8
  77971. /* The deflate compression method (the only one supported in this version) */
  77972. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  77973. #define zlib_version zlibVersion()
  77974. /* for compatibility with versions < 1.0.2 */
  77975. /* basic functions */
  77976. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  77977. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  77978. If the first character differs, the library code actually used is
  77979. not compatible with the zlib.h header file used by the application.
  77980. This check is automatically made by deflateInit and inflateInit.
  77981. */
  77982. /*
  77983. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  77984. Initializes the internal stream state for compression. The fields
  77985. zalloc, zfree and opaque must be initialized before by the caller.
  77986. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  77987. use default allocation functions.
  77988. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  77989. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  77990. all (the input data is simply copied a block at a time).
  77991. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  77992. compression (currently equivalent to level 6).
  77993. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  77994. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  77995. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  77996. with the version assumed by the caller (ZLIB_VERSION).
  77997. msg is set to null if there is no error message. deflateInit does not
  77998. perform any compression: this will be done by deflate().
  77999. */
  78000. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78001. /*
  78002. deflate compresses as much data as possible, and stops when the input
  78003. buffer becomes empty or the output buffer becomes full. It may introduce some
  78004. output latency (reading input without producing any output) except when
  78005. forced to flush.
  78006. The detailed semantics are as follows. deflate performs one or both of the
  78007. following actions:
  78008. - Compress more input starting at next_in and update next_in and avail_in
  78009. accordingly. If not all input can be processed (because there is not
  78010. enough room in the output buffer), next_in and avail_in are updated and
  78011. processing will resume at this point for the next call of deflate().
  78012. - Provide more output starting at next_out and update next_out and avail_out
  78013. accordingly. This action is forced if the parameter flush is non zero.
  78014. Forcing flush frequently degrades the compression ratio, so this parameter
  78015. should be set only when necessary (in interactive applications).
  78016. Some output may be provided even if flush is not set.
  78017. Before the call of deflate(), the application should ensure that at least
  78018. one of the actions is possible, by providing more input and/or consuming
  78019. more output, and updating avail_in or avail_out accordingly; avail_out
  78020. should never be zero before the call. The application can consume the
  78021. compressed output when it wants, for example when the output buffer is full
  78022. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78023. and with zero avail_out, it must be called again after making room in the
  78024. output buffer because there might be more output pending.
  78025. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78026. decide how much data to accumualte before producing output, in order to
  78027. maximize compression.
  78028. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78029. flushed to the output buffer and the output is aligned on a byte boundary, so
  78030. that the decompressor can get all input data available so far. (In particular
  78031. avail_in is zero after the call if enough output space has been provided
  78032. before the call.) Flushing may degrade compression for some compression
  78033. algorithms and so it should be used only when necessary.
  78034. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78035. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78036. restart from this point if previous compressed data has been damaged or if
  78037. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78038. compression.
  78039. If deflate returns with avail_out == 0, this function must be called again
  78040. with the same value of the flush parameter and more output space (updated
  78041. avail_out), until the flush is complete (deflate returns with non-zero
  78042. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78043. avail_out is greater than six to avoid repeated flush markers due to
  78044. avail_out == 0 on return.
  78045. If the parameter flush is set to Z_FINISH, pending input is processed,
  78046. pending output is flushed and deflate returns with Z_STREAM_END if there
  78047. was enough output space; if deflate returns with Z_OK, this function must be
  78048. called again with Z_FINISH and more output space (updated avail_out) but no
  78049. more input data, until it returns with Z_STREAM_END or an error. After
  78050. deflate has returned Z_STREAM_END, the only possible operations on the
  78051. stream are deflateReset or deflateEnd.
  78052. Z_FINISH can be used immediately after deflateInit if all the compression
  78053. is to be done in a single step. In this case, avail_out must be at least
  78054. the value returned by deflateBound (see below). If deflate does not return
  78055. Z_STREAM_END, then it must be called again as described above.
  78056. deflate() sets strm->adler to the adler32 checksum of all input read
  78057. so far (that is, total_in bytes).
  78058. deflate() may update strm->data_type if it can make a good guess about
  78059. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78060. binary. This field is only for information purposes and does not affect
  78061. the compression algorithm in any manner.
  78062. deflate() returns Z_OK if some progress has been made (more input
  78063. processed or more output produced), Z_STREAM_END if all input has been
  78064. consumed and all output has been produced (only when flush is set to
  78065. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78066. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78067. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78068. fatal, and deflate() can be called again with more input and more output
  78069. space to continue compressing.
  78070. */
  78071. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78072. /*
  78073. All dynamically allocated data structures for this stream are freed.
  78074. This function discards any unprocessed input and does not flush any
  78075. pending output.
  78076. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78077. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78078. prematurely (some input or output was discarded). In the error case,
  78079. msg may be set but then points to a static string (which must not be
  78080. deallocated).
  78081. */
  78082. /*
  78083. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78084. Initializes the internal stream state for decompression. The fields
  78085. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78086. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78087. value depends on the compression method), inflateInit determines the
  78088. compression method from the zlib header and allocates all data structures
  78089. accordingly; otherwise the allocation will be deferred to the first call of
  78090. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78091. use default allocation functions.
  78092. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78093. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78094. version assumed by the caller. msg is set to null if there is no error
  78095. message. inflateInit does not perform any decompression apart from reading
  78096. the zlib header if present: this will be done by inflate(). (So next_in and
  78097. avail_in may be modified, but next_out and avail_out are unchanged.)
  78098. */
  78099. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78100. /*
  78101. inflate decompresses as much data as possible, and stops when the input
  78102. buffer becomes empty or the output buffer becomes full. It may introduce
  78103. some output latency (reading input without producing any output) except when
  78104. forced to flush.
  78105. The detailed semantics are as follows. inflate performs one or both of the
  78106. following actions:
  78107. - Decompress more input starting at next_in and update next_in and avail_in
  78108. accordingly. If not all input can be processed (because there is not
  78109. enough room in the output buffer), next_in is updated and processing
  78110. will resume at this point for the next call of inflate().
  78111. - Provide more output starting at next_out and update next_out and avail_out
  78112. accordingly. inflate() provides as much output as possible, until there
  78113. is no more input data or no more space in the output buffer (see below
  78114. about the flush parameter).
  78115. Before the call of inflate(), the application should ensure that at least
  78116. one of the actions is possible, by providing more input and/or consuming
  78117. more output, and updating the next_* and avail_* values accordingly.
  78118. The application can consume the uncompressed output when it wants, for
  78119. example when the output buffer is full (avail_out == 0), or after each
  78120. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78121. must be called again after making room in the output buffer because there
  78122. might be more output pending.
  78123. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78124. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78125. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78126. if and when it gets to the next deflate block boundary. When decoding the
  78127. zlib or gzip format, this will cause inflate() to return immediately after
  78128. the header and before the first block. When doing a raw inflate, inflate()
  78129. will go ahead and process the first block, and will return when it gets to
  78130. the end of that block, or when it runs out of data.
  78131. The Z_BLOCK option assists in appending to or combining deflate streams.
  78132. Also to assist in this, on return inflate() will set strm->data_type to the
  78133. number of unused bits in the last byte taken from strm->next_in, plus 64
  78134. if inflate() is currently decoding the last block in the deflate stream,
  78135. plus 128 if inflate() returned immediately after decoding an end-of-block
  78136. code or decoding the complete header up to just before the first byte of the
  78137. deflate stream. The end-of-block will not be indicated until all of the
  78138. uncompressed data from that block has been written to strm->next_out. The
  78139. number of unused bits may in general be greater than seven, except when
  78140. bit 7 of data_type is set, in which case the number of unused bits will be
  78141. less than eight.
  78142. inflate() should normally be called until it returns Z_STREAM_END or an
  78143. error. However if all decompression is to be performed in a single step
  78144. (a single call of inflate), the parameter flush should be set to
  78145. Z_FINISH. In this case all pending input is processed and all pending
  78146. output is flushed; avail_out must be large enough to hold all the
  78147. uncompressed data. (The size of the uncompressed data may have been saved
  78148. by the compressor for this purpose.) The next operation on this stream must
  78149. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78150. is never required, but can be used to inform inflate that a faster approach
  78151. may be used for the single inflate() call.
  78152. In this implementation, inflate() always flushes as much output as
  78153. possible to the output buffer, and always uses the faster approach on the
  78154. first call. So the only effect of the flush parameter in this implementation
  78155. is on the return value of inflate(), as noted below, or when it returns early
  78156. because Z_BLOCK is used.
  78157. If a preset dictionary is needed after this call (see inflateSetDictionary
  78158. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78159. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78160. strm->adler to the adler32 checksum of all output produced so far (that is,
  78161. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78162. below. At the end of the stream, inflate() checks that its computed adler32
  78163. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78164. only if the checksum is correct.
  78165. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78166. deflate data. The header type is detected automatically. Any information
  78167. contained in the gzip header is not retained, so applications that need that
  78168. information should instead use raw inflate, see inflateInit2() below, or
  78169. inflateBack() and perform their own processing of the gzip header and
  78170. trailer.
  78171. inflate() returns Z_OK if some progress has been made (more input processed
  78172. or more output produced), Z_STREAM_END if the end of the compressed data has
  78173. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78174. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78175. corrupted (input stream not conforming to the zlib format or incorrect check
  78176. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78177. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78178. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78179. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78180. inflate() can be called again with more input and more output space to
  78181. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78182. call inflateSync() to look for a good compression block if a partial recovery
  78183. of the data is desired.
  78184. */
  78185. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78186. /*
  78187. All dynamically allocated data structures for this stream are freed.
  78188. This function discards any unprocessed input and does not flush any
  78189. pending output.
  78190. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78191. was inconsistent. In the error case, msg may be set but then points to a
  78192. static string (which must not be deallocated).
  78193. */
  78194. /* Advanced functions */
  78195. /*
  78196. The following functions are needed only in some special applications.
  78197. */
  78198. /*
  78199. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78200. int level,
  78201. int method,
  78202. int windowBits,
  78203. int memLevel,
  78204. int strategy));
  78205. This is another version of deflateInit with more compression options. The
  78206. fields next_in, zalloc, zfree and opaque must be initialized before by
  78207. the caller.
  78208. The method parameter is the compression method. It must be Z_DEFLATED in
  78209. this version of the library.
  78210. The windowBits parameter is the base two logarithm of the window size
  78211. (the size of the history buffer). It should be in the range 8..15 for this
  78212. version of the library. Larger values of this parameter result in better
  78213. compression at the expense of memory usage. The default value is 15 if
  78214. deflateInit is used instead.
  78215. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78216. determines the window size. deflate() will then generate raw deflate data
  78217. with no zlib header or trailer, and will not compute an adler32 check value.
  78218. windowBits can also be greater than 15 for optional gzip encoding. Add
  78219. 16 to windowBits to write a simple gzip header and trailer around the
  78220. compressed data instead of a zlib wrapper. The gzip header will have no
  78221. file name, no extra data, no comment, no modification time (set to zero),
  78222. no header crc, and the operating system will be set to 255 (unknown). If a
  78223. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78224. The memLevel parameter specifies how much memory should be allocated
  78225. for the internal compression state. memLevel=1 uses minimum memory but
  78226. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78227. for optimal speed. The default value is 8. See zconf.h for total memory
  78228. usage as a function of windowBits and memLevel.
  78229. The strategy parameter is used to tune the compression algorithm. Use the
  78230. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78231. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78232. string match), or Z_RLE to limit match distances to one (run-length
  78233. encoding). Filtered data consists mostly of small values with a somewhat
  78234. random distribution. In this case, the compression algorithm is tuned to
  78235. compress them better. The effect of Z_FILTERED is to force more Huffman
  78236. coding and less string matching; it is somewhat intermediate between
  78237. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78238. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78239. parameter only affects the compression ratio but not the correctness of the
  78240. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78241. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78242. applications.
  78243. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78244. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78245. method). msg is set to null if there is no error message. deflateInit2 does
  78246. not perform any compression: this will be done by deflate().
  78247. */
  78248. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78249. const Bytef *dictionary,
  78250. uInt dictLength));
  78251. /*
  78252. Initializes the compression dictionary from the given byte sequence
  78253. without producing any compressed output. This function must be called
  78254. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78255. call of deflate. The compressor and decompressor must use exactly the same
  78256. dictionary (see inflateSetDictionary).
  78257. The dictionary should consist of strings (byte sequences) that are likely
  78258. to be encountered later in the data to be compressed, with the most commonly
  78259. used strings preferably put towards the end of the dictionary. Using a
  78260. dictionary is most useful when the data to be compressed is short and can be
  78261. predicted with good accuracy; the data can then be compressed better than
  78262. with the default empty dictionary.
  78263. Depending on the size of the compression data structures selected by
  78264. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78265. discarded, for example if the dictionary is larger than the window size in
  78266. deflate or deflate2. Thus the strings most likely to be useful should be
  78267. put at the end of the dictionary, not at the front. In addition, the
  78268. current implementation of deflate will use at most the window size minus
  78269. 262 bytes of the provided dictionary.
  78270. Upon return of this function, strm->adler is set to the adler32 value
  78271. of the dictionary; the decompressor may later use this value to determine
  78272. which dictionary has been used by the compressor. (The adler32 value
  78273. applies to the whole dictionary even if only a subset of the dictionary is
  78274. actually used by the compressor.) If a raw deflate was requested, then the
  78275. adler32 value is not computed and strm->adler is not set.
  78276. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78277. parameter is invalid (such as NULL dictionary) or the stream state is
  78278. inconsistent (for example if deflate has already been called for this stream
  78279. or if the compression method is bsort). deflateSetDictionary does not
  78280. perform any compression: this will be done by deflate().
  78281. */
  78282. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78283. z_streamp source));
  78284. /*
  78285. Sets the destination stream as a complete copy of the source stream.
  78286. This function can be useful when several compression strategies will be
  78287. tried, for example when there are several ways of pre-processing the input
  78288. data with a filter. The streams that will be discarded should then be freed
  78289. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78290. compression state which can be quite large, so this strategy is slow and
  78291. can consume lots of memory.
  78292. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78293. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78294. (such as zalloc being NULL). msg is left unchanged in both source and
  78295. destination.
  78296. */
  78297. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78298. /*
  78299. This function is equivalent to deflateEnd followed by deflateInit,
  78300. but does not free and reallocate all the internal compression state.
  78301. The stream will keep the same compression level and any other attributes
  78302. that may have been set by deflateInit2.
  78303. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78304. stream state was inconsistent (such as zalloc or state being NULL).
  78305. */
  78306. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78307. int level,
  78308. int strategy));
  78309. /*
  78310. Dynamically update the compression level and compression strategy. The
  78311. interpretation of level and strategy is as in deflateInit2. This can be
  78312. used to switch between compression and straight copy of the input data, or
  78313. to switch to a different kind of input data requiring a different
  78314. strategy. If the compression level is changed, the input available so far
  78315. is compressed with the old level (and may be flushed); the new level will
  78316. take effect only at the next call of deflate().
  78317. Before the call of deflateParams, the stream state must be set as for
  78318. a call of deflate(), since the currently available input may have to
  78319. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78320. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78321. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78322. if strm->avail_out was zero.
  78323. */
  78324. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78325. int good_length,
  78326. int max_lazy,
  78327. int nice_length,
  78328. int max_chain));
  78329. /*
  78330. Fine tune deflate's internal compression parameters. This should only be
  78331. used by someone who understands the algorithm used by zlib's deflate for
  78332. searching for the best matching string, and even then only by the most
  78333. fanatic optimizer trying to squeeze out the last compressed bit for their
  78334. specific input data. Read the deflate.c source code for the meaning of the
  78335. max_lazy, good_length, nice_length, and max_chain parameters.
  78336. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78337. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78338. */
  78339. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78340. uLong sourceLen));
  78341. /*
  78342. deflateBound() returns an upper bound on the compressed size after
  78343. deflation of sourceLen bytes. It must be called after deflateInit()
  78344. or deflateInit2(). This would be used to allocate an output buffer
  78345. for deflation in a single pass, and so would be called before deflate().
  78346. */
  78347. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78348. int bits,
  78349. int value));
  78350. /*
  78351. deflatePrime() inserts bits in the deflate output stream. The intent
  78352. is that this function is used to start off the deflate output with the
  78353. bits leftover from a previous deflate stream when appending to it. As such,
  78354. this function can only be used for raw deflate, and must be used before the
  78355. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78356. less than or equal to 16, and that many of the least significant bits of
  78357. value will be inserted in the output.
  78358. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78359. stream state was inconsistent.
  78360. */
  78361. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78362. gz_headerp head));
  78363. /*
  78364. deflateSetHeader() provides gzip header information for when a gzip
  78365. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78366. after deflateInit2() or deflateReset() and before the first call of
  78367. deflate(). The text, time, os, extra field, name, and comment information
  78368. in the provided gz_header structure are written to the gzip header (xflag is
  78369. ignored -- the extra flags are set according to the compression level). The
  78370. caller must assure that, if not Z_NULL, name and comment are terminated with
  78371. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78372. available there. If hcrc is true, a gzip header crc is included. Note that
  78373. the current versions of the command-line version of gzip (up through version
  78374. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78375. gzip file" and give up.
  78376. If deflateSetHeader is not used, the default gzip header has text false,
  78377. the time set to zero, and os set to 255, with no extra, name, or comment
  78378. fields. The gzip header is returned to the default state by deflateReset().
  78379. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78380. stream state was inconsistent.
  78381. */
  78382. /*
  78383. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78384. int windowBits));
  78385. This is another version of inflateInit with an extra parameter. The
  78386. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78387. before by the caller.
  78388. The windowBits parameter is the base two logarithm of the maximum window
  78389. size (the size of the history buffer). It should be in the range 8..15 for
  78390. this version of the library. The default value is 15 if inflateInit is used
  78391. instead. windowBits must be greater than or equal to the windowBits value
  78392. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78393. deflateInit2() was not used. If a compressed stream with a larger window
  78394. size is given as input, inflate() will return with the error code
  78395. Z_DATA_ERROR instead of trying to allocate a larger window.
  78396. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78397. determines the window size. inflate() will then process raw deflate data,
  78398. not looking for a zlib or gzip header, not generating a check value, and not
  78399. looking for any check values for comparison at the end of the stream. This
  78400. is for use with other formats that use the deflate compressed data format
  78401. such as zip. Those formats provide their own check values. If a custom
  78402. format is developed using the raw deflate format for compressed data, it is
  78403. recommended that a check value such as an adler32 or a crc32 be applied to
  78404. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78405. most applications, the zlib format should be used as is. Note that comments
  78406. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78407. windowBits can also be greater than 15 for optional gzip decoding. Add
  78408. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78409. detection, or add 16 to decode only the gzip format (the zlib format will
  78410. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78411. a crc32 instead of an adler32.
  78412. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78413. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78414. is set to null if there is no error message. inflateInit2 does not perform
  78415. any decompression apart from reading the zlib header if present: this will
  78416. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78417. and avail_out are unchanged.)
  78418. */
  78419. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78420. const Bytef *dictionary,
  78421. uInt dictLength));
  78422. /*
  78423. Initializes the decompression dictionary from the given uncompressed byte
  78424. sequence. This function must be called immediately after a call of inflate,
  78425. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78426. can be determined from the adler32 value returned by that call of inflate.
  78427. The compressor and decompressor must use exactly the same dictionary (see
  78428. deflateSetDictionary). For raw inflate, this function can be called
  78429. immediately after inflateInit2() or inflateReset() and before any call of
  78430. inflate() to set the dictionary. The application must insure that the
  78431. dictionary that was used for compression is provided.
  78432. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78433. parameter is invalid (such as NULL dictionary) or the stream state is
  78434. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78435. expected one (incorrect adler32 value). inflateSetDictionary does not
  78436. perform any decompression: this will be done by subsequent calls of
  78437. inflate().
  78438. */
  78439. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78440. /*
  78441. Skips invalid compressed data until a full flush point (see above the
  78442. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78443. available input is skipped. No output is provided.
  78444. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78445. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78446. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78447. case, the application may save the current current value of total_in which
  78448. indicates where valid compressed data was found. In the error case, the
  78449. application may repeatedly call inflateSync, providing more input each time,
  78450. until success or end of the input data.
  78451. */
  78452. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78453. z_streamp source));
  78454. /*
  78455. Sets the destination stream as a complete copy of the source stream.
  78456. This function can be useful when randomly accessing a large stream. The
  78457. first pass through the stream can periodically record the inflate state,
  78458. allowing restarting inflate at those points when randomly accessing the
  78459. stream.
  78460. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78461. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78462. (such as zalloc being NULL). msg is left unchanged in both source and
  78463. destination.
  78464. */
  78465. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78466. /*
  78467. This function is equivalent to inflateEnd followed by inflateInit,
  78468. but does not free and reallocate all the internal decompression state.
  78469. The stream will keep attributes that may have been set by inflateInit2.
  78470. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78471. stream state was inconsistent (such as zalloc or state being NULL).
  78472. */
  78473. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78474. int bits,
  78475. int value));
  78476. /*
  78477. This function inserts bits in the inflate input stream. The intent is
  78478. that this function is used to start inflating at a bit position in the
  78479. middle of a byte. The provided bits will be used before any bytes are used
  78480. from next_in. This function should only be used with raw inflate, and
  78481. should be used before the first inflate() call after inflateInit2() or
  78482. inflateReset(). bits must be less than or equal to 16, and that many of the
  78483. least significant bits of value will be inserted in the input.
  78484. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78485. stream state was inconsistent.
  78486. */
  78487. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78488. gz_headerp head));
  78489. /*
  78490. inflateGetHeader() requests that gzip header information be stored in the
  78491. provided gz_header structure. inflateGetHeader() may be called after
  78492. inflateInit2() or inflateReset(), and before the first call of inflate().
  78493. As inflate() processes the gzip stream, head->done is zero until the header
  78494. is completed, at which time head->done is set to one. If a zlib stream is
  78495. being decoded, then head->done is set to -1 to indicate that there will be
  78496. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78497. force inflate() to return immediately after header processing is complete
  78498. and before any actual data is decompressed.
  78499. The text, time, xflags, and os fields are filled in with the gzip header
  78500. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78501. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78502. contains the maximum number of bytes to write to extra. Once done is true,
  78503. extra_len contains the actual extra field length, and extra contains the
  78504. extra field, or that field truncated if extra_max is less than extra_len.
  78505. If name is not Z_NULL, then up to name_max characters are written there,
  78506. terminated with a zero unless the length is greater than name_max. If
  78507. comment is not Z_NULL, then up to comm_max characters are written there,
  78508. terminated with a zero unless the length is greater than comm_max. When
  78509. any of extra, name, or comment are not Z_NULL and the respective field is
  78510. not present in the header, then that field is set to Z_NULL to signal its
  78511. absence. This allows the use of deflateSetHeader() with the returned
  78512. structure to duplicate the header. However if those fields are set to
  78513. allocated memory, then the application will need to save those pointers
  78514. elsewhere so that they can be eventually freed.
  78515. If inflateGetHeader is not used, then the header information is simply
  78516. discarded. The header is always checked for validity, including the header
  78517. CRC if present. inflateReset() will reset the process to discard the header
  78518. information. The application would need to call inflateGetHeader() again to
  78519. retrieve the header from the next gzip stream.
  78520. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78521. stream state was inconsistent.
  78522. */
  78523. /*
  78524. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78525. unsigned char FAR *window));
  78526. Initialize the internal stream state for decompression using inflateBack()
  78527. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78528. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78529. derived memory allocation routines are used. windowBits is the base two
  78530. logarithm of the window size, in the range 8..15. window is a caller
  78531. supplied buffer of that size. Except for special applications where it is
  78532. assured that deflate was used with small window sizes, windowBits must be 15
  78533. and a 32K byte window must be supplied to be able to decompress general
  78534. deflate streams.
  78535. See inflateBack() for the usage of these routines.
  78536. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78537. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78538. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78539. match the version of the header file.
  78540. */
  78541. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78542. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78543. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78544. in_func in, void FAR *in_desc,
  78545. out_func out, void FAR *out_desc));
  78546. /*
  78547. inflateBack() does a raw inflate with a single call using a call-back
  78548. interface for input and output. This is more efficient than inflate() for
  78549. file i/o applications in that it avoids copying between the output and the
  78550. sliding window by simply making the window itself the output buffer. This
  78551. function trusts the application to not change the output buffer passed by
  78552. the output function, at least until inflateBack() returns.
  78553. inflateBackInit() must be called first to allocate the internal state
  78554. and to initialize the state with the user-provided window buffer.
  78555. inflateBack() may then be used multiple times to inflate a complete, raw
  78556. deflate stream with each call. inflateBackEnd() is then called to free
  78557. the allocated state.
  78558. A raw deflate stream is one with no zlib or gzip header or trailer.
  78559. This routine would normally be used in a utility that reads zip or gzip
  78560. files and writes out uncompressed files. The utility would decode the
  78561. header and process the trailer on its own, hence this routine expects
  78562. only the raw deflate stream to decompress. This is different from the
  78563. normal behavior of inflate(), which expects either a zlib or gzip header and
  78564. trailer around the deflate stream.
  78565. inflateBack() uses two subroutines supplied by the caller that are then
  78566. called by inflateBack() for input and output. inflateBack() calls those
  78567. routines until it reads a complete deflate stream and writes out all of the
  78568. uncompressed data, or until it encounters an error. The function's
  78569. parameters and return types are defined above in the in_func and out_func
  78570. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78571. number of bytes of provided input, and a pointer to that input in buf. If
  78572. there is no input available, in() must return zero--buf is ignored in that
  78573. case--and inflateBack() will return a buffer error. inflateBack() will call
  78574. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78575. should return zero on success, or non-zero on failure. If out() returns
  78576. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78577. are permitted to change the contents of the window provided to
  78578. inflateBackInit(), which is also the buffer that out() uses to write from.
  78579. The length written by out() will be at most the window size. Any non-zero
  78580. amount of input may be provided by in().
  78581. For convenience, inflateBack() can be provided input on the first call by
  78582. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78583. in() will be called. Therefore strm->next_in must be initialized before
  78584. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78585. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78586. must also be initialized, and then if strm->avail_in is not zero, input will
  78587. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78588. The in_desc and out_desc parameters of inflateBack() is passed as the
  78589. first parameter of in() and out() respectively when they are called. These
  78590. descriptors can be optionally used to pass any information that the caller-
  78591. supplied in() and out() functions need to do their job.
  78592. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78593. pass back any unused input that was provided by the last in() call. The
  78594. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78595. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78596. error in the deflate stream (in which case strm->msg is set to indicate the
  78597. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78598. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78599. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78600. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78601. out() returning non-zero. (in() will always be called before out(), so
  78602. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78603. that inflateBack() cannot return Z_OK.
  78604. */
  78605. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78606. /*
  78607. All memory allocated by inflateBackInit() is freed.
  78608. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78609. state was inconsistent.
  78610. */
  78611. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78612. /* Return flags indicating compile-time options.
  78613. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78614. 1.0: size of uInt
  78615. 3.2: size of uLong
  78616. 5.4: size of voidpf (pointer)
  78617. 7.6: size of z_off_t
  78618. Compiler, assembler, and debug options:
  78619. 8: DEBUG
  78620. 9: ASMV or ASMINF -- use ASM code
  78621. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78622. 11: 0 (reserved)
  78623. One-time table building (smaller code, but not thread-safe if true):
  78624. 12: BUILDFIXED -- build static block decoding tables when needed
  78625. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78626. 14,15: 0 (reserved)
  78627. Library content (indicates missing functionality):
  78628. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78629. deflate code when not needed)
  78630. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78631. and decode gzip streams (to avoid linking crc code)
  78632. 18-19: 0 (reserved)
  78633. Operation variations (changes in library functionality):
  78634. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78635. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78636. 22,23: 0 (reserved)
  78637. The sprintf variant used by gzprintf (zero is best):
  78638. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78639. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78640. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78641. Remainder:
  78642. 27-31: 0 (reserved)
  78643. */
  78644. /* utility functions */
  78645. /*
  78646. The following utility functions are implemented on top of the
  78647. basic stream-oriented functions. To simplify the interface, some
  78648. default options are assumed (compression level and memory usage,
  78649. standard memory allocation functions). The source code of these
  78650. utility functions can easily be modified if you need special options.
  78651. */
  78652. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78653. const Bytef *source, uLong sourceLen));
  78654. /*
  78655. Compresses the source buffer into the destination buffer. sourceLen is
  78656. the byte length of the source buffer. Upon entry, destLen is the total
  78657. size of the destination buffer, which must be at least the value returned
  78658. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78659. compressed buffer.
  78660. This function can be used to compress a whole file at once if the
  78661. input file is mmap'ed.
  78662. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78663. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78664. buffer.
  78665. */
  78666. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78667. const Bytef *source, uLong sourceLen,
  78668. int level));
  78669. /*
  78670. Compresses the source buffer into the destination buffer. The level
  78671. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78672. length of the source buffer. Upon entry, destLen is the total size of the
  78673. destination buffer, which must be at least the value returned by
  78674. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78675. compressed buffer.
  78676. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78677. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78678. Z_STREAM_ERROR if the level parameter is invalid.
  78679. */
  78680. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78681. /*
  78682. compressBound() returns an upper bound on the compressed size after
  78683. compress() or compress2() on sourceLen bytes. It would be used before
  78684. a compress() or compress2() call to allocate the destination buffer.
  78685. */
  78686. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78687. const Bytef *source, uLong sourceLen));
  78688. /*
  78689. Decompresses the source buffer into the destination buffer. sourceLen is
  78690. the byte length of the source buffer. Upon entry, destLen is the total
  78691. size of the destination buffer, which must be large enough to hold the
  78692. entire uncompressed data. (The size of the uncompressed data must have
  78693. been saved previously by the compressor and transmitted to the decompressor
  78694. by some mechanism outside the scope of this compression library.)
  78695. Upon exit, destLen is the actual size of the compressed buffer.
  78696. This function can be used to decompress a whole file at once if the
  78697. input file is mmap'ed.
  78698. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78699. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78700. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78701. */
  78702. typedef voidp gzFile;
  78703. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78704. /*
  78705. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78706. is as in fopen ("rb" or "wb") but can also include a compression level
  78707. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78708. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78709. as in "wb1R". (See the description of deflateInit2 for more information
  78710. about the strategy parameter.)
  78711. gzopen can be used to read a file which is not in gzip format; in this
  78712. case gzread will directly read from the file without decompression.
  78713. gzopen returns NULL if the file could not be opened or if there was
  78714. insufficient memory to allocate the (de)compression state; errno
  78715. can be checked to distinguish the two cases (if errno is zero, the
  78716. zlib error is Z_MEM_ERROR). */
  78717. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78718. /*
  78719. gzdopen() associates a gzFile with the file descriptor fd. File
  78720. descriptors are obtained from calls like open, dup, creat, pipe or
  78721. fileno (in the file has been previously opened with fopen).
  78722. The mode parameter is as in gzopen.
  78723. The next call of gzclose on the returned gzFile will also close the
  78724. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78725. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78726. gzdopen returns NULL if there was insufficient memory to allocate
  78727. the (de)compression state.
  78728. */
  78729. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78730. /*
  78731. Dynamically update the compression level or strategy. See the description
  78732. of deflateInit2 for the meaning of these parameters.
  78733. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78734. opened for writing.
  78735. */
  78736. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78737. /*
  78738. Reads the given number of uncompressed bytes from the compressed file.
  78739. If the input file was not in gzip format, gzread copies the given number
  78740. of bytes into the buffer.
  78741. gzread returns the number of uncompressed bytes actually read (0 for
  78742. end of file, -1 for error). */
  78743. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78744. voidpc buf, unsigned len));
  78745. /*
  78746. Writes the given number of uncompressed bytes into the compressed file.
  78747. gzwrite returns the number of uncompressed bytes actually written
  78748. (0 in case of error).
  78749. */
  78750. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78751. /*
  78752. Converts, formats, and writes the args to the compressed file under
  78753. control of the format string, as in fprintf. gzprintf returns the number of
  78754. uncompressed bytes actually written (0 in case of error). The number of
  78755. uncompressed bytes written is limited to 4095. The caller should assure that
  78756. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78757. return an error (0) with nothing written. In this case, there may also be a
  78758. buffer overflow with unpredictable consequences, which is possible only if
  78759. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78760. because the secure snprintf() or vsnprintf() functions were not available.
  78761. */
  78762. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78763. /*
  78764. Writes the given null-terminated string to the compressed file, excluding
  78765. the terminating null character.
  78766. gzputs returns the number of characters written, or -1 in case of error.
  78767. */
  78768. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78769. /*
  78770. Reads bytes from the compressed file until len-1 characters are read, or
  78771. a newline character is read and transferred to buf, or an end-of-file
  78772. condition is encountered. The string is then terminated with a null
  78773. character.
  78774. gzgets returns buf, or Z_NULL in case of error.
  78775. */
  78776. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78777. /*
  78778. Writes c, converted to an unsigned char, into the compressed file.
  78779. gzputc returns the value that was written, or -1 in case of error.
  78780. */
  78781. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78782. /*
  78783. Reads one byte from the compressed file. gzgetc returns this byte
  78784. or -1 in case of end of file or error.
  78785. */
  78786. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78787. /*
  78788. Push one character back onto the stream to be read again later.
  78789. Only one character of push-back is allowed. gzungetc() returns the
  78790. character pushed, or -1 on failure. gzungetc() will fail if a
  78791. character has been pushed but not read yet, or if c is -1. The pushed
  78792. character will be discarded if the stream is repositioned with gzseek()
  78793. or gzrewind().
  78794. */
  78795. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  78796. /*
  78797. Flushes all pending output into the compressed file. The parameter
  78798. flush is as in the deflate() function. The return value is the zlib
  78799. error number (see function gzerror below). gzflush returns Z_OK if
  78800. the flush parameter is Z_FINISH and all output could be flushed.
  78801. gzflush should be called only when strictly necessary because it can
  78802. degrade compression.
  78803. */
  78804. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  78805. z_off_t offset, int whence));
  78806. /*
  78807. Sets the starting position for the next gzread or gzwrite on the
  78808. given compressed file. The offset represents a number of bytes in the
  78809. uncompressed data stream. The whence parameter is defined as in lseek(2);
  78810. the value SEEK_END is not supported.
  78811. If the file is opened for reading, this function is emulated but can be
  78812. extremely slow. If the file is opened for writing, only forward seeks are
  78813. supported; gzseek then compresses a sequence of zeroes up to the new
  78814. starting position.
  78815. gzseek returns the resulting offset location as measured in bytes from
  78816. the beginning of the uncompressed stream, or -1 in case of error, in
  78817. particular if the file is opened for writing and the new starting position
  78818. would be before the current position.
  78819. */
  78820. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  78821. /*
  78822. Rewinds the given file. This function is supported only for reading.
  78823. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  78824. */
  78825. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  78826. /*
  78827. Returns the starting position for the next gzread or gzwrite on the
  78828. given compressed file. This position represents a number of bytes in the
  78829. uncompressed data stream.
  78830. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  78831. */
  78832. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  78833. /*
  78834. Returns 1 when EOF has previously been detected reading the given
  78835. input stream, otherwise zero.
  78836. */
  78837. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  78838. /*
  78839. Returns 1 if file is being read directly without decompression, otherwise
  78840. zero.
  78841. */
  78842. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  78843. /*
  78844. Flushes all pending output if necessary, closes the compressed file
  78845. and deallocates all the (de)compression state. The return value is the zlib
  78846. error number (see function gzerror below).
  78847. */
  78848. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  78849. /*
  78850. Returns the error message for the last error which occurred on the
  78851. given compressed file. errnum is set to zlib error number. If an
  78852. error occurred in the file system and not in the compression library,
  78853. errnum is set to Z_ERRNO and the application may consult errno
  78854. to get the exact error code.
  78855. */
  78856. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  78857. /*
  78858. Clears the error and end-of-file flags for file. This is analogous to the
  78859. clearerr() function in stdio. This is useful for continuing to read a gzip
  78860. file that is being written concurrently.
  78861. */
  78862. /* checksum functions */
  78863. /*
  78864. These functions are not related to compression but are exported
  78865. anyway because they might be useful in applications using the
  78866. compression library.
  78867. */
  78868. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  78869. /*
  78870. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  78871. return the updated checksum. If buf is NULL, this function returns
  78872. the required initial value for the checksum.
  78873. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  78874. much faster. Usage example:
  78875. uLong adler = adler32(0L, Z_NULL, 0);
  78876. while (read_buffer(buffer, length) != EOF) {
  78877. adler = adler32(adler, buffer, length);
  78878. }
  78879. if (adler != original_adler) error();
  78880. */
  78881. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  78882. z_off_t len2));
  78883. /*
  78884. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  78885. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  78886. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  78887. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  78888. */
  78889. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  78890. /*
  78891. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  78892. updated CRC-32. If buf is NULL, this function returns the required initial
  78893. value for the for the crc. Pre- and post-conditioning (one's complement) is
  78894. performed within this function so it shouldn't be done by the application.
  78895. Usage example:
  78896. uLong crc = crc32(0L, Z_NULL, 0);
  78897. while (read_buffer(buffer, length) != EOF) {
  78898. crc = crc32(crc, buffer, length);
  78899. }
  78900. if (crc != original_crc) error();
  78901. */
  78902. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  78903. /*
  78904. Combine two CRC-32 check values into one. For two sequences of bytes,
  78905. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  78906. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  78907. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  78908. len2.
  78909. */
  78910. /* various hacks, don't look :) */
  78911. /* deflateInit and inflateInit are macros to allow checking the zlib version
  78912. * and the compiler's view of z_stream:
  78913. */
  78914. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  78915. const char *version, int stream_size));
  78916. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  78917. const char *version, int stream_size));
  78918. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  78919. int windowBits, int memLevel,
  78920. int strategy, const char *version,
  78921. int stream_size));
  78922. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  78923. const char *version, int stream_size));
  78924. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  78925. unsigned char FAR *window,
  78926. const char *version,
  78927. int stream_size));
  78928. #define deflateInit(strm, level) \
  78929. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  78930. #define inflateInit(strm) \
  78931. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  78932. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  78933. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  78934. (strategy), ZLIB_VERSION, sizeof(z_stream))
  78935. #define inflateInit2(strm, windowBits) \
  78936. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  78937. #define inflateBackInit(strm, windowBits, window) \
  78938. inflateBackInit_((strm), (windowBits), (window), \
  78939. ZLIB_VERSION, sizeof(z_stream))
  78940. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  78941. struct internal_state {int dummy;}; /* hack for buggy compilers */
  78942. #endif
  78943. ZEXTERN const char * ZEXPORT zError OF((int));
  78944. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  78945. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  78946. #ifdef __cplusplus
  78947. }
  78948. #endif
  78949. #endif /* ZLIB_H */
  78950. /*** End of inlined file: zlib.h ***/
  78951. #undef OS_CODE
  78952. #else
  78953. #include <zlib.h>
  78954. #endif
  78955. }
  78956. BEGIN_JUCE_NAMESPACE
  78957. // internal helper object that holds the zlib structures so they don't have to be
  78958. // included publicly.
  78959. class GZIPCompressorHelper
  78960. {
  78961. public:
  78962. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  78963. : data (0),
  78964. dataSize (0),
  78965. compLevel (compressionLevel),
  78966. strategy (0),
  78967. setParams (true),
  78968. streamIsValid (false),
  78969. finished (false),
  78970. shouldFinish (false)
  78971. {
  78972. using namespace zlibNamespace;
  78973. zerostruct (stream);
  78974. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  78975. nowrap ? -MAX_WBITS : MAX_WBITS,
  78976. 8, strategy) == Z_OK);
  78977. }
  78978. ~GZIPCompressorHelper()
  78979. {
  78980. using namespace zlibNamespace;
  78981. if (streamIsValid)
  78982. deflateEnd (&stream);
  78983. }
  78984. bool needsInput() const throw()
  78985. {
  78986. return dataSize <= 0;
  78987. }
  78988. void setInput (const uint8* const newData, const int size) throw()
  78989. {
  78990. data = newData;
  78991. dataSize = size;
  78992. }
  78993. int doNextBlock (uint8* const dest, const int destSize) throw()
  78994. {
  78995. using namespace zlibNamespace;
  78996. if (streamIsValid)
  78997. {
  78998. stream.next_in = const_cast <uint8*> (data);
  78999. stream.next_out = dest;
  79000. stream.avail_in = dataSize;
  79001. stream.avail_out = destSize;
  79002. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79003. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79004. setParams = false;
  79005. switch (result)
  79006. {
  79007. case Z_STREAM_END:
  79008. finished = true;
  79009. // Deliberate fall-through..
  79010. case Z_OK:
  79011. data += dataSize - stream.avail_in;
  79012. dataSize = stream.avail_in;
  79013. return destSize - stream.avail_out;
  79014. default:
  79015. break;
  79016. }
  79017. }
  79018. return 0;
  79019. }
  79020. private:
  79021. zlibNamespace::z_stream stream;
  79022. const uint8* data;
  79023. int dataSize, compLevel, strategy;
  79024. bool setParams, streamIsValid;
  79025. public:
  79026. bool finished, shouldFinish;
  79027. };
  79028. const int gzipCompBufferSize = 32768;
  79029. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79030. int compressionLevel,
  79031. const bool deleteDestStream,
  79032. const bool noWrap)
  79033. : destStream (destStream_),
  79034. streamToDelete (deleteDestStream ? destStream_ : 0),
  79035. buffer (gzipCompBufferSize)
  79036. {
  79037. if (compressionLevel < 1 || compressionLevel > 9)
  79038. compressionLevel = -1;
  79039. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79040. }
  79041. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79042. {
  79043. flush();
  79044. }
  79045. void GZIPCompressorOutputStream::flush()
  79046. {
  79047. if (! helper->finished)
  79048. {
  79049. helper->shouldFinish = true;
  79050. while (! helper->finished)
  79051. doNextBlock();
  79052. }
  79053. destStream->flush();
  79054. }
  79055. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79056. {
  79057. if (! helper->finished)
  79058. {
  79059. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79060. while (! helper->needsInput())
  79061. {
  79062. if (! doNextBlock())
  79063. return false;
  79064. }
  79065. }
  79066. return true;
  79067. }
  79068. bool GZIPCompressorOutputStream::doNextBlock()
  79069. {
  79070. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79071. if (len > 0)
  79072. return destStream->write (buffer, len);
  79073. else
  79074. return true;
  79075. }
  79076. int64 GZIPCompressorOutputStream::getPosition()
  79077. {
  79078. return destStream->getPosition();
  79079. }
  79080. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79081. {
  79082. jassertfalse; // can't do it!
  79083. return false;
  79084. }
  79085. END_JUCE_NAMESPACE
  79086. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79087. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79088. #if JUCE_MSVC
  79089. #pragma warning (push)
  79090. #pragma warning (disable: 4309 4305)
  79091. #endif
  79092. namespace zlibNamespace
  79093. {
  79094. #if JUCE_INCLUDE_ZLIB_CODE
  79095. extern "C"
  79096. {
  79097. #undef OS_CODE
  79098. #undef fdopen
  79099. #define ZLIB_INTERNAL
  79100. #define NO_DUMMY_DECL
  79101. /*** Start of inlined file: adler32.c ***/
  79102. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79103. #define ZLIB_INTERNAL
  79104. #define BASE 65521UL /* largest prime smaller than 65536 */
  79105. #define NMAX 5552
  79106. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79107. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79108. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79109. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79110. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79111. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79112. /* use NO_DIVIDE if your processor does not do division in hardware */
  79113. #ifdef NO_DIVIDE
  79114. # define MOD(a) \
  79115. do { \
  79116. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79117. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79118. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79119. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79120. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79121. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79122. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79123. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79124. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79125. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79126. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79127. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79128. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79129. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79130. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79131. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79132. if (a >= BASE) a -= BASE; \
  79133. } while (0)
  79134. # define MOD4(a) \
  79135. do { \
  79136. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79137. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79138. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79139. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79140. if (a >= BASE) a -= BASE; \
  79141. } while (0)
  79142. #else
  79143. # define MOD(a) a %= BASE
  79144. # define MOD4(a) a %= BASE
  79145. #endif
  79146. /* ========================================================================= */
  79147. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79148. {
  79149. unsigned long sum2;
  79150. unsigned n;
  79151. /* split Adler-32 into component sums */
  79152. sum2 = (adler >> 16) & 0xffff;
  79153. adler &= 0xffff;
  79154. /* in case user likes doing a byte at a time, keep it fast */
  79155. if (len == 1) {
  79156. adler += buf[0];
  79157. if (adler >= BASE)
  79158. adler -= BASE;
  79159. sum2 += adler;
  79160. if (sum2 >= BASE)
  79161. sum2 -= BASE;
  79162. return adler | (sum2 << 16);
  79163. }
  79164. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79165. if (buf == Z_NULL)
  79166. return 1L;
  79167. /* in case short lengths are provided, keep it somewhat fast */
  79168. if (len < 16) {
  79169. while (len--) {
  79170. adler += *buf++;
  79171. sum2 += adler;
  79172. }
  79173. if (adler >= BASE)
  79174. adler -= BASE;
  79175. MOD4(sum2); /* only added so many BASE's */
  79176. return adler | (sum2 << 16);
  79177. }
  79178. /* do length NMAX blocks -- requires just one modulo operation */
  79179. while (len >= NMAX) {
  79180. len -= NMAX;
  79181. n = NMAX / 16; /* NMAX is divisible by 16 */
  79182. do {
  79183. DO16(buf); /* 16 sums unrolled */
  79184. buf += 16;
  79185. } while (--n);
  79186. MOD(adler);
  79187. MOD(sum2);
  79188. }
  79189. /* do remaining bytes (less than NMAX, still just one modulo) */
  79190. if (len) { /* avoid modulos if none remaining */
  79191. while (len >= 16) {
  79192. len -= 16;
  79193. DO16(buf);
  79194. buf += 16;
  79195. }
  79196. while (len--) {
  79197. adler += *buf++;
  79198. sum2 += adler;
  79199. }
  79200. MOD(adler);
  79201. MOD(sum2);
  79202. }
  79203. /* return recombined sums */
  79204. return adler | (sum2 << 16);
  79205. }
  79206. /* ========================================================================= */
  79207. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79208. {
  79209. unsigned long sum1;
  79210. unsigned long sum2;
  79211. unsigned rem;
  79212. /* the derivation of this formula is left as an exercise for the reader */
  79213. rem = (unsigned)(len2 % BASE);
  79214. sum1 = adler1 & 0xffff;
  79215. sum2 = rem * sum1;
  79216. MOD(sum2);
  79217. sum1 += (adler2 & 0xffff) + BASE - 1;
  79218. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79219. if (sum1 > BASE) sum1 -= BASE;
  79220. if (sum1 > BASE) sum1 -= BASE;
  79221. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79222. if (sum2 > BASE) sum2 -= BASE;
  79223. return sum1 | (sum2 << 16);
  79224. }
  79225. /*** End of inlined file: adler32.c ***/
  79226. /*** Start of inlined file: compress.c ***/
  79227. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79228. #define ZLIB_INTERNAL
  79229. /* ===========================================================================
  79230. Compresses the source buffer into the destination buffer. The level
  79231. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79232. length of the source buffer. Upon entry, destLen is the total size of the
  79233. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79234. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79235. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79236. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79237. Z_STREAM_ERROR if the level parameter is invalid.
  79238. */
  79239. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79240. uLong sourceLen, int level)
  79241. {
  79242. z_stream stream;
  79243. int err;
  79244. stream.next_in = (Bytef*)source;
  79245. stream.avail_in = (uInt)sourceLen;
  79246. #ifdef MAXSEG_64K
  79247. /* Check for source > 64K on 16-bit machine: */
  79248. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79249. #endif
  79250. stream.next_out = dest;
  79251. stream.avail_out = (uInt)*destLen;
  79252. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79253. stream.zalloc = (alloc_func)0;
  79254. stream.zfree = (free_func)0;
  79255. stream.opaque = (voidpf)0;
  79256. err = deflateInit(&stream, level);
  79257. if (err != Z_OK) return err;
  79258. err = deflate(&stream, Z_FINISH);
  79259. if (err != Z_STREAM_END) {
  79260. deflateEnd(&stream);
  79261. return err == Z_OK ? Z_BUF_ERROR : err;
  79262. }
  79263. *destLen = stream.total_out;
  79264. err = deflateEnd(&stream);
  79265. return err;
  79266. }
  79267. /* ===========================================================================
  79268. */
  79269. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79270. {
  79271. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79272. }
  79273. /* ===========================================================================
  79274. If the default memLevel or windowBits for deflateInit() is changed, then
  79275. this function needs to be updated.
  79276. */
  79277. uLong ZEXPORT compressBound (uLong sourceLen)
  79278. {
  79279. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79280. }
  79281. /*** End of inlined file: compress.c ***/
  79282. #undef DO1
  79283. #undef DO8
  79284. /*** Start of inlined file: crc32.c ***/
  79285. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79286. /*
  79287. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79288. protection on the static variables used to control the first-use generation
  79289. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79290. first call get_crc_table() to initialize the tables before allowing more than
  79291. one thread to use crc32().
  79292. */
  79293. #ifdef MAKECRCH
  79294. # include <stdio.h>
  79295. # ifndef DYNAMIC_CRC_TABLE
  79296. # define DYNAMIC_CRC_TABLE
  79297. # endif /* !DYNAMIC_CRC_TABLE */
  79298. #endif /* MAKECRCH */
  79299. /*** Start of inlined file: zutil.h ***/
  79300. /* WARNING: this file should *not* be used by applications. It is
  79301. part of the implementation of the compression library and is
  79302. subject to change. Applications should only use zlib.h.
  79303. */
  79304. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79305. #ifndef ZUTIL_H
  79306. #define ZUTIL_H
  79307. #define ZLIB_INTERNAL
  79308. #ifdef STDC
  79309. # ifndef _WIN32_WCE
  79310. # include <stddef.h>
  79311. # endif
  79312. # include <string.h>
  79313. # include <stdlib.h>
  79314. #endif
  79315. #ifdef NO_ERRNO_H
  79316. # ifdef _WIN32_WCE
  79317. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79318. * errno. We define it as a global variable to simplify porting.
  79319. * Its value is always 0 and should not be used. We rename it to
  79320. * avoid conflict with other libraries that use the same workaround.
  79321. */
  79322. # define errno z_errno
  79323. # endif
  79324. extern int errno;
  79325. #else
  79326. # ifndef _WIN32_WCE
  79327. # include <errno.h>
  79328. # endif
  79329. #endif
  79330. #ifndef local
  79331. # define local static
  79332. #endif
  79333. /* compile with -Dlocal if your debugger can't find static symbols */
  79334. typedef unsigned char uch;
  79335. typedef uch FAR uchf;
  79336. typedef unsigned short ush;
  79337. typedef ush FAR ushf;
  79338. typedef unsigned long ulg;
  79339. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79340. /* (size given to avoid silly warnings with Visual C++) */
  79341. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79342. #define ERR_RETURN(strm,err) \
  79343. return (strm->msg = (char*)ERR_MSG(err), (err))
  79344. /* To be used only when the state is known to be valid */
  79345. /* common constants */
  79346. #ifndef DEF_WBITS
  79347. # define DEF_WBITS MAX_WBITS
  79348. #endif
  79349. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79350. #if MAX_MEM_LEVEL >= 8
  79351. # define DEF_MEM_LEVEL 8
  79352. #else
  79353. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79354. #endif
  79355. /* default memLevel */
  79356. #define STORED_BLOCK 0
  79357. #define STATIC_TREES 1
  79358. #define DYN_TREES 2
  79359. /* The three kinds of block type */
  79360. #define MIN_MATCH 3
  79361. #define MAX_MATCH 258
  79362. /* The minimum and maximum match lengths */
  79363. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79364. /* target dependencies */
  79365. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79366. # define OS_CODE 0x00
  79367. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79368. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79369. /* Allow compilation with ANSI keywords only enabled */
  79370. void _Cdecl farfree( void *block );
  79371. void *_Cdecl farmalloc( unsigned long nbytes );
  79372. # else
  79373. # include <alloc.h>
  79374. # endif
  79375. # else /* MSC or DJGPP */
  79376. # include <malloc.h>
  79377. # endif
  79378. #endif
  79379. #ifdef AMIGA
  79380. # define OS_CODE 0x01
  79381. #endif
  79382. #if defined(VAXC) || defined(VMS)
  79383. # define OS_CODE 0x02
  79384. # define F_OPEN(name, mode) \
  79385. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79386. #endif
  79387. #if defined(ATARI) || defined(atarist)
  79388. # define OS_CODE 0x05
  79389. #endif
  79390. #ifdef OS2
  79391. # define OS_CODE 0x06
  79392. # ifdef M_I86
  79393. #include <malloc.h>
  79394. # endif
  79395. #endif
  79396. #if defined(MACOS) || TARGET_OS_MAC
  79397. # define OS_CODE 0x07
  79398. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79399. # include <unix.h> /* for fdopen */
  79400. # else
  79401. # ifndef fdopen
  79402. # define fdopen(fd,mode) NULL /* No fdopen() */
  79403. # endif
  79404. # endif
  79405. #endif
  79406. #ifdef TOPS20
  79407. # define OS_CODE 0x0a
  79408. #endif
  79409. #ifdef WIN32
  79410. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79411. # define OS_CODE 0x0b
  79412. # endif
  79413. #endif
  79414. #ifdef __50SERIES /* Prime/PRIMOS */
  79415. # define OS_CODE 0x0f
  79416. #endif
  79417. #if defined(_BEOS_) || defined(RISCOS)
  79418. # define fdopen(fd,mode) NULL /* No fdopen() */
  79419. #endif
  79420. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79421. # if defined(_WIN32_WCE)
  79422. # define fdopen(fd,mode) NULL /* No fdopen() */
  79423. # ifndef _PTRDIFF_T_DEFINED
  79424. typedef int ptrdiff_t;
  79425. # define _PTRDIFF_T_DEFINED
  79426. # endif
  79427. # else
  79428. # define fdopen(fd,type) _fdopen(fd,type)
  79429. # endif
  79430. #endif
  79431. /* common defaults */
  79432. #ifndef OS_CODE
  79433. # define OS_CODE 0x03 /* assume Unix */
  79434. #endif
  79435. #ifndef F_OPEN
  79436. # define F_OPEN(name, mode) fopen((name), (mode))
  79437. #endif
  79438. /* functions */
  79439. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79440. # ifndef HAVE_VSNPRINTF
  79441. # define HAVE_VSNPRINTF
  79442. # endif
  79443. #endif
  79444. #if defined(__CYGWIN__)
  79445. # ifndef HAVE_VSNPRINTF
  79446. # define HAVE_VSNPRINTF
  79447. # endif
  79448. #endif
  79449. #ifndef HAVE_VSNPRINTF
  79450. # ifdef MSDOS
  79451. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79452. but for now we just assume it doesn't. */
  79453. # define NO_vsnprintf
  79454. # endif
  79455. # ifdef __TURBOC__
  79456. # define NO_vsnprintf
  79457. # endif
  79458. # ifdef WIN32
  79459. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79460. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79461. # define vsnprintf _vsnprintf
  79462. # endif
  79463. # endif
  79464. # ifdef __SASC
  79465. # define NO_vsnprintf
  79466. # endif
  79467. #endif
  79468. #ifdef VMS
  79469. # define NO_vsnprintf
  79470. #endif
  79471. #if defined(pyr)
  79472. # define NO_MEMCPY
  79473. #endif
  79474. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79475. /* Use our own functions for small and medium model with MSC <= 5.0.
  79476. * You may have to use the same strategy for Borland C (untested).
  79477. * The __SC__ check is for Symantec.
  79478. */
  79479. # define NO_MEMCPY
  79480. #endif
  79481. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79482. # define HAVE_MEMCPY
  79483. #endif
  79484. #ifdef HAVE_MEMCPY
  79485. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79486. # define zmemcpy _fmemcpy
  79487. # define zmemcmp _fmemcmp
  79488. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79489. # else
  79490. # define zmemcpy memcpy
  79491. # define zmemcmp memcmp
  79492. # define zmemzero(dest, len) memset(dest, 0, len)
  79493. # endif
  79494. #else
  79495. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79496. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79497. extern void zmemzero OF((Bytef* dest, uInt len));
  79498. #endif
  79499. /* Diagnostic functions */
  79500. #ifdef DEBUG
  79501. # include <stdio.h>
  79502. extern int z_verbose;
  79503. extern void z_error OF((const char *m));
  79504. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79505. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79506. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79507. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79508. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79509. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79510. #else
  79511. # define Assert(cond,msg)
  79512. # define Trace(x)
  79513. # define Tracev(x)
  79514. # define Tracevv(x)
  79515. # define Tracec(c,x)
  79516. # define Tracecv(c,x)
  79517. #endif
  79518. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79519. void zcfree OF((voidpf opaque, voidpf ptr));
  79520. #define ZALLOC(strm, items, size) \
  79521. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79522. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79523. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79524. #endif /* ZUTIL_H */
  79525. /*** End of inlined file: zutil.h ***/
  79526. /* for STDC and FAR definitions */
  79527. #define local static
  79528. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79529. #ifndef NOBYFOUR
  79530. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79531. # include <limits.h>
  79532. # define BYFOUR
  79533. # if (UINT_MAX == 0xffffffffUL)
  79534. typedef unsigned int u4;
  79535. # else
  79536. # if (ULONG_MAX == 0xffffffffUL)
  79537. typedef unsigned long u4;
  79538. # else
  79539. # if (USHRT_MAX == 0xffffffffUL)
  79540. typedef unsigned short u4;
  79541. # else
  79542. # undef BYFOUR /* can't find a four-byte integer type! */
  79543. # endif
  79544. # endif
  79545. # endif
  79546. # endif /* STDC */
  79547. #endif /* !NOBYFOUR */
  79548. /* Definitions for doing the crc four data bytes at a time. */
  79549. #ifdef BYFOUR
  79550. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79551. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79552. local unsigned long crc32_little OF((unsigned long,
  79553. const unsigned char FAR *, unsigned));
  79554. local unsigned long crc32_big OF((unsigned long,
  79555. const unsigned char FAR *, unsigned));
  79556. # define TBLS 8
  79557. #else
  79558. # define TBLS 1
  79559. #endif /* BYFOUR */
  79560. /* Local functions for crc concatenation */
  79561. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79562. unsigned long vec));
  79563. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79564. #ifdef DYNAMIC_CRC_TABLE
  79565. local volatile int crc_table_empty = 1;
  79566. local unsigned long FAR crc_table[TBLS][256];
  79567. local void make_crc_table OF((void));
  79568. #ifdef MAKECRCH
  79569. local void write_table OF((FILE *, const unsigned long FAR *));
  79570. #endif /* MAKECRCH */
  79571. /*
  79572. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79573. 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.
  79574. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79575. with the lowest powers in the most significant bit. Then adding polynomials
  79576. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79577. one. If we call the above polynomial p, and represent a byte as the
  79578. polynomial q, also with the lowest power in the most significant bit (so the
  79579. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79580. where a mod b means the remainder after dividing a by b.
  79581. This calculation is done using the shift-register method of multiplying and
  79582. taking the remainder. The register is initialized to zero, and for each
  79583. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79584. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79585. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79586. out is a one). We start with the highest power (least significant bit) of
  79587. q and repeat for all eight bits of q.
  79588. The first table is simply the CRC of all possible eight bit values. This is
  79589. all the information needed to generate CRCs on data a byte at a time for all
  79590. combinations of CRC register values and incoming bytes. The remaining tables
  79591. allow for word-at-a-time CRC calculation for both big-endian and little-
  79592. endian machines, where a word is four bytes.
  79593. */
  79594. local void make_crc_table()
  79595. {
  79596. unsigned long c;
  79597. int n, k;
  79598. unsigned long poly; /* polynomial exclusive-or pattern */
  79599. /* terms of polynomial defining this crc (except x^32): */
  79600. static volatile int first = 1; /* flag to limit concurrent making */
  79601. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79602. /* See if another task is already doing this (not thread-safe, but better
  79603. than nothing -- significantly reduces duration of vulnerability in
  79604. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79605. if (first) {
  79606. first = 0;
  79607. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79608. poly = 0UL;
  79609. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79610. poly |= 1UL << (31 - p[n]);
  79611. /* generate a crc for every 8-bit value */
  79612. for (n = 0; n < 256; n++) {
  79613. c = (unsigned long)n;
  79614. for (k = 0; k < 8; k++)
  79615. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79616. crc_table[0][n] = c;
  79617. }
  79618. #ifdef BYFOUR
  79619. /* generate crc for each value followed by one, two, and three zeros,
  79620. and then the byte reversal of those as well as the first table */
  79621. for (n = 0; n < 256; n++) {
  79622. c = crc_table[0][n];
  79623. crc_table[4][n] = REV(c);
  79624. for (k = 1; k < 4; k++) {
  79625. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79626. crc_table[k][n] = c;
  79627. crc_table[k + 4][n] = REV(c);
  79628. }
  79629. }
  79630. #endif /* BYFOUR */
  79631. crc_table_empty = 0;
  79632. }
  79633. else { /* not first */
  79634. /* wait for the other guy to finish (not efficient, but rare) */
  79635. while (crc_table_empty)
  79636. ;
  79637. }
  79638. #ifdef MAKECRCH
  79639. /* write out CRC tables to crc32.h */
  79640. {
  79641. FILE *out;
  79642. out = fopen("crc32.h", "w");
  79643. if (out == NULL) return;
  79644. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79645. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79646. fprintf(out, "local const unsigned long FAR ");
  79647. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79648. write_table(out, crc_table[0]);
  79649. # ifdef BYFOUR
  79650. fprintf(out, "#ifdef BYFOUR\n");
  79651. for (k = 1; k < 8; k++) {
  79652. fprintf(out, " },\n {\n");
  79653. write_table(out, crc_table[k]);
  79654. }
  79655. fprintf(out, "#endif\n");
  79656. # endif /* BYFOUR */
  79657. fprintf(out, " }\n};\n");
  79658. fclose(out);
  79659. }
  79660. #endif /* MAKECRCH */
  79661. }
  79662. #ifdef MAKECRCH
  79663. local void write_table(out, table)
  79664. FILE *out;
  79665. const unsigned long FAR *table;
  79666. {
  79667. int n;
  79668. for (n = 0; n < 256; n++)
  79669. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79670. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79671. }
  79672. #endif /* MAKECRCH */
  79673. #else /* !DYNAMIC_CRC_TABLE */
  79674. /* ========================================================================
  79675. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79676. */
  79677. /*** Start of inlined file: crc32.h ***/
  79678. local const unsigned long FAR crc_table[TBLS][256] =
  79679. {
  79680. {
  79681. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79682. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79683. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79684. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79685. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79686. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79687. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79688. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79689. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79690. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79691. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79692. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79693. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79694. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79695. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79696. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79697. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79698. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79699. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79700. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79701. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79702. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79703. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79704. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79705. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79706. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79707. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79708. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79709. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79710. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79711. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79712. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79713. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79714. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79715. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79716. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79717. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79718. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79719. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79720. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79721. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79722. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79723. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79724. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79725. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79726. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79727. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79728. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79729. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79730. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79731. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79732. 0x2d02ef8dUL
  79733. #ifdef BYFOUR
  79734. },
  79735. {
  79736. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79737. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79738. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79739. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79740. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79741. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79742. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79743. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79744. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79745. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79746. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79747. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79748. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79749. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79750. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79751. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79752. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79753. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79754. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79755. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79756. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79757. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79758. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79759. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79760. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79761. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79762. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79763. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79764. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79765. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79766. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79767. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79768. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79769. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79770. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79771. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79772. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79773. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79774. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79775. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79776. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79777. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79778. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79779. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79780. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79781. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79782. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79783. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79784. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79785. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79786. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79787. 0x9324fd72UL
  79788. },
  79789. {
  79790. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79791. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79792. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79793. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79794. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79795. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79796. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79797. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79798. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79799. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79800. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79801. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79802. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  79803. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  79804. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  79805. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  79806. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  79807. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  79808. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  79809. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  79810. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  79811. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  79812. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  79813. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  79814. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  79815. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  79816. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  79817. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  79818. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  79819. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  79820. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  79821. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  79822. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  79823. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  79824. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  79825. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  79826. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  79827. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  79828. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  79829. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  79830. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  79831. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  79832. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  79833. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  79834. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  79835. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  79836. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  79837. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  79838. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  79839. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  79840. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  79841. 0xbe9834edUL
  79842. },
  79843. {
  79844. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  79845. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  79846. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  79847. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  79848. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  79849. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  79850. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  79851. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  79852. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  79853. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  79854. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  79855. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  79856. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  79857. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  79858. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  79859. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  79860. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  79861. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  79862. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  79863. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  79864. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  79865. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  79866. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  79867. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  79868. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  79869. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  79870. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  79871. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  79872. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  79873. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  79874. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  79875. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  79876. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  79877. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  79878. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  79879. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  79880. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  79881. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  79882. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  79883. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  79884. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  79885. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  79886. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  79887. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  79888. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  79889. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  79890. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  79891. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  79892. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  79893. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  79894. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  79895. 0xde0506f1UL
  79896. },
  79897. {
  79898. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  79899. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  79900. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  79901. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  79902. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  79903. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  79904. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  79905. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  79906. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  79907. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  79908. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  79909. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  79910. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  79911. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  79912. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  79913. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  79914. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  79915. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  79916. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  79917. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  79918. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  79919. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  79920. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  79921. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  79922. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  79923. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  79924. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  79925. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  79926. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  79927. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  79928. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  79929. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  79930. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  79931. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  79932. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  79933. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  79934. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  79935. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  79936. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  79937. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  79938. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  79939. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  79940. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  79941. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  79942. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  79943. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  79944. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  79945. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  79946. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  79947. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  79948. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  79949. 0x8def022dUL
  79950. },
  79951. {
  79952. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  79953. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  79954. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  79955. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  79956. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  79957. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  79958. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  79959. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  79960. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  79961. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  79962. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  79963. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  79964. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  79965. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  79966. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  79967. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  79968. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  79969. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  79970. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  79971. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  79972. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  79973. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  79974. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  79975. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  79976. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  79977. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  79978. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  79979. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  79980. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  79981. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  79982. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  79983. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  79984. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  79985. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  79986. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  79987. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  79988. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  79989. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  79990. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  79991. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  79992. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  79993. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  79994. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  79995. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  79996. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  79997. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  79998. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  79999. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80000. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80001. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80002. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80003. 0x72fd2493UL
  80004. },
  80005. {
  80006. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80007. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80008. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80009. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80010. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80011. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80012. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80013. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80014. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80015. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80016. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80017. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80018. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80019. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80020. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80021. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80022. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80023. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80024. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80025. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80026. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80027. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80028. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80029. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80030. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80031. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80032. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80033. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80034. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80035. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80036. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80037. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80038. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80039. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80040. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80041. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80042. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80043. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80044. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80045. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80046. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80047. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80048. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80049. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80050. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80051. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80052. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80053. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80054. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80055. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80056. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80057. 0xed3498beUL
  80058. },
  80059. {
  80060. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80061. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80062. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80063. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80064. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80065. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80066. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80067. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80068. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80069. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80070. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80071. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80072. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80073. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80074. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80075. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80076. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80077. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80078. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80079. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80080. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80081. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80082. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80083. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80084. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80085. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80086. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80087. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80088. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80089. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80090. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80091. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80092. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80093. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80094. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80095. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80096. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80097. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80098. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80099. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80100. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80101. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80102. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80103. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80104. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80105. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80106. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80107. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80108. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80109. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80110. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80111. 0xf10605deUL
  80112. #endif
  80113. }
  80114. };
  80115. /*** End of inlined file: crc32.h ***/
  80116. #endif /* DYNAMIC_CRC_TABLE */
  80117. /* =========================================================================
  80118. * This function can be used by asm versions of crc32()
  80119. */
  80120. const unsigned long FAR * ZEXPORT get_crc_table()
  80121. {
  80122. #ifdef DYNAMIC_CRC_TABLE
  80123. if (crc_table_empty)
  80124. make_crc_table();
  80125. #endif /* DYNAMIC_CRC_TABLE */
  80126. return (const unsigned long FAR *)crc_table;
  80127. }
  80128. /* ========================================================================= */
  80129. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80130. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80131. /* ========================================================================= */
  80132. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80133. {
  80134. if (buf == Z_NULL) return 0UL;
  80135. #ifdef DYNAMIC_CRC_TABLE
  80136. if (crc_table_empty)
  80137. make_crc_table();
  80138. #endif /* DYNAMIC_CRC_TABLE */
  80139. #ifdef BYFOUR
  80140. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80141. u4 endian;
  80142. endian = 1;
  80143. if (*((unsigned char *)(&endian)))
  80144. return crc32_little(crc, buf, len);
  80145. else
  80146. return crc32_big(crc, buf, len);
  80147. }
  80148. #endif /* BYFOUR */
  80149. crc = crc ^ 0xffffffffUL;
  80150. while (len >= 8) {
  80151. DO8;
  80152. len -= 8;
  80153. }
  80154. if (len) do {
  80155. DO1;
  80156. } while (--len);
  80157. return crc ^ 0xffffffffUL;
  80158. }
  80159. #ifdef BYFOUR
  80160. /* ========================================================================= */
  80161. #define DOLIT4 c ^= *buf4++; \
  80162. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80163. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80164. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80165. /* ========================================================================= */
  80166. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80167. {
  80168. register u4 c;
  80169. register const u4 FAR *buf4;
  80170. c = (u4)crc;
  80171. c = ~c;
  80172. while (len && ((ptrdiff_t)buf & 3)) {
  80173. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80174. len--;
  80175. }
  80176. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80177. while (len >= 32) {
  80178. DOLIT32;
  80179. len -= 32;
  80180. }
  80181. while (len >= 4) {
  80182. DOLIT4;
  80183. len -= 4;
  80184. }
  80185. buf = (const unsigned char FAR *)buf4;
  80186. if (len) do {
  80187. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80188. } while (--len);
  80189. c = ~c;
  80190. return (unsigned long)c;
  80191. }
  80192. /* ========================================================================= */
  80193. #define DOBIG4 c ^= *++buf4; \
  80194. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80195. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80196. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80197. /* ========================================================================= */
  80198. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80199. {
  80200. register u4 c;
  80201. register const u4 FAR *buf4;
  80202. c = REV((u4)crc);
  80203. c = ~c;
  80204. while (len && ((ptrdiff_t)buf & 3)) {
  80205. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80206. len--;
  80207. }
  80208. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80209. buf4--;
  80210. while (len >= 32) {
  80211. DOBIG32;
  80212. len -= 32;
  80213. }
  80214. while (len >= 4) {
  80215. DOBIG4;
  80216. len -= 4;
  80217. }
  80218. buf4++;
  80219. buf = (const unsigned char FAR *)buf4;
  80220. if (len) do {
  80221. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80222. } while (--len);
  80223. c = ~c;
  80224. return (unsigned long)(REV(c));
  80225. }
  80226. #endif /* BYFOUR */
  80227. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80228. /* ========================================================================= */
  80229. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80230. {
  80231. unsigned long sum;
  80232. sum = 0;
  80233. while (vec) {
  80234. if (vec & 1)
  80235. sum ^= *mat;
  80236. vec >>= 1;
  80237. mat++;
  80238. }
  80239. return sum;
  80240. }
  80241. /* ========================================================================= */
  80242. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80243. {
  80244. int n;
  80245. for (n = 0; n < GF2_DIM; n++)
  80246. square[n] = gf2_matrix_times(mat, mat[n]);
  80247. }
  80248. /* ========================================================================= */
  80249. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80250. {
  80251. int n;
  80252. unsigned long row;
  80253. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80254. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80255. /* degenerate case */
  80256. if (len2 == 0)
  80257. return crc1;
  80258. /* put operator for one zero bit in odd */
  80259. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80260. row = 1;
  80261. for (n = 1; n < GF2_DIM; n++) {
  80262. odd[n] = row;
  80263. row <<= 1;
  80264. }
  80265. /* put operator for two zero bits in even */
  80266. gf2_matrix_square(even, odd);
  80267. /* put operator for four zero bits in odd */
  80268. gf2_matrix_square(odd, even);
  80269. /* apply len2 zeros to crc1 (first square will put the operator for one
  80270. zero byte, eight zero bits, in even) */
  80271. do {
  80272. /* apply zeros operator for this bit of len2 */
  80273. gf2_matrix_square(even, odd);
  80274. if (len2 & 1)
  80275. crc1 = gf2_matrix_times(even, crc1);
  80276. len2 >>= 1;
  80277. /* if no more bits set, then done */
  80278. if (len2 == 0)
  80279. break;
  80280. /* another iteration of the loop with odd and even swapped */
  80281. gf2_matrix_square(odd, even);
  80282. if (len2 & 1)
  80283. crc1 = gf2_matrix_times(odd, crc1);
  80284. len2 >>= 1;
  80285. /* if no more bits set, then done */
  80286. } while (len2 != 0);
  80287. /* return combined crc */
  80288. crc1 ^= crc2;
  80289. return crc1;
  80290. }
  80291. /*** End of inlined file: crc32.c ***/
  80292. /*** Start of inlined file: deflate.c ***/
  80293. /*
  80294. * ALGORITHM
  80295. *
  80296. * The "deflation" process depends on being able to identify portions
  80297. * of the input text which are identical to earlier input (within a
  80298. * sliding window trailing behind the input currently being processed).
  80299. *
  80300. * The most straightforward technique turns out to be the fastest for
  80301. * most input files: try all possible matches and select the longest.
  80302. * The key feature of this algorithm is that insertions into the string
  80303. * dictionary are very simple and thus fast, and deletions are avoided
  80304. * completely. Insertions are performed at each input character, whereas
  80305. * string matches are performed only when the previous match ends. So it
  80306. * is preferable to spend more time in matches to allow very fast string
  80307. * insertions and avoid deletions. The matching algorithm for small
  80308. * strings is inspired from that of Rabin & Karp. A brute force approach
  80309. * is used to find longer strings when a small match has been found.
  80310. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80311. * (by Leonid Broukhis).
  80312. * A previous version of this file used a more sophisticated algorithm
  80313. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80314. * time, but has a larger average cost, uses more memory and is patented.
  80315. * However the F&G algorithm may be faster for some highly redundant
  80316. * files if the parameter max_chain_length (described below) is too large.
  80317. *
  80318. * ACKNOWLEDGEMENTS
  80319. *
  80320. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80321. * I found it in 'freeze' written by Leonid Broukhis.
  80322. * Thanks to many people for bug reports and testing.
  80323. *
  80324. * REFERENCES
  80325. *
  80326. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80327. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80328. *
  80329. * A description of the Rabin and Karp algorithm is given in the book
  80330. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80331. *
  80332. * Fiala,E.R., and Greene,D.H.
  80333. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80334. *
  80335. */
  80336. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80337. /*** Start of inlined file: deflate.h ***/
  80338. /* WARNING: this file should *not* be used by applications. It is
  80339. part of the implementation of the compression library and is
  80340. subject to change. Applications should only use zlib.h.
  80341. */
  80342. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80343. #ifndef DEFLATE_H
  80344. #define DEFLATE_H
  80345. /* define NO_GZIP when compiling if you want to disable gzip header and
  80346. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80347. the crc code when it is not needed. For shared libraries, gzip encoding
  80348. should be left enabled. */
  80349. #ifndef NO_GZIP
  80350. # define GZIP
  80351. #endif
  80352. #define NO_DUMMY_DECL
  80353. /* ===========================================================================
  80354. * Internal compression state.
  80355. */
  80356. #define LENGTH_CODES 29
  80357. /* number of length codes, not counting the special END_BLOCK code */
  80358. #define LITERALS 256
  80359. /* number of literal bytes 0..255 */
  80360. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80361. /* number of Literal or Length codes, including the END_BLOCK code */
  80362. #define D_CODES 30
  80363. /* number of distance codes */
  80364. #define BL_CODES 19
  80365. /* number of codes used to transfer the bit lengths */
  80366. #define HEAP_SIZE (2*L_CODES+1)
  80367. /* maximum heap size */
  80368. #define MAX_BITS 15
  80369. /* All codes must not exceed MAX_BITS bits */
  80370. #define INIT_STATE 42
  80371. #define EXTRA_STATE 69
  80372. #define NAME_STATE 73
  80373. #define COMMENT_STATE 91
  80374. #define HCRC_STATE 103
  80375. #define BUSY_STATE 113
  80376. #define FINISH_STATE 666
  80377. /* Stream status */
  80378. /* Data structure describing a single value and its code string. */
  80379. typedef struct ct_data_s {
  80380. union {
  80381. ush freq; /* frequency count */
  80382. ush code; /* bit string */
  80383. } fc;
  80384. union {
  80385. ush dad; /* father node in Huffman tree */
  80386. ush len; /* length of bit string */
  80387. } dl;
  80388. } FAR ct_data;
  80389. #define Freq fc.freq
  80390. #define Code fc.code
  80391. #define Dad dl.dad
  80392. #define Len dl.len
  80393. typedef struct static_tree_desc_s static_tree_desc;
  80394. typedef struct tree_desc_s {
  80395. ct_data *dyn_tree; /* the dynamic tree */
  80396. int max_code; /* largest code with non zero frequency */
  80397. static_tree_desc *stat_desc; /* the corresponding static tree */
  80398. } FAR tree_desc;
  80399. typedef ush Pos;
  80400. typedef Pos FAR Posf;
  80401. typedef unsigned IPos;
  80402. /* A Pos is an index in the character window. We use short instead of int to
  80403. * save space in the various tables. IPos is used only for parameter passing.
  80404. */
  80405. typedef struct internal_state {
  80406. z_streamp strm; /* pointer back to this zlib stream */
  80407. int status; /* as the name implies */
  80408. Bytef *pending_buf; /* output still pending */
  80409. ulg pending_buf_size; /* size of pending_buf */
  80410. Bytef *pending_out; /* next pending byte to output to the stream */
  80411. uInt pending; /* nb of bytes in the pending buffer */
  80412. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80413. gz_headerp gzhead; /* gzip header information to write */
  80414. uInt gzindex; /* where in extra, name, or comment */
  80415. Byte method; /* STORED (for zip only) or DEFLATED */
  80416. int last_flush; /* value of flush param for previous deflate call */
  80417. /* used by deflate.c: */
  80418. uInt w_size; /* LZ77 window size (32K by default) */
  80419. uInt w_bits; /* log2(w_size) (8..16) */
  80420. uInt w_mask; /* w_size - 1 */
  80421. Bytef *window;
  80422. /* Sliding window. Input bytes are read into the second half of the window,
  80423. * and move to the first half later to keep a dictionary of at least wSize
  80424. * bytes. With this organization, matches are limited to a distance of
  80425. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80426. * performed with a length multiple of the block size. Also, it limits
  80427. * the window size to 64K, which is quite useful on MSDOS.
  80428. * To do: use the user input buffer as sliding window.
  80429. */
  80430. ulg window_size;
  80431. /* Actual size of window: 2*wSize, except when the user input buffer
  80432. * is directly used as sliding window.
  80433. */
  80434. Posf *prev;
  80435. /* Link to older string with same hash index. To limit the size of this
  80436. * array to 64K, this link is maintained only for the last 32K strings.
  80437. * An index in this array is thus a window index modulo 32K.
  80438. */
  80439. Posf *head; /* Heads of the hash chains or NIL. */
  80440. uInt ins_h; /* hash index of string to be inserted */
  80441. uInt hash_size; /* number of elements in hash table */
  80442. uInt hash_bits; /* log2(hash_size) */
  80443. uInt hash_mask; /* hash_size-1 */
  80444. uInt hash_shift;
  80445. /* Number of bits by which ins_h must be shifted at each input
  80446. * step. It must be such that after MIN_MATCH steps, the oldest
  80447. * byte no longer takes part in the hash key, that is:
  80448. * hash_shift * MIN_MATCH >= hash_bits
  80449. */
  80450. long block_start;
  80451. /* Window position at the beginning of the current output block. Gets
  80452. * negative when the window is moved backwards.
  80453. */
  80454. uInt match_length; /* length of best match */
  80455. IPos prev_match; /* previous match */
  80456. int match_available; /* set if previous match exists */
  80457. uInt strstart; /* start of string to insert */
  80458. uInt match_start; /* start of matching string */
  80459. uInt lookahead; /* number of valid bytes ahead in window */
  80460. uInt prev_length;
  80461. /* Length of the best match at previous step. Matches not greater than this
  80462. * are discarded. This is used in the lazy match evaluation.
  80463. */
  80464. uInt max_chain_length;
  80465. /* To speed up deflation, hash chains are never searched beyond this
  80466. * length. A higher limit improves compression ratio but degrades the
  80467. * speed.
  80468. */
  80469. uInt max_lazy_match;
  80470. /* Attempt to find a better match only when the current match is strictly
  80471. * smaller than this value. This mechanism is used only for compression
  80472. * levels >= 4.
  80473. */
  80474. # define max_insert_length max_lazy_match
  80475. /* Insert new strings in the hash table only if the match length is not
  80476. * greater than this length. This saves time but degrades compression.
  80477. * max_insert_length is used only for compression levels <= 3.
  80478. */
  80479. int level; /* compression level (1..9) */
  80480. int strategy; /* favor or force Huffman coding*/
  80481. uInt good_match;
  80482. /* Use a faster search when the previous match is longer than this */
  80483. int nice_match; /* Stop searching when current match exceeds this */
  80484. /* used by trees.c: */
  80485. /* Didn't use ct_data typedef below to supress compiler warning */
  80486. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80487. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80488. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80489. struct tree_desc_s l_desc; /* desc. for literal tree */
  80490. struct tree_desc_s d_desc; /* desc. for distance tree */
  80491. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80492. ush bl_count[MAX_BITS+1];
  80493. /* number of codes at each bit length for an optimal tree */
  80494. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80495. int heap_len; /* number of elements in the heap */
  80496. int heap_max; /* element of largest frequency */
  80497. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80498. * The same heap array is used to build all trees.
  80499. */
  80500. uch depth[2*L_CODES+1];
  80501. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80502. */
  80503. uchf *l_buf; /* buffer for literals or lengths */
  80504. uInt lit_bufsize;
  80505. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80506. * limiting lit_bufsize to 64K:
  80507. * - frequencies can be kept in 16 bit counters
  80508. * - if compression is not successful for the first block, all input
  80509. * data is still in the window so we can still emit a stored block even
  80510. * when input comes from standard input. (This can also be done for
  80511. * all blocks if lit_bufsize is not greater than 32K.)
  80512. * - if compression is not successful for a file smaller than 64K, we can
  80513. * even emit a stored file instead of a stored block (saving 5 bytes).
  80514. * This is applicable only for zip (not gzip or zlib).
  80515. * - creating new Huffman trees less frequently may not provide fast
  80516. * adaptation to changes in the input data statistics. (Take for
  80517. * example a binary file with poorly compressible code followed by
  80518. * a highly compressible string table.) Smaller buffer sizes give
  80519. * fast adaptation but have of course the overhead of transmitting
  80520. * trees more frequently.
  80521. * - I can't count above 4
  80522. */
  80523. uInt last_lit; /* running index in l_buf */
  80524. ushf *d_buf;
  80525. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80526. * the same number of elements. To use different lengths, an extra flag
  80527. * array would be necessary.
  80528. */
  80529. ulg opt_len; /* bit length of current block with optimal trees */
  80530. ulg static_len; /* bit length of current block with static trees */
  80531. uInt matches; /* number of string matches in current block */
  80532. int last_eob_len; /* bit length of EOB code for last block */
  80533. #ifdef DEBUG
  80534. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80535. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80536. #endif
  80537. ush bi_buf;
  80538. /* Output buffer. bits are inserted starting at the bottom (least
  80539. * significant bits).
  80540. */
  80541. int bi_valid;
  80542. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80543. * are always zero.
  80544. */
  80545. } FAR deflate_state;
  80546. /* Output a byte on the stream.
  80547. * IN assertion: there is enough room in pending_buf.
  80548. */
  80549. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80550. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80551. /* Minimum amount of lookahead, except at the end of the input file.
  80552. * See deflate.c for comments about the MIN_MATCH+1.
  80553. */
  80554. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80555. /* In order to simplify the code, particularly on 16 bit machines, match
  80556. * distances are limited to MAX_DIST instead of WSIZE.
  80557. */
  80558. /* in trees.c */
  80559. void _tr_init OF((deflate_state *s));
  80560. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80561. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80562. int eof));
  80563. void _tr_align OF((deflate_state *s));
  80564. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80565. int eof));
  80566. #define d_code(dist) \
  80567. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80568. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80569. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80570. * used.
  80571. */
  80572. #ifndef DEBUG
  80573. /* Inline versions of _tr_tally for speed: */
  80574. #if defined(GEN_TREES_H) || !defined(STDC)
  80575. extern uch _length_code[];
  80576. extern uch _dist_code[];
  80577. #else
  80578. extern const uch _length_code[];
  80579. extern const uch _dist_code[];
  80580. #endif
  80581. # define _tr_tally_lit(s, c, flush) \
  80582. { uch cc = (c); \
  80583. s->d_buf[s->last_lit] = 0; \
  80584. s->l_buf[s->last_lit++] = cc; \
  80585. s->dyn_ltree[cc].Freq++; \
  80586. flush = (s->last_lit == s->lit_bufsize-1); \
  80587. }
  80588. # define _tr_tally_dist(s, distance, length, flush) \
  80589. { uch len = (length); \
  80590. ush dist = (distance); \
  80591. s->d_buf[s->last_lit] = dist; \
  80592. s->l_buf[s->last_lit++] = len; \
  80593. dist--; \
  80594. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80595. s->dyn_dtree[d_code(dist)].Freq++; \
  80596. flush = (s->last_lit == s->lit_bufsize-1); \
  80597. }
  80598. #else
  80599. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80600. # define _tr_tally_dist(s, distance, length, flush) \
  80601. flush = _tr_tally(s, distance, length)
  80602. #endif
  80603. #endif /* DEFLATE_H */
  80604. /*** End of inlined file: deflate.h ***/
  80605. const char deflate_copyright[] =
  80606. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80607. /*
  80608. If you use the zlib library in a product, an acknowledgment is welcome
  80609. in the documentation of your product. If for some reason you cannot
  80610. include such an acknowledgment, I would appreciate that you keep this
  80611. copyright string in the executable of your product.
  80612. */
  80613. /* ===========================================================================
  80614. * Function prototypes.
  80615. */
  80616. typedef enum {
  80617. need_more, /* block not completed, need more input or more output */
  80618. block_done, /* block flush performed */
  80619. finish_started, /* finish started, need only more output at next deflate */
  80620. finish_done /* finish done, accept no more input or output */
  80621. } block_state;
  80622. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80623. /* Compression function. Returns the block state after the call. */
  80624. local void fill_window OF((deflate_state *s));
  80625. local block_state deflate_stored OF((deflate_state *s, int flush));
  80626. local block_state deflate_fast OF((deflate_state *s, int flush));
  80627. #ifndef FASTEST
  80628. local block_state deflate_slow OF((deflate_state *s, int flush));
  80629. #endif
  80630. local void lm_init OF((deflate_state *s));
  80631. local void putShortMSB OF((deflate_state *s, uInt b));
  80632. local void flush_pending OF((z_streamp strm));
  80633. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80634. #ifndef FASTEST
  80635. #ifdef ASMV
  80636. void match_init OF((void)); /* asm code initialization */
  80637. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80638. #else
  80639. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80640. #endif
  80641. #endif
  80642. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80643. #ifdef DEBUG
  80644. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80645. int length));
  80646. #endif
  80647. /* ===========================================================================
  80648. * Local data
  80649. */
  80650. #define NIL 0
  80651. /* Tail of hash chains */
  80652. #ifndef TOO_FAR
  80653. # define TOO_FAR 4096
  80654. #endif
  80655. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80656. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80657. /* Minimum amount of lookahead, except at the end of the input file.
  80658. * See deflate.c for comments about the MIN_MATCH+1.
  80659. */
  80660. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80661. * the desired pack level (0..9). The values given below have been tuned to
  80662. * exclude worst case performance for pathological files. Better values may be
  80663. * found for specific files.
  80664. */
  80665. typedef struct config_s {
  80666. ush good_length; /* reduce lazy search above this match length */
  80667. ush max_lazy; /* do not perform lazy search above this match length */
  80668. ush nice_length; /* quit search above this match length */
  80669. ush max_chain;
  80670. compress_func func;
  80671. } config;
  80672. #ifdef FASTEST
  80673. local const config configuration_table[2] = {
  80674. /* good lazy nice chain */
  80675. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80676. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80677. #else
  80678. local const config configuration_table[10] = {
  80679. /* good lazy nice chain */
  80680. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80681. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80682. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80683. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80684. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80685. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80686. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80687. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80688. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80689. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80690. #endif
  80691. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80692. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80693. * meaning.
  80694. */
  80695. #define EQUAL 0
  80696. /* result of memcmp for equal strings */
  80697. #ifndef NO_DUMMY_DECL
  80698. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80699. #endif
  80700. /* ===========================================================================
  80701. * Update a hash value with the given input byte
  80702. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80703. * input characters, so that a running hash key can be computed from the
  80704. * previous key instead of complete recalculation each time.
  80705. */
  80706. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80707. /* ===========================================================================
  80708. * Insert string str in the dictionary and set match_head to the previous head
  80709. * of the hash chain (the most recent string with same hash key). Return
  80710. * the previous length of the hash chain.
  80711. * If this file is compiled with -DFASTEST, the compression level is forced
  80712. * to 1, and no hash chains are maintained.
  80713. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80714. * input characters and the first MIN_MATCH bytes of str are valid
  80715. * (except for the last MIN_MATCH-1 bytes of the input file).
  80716. */
  80717. #ifdef FASTEST
  80718. #define INSERT_STRING(s, str, match_head) \
  80719. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80720. match_head = s->head[s->ins_h], \
  80721. s->head[s->ins_h] = (Pos)(str))
  80722. #else
  80723. #define INSERT_STRING(s, str, match_head) \
  80724. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80725. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80726. s->head[s->ins_h] = (Pos)(str))
  80727. #endif
  80728. /* ===========================================================================
  80729. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80730. * prev[] will be initialized on the fly.
  80731. */
  80732. #define CLEAR_HASH(s) \
  80733. s->head[s->hash_size-1] = NIL; \
  80734. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80735. /* ========================================================================= */
  80736. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80737. {
  80738. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80739. Z_DEFAULT_STRATEGY, version, stream_size);
  80740. /* To do: ignore strm->next_in if we use it as window */
  80741. }
  80742. /* ========================================================================= */
  80743. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80744. {
  80745. deflate_state *s;
  80746. int wrap = 1;
  80747. static const char my_version[] = ZLIB_VERSION;
  80748. ushf *overlay;
  80749. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80750. * output size for (length,distance) codes is <= 24 bits.
  80751. */
  80752. if (version == Z_NULL || version[0] != my_version[0] ||
  80753. stream_size != sizeof(z_stream)) {
  80754. return Z_VERSION_ERROR;
  80755. }
  80756. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80757. strm->msg = Z_NULL;
  80758. if (strm->zalloc == (alloc_func)0) {
  80759. strm->zalloc = zcalloc;
  80760. strm->opaque = (voidpf)0;
  80761. }
  80762. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80763. #ifdef FASTEST
  80764. if (level != 0) level = 1;
  80765. #else
  80766. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80767. #endif
  80768. if (windowBits < 0) { /* suppress zlib wrapper */
  80769. wrap = 0;
  80770. windowBits = -windowBits;
  80771. }
  80772. #ifdef GZIP
  80773. else if (windowBits > 15) {
  80774. wrap = 2; /* write gzip wrapper instead */
  80775. windowBits -= 16;
  80776. }
  80777. #endif
  80778. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80779. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80780. strategy < 0 || strategy > Z_FIXED) {
  80781. return Z_STREAM_ERROR;
  80782. }
  80783. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80784. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80785. if (s == Z_NULL) return Z_MEM_ERROR;
  80786. strm->state = (struct internal_state FAR *)s;
  80787. s->strm = strm;
  80788. s->wrap = wrap;
  80789. s->gzhead = Z_NULL;
  80790. s->w_bits = windowBits;
  80791. s->w_size = 1 << s->w_bits;
  80792. s->w_mask = s->w_size - 1;
  80793. s->hash_bits = memLevel + 7;
  80794. s->hash_size = 1 << s->hash_bits;
  80795. s->hash_mask = s->hash_size - 1;
  80796. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80797. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80798. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80799. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80800. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80801. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80802. s->pending_buf = (uchf *) overlay;
  80803. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  80804. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  80805. s->pending_buf == Z_NULL) {
  80806. s->status = FINISH_STATE;
  80807. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  80808. deflateEnd (strm);
  80809. return Z_MEM_ERROR;
  80810. }
  80811. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  80812. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  80813. s->level = level;
  80814. s->strategy = strategy;
  80815. s->method = (Byte)method;
  80816. return deflateReset(strm);
  80817. }
  80818. /* ========================================================================= */
  80819. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80820. {
  80821. deflate_state *s;
  80822. uInt length = dictLength;
  80823. uInt n;
  80824. IPos hash_head = 0;
  80825. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  80826. strm->state->wrap == 2 ||
  80827. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  80828. return Z_STREAM_ERROR;
  80829. s = strm->state;
  80830. if (s->wrap)
  80831. strm->adler = adler32(strm->adler, dictionary, dictLength);
  80832. if (length < MIN_MATCH) return Z_OK;
  80833. if (length > MAX_DIST(s)) {
  80834. length = MAX_DIST(s);
  80835. dictionary += dictLength - length; /* use the tail of the dictionary */
  80836. }
  80837. zmemcpy(s->window, dictionary, length);
  80838. s->strstart = length;
  80839. s->block_start = (long)length;
  80840. /* Insert all strings in the hash table (except for the last two bytes).
  80841. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  80842. * call of fill_window.
  80843. */
  80844. s->ins_h = s->window[0];
  80845. UPDATE_HASH(s, s->ins_h, s->window[1]);
  80846. for (n = 0; n <= length - MIN_MATCH; n++) {
  80847. INSERT_STRING(s, n, hash_head);
  80848. }
  80849. if (hash_head) hash_head = 0; /* to make compiler happy */
  80850. return Z_OK;
  80851. }
  80852. /* ========================================================================= */
  80853. int ZEXPORT deflateReset (z_streamp strm)
  80854. {
  80855. deflate_state *s;
  80856. if (strm == Z_NULL || strm->state == Z_NULL ||
  80857. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  80858. return Z_STREAM_ERROR;
  80859. }
  80860. strm->total_in = strm->total_out = 0;
  80861. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  80862. strm->data_type = Z_UNKNOWN;
  80863. s = (deflate_state *)strm->state;
  80864. s->pending = 0;
  80865. s->pending_out = s->pending_buf;
  80866. if (s->wrap < 0) {
  80867. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  80868. }
  80869. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  80870. strm->adler =
  80871. #ifdef GZIP
  80872. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  80873. #endif
  80874. adler32(0L, Z_NULL, 0);
  80875. s->last_flush = Z_NO_FLUSH;
  80876. _tr_init(s);
  80877. lm_init(s);
  80878. return Z_OK;
  80879. }
  80880. /* ========================================================================= */
  80881. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  80882. {
  80883. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80884. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  80885. strm->state->gzhead = head;
  80886. return Z_OK;
  80887. }
  80888. /* ========================================================================= */
  80889. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  80890. {
  80891. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80892. strm->state->bi_valid = bits;
  80893. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  80894. return Z_OK;
  80895. }
  80896. /* ========================================================================= */
  80897. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  80898. {
  80899. deflate_state *s;
  80900. compress_func func;
  80901. int err = Z_OK;
  80902. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80903. s = strm->state;
  80904. #ifdef FASTEST
  80905. if (level != 0) level = 1;
  80906. #else
  80907. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80908. #endif
  80909. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  80910. return Z_STREAM_ERROR;
  80911. }
  80912. func = configuration_table[s->level].func;
  80913. if (func != configuration_table[level].func && strm->total_in != 0) {
  80914. /* Flush the last buffer: */
  80915. err = deflate(strm, Z_PARTIAL_FLUSH);
  80916. }
  80917. if (s->level != level) {
  80918. s->level = level;
  80919. s->max_lazy_match = configuration_table[level].max_lazy;
  80920. s->good_match = configuration_table[level].good_length;
  80921. s->nice_match = configuration_table[level].nice_length;
  80922. s->max_chain_length = configuration_table[level].max_chain;
  80923. }
  80924. s->strategy = strategy;
  80925. return err;
  80926. }
  80927. /* ========================================================================= */
  80928. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  80929. {
  80930. deflate_state *s;
  80931. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80932. s = strm->state;
  80933. s->good_match = good_length;
  80934. s->max_lazy_match = max_lazy;
  80935. s->nice_match = nice_length;
  80936. s->max_chain_length = max_chain;
  80937. return Z_OK;
  80938. }
  80939. /* =========================================================================
  80940. * For the default windowBits of 15 and memLevel of 8, this function returns
  80941. * a close to exact, as well as small, upper bound on the compressed size.
  80942. * They are coded as constants here for a reason--if the #define's are
  80943. * changed, then this function needs to be changed as well. The return
  80944. * value for 15 and 8 only works for those exact settings.
  80945. *
  80946. * For any setting other than those defaults for windowBits and memLevel,
  80947. * the value returned is a conservative worst case for the maximum expansion
  80948. * resulting from using fixed blocks instead of stored blocks, which deflate
  80949. * can emit on compressed data for some combinations of the parameters.
  80950. *
  80951. * This function could be more sophisticated to provide closer upper bounds
  80952. * for every combination of windowBits and memLevel, as well as wrap.
  80953. * But even the conservative upper bound of about 14% expansion does not
  80954. * seem onerous for output buffer allocation.
  80955. */
  80956. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  80957. {
  80958. deflate_state *s;
  80959. uLong destLen;
  80960. /* conservative upper bound */
  80961. destLen = sourceLen +
  80962. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  80963. /* if can't get parameters, return conservative bound */
  80964. if (strm == Z_NULL || strm->state == Z_NULL)
  80965. return destLen;
  80966. /* if not default parameters, return conservative bound */
  80967. s = strm->state;
  80968. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  80969. return destLen;
  80970. /* default settings: return tight bound for that case */
  80971. return compressBound(sourceLen);
  80972. }
  80973. /* =========================================================================
  80974. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  80975. * IN assertion: the stream state is correct and there is enough room in
  80976. * pending_buf.
  80977. */
  80978. local void putShortMSB (deflate_state *s, uInt b)
  80979. {
  80980. put_byte(s, (Byte)(b >> 8));
  80981. put_byte(s, (Byte)(b & 0xff));
  80982. }
  80983. /* =========================================================================
  80984. * Flush as much pending output as possible. All deflate() output goes
  80985. * through this function so some applications may wish to modify it
  80986. * to avoid allocating a large strm->next_out buffer and copying into it.
  80987. * (See also read_buf()).
  80988. */
  80989. local void flush_pending (z_streamp strm)
  80990. {
  80991. unsigned len = strm->state->pending;
  80992. if (len > strm->avail_out) len = strm->avail_out;
  80993. if (len == 0) return;
  80994. zmemcpy(strm->next_out, strm->state->pending_out, len);
  80995. strm->next_out += len;
  80996. strm->state->pending_out += len;
  80997. strm->total_out += len;
  80998. strm->avail_out -= len;
  80999. strm->state->pending -= len;
  81000. if (strm->state->pending == 0) {
  81001. strm->state->pending_out = strm->state->pending_buf;
  81002. }
  81003. }
  81004. /* ========================================================================= */
  81005. int ZEXPORT deflate (z_streamp strm, int flush)
  81006. {
  81007. int old_flush; /* value of flush param for previous deflate call */
  81008. deflate_state *s;
  81009. if (strm == Z_NULL || strm->state == Z_NULL ||
  81010. flush > Z_FINISH || flush < 0) {
  81011. return Z_STREAM_ERROR;
  81012. }
  81013. s = strm->state;
  81014. if (strm->next_out == Z_NULL ||
  81015. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81016. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81017. ERR_RETURN(strm, Z_STREAM_ERROR);
  81018. }
  81019. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81020. s->strm = strm; /* just in case */
  81021. old_flush = s->last_flush;
  81022. s->last_flush = flush;
  81023. /* Write the header */
  81024. if (s->status == INIT_STATE) {
  81025. #ifdef GZIP
  81026. if (s->wrap == 2) {
  81027. strm->adler = crc32(0L, Z_NULL, 0);
  81028. put_byte(s, 31);
  81029. put_byte(s, 139);
  81030. put_byte(s, 8);
  81031. if (s->gzhead == NULL) {
  81032. put_byte(s, 0);
  81033. put_byte(s, 0);
  81034. put_byte(s, 0);
  81035. put_byte(s, 0);
  81036. put_byte(s, 0);
  81037. put_byte(s, s->level == 9 ? 2 :
  81038. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81039. 4 : 0));
  81040. put_byte(s, OS_CODE);
  81041. s->status = BUSY_STATE;
  81042. }
  81043. else {
  81044. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81045. (s->gzhead->hcrc ? 2 : 0) +
  81046. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81047. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81048. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81049. );
  81050. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81051. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81052. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81053. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81054. put_byte(s, s->level == 9 ? 2 :
  81055. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81056. 4 : 0));
  81057. put_byte(s, s->gzhead->os & 0xff);
  81058. if (s->gzhead->extra != NULL) {
  81059. put_byte(s, s->gzhead->extra_len & 0xff);
  81060. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81061. }
  81062. if (s->gzhead->hcrc)
  81063. strm->adler = crc32(strm->adler, s->pending_buf,
  81064. s->pending);
  81065. s->gzindex = 0;
  81066. s->status = EXTRA_STATE;
  81067. }
  81068. }
  81069. else
  81070. #endif
  81071. {
  81072. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81073. uInt level_flags;
  81074. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81075. level_flags = 0;
  81076. else if (s->level < 6)
  81077. level_flags = 1;
  81078. else if (s->level == 6)
  81079. level_flags = 2;
  81080. else
  81081. level_flags = 3;
  81082. header |= (level_flags << 6);
  81083. if (s->strstart != 0) header |= PRESET_DICT;
  81084. header += 31 - (header % 31);
  81085. s->status = BUSY_STATE;
  81086. putShortMSB(s, header);
  81087. /* Save the adler32 of the preset dictionary: */
  81088. if (s->strstart != 0) {
  81089. putShortMSB(s, (uInt)(strm->adler >> 16));
  81090. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81091. }
  81092. strm->adler = adler32(0L, Z_NULL, 0);
  81093. }
  81094. }
  81095. #ifdef GZIP
  81096. if (s->status == EXTRA_STATE) {
  81097. if (s->gzhead->extra != NULL) {
  81098. uInt beg = s->pending; /* start of bytes to update crc */
  81099. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81100. if (s->pending == s->pending_buf_size) {
  81101. if (s->gzhead->hcrc && s->pending > beg)
  81102. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81103. s->pending - beg);
  81104. flush_pending(strm);
  81105. beg = s->pending;
  81106. if (s->pending == s->pending_buf_size)
  81107. break;
  81108. }
  81109. put_byte(s, s->gzhead->extra[s->gzindex]);
  81110. s->gzindex++;
  81111. }
  81112. if (s->gzhead->hcrc && s->pending > beg)
  81113. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81114. s->pending - beg);
  81115. if (s->gzindex == s->gzhead->extra_len) {
  81116. s->gzindex = 0;
  81117. s->status = NAME_STATE;
  81118. }
  81119. }
  81120. else
  81121. s->status = NAME_STATE;
  81122. }
  81123. if (s->status == NAME_STATE) {
  81124. if (s->gzhead->name != NULL) {
  81125. uInt beg = s->pending; /* start of bytes to update crc */
  81126. int val;
  81127. do {
  81128. if (s->pending == s->pending_buf_size) {
  81129. if (s->gzhead->hcrc && s->pending > beg)
  81130. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81131. s->pending - beg);
  81132. flush_pending(strm);
  81133. beg = s->pending;
  81134. if (s->pending == s->pending_buf_size) {
  81135. val = 1;
  81136. break;
  81137. }
  81138. }
  81139. val = s->gzhead->name[s->gzindex++];
  81140. put_byte(s, val);
  81141. } while (val != 0);
  81142. if (s->gzhead->hcrc && s->pending > beg)
  81143. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81144. s->pending - beg);
  81145. if (val == 0) {
  81146. s->gzindex = 0;
  81147. s->status = COMMENT_STATE;
  81148. }
  81149. }
  81150. else
  81151. s->status = COMMENT_STATE;
  81152. }
  81153. if (s->status == COMMENT_STATE) {
  81154. if (s->gzhead->comment != NULL) {
  81155. uInt beg = s->pending; /* start of bytes to update crc */
  81156. int val;
  81157. do {
  81158. if (s->pending == s->pending_buf_size) {
  81159. if (s->gzhead->hcrc && s->pending > beg)
  81160. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81161. s->pending - beg);
  81162. flush_pending(strm);
  81163. beg = s->pending;
  81164. if (s->pending == s->pending_buf_size) {
  81165. val = 1;
  81166. break;
  81167. }
  81168. }
  81169. val = s->gzhead->comment[s->gzindex++];
  81170. put_byte(s, val);
  81171. } while (val != 0);
  81172. if (s->gzhead->hcrc && s->pending > beg)
  81173. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81174. s->pending - beg);
  81175. if (val == 0)
  81176. s->status = HCRC_STATE;
  81177. }
  81178. else
  81179. s->status = HCRC_STATE;
  81180. }
  81181. if (s->status == HCRC_STATE) {
  81182. if (s->gzhead->hcrc) {
  81183. if (s->pending + 2 > s->pending_buf_size)
  81184. flush_pending(strm);
  81185. if (s->pending + 2 <= s->pending_buf_size) {
  81186. put_byte(s, (Byte)(strm->adler & 0xff));
  81187. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81188. strm->adler = crc32(0L, Z_NULL, 0);
  81189. s->status = BUSY_STATE;
  81190. }
  81191. }
  81192. else
  81193. s->status = BUSY_STATE;
  81194. }
  81195. #endif
  81196. /* Flush as much pending output as possible */
  81197. if (s->pending != 0) {
  81198. flush_pending(strm);
  81199. if (strm->avail_out == 0) {
  81200. /* Since avail_out is 0, deflate will be called again with
  81201. * more output space, but possibly with both pending and
  81202. * avail_in equal to zero. There won't be anything to do,
  81203. * but this is not an error situation so make sure we
  81204. * return OK instead of BUF_ERROR at next call of deflate:
  81205. */
  81206. s->last_flush = -1;
  81207. return Z_OK;
  81208. }
  81209. /* Make sure there is something to do and avoid duplicate consecutive
  81210. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81211. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81212. */
  81213. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81214. flush != Z_FINISH) {
  81215. ERR_RETURN(strm, Z_BUF_ERROR);
  81216. }
  81217. /* User must not provide more input after the first FINISH: */
  81218. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81219. ERR_RETURN(strm, Z_BUF_ERROR);
  81220. }
  81221. /* Start a new block or continue the current one.
  81222. */
  81223. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81224. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81225. block_state bstate;
  81226. bstate = (*(configuration_table[s->level].func))(s, flush);
  81227. if (bstate == finish_started || bstate == finish_done) {
  81228. s->status = FINISH_STATE;
  81229. }
  81230. if (bstate == need_more || bstate == finish_started) {
  81231. if (strm->avail_out == 0) {
  81232. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81233. }
  81234. return Z_OK;
  81235. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81236. * of deflate should use the same flush parameter to make sure
  81237. * that the flush is complete. So we don't have to output an
  81238. * empty block here, this will be done at next call. This also
  81239. * ensures that for a very small output buffer, we emit at most
  81240. * one empty block.
  81241. */
  81242. }
  81243. if (bstate == block_done) {
  81244. if (flush == Z_PARTIAL_FLUSH) {
  81245. _tr_align(s);
  81246. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81247. _tr_stored_block(s, (char*)0, 0L, 0);
  81248. /* For a full flush, this empty block will be recognized
  81249. * as a special marker by inflate_sync().
  81250. */
  81251. if (flush == Z_FULL_FLUSH) {
  81252. CLEAR_HASH(s); /* forget history */
  81253. }
  81254. }
  81255. flush_pending(strm);
  81256. if (strm->avail_out == 0) {
  81257. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81258. return Z_OK;
  81259. }
  81260. }
  81261. }
  81262. Assert(strm->avail_out > 0, "bug2");
  81263. if (flush != Z_FINISH) return Z_OK;
  81264. if (s->wrap <= 0) return Z_STREAM_END;
  81265. /* Write the trailer */
  81266. #ifdef GZIP
  81267. if (s->wrap == 2) {
  81268. put_byte(s, (Byte)(strm->adler & 0xff));
  81269. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81270. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81271. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81272. put_byte(s, (Byte)(strm->total_in & 0xff));
  81273. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81274. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81275. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81276. }
  81277. else
  81278. #endif
  81279. {
  81280. putShortMSB(s, (uInt)(strm->adler >> 16));
  81281. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81282. }
  81283. flush_pending(strm);
  81284. /* If avail_out is zero, the application will call deflate again
  81285. * to flush the rest.
  81286. */
  81287. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81288. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81289. }
  81290. /* ========================================================================= */
  81291. int ZEXPORT deflateEnd (z_streamp strm)
  81292. {
  81293. int status;
  81294. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81295. status = strm->state->status;
  81296. if (status != INIT_STATE &&
  81297. status != EXTRA_STATE &&
  81298. status != NAME_STATE &&
  81299. status != COMMENT_STATE &&
  81300. status != HCRC_STATE &&
  81301. status != BUSY_STATE &&
  81302. status != FINISH_STATE) {
  81303. return Z_STREAM_ERROR;
  81304. }
  81305. /* Deallocate in reverse order of allocations: */
  81306. TRY_FREE(strm, strm->state->pending_buf);
  81307. TRY_FREE(strm, strm->state->head);
  81308. TRY_FREE(strm, strm->state->prev);
  81309. TRY_FREE(strm, strm->state->window);
  81310. ZFREE(strm, strm->state);
  81311. strm->state = Z_NULL;
  81312. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81313. }
  81314. /* =========================================================================
  81315. * Copy the source state to the destination state.
  81316. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81317. * doesn't have enough memory anyway to duplicate compression states).
  81318. */
  81319. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81320. {
  81321. #ifdef MAXSEG_64K
  81322. return Z_STREAM_ERROR;
  81323. #else
  81324. deflate_state *ds;
  81325. deflate_state *ss;
  81326. ushf *overlay;
  81327. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81328. return Z_STREAM_ERROR;
  81329. }
  81330. ss = source->state;
  81331. zmemcpy(dest, source, sizeof(z_stream));
  81332. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81333. if (ds == Z_NULL) return Z_MEM_ERROR;
  81334. dest->state = (struct internal_state FAR *) ds;
  81335. zmemcpy(ds, ss, sizeof(deflate_state));
  81336. ds->strm = dest;
  81337. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81338. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81339. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81340. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81341. ds->pending_buf = (uchf *) overlay;
  81342. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81343. ds->pending_buf == Z_NULL) {
  81344. deflateEnd (dest);
  81345. return Z_MEM_ERROR;
  81346. }
  81347. /* following zmemcpy do not work for 16-bit MSDOS */
  81348. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81349. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81350. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81351. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81352. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81353. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81354. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81355. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81356. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81357. ds->bl_desc.dyn_tree = ds->bl_tree;
  81358. return Z_OK;
  81359. #endif /* MAXSEG_64K */
  81360. }
  81361. /* ===========================================================================
  81362. * Read a new buffer from the current input stream, update the adler32
  81363. * and total number of bytes read. All deflate() input goes through
  81364. * this function so some applications may wish to modify it to avoid
  81365. * allocating a large strm->next_in buffer and copying from it.
  81366. * (See also flush_pending()).
  81367. */
  81368. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81369. {
  81370. unsigned len = strm->avail_in;
  81371. if (len > size) len = size;
  81372. if (len == 0) return 0;
  81373. strm->avail_in -= len;
  81374. if (strm->state->wrap == 1) {
  81375. strm->adler = adler32(strm->adler, strm->next_in, len);
  81376. }
  81377. #ifdef GZIP
  81378. else if (strm->state->wrap == 2) {
  81379. strm->adler = crc32(strm->adler, strm->next_in, len);
  81380. }
  81381. #endif
  81382. zmemcpy(buf, strm->next_in, len);
  81383. strm->next_in += len;
  81384. strm->total_in += len;
  81385. return (int)len;
  81386. }
  81387. /* ===========================================================================
  81388. * Initialize the "longest match" routines for a new zlib stream
  81389. */
  81390. local void lm_init (deflate_state *s)
  81391. {
  81392. s->window_size = (ulg)2L*s->w_size;
  81393. CLEAR_HASH(s);
  81394. /* Set the default configuration parameters:
  81395. */
  81396. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81397. s->good_match = configuration_table[s->level].good_length;
  81398. s->nice_match = configuration_table[s->level].nice_length;
  81399. s->max_chain_length = configuration_table[s->level].max_chain;
  81400. s->strstart = 0;
  81401. s->block_start = 0L;
  81402. s->lookahead = 0;
  81403. s->match_length = s->prev_length = MIN_MATCH-1;
  81404. s->match_available = 0;
  81405. s->ins_h = 0;
  81406. #ifndef FASTEST
  81407. #ifdef ASMV
  81408. match_init(); /* initialize the asm code */
  81409. #endif
  81410. #endif
  81411. }
  81412. #ifndef FASTEST
  81413. /* ===========================================================================
  81414. * Set match_start to the longest match starting at the given string and
  81415. * return its length. Matches shorter or equal to prev_length are discarded,
  81416. * in which case the result is equal to prev_length and match_start is
  81417. * garbage.
  81418. * IN assertions: cur_match is the head of the hash chain for the current
  81419. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81420. * OUT assertion: the match length is not greater than s->lookahead.
  81421. */
  81422. #ifndef ASMV
  81423. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81424. * match.S. The code will be functionally equivalent.
  81425. */
  81426. local uInt longest_match(deflate_state *s, IPos cur_match)
  81427. {
  81428. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81429. register Bytef *scan = s->window + s->strstart; /* current string */
  81430. register Bytef *match; /* matched string */
  81431. register int len; /* length of current match */
  81432. int best_len = s->prev_length; /* best match length so far */
  81433. int nice_match = s->nice_match; /* stop if match long enough */
  81434. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81435. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81436. /* Stop when cur_match becomes <= limit. To simplify the code,
  81437. * we prevent matches with the string of window index 0.
  81438. */
  81439. Posf *prev = s->prev;
  81440. uInt wmask = s->w_mask;
  81441. #ifdef UNALIGNED_OK
  81442. /* Compare two bytes at a time. Note: this is not always beneficial.
  81443. * Try with and without -DUNALIGNED_OK to check.
  81444. */
  81445. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81446. register ush scan_start = *(ushf*)scan;
  81447. register ush scan_end = *(ushf*)(scan+best_len-1);
  81448. #else
  81449. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81450. register Byte scan_end1 = scan[best_len-1];
  81451. register Byte scan_end = scan[best_len];
  81452. #endif
  81453. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81454. * It is easy to get rid of this optimization if necessary.
  81455. */
  81456. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81457. /* Do not waste too much time if we already have a good match: */
  81458. if (s->prev_length >= s->good_match) {
  81459. chain_length >>= 2;
  81460. }
  81461. /* Do not look for matches beyond the end of the input. This is necessary
  81462. * to make deflate deterministic.
  81463. */
  81464. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81465. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81466. do {
  81467. Assert(cur_match < s->strstart, "no future");
  81468. match = s->window + cur_match;
  81469. /* Skip to next match if the match length cannot increase
  81470. * or if the match length is less than 2. Note that the checks below
  81471. * for insufficient lookahead only occur occasionally for performance
  81472. * reasons. Therefore uninitialized memory will be accessed, and
  81473. * conditional jumps will be made that depend on those values.
  81474. * However the length of the match is limited to the lookahead, so
  81475. * the output of deflate is not affected by the uninitialized values.
  81476. */
  81477. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81478. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81479. * UNALIGNED_OK if your compiler uses a different size.
  81480. */
  81481. if (*(ushf*)(match+best_len-1) != scan_end ||
  81482. *(ushf*)match != scan_start) continue;
  81483. /* It is not necessary to compare scan[2] and match[2] since they are
  81484. * always equal when the other bytes match, given that the hash keys
  81485. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81486. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81487. * lookahead only every 4th comparison; the 128th check will be made
  81488. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81489. * necessary to put more guard bytes at the end of the window, or
  81490. * to check more often for insufficient lookahead.
  81491. */
  81492. Assert(scan[2] == match[2], "scan[2]?");
  81493. scan++, match++;
  81494. do {
  81495. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81496. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81497. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81498. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81499. scan < strend);
  81500. /* The funny "do {}" generates better code on most compilers */
  81501. /* Here, scan <= window+strstart+257 */
  81502. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81503. if (*scan == *match) scan++;
  81504. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81505. scan = strend - (MAX_MATCH-1);
  81506. #else /* UNALIGNED_OK */
  81507. if (match[best_len] != scan_end ||
  81508. match[best_len-1] != scan_end1 ||
  81509. *match != *scan ||
  81510. *++match != scan[1]) continue;
  81511. /* The check at best_len-1 can be removed because it will be made
  81512. * again later. (This heuristic is not always a win.)
  81513. * It is not necessary to compare scan[2] and match[2] since they
  81514. * are always equal when the other bytes match, given that
  81515. * the hash keys are equal and that HASH_BITS >= 8.
  81516. */
  81517. scan += 2, match++;
  81518. Assert(*scan == *match, "match[2]?");
  81519. /* We check for insufficient lookahead only every 8th comparison;
  81520. * the 256th check will be made at strstart+258.
  81521. */
  81522. do {
  81523. } while (*++scan == *++match && *++scan == *++match &&
  81524. *++scan == *++match && *++scan == *++match &&
  81525. *++scan == *++match && *++scan == *++match &&
  81526. *++scan == *++match && *++scan == *++match &&
  81527. scan < strend);
  81528. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81529. len = MAX_MATCH - (int)(strend - scan);
  81530. scan = strend - MAX_MATCH;
  81531. #endif /* UNALIGNED_OK */
  81532. if (len > best_len) {
  81533. s->match_start = cur_match;
  81534. best_len = len;
  81535. if (len >= nice_match) break;
  81536. #ifdef UNALIGNED_OK
  81537. scan_end = *(ushf*)(scan+best_len-1);
  81538. #else
  81539. scan_end1 = scan[best_len-1];
  81540. scan_end = scan[best_len];
  81541. #endif
  81542. }
  81543. } while ((cur_match = prev[cur_match & wmask]) > limit
  81544. && --chain_length != 0);
  81545. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81546. return s->lookahead;
  81547. }
  81548. #endif /* ASMV */
  81549. #endif /* FASTEST */
  81550. /* ---------------------------------------------------------------------------
  81551. * Optimized version for level == 1 or strategy == Z_RLE only
  81552. */
  81553. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81554. {
  81555. register Bytef *scan = s->window + s->strstart; /* current string */
  81556. register Bytef *match; /* matched string */
  81557. register int len; /* length of current match */
  81558. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81559. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81560. * It is easy to get rid of this optimization if necessary.
  81561. */
  81562. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81563. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81564. Assert(cur_match < s->strstart, "no future");
  81565. match = s->window + cur_match;
  81566. /* Return failure if the match length is less than 2:
  81567. */
  81568. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81569. /* The check at best_len-1 can be removed because it will be made
  81570. * again later. (This heuristic is not always a win.)
  81571. * It is not necessary to compare scan[2] and match[2] since they
  81572. * are always equal when the other bytes match, given that
  81573. * the hash keys are equal and that HASH_BITS >= 8.
  81574. */
  81575. scan += 2, match += 2;
  81576. Assert(*scan == *match, "match[2]?");
  81577. /* We check for insufficient lookahead only every 8th comparison;
  81578. * the 256th check will be made at strstart+258.
  81579. */
  81580. do {
  81581. } while (*++scan == *++match && *++scan == *++match &&
  81582. *++scan == *++match && *++scan == *++match &&
  81583. *++scan == *++match && *++scan == *++match &&
  81584. *++scan == *++match && *++scan == *++match &&
  81585. scan < strend);
  81586. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81587. len = MAX_MATCH - (int)(strend - scan);
  81588. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81589. s->match_start = cur_match;
  81590. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81591. }
  81592. #ifdef DEBUG
  81593. /* ===========================================================================
  81594. * Check that the match at match_start is indeed a match.
  81595. */
  81596. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81597. {
  81598. /* check that the match is indeed a match */
  81599. if (zmemcmp(s->window + match,
  81600. s->window + start, length) != EQUAL) {
  81601. fprintf(stderr, " start %u, match %u, length %d\n",
  81602. start, match, length);
  81603. do {
  81604. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81605. } while (--length != 0);
  81606. z_error("invalid match");
  81607. }
  81608. if (z_verbose > 1) {
  81609. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81610. do { putc(s->window[start++], stderr); } while (--length != 0);
  81611. }
  81612. }
  81613. #else
  81614. # define check_match(s, start, match, length)
  81615. #endif /* DEBUG */
  81616. /* ===========================================================================
  81617. * Fill the window when the lookahead becomes insufficient.
  81618. * Updates strstart and lookahead.
  81619. *
  81620. * IN assertion: lookahead < MIN_LOOKAHEAD
  81621. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81622. * At least one byte has been read, or avail_in == 0; reads are
  81623. * performed for at least two bytes (required for the zip translate_eol
  81624. * option -- not supported here).
  81625. */
  81626. local void fill_window (deflate_state *s)
  81627. {
  81628. register unsigned n, m;
  81629. register Posf *p;
  81630. unsigned more; /* Amount of free space at the end of the window. */
  81631. uInt wsize = s->w_size;
  81632. do {
  81633. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81634. /* Deal with !@#$% 64K limit: */
  81635. if (sizeof(int) <= 2) {
  81636. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81637. more = wsize;
  81638. } else if (more == (unsigned)(-1)) {
  81639. /* Very unlikely, but possible on 16 bit machine if
  81640. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81641. */
  81642. more--;
  81643. }
  81644. }
  81645. /* If the window is almost full and there is insufficient lookahead,
  81646. * move the upper half to the lower one to make room in the upper half.
  81647. */
  81648. if (s->strstart >= wsize+MAX_DIST(s)) {
  81649. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81650. s->match_start -= wsize;
  81651. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81652. s->block_start -= (long) wsize;
  81653. /* Slide the hash table (could be avoided with 32 bit values
  81654. at the expense of memory usage). We slide even when level == 0
  81655. to keep the hash table consistent if we switch back to level > 0
  81656. later. (Using level 0 permanently is not an optimal usage of
  81657. zlib, so we don't care about this pathological case.)
  81658. */
  81659. /* %%% avoid this when Z_RLE */
  81660. n = s->hash_size;
  81661. p = &s->head[n];
  81662. do {
  81663. m = *--p;
  81664. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81665. } while (--n);
  81666. n = wsize;
  81667. #ifndef FASTEST
  81668. p = &s->prev[n];
  81669. do {
  81670. m = *--p;
  81671. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81672. /* If n is not on any hash chain, prev[n] is garbage but
  81673. * its value will never be used.
  81674. */
  81675. } while (--n);
  81676. #endif
  81677. more += wsize;
  81678. }
  81679. if (s->strm->avail_in == 0) return;
  81680. /* If there was no sliding:
  81681. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81682. * more == window_size - lookahead - strstart
  81683. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81684. * => more >= window_size - 2*WSIZE + 2
  81685. * In the BIG_MEM or MMAP case (not yet supported),
  81686. * window_size == input_size + MIN_LOOKAHEAD &&
  81687. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81688. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81689. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81690. */
  81691. Assert(more >= 2, "more < 2");
  81692. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81693. s->lookahead += n;
  81694. /* Initialize the hash value now that we have some input: */
  81695. if (s->lookahead >= MIN_MATCH) {
  81696. s->ins_h = s->window[s->strstart];
  81697. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81698. #if MIN_MATCH != 3
  81699. Call UPDATE_HASH() MIN_MATCH-3 more times
  81700. #endif
  81701. }
  81702. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81703. * but this is not important since only literal bytes will be emitted.
  81704. */
  81705. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81706. }
  81707. /* ===========================================================================
  81708. * Flush the current block, with given end-of-file flag.
  81709. * IN assertion: strstart is set to the end of the current match.
  81710. */
  81711. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81712. _tr_flush_block(s, (s->block_start >= 0L ? \
  81713. (charf *)&s->window[(unsigned)s->block_start] : \
  81714. (charf *)Z_NULL), \
  81715. (ulg)((long)s->strstart - s->block_start), \
  81716. (eof)); \
  81717. s->block_start = s->strstart; \
  81718. flush_pending(s->strm); \
  81719. Tracev((stderr,"[FLUSH]")); \
  81720. }
  81721. /* Same but force premature exit if necessary. */
  81722. #define FLUSH_BLOCK(s, eof) { \
  81723. FLUSH_BLOCK_ONLY(s, eof); \
  81724. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81725. }
  81726. /* ===========================================================================
  81727. * Copy without compression as much as possible from the input stream, return
  81728. * the current block state.
  81729. * This function does not insert new strings in the dictionary since
  81730. * uncompressible data is probably not useful. This function is used
  81731. * only for the level=0 compression option.
  81732. * NOTE: this function should be optimized to avoid extra copying from
  81733. * window to pending_buf.
  81734. */
  81735. local block_state deflate_stored(deflate_state *s, int flush)
  81736. {
  81737. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81738. * to pending_buf_size, and each stored block has a 5 byte header:
  81739. */
  81740. ulg max_block_size = 0xffff;
  81741. ulg max_start;
  81742. if (max_block_size > s->pending_buf_size - 5) {
  81743. max_block_size = s->pending_buf_size - 5;
  81744. }
  81745. /* Copy as much as possible from input to output: */
  81746. for (;;) {
  81747. /* Fill the window as much as possible: */
  81748. if (s->lookahead <= 1) {
  81749. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81750. s->block_start >= (long)s->w_size, "slide too late");
  81751. fill_window(s);
  81752. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81753. if (s->lookahead == 0) break; /* flush the current block */
  81754. }
  81755. Assert(s->block_start >= 0L, "block gone");
  81756. s->strstart += s->lookahead;
  81757. s->lookahead = 0;
  81758. /* Emit a stored block if pending_buf will be full: */
  81759. max_start = s->block_start + max_block_size;
  81760. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81761. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81762. s->lookahead = (uInt)(s->strstart - max_start);
  81763. s->strstart = (uInt)max_start;
  81764. FLUSH_BLOCK(s, 0);
  81765. }
  81766. /* Flush if we may have to slide, otherwise block_start may become
  81767. * negative and the data will be gone:
  81768. */
  81769. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81770. FLUSH_BLOCK(s, 0);
  81771. }
  81772. }
  81773. FLUSH_BLOCK(s, flush == Z_FINISH);
  81774. return flush == Z_FINISH ? finish_done : block_done;
  81775. }
  81776. /* ===========================================================================
  81777. * Compress as much as possible from the input stream, return the current
  81778. * block state.
  81779. * This function does not perform lazy evaluation of matches and inserts
  81780. * new strings in the dictionary only for unmatched strings or for short
  81781. * matches. It is used only for the fast compression options.
  81782. */
  81783. local block_state deflate_fast(deflate_state *s, int flush)
  81784. {
  81785. IPos hash_head = NIL; /* head of the hash chain */
  81786. int bflush; /* set if current block must be flushed */
  81787. for (;;) {
  81788. /* Make sure that we always have enough lookahead, except
  81789. * at the end of the input file. We need MAX_MATCH bytes
  81790. * for the next match, plus MIN_MATCH bytes to insert the
  81791. * string following the next match.
  81792. */
  81793. if (s->lookahead < MIN_LOOKAHEAD) {
  81794. fill_window(s);
  81795. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81796. return need_more;
  81797. }
  81798. if (s->lookahead == 0) break; /* flush the current block */
  81799. }
  81800. /* Insert the string window[strstart .. strstart+2] in the
  81801. * dictionary, and set hash_head to the head of the hash chain:
  81802. */
  81803. if (s->lookahead >= MIN_MATCH) {
  81804. INSERT_STRING(s, s->strstart, hash_head);
  81805. }
  81806. /* Find the longest match, discarding those <= prev_length.
  81807. * At this point we have always match_length < MIN_MATCH
  81808. */
  81809. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  81810. /* To simplify the code, we prevent matches with the string
  81811. * of window index 0 (in particular we have to avoid a match
  81812. * of the string with itself at the start of the input file).
  81813. */
  81814. #ifdef FASTEST
  81815. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  81816. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  81817. s->match_length = longest_match_fast (s, hash_head);
  81818. }
  81819. #else
  81820. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81821. s->match_length = longest_match (s, hash_head);
  81822. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81823. s->match_length = longest_match_fast (s, hash_head);
  81824. }
  81825. #endif
  81826. /* longest_match() or longest_match_fast() sets match_start */
  81827. }
  81828. if (s->match_length >= MIN_MATCH) {
  81829. check_match(s, s->strstart, s->match_start, s->match_length);
  81830. _tr_tally_dist(s, s->strstart - s->match_start,
  81831. s->match_length - MIN_MATCH, bflush);
  81832. s->lookahead -= s->match_length;
  81833. /* Insert new strings in the hash table only if the match length
  81834. * is not too large. This saves time but degrades compression.
  81835. */
  81836. #ifndef FASTEST
  81837. if (s->match_length <= s->max_insert_length &&
  81838. s->lookahead >= MIN_MATCH) {
  81839. s->match_length--; /* string at strstart already in table */
  81840. do {
  81841. s->strstart++;
  81842. INSERT_STRING(s, s->strstart, hash_head);
  81843. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  81844. * always MIN_MATCH bytes ahead.
  81845. */
  81846. } while (--s->match_length != 0);
  81847. s->strstart++;
  81848. } else
  81849. #endif
  81850. {
  81851. s->strstart += s->match_length;
  81852. s->match_length = 0;
  81853. s->ins_h = s->window[s->strstart];
  81854. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81855. #if MIN_MATCH != 3
  81856. Call UPDATE_HASH() MIN_MATCH-3 more times
  81857. #endif
  81858. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  81859. * matter since it will be recomputed at next deflate call.
  81860. */
  81861. }
  81862. } else {
  81863. /* No match, output a literal byte */
  81864. Tracevv((stderr,"%c", s->window[s->strstart]));
  81865. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81866. s->lookahead--;
  81867. s->strstart++;
  81868. }
  81869. if (bflush) FLUSH_BLOCK(s, 0);
  81870. }
  81871. FLUSH_BLOCK(s, flush == Z_FINISH);
  81872. return flush == Z_FINISH ? finish_done : block_done;
  81873. }
  81874. #ifndef FASTEST
  81875. /* ===========================================================================
  81876. * Same as above, but achieves better compression. We use a lazy
  81877. * evaluation for matches: a match is finally adopted only if there is
  81878. * no better match at the next window position.
  81879. */
  81880. local block_state deflate_slow(deflate_state *s, int flush)
  81881. {
  81882. IPos hash_head = NIL; /* head of hash chain */
  81883. int bflush; /* set if current block must be flushed */
  81884. /* Process the input block. */
  81885. for (;;) {
  81886. /* Make sure that we always have enough lookahead, except
  81887. * at the end of the input file. We need MAX_MATCH bytes
  81888. * for the next match, plus MIN_MATCH bytes to insert the
  81889. * string following the next match.
  81890. */
  81891. if (s->lookahead < MIN_LOOKAHEAD) {
  81892. fill_window(s);
  81893. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81894. return need_more;
  81895. }
  81896. if (s->lookahead == 0) break; /* flush the current block */
  81897. }
  81898. /* Insert the string window[strstart .. strstart+2] in the
  81899. * dictionary, and set hash_head to the head of the hash chain:
  81900. */
  81901. if (s->lookahead >= MIN_MATCH) {
  81902. INSERT_STRING(s, s->strstart, hash_head);
  81903. }
  81904. /* Find the longest match, discarding those <= prev_length.
  81905. */
  81906. s->prev_length = s->match_length, s->prev_match = s->match_start;
  81907. s->match_length = MIN_MATCH-1;
  81908. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  81909. s->strstart - hash_head <= MAX_DIST(s)) {
  81910. /* To simplify the code, we prevent matches with the string
  81911. * of window index 0 (in particular we have to avoid a match
  81912. * of the string with itself at the start of the input file).
  81913. */
  81914. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81915. s->match_length = longest_match (s, hash_head);
  81916. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81917. s->match_length = longest_match_fast (s, hash_head);
  81918. }
  81919. /* longest_match() or longest_match_fast() sets match_start */
  81920. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  81921. #if TOO_FAR <= 32767
  81922. || (s->match_length == MIN_MATCH &&
  81923. s->strstart - s->match_start > TOO_FAR)
  81924. #endif
  81925. )) {
  81926. /* If prev_match is also MIN_MATCH, match_start is garbage
  81927. * but we will ignore the current match anyway.
  81928. */
  81929. s->match_length = MIN_MATCH-1;
  81930. }
  81931. }
  81932. /* If there was a match at the previous step and the current
  81933. * match is not better, output the previous match:
  81934. */
  81935. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  81936. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  81937. /* Do not insert strings in hash table beyond this. */
  81938. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  81939. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  81940. s->prev_length - MIN_MATCH, bflush);
  81941. /* Insert in hash table all strings up to the end of the match.
  81942. * strstart-1 and strstart are already inserted. If there is not
  81943. * enough lookahead, the last two strings are not inserted in
  81944. * the hash table.
  81945. */
  81946. s->lookahead -= s->prev_length-1;
  81947. s->prev_length -= 2;
  81948. do {
  81949. if (++s->strstart <= max_insert) {
  81950. INSERT_STRING(s, s->strstart, hash_head);
  81951. }
  81952. } while (--s->prev_length != 0);
  81953. s->match_available = 0;
  81954. s->match_length = MIN_MATCH-1;
  81955. s->strstart++;
  81956. if (bflush) FLUSH_BLOCK(s, 0);
  81957. } else if (s->match_available) {
  81958. /* If there was no match at the previous position, output a
  81959. * single literal. If there was a match but the current match
  81960. * is longer, truncate the previous match to a single literal.
  81961. */
  81962. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81963. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81964. if (bflush) {
  81965. FLUSH_BLOCK_ONLY(s, 0);
  81966. }
  81967. s->strstart++;
  81968. s->lookahead--;
  81969. if (s->strm->avail_out == 0) return need_more;
  81970. } else {
  81971. /* There is no previous match to compare with, wait for
  81972. * the next step to decide.
  81973. */
  81974. s->match_available = 1;
  81975. s->strstart++;
  81976. s->lookahead--;
  81977. }
  81978. }
  81979. Assert (flush != Z_NO_FLUSH, "no flush?");
  81980. if (s->match_available) {
  81981. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81982. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81983. s->match_available = 0;
  81984. }
  81985. FLUSH_BLOCK(s, flush == Z_FINISH);
  81986. return flush == Z_FINISH ? finish_done : block_done;
  81987. }
  81988. #endif /* FASTEST */
  81989. #if 0
  81990. /* ===========================================================================
  81991. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  81992. * one. Do not maintain a hash table. (It will be regenerated if this run of
  81993. * deflate switches away from Z_RLE.)
  81994. */
  81995. local block_state deflate_rle(s, flush)
  81996. deflate_state *s;
  81997. int flush;
  81998. {
  81999. int bflush; /* set if current block must be flushed */
  82000. uInt run; /* length of run */
  82001. uInt max; /* maximum length of run */
  82002. uInt prev; /* byte at distance one to match */
  82003. Bytef *scan; /* scan for end of run */
  82004. for (;;) {
  82005. /* Make sure that we always have enough lookahead, except
  82006. * at the end of the input file. We need MAX_MATCH bytes
  82007. * for the longest encodable run.
  82008. */
  82009. if (s->lookahead < MAX_MATCH) {
  82010. fill_window(s);
  82011. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82012. return need_more;
  82013. }
  82014. if (s->lookahead == 0) break; /* flush the current block */
  82015. }
  82016. /* See how many times the previous byte repeats */
  82017. run = 0;
  82018. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82019. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82020. scan = s->window + s->strstart - 1;
  82021. prev = *scan++;
  82022. do {
  82023. if (*scan++ != prev)
  82024. break;
  82025. } while (++run < max);
  82026. }
  82027. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82028. if (run >= MIN_MATCH) {
  82029. check_match(s, s->strstart, s->strstart - 1, run);
  82030. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82031. s->lookahead -= run;
  82032. s->strstart += run;
  82033. } else {
  82034. /* No match, output a literal byte */
  82035. Tracevv((stderr,"%c", s->window[s->strstart]));
  82036. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82037. s->lookahead--;
  82038. s->strstart++;
  82039. }
  82040. if (bflush) FLUSH_BLOCK(s, 0);
  82041. }
  82042. FLUSH_BLOCK(s, flush == Z_FINISH);
  82043. return flush == Z_FINISH ? finish_done : block_done;
  82044. }
  82045. #endif
  82046. /*** End of inlined file: deflate.c ***/
  82047. /*** Start of inlined file: inffast.c ***/
  82048. /*** Start of inlined file: inftrees.h ***/
  82049. /* WARNING: this file should *not* be used by applications. It is
  82050. part of the implementation of the compression library and is
  82051. subject to change. Applications should only use zlib.h.
  82052. */
  82053. #ifndef _INFTREES_H_
  82054. #define _INFTREES_H_
  82055. /* Structure for decoding tables. Each entry provides either the
  82056. information needed to do the operation requested by the code that
  82057. indexed that table entry, or it provides a pointer to another
  82058. table that indexes more bits of the code. op indicates whether
  82059. the entry is a pointer to another table, a literal, a length or
  82060. distance, an end-of-block, or an invalid code. For a table
  82061. pointer, the low four bits of op is the number of index bits of
  82062. that table. For a length or distance, the low four bits of op
  82063. is the number of extra bits to get after the code. bits is
  82064. the number of bits in this code or part of the code to drop off
  82065. of the bit buffer. val is the actual byte to output in the case
  82066. of a literal, the base length or distance, or the offset from
  82067. the current table to the next table. Each entry is four bytes. */
  82068. typedef struct {
  82069. unsigned char op; /* operation, extra bits, table bits */
  82070. unsigned char bits; /* bits in this part of the code */
  82071. unsigned short val; /* offset in table or code value */
  82072. } code;
  82073. /* op values as set by inflate_table():
  82074. 00000000 - literal
  82075. 0000tttt - table link, tttt != 0 is the number of table index bits
  82076. 0001eeee - length or distance, eeee is the number of extra bits
  82077. 01100000 - end of block
  82078. 01000000 - invalid code
  82079. */
  82080. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82081. exhaustive search was 1444 code structures (852 for length/literals
  82082. and 592 for distances, the latter actually the result of an
  82083. exhaustive search). The true maximum is not known, but the value
  82084. below is more than safe. */
  82085. #define ENOUGH 2048
  82086. #define MAXD 592
  82087. /* Type of code to build for inftable() */
  82088. typedef enum {
  82089. CODES,
  82090. LENS,
  82091. DISTS
  82092. } codetype;
  82093. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82094. unsigned codes, code FAR * FAR *table,
  82095. unsigned FAR *bits, unsigned short FAR *work));
  82096. #endif
  82097. /*** End of inlined file: inftrees.h ***/
  82098. /*** Start of inlined file: inflate.h ***/
  82099. /* WARNING: this file should *not* be used by applications. It is
  82100. part of the implementation of the compression library and is
  82101. subject to change. Applications should only use zlib.h.
  82102. */
  82103. #ifndef _INFLATE_H_
  82104. #define _INFLATE_H_
  82105. /* define NO_GZIP when compiling if you want to disable gzip header and
  82106. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82107. the crc code when it is not needed. For shared libraries, gzip decoding
  82108. should be left enabled. */
  82109. #ifndef NO_GZIP
  82110. # define GUNZIP
  82111. #endif
  82112. /* Possible inflate modes between inflate() calls */
  82113. typedef enum {
  82114. HEAD, /* i: waiting for magic header */
  82115. FLAGS, /* i: waiting for method and flags (gzip) */
  82116. TIME, /* i: waiting for modification time (gzip) */
  82117. OS, /* i: waiting for extra flags and operating system (gzip) */
  82118. EXLEN, /* i: waiting for extra length (gzip) */
  82119. EXTRA, /* i: waiting for extra bytes (gzip) */
  82120. NAME, /* i: waiting for end of file name (gzip) */
  82121. COMMENT, /* i: waiting for end of comment (gzip) */
  82122. HCRC, /* i: waiting for header crc (gzip) */
  82123. DICTID, /* i: waiting for dictionary check value */
  82124. DICT, /* waiting for inflateSetDictionary() call */
  82125. TYPE, /* i: waiting for type bits, including last-flag bit */
  82126. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82127. STORED, /* i: waiting for stored size (length and complement) */
  82128. COPY, /* i/o: waiting for input or output to copy stored block */
  82129. TABLE, /* i: waiting for dynamic block table lengths */
  82130. LENLENS, /* i: waiting for code length code lengths */
  82131. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82132. LEN, /* i: waiting for length/lit code */
  82133. LENEXT, /* i: waiting for length extra bits */
  82134. DIST, /* i: waiting for distance code */
  82135. DISTEXT, /* i: waiting for distance extra bits */
  82136. MATCH, /* o: waiting for output space to copy string */
  82137. LIT, /* o: waiting for output space to write literal */
  82138. CHECK, /* i: waiting for 32-bit check value */
  82139. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82140. DONE, /* finished check, done -- remain here until reset */
  82141. BAD, /* got a data error -- remain here until reset */
  82142. MEM, /* got an inflate() memory error -- remain here until reset */
  82143. SYNC /* looking for synchronization bytes to restart inflate() */
  82144. } inflate_mode;
  82145. /*
  82146. State transitions between above modes -
  82147. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82148. Process header:
  82149. HEAD -> (gzip) or (zlib)
  82150. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82151. NAME -> COMMENT -> HCRC -> TYPE
  82152. (zlib) -> DICTID or TYPE
  82153. DICTID -> DICT -> TYPE
  82154. Read deflate blocks:
  82155. TYPE -> STORED or TABLE or LEN or CHECK
  82156. STORED -> COPY -> TYPE
  82157. TABLE -> LENLENS -> CODELENS -> LEN
  82158. Read deflate codes:
  82159. LEN -> LENEXT or LIT or TYPE
  82160. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82161. LIT -> LEN
  82162. Process trailer:
  82163. CHECK -> LENGTH -> DONE
  82164. */
  82165. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82166. struct inflate_state {
  82167. inflate_mode mode; /* current inflate mode */
  82168. int last; /* true if processing last block */
  82169. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82170. int havedict; /* true if dictionary provided */
  82171. int flags; /* gzip header method and flags (0 if zlib) */
  82172. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82173. unsigned long check; /* protected copy of check value */
  82174. unsigned long total; /* protected copy of output count */
  82175. gz_headerp head; /* where to save gzip header information */
  82176. /* sliding window */
  82177. unsigned wbits; /* log base 2 of requested window size */
  82178. unsigned wsize; /* window size or zero if not using window */
  82179. unsigned whave; /* valid bytes in the window */
  82180. unsigned write; /* window write index */
  82181. unsigned char FAR *window; /* allocated sliding window, if needed */
  82182. /* bit accumulator */
  82183. unsigned long hold; /* input bit accumulator */
  82184. unsigned bits; /* number of bits in "in" */
  82185. /* for string and stored block copying */
  82186. unsigned length; /* literal or length of data to copy */
  82187. unsigned offset; /* distance back to copy string from */
  82188. /* for table and code decoding */
  82189. unsigned extra; /* extra bits needed */
  82190. /* fixed and dynamic code tables */
  82191. code const FAR *lencode; /* starting table for length/literal codes */
  82192. code const FAR *distcode; /* starting table for distance codes */
  82193. unsigned lenbits; /* index bits for lencode */
  82194. unsigned distbits; /* index bits for distcode */
  82195. /* dynamic table building */
  82196. unsigned ncode; /* number of code length code lengths */
  82197. unsigned nlen; /* number of length code lengths */
  82198. unsigned ndist; /* number of distance code lengths */
  82199. unsigned have; /* number of code lengths in lens[] */
  82200. code FAR *next; /* next available space in codes[] */
  82201. unsigned short lens[320]; /* temporary storage for code lengths */
  82202. unsigned short work[288]; /* work area for code table building */
  82203. code codes[ENOUGH]; /* space for code tables */
  82204. };
  82205. #endif
  82206. /*** End of inlined file: inflate.h ***/
  82207. /*** Start of inlined file: inffast.h ***/
  82208. /* WARNING: this file should *not* be used by applications. It is
  82209. part of the implementation of the compression library and is
  82210. subject to change. Applications should only use zlib.h.
  82211. */
  82212. void inflate_fast OF((z_streamp strm, unsigned start));
  82213. /*** End of inlined file: inffast.h ***/
  82214. #ifndef ASMINF
  82215. /* Allow machine dependent optimization for post-increment or pre-increment.
  82216. Based on testing to date,
  82217. Pre-increment preferred for:
  82218. - PowerPC G3 (Adler)
  82219. - MIPS R5000 (Randers-Pehrson)
  82220. Post-increment preferred for:
  82221. - none
  82222. No measurable difference:
  82223. - Pentium III (Anderson)
  82224. - M68060 (Nikl)
  82225. */
  82226. #ifdef POSTINC
  82227. # define OFF 0
  82228. # define PUP(a) *(a)++
  82229. #else
  82230. # define OFF 1
  82231. # define PUP(a) *++(a)
  82232. #endif
  82233. /*
  82234. Decode literal, length, and distance codes and write out the resulting
  82235. literal and match bytes until either not enough input or output is
  82236. available, an end-of-block is encountered, or a data error is encountered.
  82237. When large enough input and output buffers are supplied to inflate(), for
  82238. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82239. inflate execution time is spent in this routine.
  82240. Entry assumptions:
  82241. state->mode == LEN
  82242. strm->avail_in >= 6
  82243. strm->avail_out >= 258
  82244. start >= strm->avail_out
  82245. state->bits < 8
  82246. On return, state->mode is one of:
  82247. LEN -- ran out of enough output space or enough available input
  82248. TYPE -- reached end of block code, inflate() to interpret next block
  82249. BAD -- error in block data
  82250. Notes:
  82251. - The maximum input bits used by a length/distance pair is 15 bits for the
  82252. length code, 5 bits for the length extra, 15 bits for the distance code,
  82253. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82254. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82255. checking for available input while decoding.
  82256. - The maximum bytes that a single length/distance pair can output is 258
  82257. bytes, which is the maximum length that can be coded. inflate_fast()
  82258. requires strm->avail_out >= 258 for each loop to avoid checking for
  82259. output space.
  82260. */
  82261. void inflate_fast (z_streamp strm, unsigned start)
  82262. {
  82263. struct inflate_state FAR *state;
  82264. unsigned char FAR *in; /* local strm->next_in */
  82265. unsigned char FAR *last; /* while in < last, enough input available */
  82266. unsigned char FAR *out; /* local strm->next_out */
  82267. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82268. unsigned char FAR *end; /* while out < end, enough space available */
  82269. #ifdef INFLATE_STRICT
  82270. unsigned dmax; /* maximum distance from zlib header */
  82271. #endif
  82272. unsigned wsize; /* window size or zero if not using window */
  82273. unsigned whave; /* valid bytes in the window */
  82274. unsigned write; /* window write index */
  82275. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82276. unsigned long hold; /* local strm->hold */
  82277. unsigned bits; /* local strm->bits */
  82278. code const FAR *lcode; /* local strm->lencode */
  82279. code const FAR *dcode; /* local strm->distcode */
  82280. unsigned lmask; /* mask for first level of length codes */
  82281. unsigned dmask; /* mask for first level of distance codes */
  82282. code thisx; /* retrieved table entry */
  82283. unsigned op; /* code bits, operation, extra bits, or */
  82284. /* window position, window bytes to copy */
  82285. unsigned len; /* match length, unused bytes */
  82286. unsigned dist; /* match distance */
  82287. unsigned char FAR *from; /* where to copy match from */
  82288. /* copy state to local variables */
  82289. state = (struct inflate_state FAR *)strm->state;
  82290. in = strm->next_in - OFF;
  82291. last = in + (strm->avail_in - 5);
  82292. out = strm->next_out - OFF;
  82293. beg = out - (start - strm->avail_out);
  82294. end = out + (strm->avail_out - 257);
  82295. #ifdef INFLATE_STRICT
  82296. dmax = state->dmax;
  82297. #endif
  82298. wsize = state->wsize;
  82299. whave = state->whave;
  82300. write = state->write;
  82301. window = state->window;
  82302. hold = state->hold;
  82303. bits = state->bits;
  82304. lcode = state->lencode;
  82305. dcode = state->distcode;
  82306. lmask = (1U << state->lenbits) - 1;
  82307. dmask = (1U << state->distbits) - 1;
  82308. /* decode literals and length/distances until end-of-block or not enough
  82309. input data or output space */
  82310. do {
  82311. if (bits < 15) {
  82312. hold += (unsigned long)(PUP(in)) << bits;
  82313. bits += 8;
  82314. hold += (unsigned long)(PUP(in)) << bits;
  82315. bits += 8;
  82316. }
  82317. thisx = lcode[hold & lmask];
  82318. dolen:
  82319. op = (unsigned)(thisx.bits);
  82320. hold >>= op;
  82321. bits -= op;
  82322. op = (unsigned)(thisx.op);
  82323. if (op == 0) { /* literal */
  82324. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82325. "inflate: literal '%c'\n" :
  82326. "inflate: literal 0x%02x\n", thisx.val));
  82327. PUP(out) = (unsigned char)(thisx.val);
  82328. }
  82329. else if (op & 16) { /* length base */
  82330. len = (unsigned)(thisx.val);
  82331. op &= 15; /* number of extra bits */
  82332. if (op) {
  82333. if (bits < op) {
  82334. hold += (unsigned long)(PUP(in)) << bits;
  82335. bits += 8;
  82336. }
  82337. len += (unsigned)hold & ((1U << op) - 1);
  82338. hold >>= op;
  82339. bits -= op;
  82340. }
  82341. Tracevv((stderr, "inflate: length %u\n", len));
  82342. if (bits < 15) {
  82343. hold += (unsigned long)(PUP(in)) << bits;
  82344. bits += 8;
  82345. hold += (unsigned long)(PUP(in)) << bits;
  82346. bits += 8;
  82347. }
  82348. thisx = dcode[hold & dmask];
  82349. dodist:
  82350. op = (unsigned)(thisx.bits);
  82351. hold >>= op;
  82352. bits -= op;
  82353. op = (unsigned)(thisx.op);
  82354. if (op & 16) { /* distance base */
  82355. dist = (unsigned)(thisx.val);
  82356. op &= 15; /* number of extra bits */
  82357. if (bits < op) {
  82358. hold += (unsigned long)(PUP(in)) << bits;
  82359. bits += 8;
  82360. if (bits < op) {
  82361. hold += (unsigned long)(PUP(in)) << bits;
  82362. bits += 8;
  82363. }
  82364. }
  82365. dist += (unsigned)hold & ((1U << op) - 1);
  82366. #ifdef INFLATE_STRICT
  82367. if (dist > dmax) {
  82368. strm->msg = (char *)"invalid distance too far back";
  82369. state->mode = BAD;
  82370. break;
  82371. }
  82372. #endif
  82373. hold >>= op;
  82374. bits -= op;
  82375. Tracevv((stderr, "inflate: distance %u\n", dist));
  82376. op = (unsigned)(out - beg); /* max distance in output */
  82377. if (dist > op) { /* see if copy from window */
  82378. op = dist - op; /* distance back in window */
  82379. if (op > whave) {
  82380. strm->msg = (char *)"invalid distance too far back";
  82381. state->mode = BAD;
  82382. break;
  82383. }
  82384. from = window - OFF;
  82385. if (write == 0) { /* very common case */
  82386. from += wsize - op;
  82387. if (op < len) { /* some from window */
  82388. len -= op;
  82389. do {
  82390. PUP(out) = PUP(from);
  82391. } while (--op);
  82392. from = out - dist; /* rest from output */
  82393. }
  82394. }
  82395. else if (write < op) { /* wrap around window */
  82396. from += wsize + write - op;
  82397. op -= write;
  82398. if (op < len) { /* some from end of window */
  82399. len -= op;
  82400. do {
  82401. PUP(out) = PUP(from);
  82402. } while (--op);
  82403. from = window - OFF;
  82404. if (write < len) { /* some from start of window */
  82405. op = write;
  82406. len -= op;
  82407. do {
  82408. PUP(out) = PUP(from);
  82409. } while (--op);
  82410. from = out - dist; /* rest from output */
  82411. }
  82412. }
  82413. }
  82414. else { /* contiguous in window */
  82415. from += write - op;
  82416. if (op < len) { /* some from window */
  82417. len -= op;
  82418. do {
  82419. PUP(out) = PUP(from);
  82420. } while (--op);
  82421. from = out - dist; /* rest from output */
  82422. }
  82423. }
  82424. while (len > 2) {
  82425. PUP(out) = PUP(from);
  82426. PUP(out) = PUP(from);
  82427. PUP(out) = PUP(from);
  82428. len -= 3;
  82429. }
  82430. if (len) {
  82431. PUP(out) = PUP(from);
  82432. if (len > 1)
  82433. PUP(out) = PUP(from);
  82434. }
  82435. }
  82436. else {
  82437. from = out - dist; /* copy direct from output */
  82438. do { /* minimum length is three */
  82439. PUP(out) = PUP(from);
  82440. PUP(out) = PUP(from);
  82441. PUP(out) = PUP(from);
  82442. len -= 3;
  82443. } while (len > 2);
  82444. if (len) {
  82445. PUP(out) = PUP(from);
  82446. if (len > 1)
  82447. PUP(out) = PUP(from);
  82448. }
  82449. }
  82450. }
  82451. else if ((op & 64) == 0) { /* 2nd level distance code */
  82452. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82453. goto dodist;
  82454. }
  82455. else {
  82456. strm->msg = (char *)"invalid distance code";
  82457. state->mode = BAD;
  82458. break;
  82459. }
  82460. }
  82461. else if ((op & 64) == 0) { /* 2nd level length code */
  82462. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82463. goto dolen;
  82464. }
  82465. else if (op & 32) { /* end-of-block */
  82466. Tracevv((stderr, "inflate: end of block\n"));
  82467. state->mode = TYPE;
  82468. break;
  82469. }
  82470. else {
  82471. strm->msg = (char *)"invalid literal/length code";
  82472. state->mode = BAD;
  82473. break;
  82474. }
  82475. } while (in < last && out < end);
  82476. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82477. len = bits >> 3;
  82478. in -= len;
  82479. bits -= len << 3;
  82480. hold &= (1U << bits) - 1;
  82481. /* update state and return */
  82482. strm->next_in = in + OFF;
  82483. strm->next_out = out + OFF;
  82484. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82485. strm->avail_out = (unsigned)(out < end ?
  82486. 257 + (end - out) : 257 - (out - end));
  82487. state->hold = hold;
  82488. state->bits = bits;
  82489. return;
  82490. }
  82491. /*
  82492. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82493. - Using bit fields for code structure
  82494. - Different op definition to avoid & for extra bits (do & for table bits)
  82495. - Three separate decoding do-loops for direct, window, and write == 0
  82496. - Special case for distance > 1 copies to do overlapped load and store copy
  82497. - Explicit branch predictions (based on measured branch probabilities)
  82498. - Deferring match copy and interspersed it with decoding subsequent codes
  82499. - Swapping literal/length else
  82500. - Swapping window/direct else
  82501. - Larger unrolled copy loops (three is about right)
  82502. - Moving len -= 3 statement into middle of loop
  82503. */
  82504. #endif /* !ASMINF */
  82505. /*** End of inlined file: inffast.c ***/
  82506. #undef PULLBYTE
  82507. #undef LOAD
  82508. #undef RESTORE
  82509. #undef INITBITS
  82510. #undef NEEDBITS
  82511. #undef DROPBITS
  82512. #undef BYTEBITS
  82513. /*** Start of inlined file: inflate.c ***/
  82514. /*
  82515. * Change history:
  82516. *
  82517. * 1.2.beta0 24 Nov 2002
  82518. * - First version -- complete rewrite of inflate to simplify code, avoid
  82519. * creation of window when not needed, minimize use of window when it is
  82520. * needed, make inffast.c even faster, implement gzip decoding, and to
  82521. * improve code readability and style over the previous zlib inflate code
  82522. *
  82523. * 1.2.beta1 25 Nov 2002
  82524. * - Use pointers for available input and output checking in inffast.c
  82525. * - Remove input and output counters in inffast.c
  82526. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82527. * - Remove unnecessary second byte pull from length extra in inffast.c
  82528. * - Unroll direct copy to three copies per loop in inffast.c
  82529. *
  82530. * 1.2.beta2 4 Dec 2002
  82531. * - Change external routine names to reduce potential conflicts
  82532. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82533. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82534. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82535. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82536. *
  82537. * 1.2.beta3 22 Dec 2002
  82538. * - Add comments on state->bits assertion in inffast.c
  82539. * - Add comments on op field in inftrees.h
  82540. * - Fix bug in reuse of allocated window after inflateReset()
  82541. * - Remove bit fields--back to byte structure for speed
  82542. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82543. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82544. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82545. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82546. * - Use local copies of stream next and avail values, as well as local bit
  82547. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82548. *
  82549. * 1.2.beta4 1 Jan 2003
  82550. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82551. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82552. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82553. * - Rearrange window copies in inflate_fast() for speed and simplification
  82554. * - Unroll last copy for window match in inflate_fast()
  82555. * - Use local copies of window variables in inflate_fast() for speed
  82556. * - Pull out common write == 0 case for speed in inflate_fast()
  82557. * - Make op and len in inflate_fast() unsigned for consistency
  82558. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82559. * - Simplified bad distance check in inflate_fast()
  82560. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82561. * source file infback.c to provide a call-back interface to inflate for
  82562. * programs like gzip and unzip -- uses window as output buffer to avoid
  82563. * window copying
  82564. *
  82565. * 1.2.beta5 1 Jan 2003
  82566. * - Improved inflateBack() interface to allow the caller to provide initial
  82567. * input in strm.
  82568. * - Fixed stored blocks bug in inflateBack()
  82569. *
  82570. * 1.2.beta6 4 Jan 2003
  82571. * - Added comments in inffast.c on effectiveness of POSTINC
  82572. * - Typecasting all around to reduce compiler warnings
  82573. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82574. * make compilers happy
  82575. * - Changed type of window in inflateBackInit() to unsigned char *
  82576. *
  82577. * 1.2.beta7 27 Jan 2003
  82578. * - Changed many types to unsigned or unsigned short to avoid warnings
  82579. * - Added inflateCopy() function
  82580. *
  82581. * 1.2.0 9 Mar 2003
  82582. * - Changed inflateBack() interface to provide separate opaque descriptors
  82583. * for the in() and out() functions
  82584. * - Changed inflateBack() argument and in_func typedef to swap the length
  82585. * and buffer address return values for the input function
  82586. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82587. *
  82588. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82589. */
  82590. /*** Start of inlined file: inffast.h ***/
  82591. /* WARNING: this file should *not* be used by applications. It is
  82592. part of the implementation of the compression library and is
  82593. subject to change. Applications should only use zlib.h.
  82594. */
  82595. void inflate_fast OF((z_streamp strm, unsigned start));
  82596. /*** End of inlined file: inffast.h ***/
  82597. #ifdef MAKEFIXED
  82598. # ifndef BUILDFIXED
  82599. # define BUILDFIXED
  82600. # endif
  82601. #endif
  82602. /* function prototypes */
  82603. local void fixedtables OF((struct inflate_state FAR *state));
  82604. local int updatewindow OF((z_streamp strm, unsigned out));
  82605. #ifdef BUILDFIXED
  82606. void makefixed OF((void));
  82607. #endif
  82608. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82609. unsigned len));
  82610. int ZEXPORT inflateReset (z_streamp strm)
  82611. {
  82612. struct inflate_state FAR *state;
  82613. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82614. state = (struct inflate_state FAR *)strm->state;
  82615. strm->total_in = strm->total_out = state->total = 0;
  82616. strm->msg = Z_NULL;
  82617. strm->adler = 1; /* to support ill-conceived Java test suite */
  82618. state->mode = HEAD;
  82619. state->last = 0;
  82620. state->havedict = 0;
  82621. state->dmax = 32768U;
  82622. state->head = Z_NULL;
  82623. state->wsize = 0;
  82624. state->whave = 0;
  82625. state->write = 0;
  82626. state->hold = 0;
  82627. state->bits = 0;
  82628. state->lencode = state->distcode = state->next = state->codes;
  82629. Tracev((stderr, "inflate: reset\n"));
  82630. return Z_OK;
  82631. }
  82632. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82633. {
  82634. struct inflate_state FAR *state;
  82635. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82636. state = (struct inflate_state FAR *)strm->state;
  82637. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82638. value &= (1L << bits) - 1;
  82639. state->hold += value << state->bits;
  82640. state->bits += bits;
  82641. return Z_OK;
  82642. }
  82643. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82644. {
  82645. struct inflate_state FAR *state;
  82646. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82647. stream_size != (int)(sizeof(z_stream)))
  82648. return Z_VERSION_ERROR;
  82649. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82650. strm->msg = Z_NULL; /* in case we return an error */
  82651. if (strm->zalloc == (alloc_func)0) {
  82652. strm->zalloc = zcalloc;
  82653. strm->opaque = (voidpf)0;
  82654. }
  82655. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82656. state = (struct inflate_state FAR *)
  82657. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82658. if (state == Z_NULL) return Z_MEM_ERROR;
  82659. Tracev((stderr, "inflate: allocated\n"));
  82660. strm->state = (struct internal_state FAR *)state;
  82661. if (windowBits < 0) {
  82662. state->wrap = 0;
  82663. windowBits = -windowBits;
  82664. }
  82665. else {
  82666. state->wrap = (windowBits >> 4) + 1;
  82667. #ifdef GUNZIP
  82668. if (windowBits < 48) windowBits &= 15;
  82669. #endif
  82670. }
  82671. if (windowBits < 8 || windowBits > 15) {
  82672. ZFREE(strm, state);
  82673. strm->state = Z_NULL;
  82674. return Z_STREAM_ERROR;
  82675. }
  82676. state->wbits = (unsigned)windowBits;
  82677. state->window = Z_NULL;
  82678. return inflateReset(strm);
  82679. }
  82680. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82681. {
  82682. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82683. }
  82684. /*
  82685. Return state with length and distance decoding tables and index sizes set to
  82686. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82687. If BUILDFIXED is defined, then instead this routine builds the tables the
  82688. first time it's called, and returns those tables the first time and
  82689. thereafter. This reduces the size of the code by about 2K bytes, in
  82690. exchange for a little execution time. However, BUILDFIXED should not be
  82691. used for threaded applications, since the rewriting of the tables and virgin
  82692. may not be thread-safe.
  82693. */
  82694. local void fixedtables (struct inflate_state FAR *state)
  82695. {
  82696. #ifdef BUILDFIXED
  82697. static int virgin = 1;
  82698. static code *lenfix, *distfix;
  82699. static code fixed[544];
  82700. /* build fixed huffman tables if first call (may not be thread safe) */
  82701. if (virgin) {
  82702. unsigned sym, bits;
  82703. static code *next;
  82704. /* literal/length table */
  82705. sym = 0;
  82706. while (sym < 144) state->lens[sym++] = 8;
  82707. while (sym < 256) state->lens[sym++] = 9;
  82708. while (sym < 280) state->lens[sym++] = 7;
  82709. while (sym < 288) state->lens[sym++] = 8;
  82710. next = fixed;
  82711. lenfix = next;
  82712. bits = 9;
  82713. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82714. /* distance table */
  82715. sym = 0;
  82716. while (sym < 32) state->lens[sym++] = 5;
  82717. distfix = next;
  82718. bits = 5;
  82719. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82720. /* do this just once */
  82721. virgin = 0;
  82722. }
  82723. #else /* !BUILDFIXED */
  82724. /*** Start of inlined file: inffixed.h ***/
  82725. /* WARNING: this file should *not* be used by applications. It
  82726. is part of the implementation of the compression library and
  82727. is subject to change. Applications should only use zlib.h.
  82728. */
  82729. static const code lenfix[512] = {
  82730. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82731. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82732. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82733. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82734. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82735. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82736. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82737. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82738. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82739. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82740. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82741. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82742. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82743. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82744. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82745. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82746. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82747. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82748. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82749. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82750. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82751. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82752. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82753. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82754. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82755. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82756. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82757. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82758. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82759. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82760. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82761. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82762. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82763. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82764. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82765. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82766. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82767. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82768. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82769. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82770. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82771. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82772. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82773. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82774. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82775. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82776. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82777. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82778. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82779. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82780. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82781. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82782. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82783. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82784. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82785. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82786. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82787. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82788. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82789. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82790. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82791. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82792. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82793. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82794. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82795. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82796. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82797. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82798. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82799. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82800. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82801. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82802. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  82803. {0,9,255}
  82804. };
  82805. static const code distfix[32] = {
  82806. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  82807. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  82808. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  82809. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  82810. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  82811. {22,5,193},{64,5,0}
  82812. };
  82813. /*** End of inlined file: inffixed.h ***/
  82814. #endif /* BUILDFIXED */
  82815. state->lencode = lenfix;
  82816. state->lenbits = 9;
  82817. state->distcode = distfix;
  82818. state->distbits = 5;
  82819. }
  82820. #ifdef MAKEFIXED
  82821. #include <stdio.h>
  82822. /*
  82823. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  82824. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  82825. those tables to stdout, which would be piped to inffixed.h. A small program
  82826. can simply call makefixed to do this:
  82827. void makefixed(void);
  82828. int main(void)
  82829. {
  82830. makefixed();
  82831. return 0;
  82832. }
  82833. Then that can be linked with zlib built with MAKEFIXED defined and run:
  82834. a.out > inffixed.h
  82835. */
  82836. void makefixed()
  82837. {
  82838. unsigned low, size;
  82839. struct inflate_state state;
  82840. fixedtables(&state);
  82841. puts(" /* inffixed.h -- table for decoding fixed codes");
  82842. puts(" * Generated automatically by makefixed().");
  82843. puts(" */");
  82844. puts("");
  82845. puts(" /* WARNING: this file should *not* be used by applications.");
  82846. puts(" It is part of the implementation of this library and is");
  82847. puts(" subject to change. Applications should only use zlib.h.");
  82848. puts(" */");
  82849. puts("");
  82850. size = 1U << 9;
  82851. printf(" static const code lenfix[%u] = {", size);
  82852. low = 0;
  82853. for (;;) {
  82854. if ((low % 7) == 0) printf("\n ");
  82855. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  82856. state.lencode[low].val);
  82857. if (++low == size) break;
  82858. putchar(',');
  82859. }
  82860. puts("\n };");
  82861. size = 1U << 5;
  82862. printf("\n static const code distfix[%u] = {", size);
  82863. low = 0;
  82864. for (;;) {
  82865. if ((low % 6) == 0) printf("\n ");
  82866. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  82867. state.distcode[low].val);
  82868. if (++low == size) break;
  82869. putchar(',');
  82870. }
  82871. puts("\n };");
  82872. }
  82873. #endif /* MAKEFIXED */
  82874. /*
  82875. Update the window with the last wsize (normally 32K) bytes written before
  82876. returning. If window does not exist yet, create it. This is only called
  82877. when a window is already in use, or when output has been written during this
  82878. inflate call, but the end of the deflate stream has not been reached yet.
  82879. It is also called to create a window for dictionary data when a dictionary
  82880. is loaded.
  82881. Providing output buffers larger than 32K to inflate() should provide a speed
  82882. advantage, since only the last 32K of output is copied to the sliding window
  82883. upon return from inflate(), and since all distances after the first 32K of
  82884. output will fall in the output data, making match copies simpler and faster.
  82885. The advantage may be dependent on the size of the processor's data caches.
  82886. */
  82887. local int updatewindow (z_streamp strm, unsigned out)
  82888. {
  82889. struct inflate_state FAR *state;
  82890. unsigned copy, dist;
  82891. state = (struct inflate_state FAR *)strm->state;
  82892. /* if it hasn't been done already, allocate space for the window */
  82893. if (state->window == Z_NULL) {
  82894. state->window = (unsigned char FAR *)
  82895. ZALLOC(strm, 1U << state->wbits,
  82896. sizeof(unsigned char));
  82897. if (state->window == Z_NULL) return 1;
  82898. }
  82899. /* if window not in use yet, initialize */
  82900. if (state->wsize == 0) {
  82901. state->wsize = 1U << state->wbits;
  82902. state->write = 0;
  82903. state->whave = 0;
  82904. }
  82905. /* copy state->wsize or less output bytes into the circular window */
  82906. copy = out - strm->avail_out;
  82907. if (copy >= state->wsize) {
  82908. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  82909. state->write = 0;
  82910. state->whave = state->wsize;
  82911. }
  82912. else {
  82913. dist = state->wsize - state->write;
  82914. if (dist > copy) dist = copy;
  82915. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  82916. copy -= dist;
  82917. if (copy) {
  82918. zmemcpy(state->window, strm->next_out - copy, copy);
  82919. state->write = copy;
  82920. state->whave = state->wsize;
  82921. }
  82922. else {
  82923. state->write += dist;
  82924. if (state->write == state->wsize) state->write = 0;
  82925. if (state->whave < state->wsize) state->whave += dist;
  82926. }
  82927. }
  82928. return 0;
  82929. }
  82930. /* Macros for inflate(): */
  82931. /* check function to use adler32() for zlib or crc32() for gzip */
  82932. #ifdef GUNZIP
  82933. # define UPDATE(check, buf, len) \
  82934. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  82935. #else
  82936. # define UPDATE(check, buf, len) adler32(check, buf, len)
  82937. #endif
  82938. /* check macros for header crc */
  82939. #ifdef GUNZIP
  82940. # define CRC2(check, word) \
  82941. do { \
  82942. hbuf[0] = (unsigned char)(word); \
  82943. hbuf[1] = (unsigned char)((word) >> 8); \
  82944. check = crc32(check, hbuf, 2); \
  82945. } while (0)
  82946. # define CRC4(check, word) \
  82947. do { \
  82948. hbuf[0] = (unsigned char)(word); \
  82949. hbuf[1] = (unsigned char)((word) >> 8); \
  82950. hbuf[2] = (unsigned char)((word) >> 16); \
  82951. hbuf[3] = (unsigned char)((word) >> 24); \
  82952. check = crc32(check, hbuf, 4); \
  82953. } while (0)
  82954. #endif
  82955. /* Load registers with state in inflate() for speed */
  82956. #define LOAD() \
  82957. do { \
  82958. put = strm->next_out; \
  82959. left = strm->avail_out; \
  82960. next = strm->next_in; \
  82961. have = strm->avail_in; \
  82962. hold = state->hold; \
  82963. bits = state->bits; \
  82964. } while (0)
  82965. /* Restore state from registers in inflate() */
  82966. #define RESTORE() \
  82967. do { \
  82968. strm->next_out = put; \
  82969. strm->avail_out = left; \
  82970. strm->next_in = next; \
  82971. strm->avail_in = have; \
  82972. state->hold = hold; \
  82973. state->bits = bits; \
  82974. } while (0)
  82975. /* Clear the input bit accumulator */
  82976. #define INITBITS() \
  82977. do { \
  82978. hold = 0; \
  82979. bits = 0; \
  82980. } while (0)
  82981. /* Get a byte of input into the bit accumulator, or return from inflate()
  82982. if there is no input available. */
  82983. #define PULLBYTE() \
  82984. do { \
  82985. if (have == 0) goto inf_leave; \
  82986. have--; \
  82987. hold += (unsigned long)(*next++) << bits; \
  82988. bits += 8; \
  82989. } while (0)
  82990. /* Assure that there are at least n bits in the bit accumulator. If there is
  82991. not enough available input to do that, then return from inflate(). */
  82992. #define NEEDBITS(n) \
  82993. do { \
  82994. while (bits < (unsigned)(n)) \
  82995. PULLBYTE(); \
  82996. } while (0)
  82997. /* Return the low n bits of the bit accumulator (n < 16) */
  82998. #define BITS(n) \
  82999. ((unsigned)hold & ((1U << (n)) - 1))
  83000. /* Remove n bits from the bit accumulator */
  83001. #define DROPBITS(n) \
  83002. do { \
  83003. hold >>= (n); \
  83004. bits -= (unsigned)(n); \
  83005. } while (0)
  83006. /* Remove zero to seven bits as needed to go to a byte boundary */
  83007. #define BYTEBITS() \
  83008. do { \
  83009. hold >>= bits & 7; \
  83010. bits -= bits & 7; \
  83011. } while (0)
  83012. /* Reverse the bytes in a 32-bit value */
  83013. #define REVERSE(q) \
  83014. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83015. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83016. /*
  83017. inflate() uses a state machine to process as much input data and generate as
  83018. much output data as possible before returning. The state machine is
  83019. structured roughly as follows:
  83020. for (;;) switch (state) {
  83021. ...
  83022. case STATEn:
  83023. if (not enough input data or output space to make progress)
  83024. return;
  83025. ... make progress ...
  83026. state = STATEm;
  83027. break;
  83028. ...
  83029. }
  83030. so when inflate() is called again, the same case is attempted again, and
  83031. if the appropriate resources are provided, the machine proceeds to the
  83032. next state. The NEEDBITS() macro is usually the way the state evaluates
  83033. whether it can proceed or should return. NEEDBITS() does the return if
  83034. the requested bits are not available. The typical use of the BITS macros
  83035. is:
  83036. NEEDBITS(n);
  83037. ... do something with BITS(n) ...
  83038. DROPBITS(n);
  83039. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83040. input left to load n bits into the accumulator, or it continues. BITS(n)
  83041. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83042. the low n bits off the accumulator. INITBITS() clears the accumulator
  83043. and sets the number of available bits to zero. BYTEBITS() discards just
  83044. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83045. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83046. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83047. if there is no input available. The decoding of variable length codes uses
  83048. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83049. code, and no more.
  83050. Some states loop until they get enough input, making sure that enough
  83051. state information is maintained to continue the loop where it left off
  83052. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83053. would all have to actually be part of the saved state in case NEEDBITS()
  83054. returns:
  83055. case STATEw:
  83056. while (want < need) {
  83057. NEEDBITS(n);
  83058. keep[want++] = BITS(n);
  83059. DROPBITS(n);
  83060. }
  83061. state = STATEx;
  83062. case STATEx:
  83063. As shown above, if the next state is also the next case, then the break
  83064. is omitted.
  83065. A state may also return if there is not enough output space available to
  83066. complete that state. Those states are copying stored data, writing a
  83067. literal byte, and copying a matching string.
  83068. When returning, a "goto inf_leave" is used to update the total counters,
  83069. update the check value, and determine whether any progress has been made
  83070. during that inflate() call in order to return the proper return code.
  83071. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83072. When there is a window, goto inf_leave will update the window with the last
  83073. output written. If a goto inf_leave occurs in the middle of decompression
  83074. and there is no window currently, goto inf_leave will create one and copy
  83075. output to the window for the next call of inflate().
  83076. In this implementation, the flush parameter of inflate() only affects the
  83077. return code (per zlib.h). inflate() always writes as much as possible to
  83078. strm->next_out, given the space available and the provided input--the effect
  83079. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83080. the allocation of and copying into a sliding window until necessary, which
  83081. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83082. stream available. So the only thing the flush parameter actually does is:
  83083. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83084. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83085. */
  83086. int ZEXPORT inflate (z_streamp strm, int flush)
  83087. {
  83088. struct inflate_state FAR *state;
  83089. unsigned char FAR *next; /* next input */
  83090. unsigned char FAR *put; /* next output */
  83091. unsigned have, left; /* available input and output */
  83092. unsigned long hold; /* bit buffer */
  83093. unsigned bits; /* bits in bit buffer */
  83094. unsigned in, out; /* save starting available input and output */
  83095. unsigned copy; /* number of stored or match bytes to copy */
  83096. unsigned char FAR *from; /* where to copy match bytes from */
  83097. code thisx; /* current decoding table entry */
  83098. code last; /* parent table entry */
  83099. unsigned len; /* length to copy for repeats, bits to drop */
  83100. int ret; /* return code */
  83101. #ifdef GUNZIP
  83102. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83103. #endif
  83104. static const unsigned short order[19] = /* permutation of code lengths */
  83105. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83106. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83107. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83108. return Z_STREAM_ERROR;
  83109. state = (struct inflate_state FAR *)strm->state;
  83110. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83111. LOAD();
  83112. in = have;
  83113. out = left;
  83114. ret = Z_OK;
  83115. for (;;)
  83116. switch (state->mode) {
  83117. case HEAD:
  83118. if (state->wrap == 0) {
  83119. state->mode = TYPEDO;
  83120. break;
  83121. }
  83122. NEEDBITS(16);
  83123. #ifdef GUNZIP
  83124. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83125. state->check = crc32(0L, Z_NULL, 0);
  83126. CRC2(state->check, hold);
  83127. INITBITS();
  83128. state->mode = FLAGS;
  83129. break;
  83130. }
  83131. state->flags = 0; /* expect zlib header */
  83132. if (state->head != Z_NULL)
  83133. state->head->done = -1;
  83134. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83135. #else
  83136. if (
  83137. #endif
  83138. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83139. strm->msg = (char *)"incorrect header check";
  83140. state->mode = BAD;
  83141. break;
  83142. }
  83143. if (BITS(4) != Z_DEFLATED) {
  83144. strm->msg = (char *)"unknown compression method";
  83145. state->mode = BAD;
  83146. break;
  83147. }
  83148. DROPBITS(4);
  83149. len = BITS(4) + 8;
  83150. if (len > state->wbits) {
  83151. strm->msg = (char *)"invalid window size";
  83152. state->mode = BAD;
  83153. break;
  83154. }
  83155. state->dmax = 1U << len;
  83156. Tracev((stderr, "inflate: zlib header ok\n"));
  83157. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83158. state->mode = hold & 0x200 ? DICTID : TYPE;
  83159. INITBITS();
  83160. break;
  83161. #ifdef GUNZIP
  83162. case FLAGS:
  83163. NEEDBITS(16);
  83164. state->flags = (int)(hold);
  83165. if ((state->flags & 0xff) != Z_DEFLATED) {
  83166. strm->msg = (char *)"unknown compression method";
  83167. state->mode = BAD;
  83168. break;
  83169. }
  83170. if (state->flags & 0xe000) {
  83171. strm->msg = (char *)"unknown header flags set";
  83172. state->mode = BAD;
  83173. break;
  83174. }
  83175. if (state->head != Z_NULL)
  83176. state->head->text = (int)((hold >> 8) & 1);
  83177. if (state->flags & 0x0200) CRC2(state->check, hold);
  83178. INITBITS();
  83179. state->mode = TIME;
  83180. case TIME:
  83181. NEEDBITS(32);
  83182. if (state->head != Z_NULL)
  83183. state->head->time = hold;
  83184. if (state->flags & 0x0200) CRC4(state->check, hold);
  83185. INITBITS();
  83186. state->mode = OS;
  83187. case OS:
  83188. NEEDBITS(16);
  83189. if (state->head != Z_NULL) {
  83190. state->head->xflags = (int)(hold & 0xff);
  83191. state->head->os = (int)(hold >> 8);
  83192. }
  83193. if (state->flags & 0x0200) CRC2(state->check, hold);
  83194. INITBITS();
  83195. state->mode = EXLEN;
  83196. case EXLEN:
  83197. if (state->flags & 0x0400) {
  83198. NEEDBITS(16);
  83199. state->length = (unsigned)(hold);
  83200. if (state->head != Z_NULL)
  83201. state->head->extra_len = (unsigned)hold;
  83202. if (state->flags & 0x0200) CRC2(state->check, hold);
  83203. INITBITS();
  83204. }
  83205. else if (state->head != Z_NULL)
  83206. state->head->extra = Z_NULL;
  83207. state->mode = EXTRA;
  83208. case EXTRA:
  83209. if (state->flags & 0x0400) {
  83210. copy = state->length;
  83211. if (copy > have) copy = have;
  83212. if (copy) {
  83213. if (state->head != Z_NULL &&
  83214. state->head->extra != Z_NULL) {
  83215. len = state->head->extra_len - state->length;
  83216. zmemcpy(state->head->extra + len, next,
  83217. len + copy > state->head->extra_max ?
  83218. state->head->extra_max - len : copy);
  83219. }
  83220. if (state->flags & 0x0200)
  83221. state->check = crc32(state->check, next, copy);
  83222. have -= copy;
  83223. next += copy;
  83224. state->length -= copy;
  83225. }
  83226. if (state->length) goto inf_leave;
  83227. }
  83228. state->length = 0;
  83229. state->mode = NAME;
  83230. case NAME:
  83231. if (state->flags & 0x0800) {
  83232. if (have == 0) goto inf_leave;
  83233. copy = 0;
  83234. do {
  83235. len = (unsigned)(next[copy++]);
  83236. if (state->head != Z_NULL &&
  83237. state->head->name != Z_NULL &&
  83238. state->length < state->head->name_max)
  83239. state->head->name[state->length++] = len;
  83240. } while (len && copy < have);
  83241. if (state->flags & 0x0200)
  83242. state->check = crc32(state->check, next, copy);
  83243. have -= copy;
  83244. next += copy;
  83245. if (len) goto inf_leave;
  83246. }
  83247. else if (state->head != Z_NULL)
  83248. state->head->name = Z_NULL;
  83249. state->length = 0;
  83250. state->mode = COMMENT;
  83251. case COMMENT:
  83252. if (state->flags & 0x1000) {
  83253. if (have == 0) goto inf_leave;
  83254. copy = 0;
  83255. do {
  83256. len = (unsigned)(next[copy++]);
  83257. if (state->head != Z_NULL &&
  83258. state->head->comment != Z_NULL &&
  83259. state->length < state->head->comm_max)
  83260. state->head->comment[state->length++] = len;
  83261. } while (len && copy < have);
  83262. if (state->flags & 0x0200)
  83263. state->check = crc32(state->check, next, copy);
  83264. have -= copy;
  83265. next += copy;
  83266. if (len) goto inf_leave;
  83267. }
  83268. else if (state->head != Z_NULL)
  83269. state->head->comment = Z_NULL;
  83270. state->mode = HCRC;
  83271. case HCRC:
  83272. if (state->flags & 0x0200) {
  83273. NEEDBITS(16);
  83274. if (hold != (state->check & 0xffff)) {
  83275. strm->msg = (char *)"header crc mismatch";
  83276. state->mode = BAD;
  83277. break;
  83278. }
  83279. INITBITS();
  83280. }
  83281. if (state->head != Z_NULL) {
  83282. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83283. state->head->done = 1;
  83284. }
  83285. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83286. state->mode = TYPE;
  83287. break;
  83288. #endif
  83289. case DICTID:
  83290. NEEDBITS(32);
  83291. strm->adler = state->check = REVERSE(hold);
  83292. INITBITS();
  83293. state->mode = DICT;
  83294. case DICT:
  83295. if (state->havedict == 0) {
  83296. RESTORE();
  83297. return Z_NEED_DICT;
  83298. }
  83299. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83300. state->mode = TYPE;
  83301. case TYPE:
  83302. if (flush == Z_BLOCK) goto inf_leave;
  83303. case TYPEDO:
  83304. if (state->last) {
  83305. BYTEBITS();
  83306. state->mode = CHECK;
  83307. break;
  83308. }
  83309. NEEDBITS(3);
  83310. state->last = BITS(1);
  83311. DROPBITS(1);
  83312. switch (BITS(2)) {
  83313. case 0: /* stored block */
  83314. Tracev((stderr, "inflate: stored block%s\n",
  83315. state->last ? " (last)" : ""));
  83316. state->mode = STORED;
  83317. break;
  83318. case 1: /* fixed block */
  83319. fixedtables(state);
  83320. Tracev((stderr, "inflate: fixed codes block%s\n",
  83321. state->last ? " (last)" : ""));
  83322. state->mode = LEN; /* decode codes */
  83323. break;
  83324. case 2: /* dynamic block */
  83325. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83326. state->last ? " (last)" : ""));
  83327. state->mode = TABLE;
  83328. break;
  83329. case 3:
  83330. strm->msg = (char *)"invalid block type";
  83331. state->mode = BAD;
  83332. }
  83333. DROPBITS(2);
  83334. break;
  83335. case STORED:
  83336. BYTEBITS(); /* go to byte boundary */
  83337. NEEDBITS(32);
  83338. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83339. strm->msg = (char *)"invalid stored block lengths";
  83340. state->mode = BAD;
  83341. break;
  83342. }
  83343. state->length = (unsigned)hold & 0xffff;
  83344. Tracev((stderr, "inflate: stored length %u\n",
  83345. state->length));
  83346. INITBITS();
  83347. state->mode = COPY;
  83348. case COPY:
  83349. copy = state->length;
  83350. if (copy) {
  83351. if (copy > have) copy = have;
  83352. if (copy > left) copy = left;
  83353. if (copy == 0) goto inf_leave;
  83354. zmemcpy(put, next, copy);
  83355. have -= copy;
  83356. next += copy;
  83357. left -= copy;
  83358. put += copy;
  83359. state->length -= copy;
  83360. break;
  83361. }
  83362. Tracev((stderr, "inflate: stored end\n"));
  83363. state->mode = TYPE;
  83364. break;
  83365. case TABLE:
  83366. NEEDBITS(14);
  83367. state->nlen = BITS(5) + 257;
  83368. DROPBITS(5);
  83369. state->ndist = BITS(5) + 1;
  83370. DROPBITS(5);
  83371. state->ncode = BITS(4) + 4;
  83372. DROPBITS(4);
  83373. #ifndef PKZIP_BUG_WORKAROUND
  83374. if (state->nlen > 286 || state->ndist > 30) {
  83375. strm->msg = (char *)"too many length or distance symbols";
  83376. state->mode = BAD;
  83377. break;
  83378. }
  83379. #endif
  83380. Tracev((stderr, "inflate: table sizes ok\n"));
  83381. state->have = 0;
  83382. state->mode = LENLENS;
  83383. case LENLENS:
  83384. while (state->have < state->ncode) {
  83385. NEEDBITS(3);
  83386. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83387. DROPBITS(3);
  83388. }
  83389. while (state->have < 19)
  83390. state->lens[order[state->have++]] = 0;
  83391. state->next = state->codes;
  83392. state->lencode = (code const FAR *)(state->next);
  83393. state->lenbits = 7;
  83394. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83395. &(state->lenbits), state->work);
  83396. if (ret) {
  83397. strm->msg = (char *)"invalid code lengths set";
  83398. state->mode = BAD;
  83399. break;
  83400. }
  83401. Tracev((stderr, "inflate: code lengths ok\n"));
  83402. state->have = 0;
  83403. state->mode = CODELENS;
  83404. case CODELENS:
  83405. while (state->have < state->nlen + state->ndist) {
  83406. for (;;) {
  83407. thisx = state->lencode[BITS(state->lenbits)];
  83408. if ((unsigned)(thisx.bits) <= bits) break;
  83409. PULLBYTE();
  83410. }
  83411. if (thisx.val < 16) {
  83412. NEEDBITS(thisx.bits);
  83413. DROPBITS(thisx.bits);
  83414. state->lens[state->have++] = thisx.val;
  83415. }
  83416. else {
  83417. if (thisx.val == 16) {
  83418. NEEDBITS(thisx.bits + 2);
  83419. DROPBITS(thisx.bits);
  83420. if (state->have == 0) {
  83421. strm->msg = (char *)"invalid bit length repeat";
  83422. state->mode = BAD;
  83423. break;
  83424. }
  83425. len = state->lens[state->have - 1];
  83426. copy = 3 + BITS(2);
  83427. DROPBITS(2);
  83428. }
  83429. else if (thisx.val == 17) {
  83430. NEEDBITS(thisx.bits + 3);
  83431. DROPBITS(thisx.bits);
  83432. len = 0;
  83433. copy = 3 + BITS(3);
  83434. DROPBITS(3);
  83435. }
  83436. else {
  83437. NEEDBITS(thisx.bits + 7);
  83438. DROPBITS(thisx.bits);
  83439. len = 0;
  83440. copy = 11 + BITS(7);
  83441. DROPBITS(7);
  83442. }
  83443. if (state->have + copy > state->nlen + state->ndist) {
  83444. strm->msg = (char *)"invalid bit length repeat";
  83445. state->mode = BAD;
  83446. break;
  83447. }
  83448. while (copy--)
  83449. state->lens[state->have++] = (unsigned short)len;
  83450. }
  83451. }
  83452. /* handle error breaks in while */
  83453. if (state->mode == BAD) break;
  83454. /* build code tables */
  83455. state->next = state->codes;
  83456. state->lencode = (code const FAR *)(state->next);
  83457. state->lenbits = 9;
  83458. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83459. &(state->lenbits), state->work);
  83460. if (ret) {
  83461. strm->msg = (char *)"invalid literal/lengths set";
  83462. state->mode = BAD;
  83463. break;
  83464. }
  83465. state->distcode = (code const FAR *)(state->next);
  83466. state->distbits = 6;
  83467. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83468. &(state->next), &(state->distbits), state->work);
  83469. if (ret) {
  83470. strm->msg = (char *)"invalid distances set";
  83471. state->mode = BAD;
  83472. break;
  83473. }
  83474. Tracev((stderr, "inflate: codes ok\n"));
  83475. state->mode = LEN;
  83476. case LEN:
  83477. if (have >= 6 && left >= 258) {
  83478. RESTORE();
  83479. inflate_fast(strm, out);
  83480. LOAD();
  83481. break;
  83482. }
  83483. for (;;) {
  83484. thisx = state->lencode[BITS(state->lenbits)];
  83485. if ((unsigned)(thisx.bits) <= bits) break;
  83486. PULLBYTE();
  83487. }
  83488. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83489. last = thisx;
  83490. for (;;) {
  83491. thisx = state->lencode[last.val +
  83492. (BITS(last.bits + last.op) >> last.bits)];
  83493. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83494. PULLBYTE();
  83495. }
  83496. DROPBITS(last.bits);
  83497. }
  83498. DROPBITS(thisx.bits);
  83499. state->length = (unsigned)thisx.val;
  83500. if ((int)(thisx.op) == 0) {
  83501. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83502. "inflate: literal '%c'\n" :
  83503. "inflate: literal 0x%02x\n", thisx.val));
  83504. state->mode = LIT;
  83505. break;
  83506. }
  83507. if (thisx.op & 32) {
  83508. Tracevv((stderr, "inflate: end of block\n"));
  83509. state->mode = TYPE;
  83510. break;
  83511. }
  83512. if (thisx.op & 64) {
  83513. strm->msg = (char *)"invalid literal/length code";
  83514. state->mode = BAD;
  83515. break;
  83516. }
  83517. state->extra = (unsigned)(thisx.op) & 15;
  83518. state->mode = LENEXT;
  83519. case LENEXT:
  83520. if (state->extra) {
  83521. NEEDBITS(state->extra);
  83522. state->length += BITS(state->extra);
  83523. DROPBITS(state->extra);
  83524. }
  83525. Tracevv((stderr, "inflate: length %u\n", state->length));
  83526. state->mode = DIST;
  83527. case DIST:
  83528. for (;;) {
  83529. thisx = state->distcode[BITS(state->distbits)];
  83530. if ((unsigned)(thisx.bits) <= bits) break;
  83531. PULLBYTE();
  83532. }
  83533. if ((thisx.op & 0xf0) == 0) {
  83534. last = thisx;
  83535. for (;;) {
  83536. thisx = state->distcode[last.val +
  83537. (BITS(last.bits + last.op) >> last.bits)];
  83538. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83539. PULLBYTE();
  83540. }
  83541. DROPBITS(last.bits);
  83542. }
  83543. DROPBITS(thisx.bits);
  83544. if (thisx.op & 64) {
  83545. strm->msg = (char *)"invalid distance code";
  83546. state->mode = BAD;
  83547. break;
  83548. }
  83549. state->offset = (unsigned)thisx.val;
  83550. state->extra = (unsigned)(thisx.op) & 15;
  83551. state->mode = DISTEXT;
  83552. case DISTEXT:
  83553. if (state->extra) {
  83554. NEEDBITS(state->extra);
  83555. state->offset += BITS(state->extra);
  83556. DROPBITS(state->extra);
  83557. }
  83558. #ifdef INFLATE_STRICT
  83559. if (state->offset > state->dmax) {
  83560. strm->msg = (char *)"invalid distance too far back";
  83561. state->mode = BAD;
  83562. break;
  83563. }
  83564. #endif
  83565. if (state->offset > state->whave + out - left) {
  83566. strm->msg = (char *)"invalid distance too far back";
  83567. state->mode = BAD;
  83568. break;
  83569. }
  83570. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83571. state->mode = MATCH;
  83572. case MATCH:
  83573. if (left == 0) goto inf_leave;
  83574. copy = out - left;
  83575. if (state->offset > copy) { /* copy from window */
  83576. copy = state->offset - copy;
  83577. if (copy > state->write) {
  83578. copy -= state->write;
  83579. from = state->window + (state->wsize - copy);
  83580. }
  83581. else
  83582. from = state->window + (state->write - copy);
  83583. if (copy > state->length) copy = state->length;
  83584. }
  83585. else { /* copy from output */
  83586. from = put - state->offset;
  83587. copy = state->length;
  83588. }
  83589. if (copy > left) copy = left;
  83590. left -= copy;
  83591. state->length -= copy;
  83592. do {
  83593. *put++ = *from++;
  83594. } while (--copy);
  83595. if (state->length == 0) state->mode = LEN;
  83596. break;
  83597. case LIT:
  83598. if (left == 0) goto inf_leave;
  83599. *put++ = (unsigned char)(state->length);
  83600. left--;
  83601. state->mode = LEN;
  83602. break;
  83603. case CHECK:
  83604. if (state->wrap) {
  83605. NEEDBITS(32);
  83606. out -= left;
  83607. strm->total_out += out;
  83608. state->total += out;
  83609. if (out)
  83610. strm->adler = state->check =
  83611. UPDATE(state->check, put - out, out);
  83612. out = left;
  83613. if ((
  83614. #ifdef GUNZIP
  83615. state->flags ? hold :
  83616. #endif
  83617. REVERSE(hold)) != state->check) {
  83618. strm->msg = (char *)"incorrect data check";
  83619. state->mode = BAD;
  83620. break;
  83621. }
  83622. INITBITS();
  83623. Tracev((stderr, "inflate: check matches trailer\n"));
  83624. }
  83625. #ifdef GUNZIP
  83626. state->mode = LENGTH;
  83627. case LENGTH:
  83628. if (state->wrap && state->flags) {
  83629. NEEDBITS(32);
  83630. if (hold != (state->total & 0xffffffffUL)) {
  83631. strm->msg = (char *)"incorrect length check";
  83632. state->mode = BAD;
  83633. break;
  83634. }
  83635. INITBITS();
  83636. Tracev((stderr, "inflate: length matches trailer\n"));
  83637. }
  83638. #endif
  83639. state->mode = DONE;
  83640. case DONE:
  83641. ret = Z_STREAM_END;
  83642. goto inf_leave;
  83643. case BAD:
  83644. ret = Z_DATA_ERROR;
  83645. goto inf_leave;
  83646. case MEM:
  83647. return Z_MEM_ERROR;
  83648. case SYNC:
  83649. default:
  83650. return Z_STREAM_ERROR;
  83651. }
  83652. /*
  83653. Return from inflate(), updating the total counts and the check value.
  83654. If there was no progress during the inflate() call, return a buffer
  83655. error. Call updatewindow() to create and/or update the window state.
  83656. Note: a memory error from inflate() is non-recoverable.
  83657. */
  83658. inf_leave:
  83659. RESTORE();
  83660. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83661. if (updatewindow(strm, out)) {
  83662. state->mode = MEM;
  83663. return Z_MEM_ERROR;
  83664. }
  83665. in -= strm->avail_in;
  83666. out -= strm->avail_out;
  83667. strm->total_in += in;
  83668. strm->total_out += out;
  83669. state->total += out;
  83670. if (state->wrap && out)
  83671. strm->adler = state->check =
  83672. UPDATE(state->check, strm->next_out - out, out);
  83673. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83674. (state->mode == TYPE ? 128 : 0);
  83675. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83676. ret = Z_BUF_ERROR;
  83677. return ret;
  83678. }
  83679. int ZEXPORT inflateEnd (z_streamp strm)
  83680. {
  83681. struct inflate_state FAR *state;
  83682. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83683. return Z_STREAM_ERROR;
  83684. state = (struct inflate_state FAR *)strm->state;
  83685. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83686. ZFREE(strm, strm->state);
  83687. strm->state = Z_NULL;
  83688. Tracev((stderr, "inflate: end\n"));
  83689. return Z_OK;
  83690. }
  83691. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83692. {
  83693. struct inflate_state FAR *state;
  83694. unsigned long id_;
  83695. /* check state */
  83696. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83697. state = (struct inflate_state FAR *)strm->state;
  83698. if (state->wrap != 0 && state->mode != DICT)
  83699. return Z_STREAM_ERROR;
  83700. /* check for correct dictionary id */
  83701. if (state->mode == DICT) {
  83702. id_ = adler32(0L, Z_NULL, 0);
  83703. id_ = adler32(id_, dictionary, dictLength);
  83704. if (id_ != state->check)
  83705. return Z_DATA_ERROR;
  83706. }
  83707. /* copy dictionary to window */
  83708. if (updatewindow(strm, strm->avail_out)) {
  83709. state->mode = MEM;
  83710. return Z_MEM_ERROR;
  83711. }
  83712. if (dictLength > state->wsize) {
  83713. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83714. state->wsize);
  83715. state->whave = state->wsize;
  83716. }
  83717. else {
  83718. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83719. dictLength);
  83720. state->whave = dictLength;
  83721. }
  83722. state->havedict = 1;
  83723. Tracev((stderr, "inflate: dictionary set\n"));
  83724. return Z_OK;
  83725. }
  83726. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83727. {
  83728. struct inflate_state FAR *state;
  83729. /* check state */
  83730. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83731. state = (struct inflate_state FAR *)strm->state;
  83732. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83733. /* save header structure */
  83734. state->head = head;
  83735. head->done = 0;
  83736. return Z_OK;
  83737. }
  83738. /*
  83739. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83740. or when out of input. When called, *have is the number of pattern bytes
  83741. found in order so far, in 0..3. On return *have is updated to the new
  83742. state. If on return *have equals four, then the pattern was found and the
  83743. return value is how many bytes were read including the last byte of the
  83744. pattern. If *have is less than four, then the pattern has not been found
  83745. yet and the return value is len. In the latter case, syncsearch() can be
  83746. called again with more data and the *have state. *have is initialized to
  83747. zero for the first call.
  83748. */
  83749. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83750. {
  83751. unsigned got;
  83752. unsigned next;
  83753. got = *have;
  83754. next = 0;
  83755. while (next < len && got < 4) {
  83756. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83757. got++;
  83758. else if (buf[next])
  83759. got = 0;
  83760. else
  83761. got = 4 - got;
  83762. next++;
  83763. }
  83764. *have = got;
  83765. return next;
  83766. }
  83767. int ZEXPORT inflateSync (z_streamp strm)
  83768. {
  83769. unsigned len; /* number of bytes to look at or looked at */
  83770. unsigned long in, out; /* temporary to save total_in and total_out */
  83771. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83772. struct inflate_state FAR *state;
  83773. /* check parameters */
  83774. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83775. state = (struct inflate_state FAR *)strm->state;
  83776. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83777. /* if first time, start search in bit buffer */
  83778. if (state->mode != SYNC) {
  83779. state->mode = SYNC;
  83780. state->hold <<= state->bits & 7;
  83781. state->bits -= state->bits & 7;
  83782. len = 0;
  83783. while (state->bits >= 8) {
  83784. buf[len++] = (unsigned char)(state->hold);
  83785. state->hold >>= 8;
  83786. state->bits -= 8;
  83787. }
  83788. state->have = 0;
  83789. syncsearch(&(state->have), buf, len);
  83790. }
  83791. /* search available input */
  83792. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83793. strm->avail_in -= len;
  83794. strm->next_in += len;
  83795. strm->total_in += len;
  83796. /* return no joy or set up to restart inflate() on a new block */
  83797. if (state->have != 4) return Z_DATA_ERROR;
  83798. in = strm->total_in; out = strm->total_out;
  83799. inflateReset(strm);
  83800. strm->total_in = in; strm->total_out = out;
  83801. state->mode = TYPE;
  83802. return Z_OK;
  83803. }
  83804. /*
  83805. Returns true if inflate is currently at the end of a block generated by
  83806. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  83807. implementation to provide an additional safety check. PPP uses
  83808. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  83809. block. When decompressing, PPP checks that at the end of input packet,
  83810. inflate is waiting for these length bytes.
  83811. */
  83812. int ZEXPORT inflateSyncPoint (z_streamp strm)
  83813. {
  83814. struct inflate_state FAR *state;
  83815. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83816. state = (struct inflate_state FAR *)strm->state;
  83817. return state->mode == STORED && state->bits == 0;
  83818. }
  83819. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  83820. {
  83821. struct inflate_state FAR *state;
  83822. struct inflate_state FAR *copy;
  83823. unsigned char FAR *window;
  83824. unsigned wsize;
  83825. /* check input */
  83826. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  83827. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  83828. return Z_STREAM_ERROR;
  83829. state = (struct inflate_state FAR *)source->state;
  83830. /* allocate space */
  83831. copy = (struct inflate_state FAR *)
  83832. ZALLOC(source, 1, sizeof(struct inflate_state));
  83833. if (copy == Z_NULL) return Z_MEM_ERROR;
  83834. window = Z_NULL;
  83835. if (state->window != Z_NULL) {
  83836. window = (unsigned char FAR *)
  83837. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  83838. if (window == Z_NULL) {
  83839. ZFREE(source, copy);
  83840. return Z_MEM_ERROR;
  83841. }
  83842. }
  83843. /* copy state */
  83844. zmemcpy(dest, source, sizeof(z_stream));
  83845. zmemcpy(copy, state, sizeof(struct inflate_state));
  83846. if (state->lencode >= state->codes &&
  83847. state->lencode <= state->codes + ENOUGH - 1) {
  83848. copy->lencode = copy->codes + (state->lencode - state->codes);
  83849. copy->distcode = copy->codes + (state->distcode - state->codes);
  83850. }
  83851. copy->next = copy->codes + (state->next - state->codes);
  83852. if (window != Z_NULL) {
  83853. wsize = 1U << state->wbits;
  83854. zmemcpy(window, state->window, wsize);
  83855. }
  83856. copy->window = window;
  83857. dest->state = (struct internal_state FAR *)copy;
  83858. return Z_OK;
  83859. }
  83860. /*** End of inlined file: inflate.c ***/
  83861. /*** Start of inlined file: inftrees.c ***/
  83862. #define MAXBITS 15
  83863. const char inflate_copyright[] =
  83864. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  83865. /*
  83866. If you use the zlib library in a product, an acknowledgment is welcome
  83867. in the documentation of your product. If for some reason you cannot
  83868. include such an acknowledgment, I would appreciate that you keep this
  83869. copyright string in the executable of your product.
  83870. */
  83871. /*
  83872. Build a set of tables to decode the provided canonical Huffman code.
  83873. The code lengths are lens[0..codes-1]. The result starts at *table,
  83874. whose indices are 0..2^bits-1. work is a writable array of at least
  83875. lens shorts, which is used as a work area. type is the type of code
  83876. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  83877. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  83878. on return points to the next available entry's address. bits is the
  83879. requested root table index bits, and on return it is the actual root
  83880. table index bits. It will differ if the request is greater than the
  83881. longest code or if it is less than the shortest code.
  83882. */
  83883. int inflate_table (codetype type,
  83884. unsigned short FAR *lens,
  83885. unsigned codes,
  83886. code FAR * FAR *table,
  83887. unsigned FAR *bits,
  83888. unsigned short FAR *work)
  83889. {
  83890. unsigned len; /* a code's length in bits */
  83891. unsigned sym; /* index of code symbols */
  83892. unsigned min, max; /* minimum and maximum code lengths */
  83893. unsigned root; /* number of index bits for root table */
  83894. unsigned curr; /* number of index bits for current table */
  83895. unsigned drop; /* code bits to drop for sub-table */
  83896. int left; /* number of prefix codes available */
  83897. unsigned used; /* code entries in table used */
  83898. unsigned huff; /* Huffman code */
  83899. unsigned incr; /* for incrementing code, index */
  83900. unsigned fill; /* index for replicating entries */
  83901. unsigned low; /* low bits for current root entry */
  83902. unsigned mask; /* mask for low root bits */
  83903. code thisx; /* table entry for duplication */
  83904. code FAR *next; /* next available space in table */
  83905. const unsigned short FAR *base; /* base value table to use */
  83906. const unsigned short FAR *extra; /* extra bits table to use */
  83907. int end; /* use base and extra for symbol > end */
  83908. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  83909. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  83910. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  83911. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  83912. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  83913. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  83914. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  83915. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  83916. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  83917. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  83918. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  83919. 8193, 12289, 16385, 24577, 0, 0};
  83920. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  83921. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  83922. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  83923. 28, 28, 29, 29, 64, 64};
  83924. /*
  83925. Process a set of code lengths to create a canonical Huffman code. The
  83926. code lengths are lens[0..codes-1]. Each length corresponds to the
  83927. symbols 0..codes-1. The Huffman code is generated by first sorting the
  83928. symbols by length from short to long, and retaining the symbol order
  83929. for codes with equal lengths. Then the code starts with all zero bits
  83930. for the first code of the shortest length, and the codes are integer
  83931. increments for the same length, and zeros are appended as the length
  83932. increases. For the deflate format, these bits are stored backwards
  83933. from their more natural integer increment ordering, and so when the
  83934. decoding tables are built in the large loop below, the integer codes
  83935. are incremented backwards.
  83936. This routine assumes, but does not check, that all of the entries in
  83937. lens[] are in the range 0..MAXBITS. The caller must assure this.
  83938. 1..MAXBITS is interpreted as that code length. zero means that that
  83939. symbol does not occur in this code.
  83940. The codes are sorted by computing a count of codes for each length,
  83941. creating from that a table of starting indices for each length in the
  83942. sorted table, and then entering the symbols in order in the sorted
  83943. table. The sorted table is work[], with that space being provided by
  83944. the caller.
  83945. The length counts are used for other purposes as well, i.e. finding
  83946. the minimum and maximum length codes, determining if there are any
  83947. codes at all, checking for a valid set of lengths, and looking ahead
  83948. at length counts to determine sub-table sizes when building the
  83949. decoding tables.
  83950. */
  83951. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  83952. for (len = 0; len <= MAXBITS; len++)
  83953. count[len] = 0;
  83954. for (sym = 0; sym < codes; sym++)
  83955. count[lens[sym]]++;
  83956. /* bound code lengths, force root to be within code lengths */
  83957. root = *bits;
  83958. for (max = MAXBITS; max >= 1; max--)
  83959. if (count[max] != 0) break;
  83960. if (root > max) root = max;
  83961. if (max == 0) { /* no symbols to code at all */
  83962. thisx.op = (unsigned char)64; /* invalid code marker */
  83963. thisx.bits = (unsigned char)1;
  83964. thisx.val = (unsigned short)0;
  83965. *(*table)++ = thisx; /* make a table to force an error */
  83966. *(*table)++ = thisx;
  83967. *bits = 1;
  83968. return 0; /* no symbols, but wait for decoding to report error */
  83969. }
  83970. for (min = 1; min <= MAXBITS; min++)
  83971. if (count[min] != 0) break;
  83972. if (root < min) root = min;
  83973. /* check for an over-subscribed or incomplete set of lengths */
  83974. left = 1;
  83975. for (len = 1; len <= MAXBITS; len++) {
  83976. left <<= 1;
  83977. left -= count[len];
  83978. if (left < 0) return -1; /* over-subscribed */
  83979. }
  83980. if (left > 0 && (type == CODES || max != 1))
  83981. return -1; /* incomplete set */
  83982. /* generate offsets into symbol table for each length for sorting */
  83983. offs[1] = 0;
  83984. for (len = 1; len < MAXBITS; len++)
  83985. offs[len + 1] = offs[len] + count[len];
  83986. /* sort symbols by length, by symbol order within each length */
  83987. for (sym = 0; sym < codes; sym++)
  83988. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  83989. /*
  83990. Create and fill in decoding tables. In this loop, the table being
  83991. filled is at next and has curr index bits. The code being used is huff
  83992. with length len. That code is converted to an index by dropping drop
  83993. bits off of the bottom. For codes where len is less than drop + curr,
  83994. those top drop + curr - len bits are incremented through all values to
  83995. fill the table with replicated entries.
  83996. root is the number of index bits for the root table. When len exceeds
  83997. root, sub-tables are created pointed to by the root entry with an index
  83998. of the low root bits of huff. This is saved in low to check for when a
  83999. new sub-table should be started. drop is zero when the root table is
  84000. being filled, and drop is root when sub-tables are being filled.
  84001. When a new sub-table is needed, it is necessary to look ahead in the
  84002. code lengths to determine what size sub-table is needed. The length
  84003. counts are used for this, and so count[] is decremented as codes are
  84004. entered in the tables.
  84005. used keeps track of how many table entries have been allocated from the
  84006. provided *table space. It is checked when a LENS table is being made
  84007. against the space in *table, ENOUGH, minus the maximum space needed by
  84008. the worst case distance code, MAXD. This should never happen, but the
  84009. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84010. This assumes that when type == LENS, bits == 9.
  84011. sym increments through all symbols, and the loop terminates when
  84012. all codes of length max, i.e. all codes, have been processed. This
  84013. routine permits incomplete codes, so another loop after this one fills
  84014. in the rest of the decoding tables with invalid code markers.
  84015. */
  84016. /* set up for code type */
  84017. switch (type) {
  84018. case CODES:
  84019. base = extra = work; /* dummy value--not used */
  84020. end = 19;
  84021. break;
  84022. case LENS:
  84023. base = lbase;
  84024. base -= 257;
  84025. extra = lext;
  84026. extra -= 257;
  84027. end = 256;
  84028. break;
  84029. default: /* DISTS */
  84030. base = dbase;
  84031. extra = dext;
  84032. end = -1;
  84033. }
  84034. /* initialize state for loop */
  84035. huff = 0; /* starting code */
  84036. sym = 0; /* starting code symbol */
  84037. len = min; /* starting code length */
  84038. next = *table; /* current table to fill in */
  84039. curr = root; /* current table index bits */
  84040. drop = 0; /* current bits to drop from code for index */
  84041. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84042. used = 1U << root; /* use root table entries */
  84043. mask = used - 1; /* mask for comparing low */
  84044. /* check available table space */
  84045. if (type == LENS && used >= ENOUGH - MAXD)
  84046. return 1;
  84047. /* process all codes and make table entries */
  84048. for (;;) {
  84049. /* create table entry */
  84050. thisx.bits = (unsigned char)(len - drop);
  84051. if ((int)(work[sym]) < end) {
  84052. thisx.op = (unsigned char)0;
  84053. thisx.val = work[sym];
  84054. }
  84055. else if ((int)(work[sym]) > end) {
  84056. thisx.op = (unsigned char)(extra[work[sym]]);
  84057. thisx.val = base[work[sym]];
  84058. }
  84059. else {
  84060. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84061. thisx.val = 0;
  84062. }
  84063. /* replicate for those indices with low len bits equal to huff */
  84064. incr = 1U << (len - drop);
  84065. fill = 1U << curr;
  84066. min = fill; /* save offset to next table */
  84067. do {
  84068. fill -= incr;
  84069. next[(huff >> drop) + fill] = thisx;
  84070. } while (fill != 0);
  84071. /* backwards increment the len-bit code huff */
  84072. incr = 1U << (len - 1);
  84073. while (huff & incr)
  84074. incr >>= 1;
  84075. if (incr != 0) {
  84076. huff &= incr - 1;
  84077. huff += incr;
  84078. }
  84079. else
  84080. huff = 0;
  84081. /* go to next symbol, update count, len */
  84082. sym++;
  84083. if (--(count[len]) == 0) {
  84084. if (len == max) break;
  84085. len = lens[work[sym]];
  84086. }
  84087. /* create new sub-table if needed */
  84088. if (len > root && (huff & mask) != low) {
  84089. /* if first time, transition to sub-tables */
  84090. if (drop == 0)
  84091. drop = root;
  84092. /* increment past last table */
  84093. next += min; /* here min is 1 << curr */
  84094. /* determine length of next table */
  84095. curr = len - drop;
  84096. left = (int)(1 << curr);
  84097. while (curr + drop < max) {
  84098. left -= count[curr + drop];
  84099. if (left <= 0) break;
  84100. curr++;
  84101. left <<= 1;
  84102. }
  84103. /* check for enough space */
  84104. used += 1U << curr;
  84105. if (type == LENS && used >= ENOUGH - MAXD)
  84106. return 1;
  84107. /* point entry in root table to sub-table */
  84108. low = huff & mask;
  84109. (*table)[low].op = (unsigned char)curr;
  84110. (*table)[low].bits = (unsigned char)root;
  84111. (*table)[low].val = (unsigned short)(next - *table);
  84112. }
  84113. }
  84114. /*
  84115. Fill in rest of table for incomplete codes. This loop is similar to the
  84116. loop above in incrementing huff for table indices. It is assumed that
  84117. len is equal to curr + drop, so there is no loop needed to increment
  84118. through high index bits. When the current sub-table is filled, the loop
  84119. drops back to the root table to fill in any remaining entries there.
  84120. */
  84121. thisx.op = (unsigned char)64; /* invalid code marker */
  84122. thisx.bits = (unsigned char)(len - drop);
  84123. thisx.val = (unsigned short)0;
  84124. while (huff != 0) {
  84125. /* when done with sub-table, drop back to root table */
  84126. if (drop != 0 && (huff & mask) != low) {
  84127. drop = 0;
  84128. len = root;
  84129. next = *table;
  84130. thisx.bits = (unsigned char)len;
  84131. }
  84132. /* put invalid code marker in table */
  84133. next[huff >> drop] = thisx;
  84134. /* backwards increment the len-bit code huff */
  84135. incr = 1U << (len - 1);
  84136. while (huff & incr)
  84137. incr >>= 1;
  84138. if (incr != 0) {
  84139. huff &= incr - 1;
  84140. huff += incr;
  84141. }
  84142. else
  84143. huff = 0;
  84144. }
  84145. /* set return parameters */
  84146. *table += used;
  84147. *bits = root;
  84148. return 0;
  84149. }
  84150. /*** End of inlined file: inftrees.c ***/
  84151. /*** Start of inlined file: trees.c ***/
  84152. /*
  84153. * ALGORITHM
  84154. *
  84155. * The "deflation" process uses several Huffman trees. The more
  84156. * common source values are represented by shorter bit sequences.
  84157. *
  84158. * Each code tree is stored in a compressed form which is itself
  84159. * a Huffman encoding of the lengths of all the code strings (in
  84160. * ascending order by source values). The actual code strings are
  84161. * reconstructed from the lengths in the inflate process, as described
  84162. * in the deflate specification.
  84163. *
  84164. * REFERENCES
  84165. *
  84166. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84167. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84168. *
  84169. * Storer, James A.
  84170. * Data Compression: Methods and Theory, pp. 49-50.
  84171. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84172. *
  84173. * Sedgewick, R.
  84174. * Algorithms, p290.
  84175. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84176. */
  84177. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84178. /* #define GEN_TREES_H */
  84179. #ifdef DEBUG
  84180. # include <ctype.h>
  84181. #endif
  84182. /* ===========================================================================
  84183. * Constants
  84184. */
  84185. #define MAX_BL_BITS 7
  84186. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84187. #define END_BLOCK 256
  84188. /* end of block literal code */
  84189. #define REP_3_6 16
  84190. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84191. #define REPZ_3_10 17
  84192. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84193. #define REPZ_11_138 18
  84194. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84195. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84196. = {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};
  84197. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84198. = {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};
  84199. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84200. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84201. local const uch bl_order[BL_CODES]
  84202. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84203. /* The lengths of the bit length codes are sent in order of decreasing
  84204. * probability, to avoid transmitting the lengths for unused bit length codes.
  84205. */
  84206. #define Buf_size (8 * 2*sizeof(char))
  84207. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84208. * more than 16 bits on some systems.)
  84209. */
  84210. /* ===========================================================================
  84211. * Local data. These are initialized only once.
  84212. */
  84213. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84214. #if defined(GEN_TREES_H) || !defined(STDC)
  84215. /* non ANSI compilers may not accept trees.h */
  84216. local ct_data static_ltree[L_CODES+2];
  84217. /* The static literal tree. Since the bit lengths are imposed, there is no
  84218. * need for the L_CODES extra codes used during heap construction. However
  84219. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84220. * below).
  84221. */
  84222. local ct_data static_dtree[D_CODES];
  84223. /* The static distance tree. (Actually a trivial tree since all codes use
  84224. * 5 bits.)
  84225. */
  84226. uch _dist_code[DIST_CODE_LEN];
  84227. /* Distance codes. The first 256 values correspond to the distances
  84228. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84229. * the 15 bit distances.
  84230. */
  84231. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84232. /* length code for each normalized match length (0 == MIN_MATCH) */
  84233. local int base_length[LENGTH_CODES];
  84234. /* First normalized length for each code (0 = MIN_MATCH) */
  84235. local int base_dist[D_CODES];
  84236. /* First normalized distance for each code (0 = distance of 1) */
  84237. #else
  84238. /*** Start of inlined file: trees.h ***/
  84239. local const ct_data static_ltree[L_CODES+2] = {
  84240. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84241. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84242. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84243. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84244. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84245. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84246. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84247. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84248. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84249. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84250. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84251. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84252. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84253. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84254. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84255. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84256. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84257. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84258. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84259. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84260. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84261. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84262. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84263. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84264. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84265. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84266. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84267. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84268. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84269. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84270. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84271. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84272. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84273. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84274. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84275. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84276. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84277. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84278. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84279. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84280. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84281. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84282. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84283. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84284. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84285. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84286. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84287. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84288. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84289. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84290. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84291. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84292. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84293. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84294. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84295. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84296. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84297. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84298. };
  84299. local const ct_data static_dtree[D_CODES] = {
  84300. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84301. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84302. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84303. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84304. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84305. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84306. };
  84307. const uch _dist_code[DIST_CODE_LEN] = {
  84308. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84309. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84310. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84311. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84312. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84313. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84314. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84315. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84316. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84317. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84318. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84319. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84320. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84321. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84322. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84323. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84324. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84325. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84326. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84327. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84328. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84329. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84330. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84331. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84332. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84333. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84334. };
  84335. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84336. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84337. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84338. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84339. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84340. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84341. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84342. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84343. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84344. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84345. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84346. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84347. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84348. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84349. };
  84350. local const int base_length[LENGTH_CODES] = {
  84351. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84352. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84353. };
  84354. local const int base_dist[D_CODES] = {
  84355. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84356. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84357. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84358. };
  84359. /*** End of inlined file: trees.h ***/
  84360. #endif /* GEN_TREES_H */
  84361. struct static_tree_desc_s {
  84362. const ct_data *static_tree; /* static tree or NULL */
  84363. const intf *extra_bits; /* extra bits for each code or NULL */
  84364. int extra_base; /* base index for extra_bits */
  84365. int elems; /* max number of elements in the tree */
  84366. int max_length; /* max bit length for the codes */
  84367. };
  84368. local static_tree_desc static_l_desc =
  84369. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84370. local static_tree_desc static_d_desc =
  84371. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84372. local static_tree_desc static_bl_desc =
  84373. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84374. /* ===========================================================================
  84375. * Local (static) routines in this file.
  84376. */
  84377. local void tr_static_init OF((void));
  84378. local void init_block OF((deflate_state *s));
  84379. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84380. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84381. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84382. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84383. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84384. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84385. local int build_bl_tree OF((deflate_state *s));
  84386. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84387. int blcodes));
  84388. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84389. ct_data *dtree));
  84390. local void set_data_type OF((deflate_state *s));
  84391. local unsigned bi_reverse OF((unsigned value, int length));
  84392. local void bi_windup OF((deflate_state *s));
  84393. local void bi_flush OF((deflate_state *s));
  84394. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84395. int header));
  84396. #ifdef GEN_TREES_H
  84397. local void gen_trees_header OF((void));
  84398. #endif
  84399. #ifndef DEBUG
  84400. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84401. /* Send a code of the given tree. c and tree must not have side effects */
  84402. #else /* DEBUG */
  84403. # define send_code(s, c, tree) \
  84404. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84405. send_bits(s, tree[c].Code, tree[c].Len); }
  84406. #endif
  84407. /* ===========================================================================
  84408. * Output a short LSB first on the stream.
  84409. * IN assertion: there is enough room in pendingBuf.
  84410. */
  84411. #define put_short(s, w) { \
  84412. put_byte(s, (uch)((w) & 0xff)); \
  84413. put_byte(s, (uch)((ush)(w) >> 8)); \
  84414. }
  84415. /* ===========================================================================
  84416. * Send a value on a given number of bits.
  84417. * IN assertion: length <= 16 and value fits in length bits.
  84418. */
  84419. #ifdef DEBUG
  84420. local void send_bits OF((deflate_state *s, int value, int length));
  84421. local void send_bits (deflate_state *s, int value, int length)
  84422. {
  84423. Tracevv((stderr," l %2d v %4x ", length, value));
  84424. Assert(length > 0 && length <= 15, "invalid length");
  84425. s->bits_sent += (ulg)length;
  84426. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84427. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84428. * unused bits in value.
  84429. */
  84430. if (s->bi_valid > (int)Buf_size - length) {
  84431. s->bi_buf |= (value << s->bi_valid);
  84432. put_short(s, s->bi_buf);
  84433. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84434. s->bi_valid += length - Buf_size;
  84435. } else {
  84436. s->bi_buf |= value << s->bi_valid;
  84437. s->bi_valid += length;
  84438. }
  84439. }
  84440. #else /* !DEBUG */
  84441. #define send_bits(s, value, length) \
  84442. { int len = length;\
  84443. if (s->bi_valid > (int)Buf_size - len) {\
  84444. int val = value;\
  84445. s->bi_buf |= (val << s->bi_valid);\
  84446. put_short(s, s->bi_buf);\
  84447. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84448. s->bi_valid += len - Buf_size;\
  84449. } else {\
  84450. s->bi_buf |= (value) << s->bi_valid;\
  84451. s->bi_valid += len;\
  84452. }\
  84453. }
  84454. #endif /* DEBUG */
  84455. /* the arguments must not have side effects */
  84456. /* ===========================================================================
  84457. * Initialize the various 'constant' tables.
  84458. */
  84459. local void tr_static_init()
  84460. {
  84461. #if defined(GEN_TREES_H) || !defined(STDC)
  84462. static int static_init_done = 0;
  84463. int n; /* iterates over tree elements */
  84464. int bits; /* bit counter */
  84465. int length; /* length value */
  84466. int code; /* code value */
  84467. int dist; /* distance index */
  84468. ush bl_count[MAX_BITS+1];
  84469. /* number of codes at each bit length for an optimal tree */
  84470. if (static_init_done) return;
  84471. /* For some embedded targets, global variables are not initialized: */
  84472. static_l_desc.static_tree = static_ltree;
  84473. static_l_desc.extra_bits = extra_lbits;
  84474. static_d_desc.static_tree = static_dtree;
  84475. static_d_desc.extra_bits = extra_dbits;
  84476. static_bl_desc.extra_bits = extra_blbits;
  84477. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84478. length = 0;
  84479. for (code = 0; code < LENGTH_CODES-1; code++) {
  84480. base_length[code] = length;
  84481. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84482. _length_code[length++] = (uch)code;
  84483. }
  84484. }
  84485. Assert (length == 256, "tr_static_init: length != 256");
  84486. /* Note that the length 255 (match length 258) can be represented
  84487. * in two different ways: code 284 + 5 bits or code 285, so we
  84488. * overwrite length_code[255] to use the best encoding:
  84489. */
  84490. _length_code[length-1] = (uch)code;
  84491. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84492. dist = 0;
  84493. for (code = 0 ; code < 16; code++) {
  84494. base_dist[code] = dist;
  84495. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84496. _dist_code[dist++] = (uch)code;
  84497. }
  84498. }
  84499. Assert (dist == 256, "tr_static_init: dist != 256");
  84500. dist >>= 7; /* from now on, all distances are divided by 128 */
  84501. for ( ; code < D_CODES; code++) {
  84502. base_dist[code] = dist << 7;
  84503. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84504. _dist_code[256 + dist++] = (uch)code;
  84505. }
  84506. }
  84507. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84508. /* Construct the codes of the static literal tree */
  84509. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84510. n = 0;
  84511. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84512. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84513. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84514. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84515. /* Codes 286 and 287 do not exist, but we must include them in the
  84516. * tree construction to get a canonical Huffman tree (longest code
  84517. * all ones)
  84518. */
  84519. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84520. /* The static distance tree is trivial: */
  84521. for (n = 0; n < D_CODES; n++) {
  84522. static_dtree[n].Len = 5;
  84523. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84524. }
  84525. static_init_done = 1;
  84526. # ifdef GEN_TREES_H
  84527. gen_trees_header();
  84528. # endif
  84529. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84530. }
  84531. /* ===========================================================================
  84532. * Genererate the file trees.h describing the static trees.
  84533. */
  84534. #ifdef GEN_TREES_H
  84535. # ifndef DEBUG
  84536. # include <stdio.h>
  84537. # endif
  84538. # define SEPARATOR(i, last, width) \
  84539. ((i) == (last)? "\n};\n\n" : \
  84540. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84541. void gen_trees_header()
  84542. {
  84543. FILE *header = fopen("trees.h", "w");
  84544. int i;
  84545. Assert (header != NULL, "Can't open trees.h");
  84546. fprintf(header,
  84547. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84548. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84549. for (i = 0; i < L_CODES+2; i++) {
  84550. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84551. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84552. }
  84553. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84554. for (i = 0; i < D_CODES; i++) {
  84555. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84556. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84557. }
  84558. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84559. for (i = 0; i < DIST_CODE_LEN; i++) {
  84560. fprintf(header, "%2u%s", _dist_code[i],
  84561. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84562. }
  84563. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84564. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84565. fprintf(header, "%2u%s", _length_code[i],
  84566. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84567. }
  84568. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84569. for (i = 0; i < LENGTH_CODES; i++) {
  84570. fprintf(header, "%1u%s", base_length[i],
  84571. SEPARATOR(i, LENGTH_CODES-1, 20));
  84572. }
  84573. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84574. for (i = 0; i < D_CODES; i++) {
  84575. fprintf(header, "%5u%s", base_dist[i],
  84576. SEPARATOR(i, D_CODES-1, 10));
  84577. }
  84578. fclose(header);
  84579. }
  84580. #endif /* GEN_TREES_H */
  84581. /* ===========================================================================
  84582. * Initialize the tree data structures for a new zlib stream.
  84583. */
  84584. void _tr_init(deflate_state *s)
  84585. {
  84586. tr_static_init();
  84587. s->l_desc.dyn_tree = s->dyn_ltree;
  84588. s->l_desc.stat_desc = &static_l_desc;
  84589. s->d_desc.dyn_tree = s->dyn_dtree;
  84590. s->d_desc.stat_desc = &static_d_desc;
  84591. s->bl_desc.dyn_tree = s->bl_tree;
  84592. s->bl_desc.stat_desc = &static_bl_desc;
  84593. s->bi_buf = 0;
  84594. s->bi_valid = 0;
  84595. s->last_eob_len = 8; /* enough lookahead for inflate */
  84596. #ifdef DEBUG
  84597. s->compressed_len = 0L;
  84598. s->bits_sent = 0L;
  84599. #endif
  84600. /* Initialize the first block of the first file: */
  84601. init_block(s);
  84602. }
  84603. /* ===========================================================================
  84604. * Initialize a new block.
  84605. */
  84606. local void init_block (deflate_state *s)
  84607. {
  84608. int n; /* iterates over tree elements */
  84609. /* Initialize the trees. */
  84610. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84611. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84612. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84613. s->dyn_ltree[END_BLOCK].Freq = 1;
  84614. s->opt_len = s->static_len = 0L;
  84615. s->last_lit = s->matches = 0;
  84616. }
  84617. #define SMALLEST 1
  84618. /* Index within the heap array of least frequent node in the Huffman tree */
  84619. /* ===========================================================================
  84620. * Remove the smallest element from the heap and recreate the heap with
  84621. * one less element. Updates heap and heap_len.
  84622. */
  84623. #define pqremove(s, tree, top) \
  84624. {\
  84625. top = s->heap[SMALLEST]; \
  84626. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84627. pqdownheap(s, tree, SMALLEST); \
  84628. }
  84629. /* ===========================================================================
  84630. * Compares to subtrees, using the tree depth as tie breaker when
  84631. * the subtrees have equal frequency. This minimizes the worst case length.
  84632. */
  84633. #define smaller(tree, n, m, depth) \
  84634. (tree[n].Freq < tree[m].Freq || \
  84635. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84636. /* ===========================================================================
  84637. * Restore the heap property by moving down the tree starting at node k,
  84638. * exchanging a node with the smallest of its two sons if necessary, stopping
  84639. * when the heap property is re-established (each father smaller than its
  84640. * two sons).
  84641. */
  84642. local void pqdownheap (deflate_state *s,
  84643. ct_data *tree, /* the tree to restore */
  84644. int k) /* node to move down */
  84645. {
  84646. int v = s->heap[k];
  84647. int j = k << 1; /* left son of k */
  84648. while (j <= s->heap_len) {
  84649. /* Set j to the smallest of the two sons: */
  84650. if (j < s->heap_len &&
  84651. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84652. j++;
  84653. }
  84654. /* Exit if v is smaller than both sons */
  84655. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84656. /* Exchange v with the smallest son */
  84657. s->heap[k] = s->heap[j]; k = j;
  84658. /* And continue down the tree, setting j to the left son of k */
  84659. j <<= 1;
  84660. }
  84661. s->heap[k] = v;
  84662. }
  84663. /* ===========================================================================
  84664. * Compute the optimal bit lengths for a tree and update the total bit length
  84665. * for the current block.
  84666. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84667. * above are the tree nodes sorted by increasing frequency.
  84668. * OUT assertions: the field len is set to the optimal bit length, the
  84669. * array bl_count contains the frequencies for each bit length.
  84670. * The length opt_len is updated; static_len is also updated if stree is
  84671. * not null.
  84672. */
  84673. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84674. {
  84675. ct_data *tree = desc->dyn_tree;
  84676. int max_code = desc->max_code;
  84677. const ct_data *stree = desc->stat_desc->static_tree;
  84678. const intf *extra = desc->stat_desc->extra_bits;
  84679. int base = desc->stat_desc->extra_base;
  84680. int max_length = desc->stat_desc->max_length;
  84681. int h; /* heap index */
  84682. int n, m; /* iterate over the tree elements */
  84683. int bits; /* bit length */
  84684. int xbits; /* extra bits */
  84685. ush f; /* frequency */
  84686. int overflow = 0; /* number of elements with bit length too large */
  84687. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84688. /* In a first pass, compute the optimal bit lengths (which may
  84689. * overflow in the case of the bit length tree).
  84690. */
  84691. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84692. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84693. n = s->heap[h];
  84694. bits = tree[tree[n].Dad].Len + 1;
  84695. if (bits > max_length) bits = max_length, overflow++;
  84696. tree[n].Len = (ush)bits;
  84697. /* We overwrite tree[n].Dad which is no longer needed */
  84698. if (n > max_code) continue; /* not a leaf node */
  84699. s->bl_count[bits]++;
  84700. xbits = 0;
  84701. if (n >= base) xbits = extra[n-base];
  84702. f = tree[n].Freq;
  84703. s->opt_len += (ulg)f * (bits + xbits);
  84704. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84705. }
  84706. if (overflow == 0) return;
  84707. Trace((stderr,"\nbit length overflow\n"));
  84708. /* This happens for example on obj2 and pic of the Calgary corpus */
  84709. /* Find the first bit length which could increase: */
  84710. do {
  84711. bits = max_length-1;
  84712. while (s->bl_count[bits] == 0) bits--;
  84713. s->bl_count[bits]--; /* move one leaf down the tree */
  84714. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84715. s->bl_count[max_length]--;
  84716. /* The brother of the overflow item also moves one step up,
  84717. * but this does not affect bl_count[max_length]
  84718. */
  84719. overflow -= 2;
  84720. } while (overflow > 0);
  84721. /* Now recompute all bit lengths, scanning in increasing frequency.
  84722. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84723. * lengths instead of fixing only the wrong ones. This idea is taken
  84724. * from 'ar' written by Haruhiko Okumura.)
  84725. */
  84726. for (bits = max_length; bits != 0; bits--) {
  84727. n = s->bl_count[bits];
  84728. while (n != 0) {
  84729. m = s->heap[--h];
  84730. if (m > max_code) continue;
  84731. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84732. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84733. s->opt_len += ((long)bits - (long)tree[m].Len)
  84734. *(long)tree[m].Freq;
  84735. tree[m].Len = (ush)bits;
  84736. }
  84737. n--;
  84738. }
  84739. }
  84740. }
  84741. /* ===========================================================================
  84742. * Generate the codes for a given tree and bit counts (which need not be
  84743. * optimal).
  84744. * IN assertion: the array bl_count contains the bit length statistics for
  84745. * the given tree and the field len is set for all tree elements.
  84746. * OUT assertion: the field code is set for all tree elements of non
  84747. * zero code length.
  84748. */
  84749. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84750. int max_code, /* largest code with non zero frequency */
  84751. ushf *bl_count) /* number of codes at each bit length */
  84752. {
  84753. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84754. ush code = 0; /* running code value */
  84755. int bits; /* bit index */
  84756. int n; /* code index */
  84757. /* The distribution counts are first used to generate the code values
  84758. * without bit reversal.
  84759. */
  84760. for (bits = 1; bits <= MAX_BITS; bits++) {
  84761. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84762. }
  84763. /* Check that the bit counts in bl_count are consistent. The last code
  84764. * must be all ones.
  84765. */
  84766. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84767. "inconsistent bit counts");
  84768. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84769. for (n = 0; n <= max_code; n++) {
  84770. int len = tree[n].Len;
  84771. if (len == 0) continue;
  84772. /* Now reverse the bits */
  84773. tree[n].Code = bi_reverse(next_code[len]++, len);
  84774. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84775. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84776. }
  84777. }
  84778. /* ===========================================================================
  84779. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84780. * Update the total bit length for the current block.
  84781. * IN assertion: the field freq is set for all tree elements.
  84782. * OUT assertions: the fields len and code are set to the optimal bit length
  84783. * and corresponding code. The length opt_len is updated; static_len is
  84784. * also updated if stree is not null. The field max_code is set.
  84785. */
  84786. local void build_tree (deflate_state *s,
  84787. tree_desc *desc) /* the tree descriptor */
  84788. {
  84789. ct_data *tree = desc->dyn_tree;
  84790. const ct_data *stree = desc->stat_desc->static_tree;
  84791. int elems = desc->stat_desc->elems;
  84792. int n, m; /* iterate over heap elements */
  84793. int max_code = -1; /* largest code with non zero frequency */
  84794. int node; /* new node being created */
  84795. /* Construct the initial heap, with least frequent element in
  84796. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84797. * heap[0] is not used.
  84798. */
  84799. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84800. for (n = 0; n < elems; n++) {
  84801. if (tree[n].Freq != 0) {
  84802. s->heap[++(s->heap_len)] = max_code = n;
  84803. s->depth[n] = 0;
  84804. } else {
  84805. tree[n].Len = 0;
  84806. }
  84807. }
  84808. /* The pkzip format requires that at least one distance code exists,
  84809. * and that at least one bit should be sent even if there is only one
  84810. * possible code. So to avoid special checks later on we force at least
  84811. * two codes of non zero frequency.
  84812. */
  84813. while (s->heap_len < 2) {
  84814. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  84815. tree[node].Freq = 1;
  84816. s->depth[node] = 0;
  84817. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  84818. /* node is 0 or 1 so it does not have extra bits */
  84819. }
  84820. desc->max_code = max_code;
  84821. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  84822. * establish sub-heaps of increasing lengths:
  84823. */
  84824. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  84825. /* Construct the Huffman tree by repeatedly combining the least two
  84826. * frequent nodes.
  84827. */
  84828. node = elems; /* next internal node of the tree */
  84829. do {
  84830. pqremove(s, tree, n); /* n = node of least frequency */
  84831. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  84832. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  84833. s->heap[--(s->heap_max)] = m;
  84834. /* Create a new node father of n and m */
  84835. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  84836. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  84837. s->depth[n] : s->depth[m]) + 1);
  84838. tree[n].Dad = tree[m].Dad = (ush)node;
  84839. #ifdef DUMP_BL_TREE
  84840. if (tree == s->bl_tree) {
  84841. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  84842. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  84843. }
  84844. #endif
  84845. /* and insert the new node in the heap */
  84846. s->heap[SMALLEST] = node++;
  84847. pqdownheap(s, tree, SMALLEST);
  84848. } while (s->heap_len >= 2);
  84849. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  84850. /* At this point, the fields freq and dad are set. We can now
  84851. * generate the bit lengths.
  84852. */
  84853. gen_bitlen(s, (tree_desc *)desc);
  84854. /* The field len is now set, we can generate the bit codes */
  84855. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  84856. }
  84857. /* ===========================================================================
  84858. * Scan a literal or distance tree to determine the frequencies of the codes
  84859. * in the bit length tree.
  84860. */
  84861. local void scan_tree (deflate_state *s,
  84862. ct_data *tree, /* the tree to be scanned */
  84863. int max_code) /* and its largest code of non zero frequency */
  84864. {
  84865. int n; /* iterates over all tree elements */
  84866. int prevlen = -1; /* last emitted length */
  84867. int curlen; /* length of current code */
  84868. int nextlen = tree[0].Len; /* length of next code */
  84869. int count = 0; /* repeat count of the current code */
  84870. int max_count = 7; /* max repeat count */
  84871. int min_count = 4; /* min repeat count */
  84872. if (nextlen == 0) max_count = 138, min_count = 3;
  84873. tree[max_code+1].Len = (ush)0xffff; /* guard */
  84874. for (n = 0; n <= max_code; n++) {
  84875. curlen = nextlen; nextlen = tree[n+1].Len;
  84876. if (++count < max_count && curlen == nextlen) {
  84877. continue;
  84878. } else if (count < min_count) {
  84879. s->bl_tree[curlen].Freq += count;
  84880. } else if (curlen != 0) {
  84881. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  84882. s->bl_tree[REP_3_6].Freq++;
  84883. } else if (count <= 10) {
  84884. s->bl_tree[REPZ_3_10].Freq++;
  84885. } else {
  84886. s->bl_tree[REPZ_11_138].Freq++;
  84887. }
  84888. count = 0; prevlen = curlen;
  84889. if (nextlen == 0) {
  84890. max_count = 138, min_count = 3;
  84891. } else if (curlen == nextlen) {
  84892. max_count = 6, min_count = 3;
  84893. } else {
  84894. max_count = 7, min_count = 4;
  84895. }
  84896. }
  84897. }
  84898. /* ===========================================================================
  84899. * Send a literal or distance tree in compressed form, using the codes in
  84900. * bl_tree.
  84901. */
  84902. local void send_tree (deflate_state *s,
  84903. ct_data *tree, /* the tree to be scanned */
  84904. int max_code) /* and its largest code of non zero frequency */
  84905. {
  84906. int n; /* iterates over all tree elements */
  84907. int prevlen = -1; /* last emitted length */
  84908. int curlen; /* length of current code */
  84909. int nextlen = tree[0].Len; /* length of next code */
  84910. int count = 0; /* repeat count of the current code */
  84911. int max_count = 7; /* max repeat count */
  84912. int min_count = 4; /* min repeat count */
  84913. /* tree[max_code+1].Len = -1; */ /* guard already set */
  84914. if (nextlen == 0) max_count = 138, min_count = 3;
  84915. for (n = 0; n <= max_code; n++) {
  84916. curlen = nextlen; nextlen = tree[n+1].Len;
  84917. if (++count < max_count && curlen == nextlen) {
  84918. continue;
  84919. } else if (count < min_count) {
  84920. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  84921. } else if (curlen != 0) {
  84922. if (curlen != prevlen) {
  84923. send_code(s, curlen, s->bl_tree); count--;
  84924. }
  84925. Assert(count >= 3 && count <= 6, " 3_6?");
  84926. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  84927. } else if (count <= 10) {
  84928. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  84929. } else {
  84930. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  84931. }
  84932. count = 0; prevlen = curlen;
  84933. if (nextlen == 0) {
  84934. max_count = 138, min_count = 3;
  84935. } else if (curlen == nextlen) {
  84936. max_count = 6, min_count = 3;
  84937. } else {
  84938. max_count = 7, min_count = 4;
  84939. }
  84940. }
  84941. }
  84942. /* ===========================================================================
  84943. * Construct the Huffman tree for the bit lengths and return the index in
  84944. * bl_order of the last bit length code to send.
  84945. */
  84946. local int build_bl_tree (deflate_state *s)
  84947. {
  84948. int max_blindex; /* index of last bit length code of non zero freq */
  84949. /* Determine the bit length frequencies for literal and distance trees */
  84950. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  84951. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  84952. /* Build the bit length tree: */
  84953. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  84954. /* opt_len now includes the length of the tree representations, except
  84955. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  84956. */
  84957. /* Determine the number of bit length codes to send. The pkzip format
  84958. * requires that at least 4 bit length codes be sent. (appnote.txt says
  84959. * 3 but the actual value used is 4.)
  84960. */
  84961. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  84962. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  84963. }
  84964. /* Update opt_len to include the bit length tree and counts */
  84965. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  84966. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  84967. s->opt_len, s->static_len));
  84968. return max_blindex;
  84969. }
  84970. /* ===========================================================================
  84971. * Send the header for a block using dynamic Huffman trees: the counts, the
  84972. * lengths of the bit length codes, the literal tree and the distance tree.
  84973. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  84974. */
  84975. local void send_all_trees (deflate_state *s,
  84976. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  84977. {
  84978. int rank; /* index in bl_order */
  84979. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  84980. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  84981. "too many codes");
  84982. Tracev((stderr, "\nbl counts: "));
  84983. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  84984. send_bits(s, dcodes-1, 5);
  84985. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  84986. for (rank = 0; rank < blcodes; rank++) {
  84987. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  84988. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  84989. }
  84990. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  84991. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  84992. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  84993. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  84994. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  84995. }
  84996. /* ===========================================================================
  84997. * Send a stored block
  84998. */
  84999. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85000. {
  85001. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85002. #ifdef DEBUG
  85003. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85004. s->compressed_len += (stored_len + 4) << 3;
  85005. #endif
  85006. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85007. }
  85008. /* ===========================================================================
  85009. * Send one empty static block to give enough lookahead for inflate.
  85010. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85011. * The current inflate code requires 9 bits of lookahead. If the
  85012. * last two codes for the previous block (real code plus EOB) were coded
  85013. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85014. * the last real code. In this case we send two empty static blocks instead
  85015. * of one. (There are no problems if the previous block is stored or fixed.)
  85016. * To simplify the code, we assume the worst case of last real code encoded
  85017. * on one bit only.
  85018. */
  85019. void _tr_align (deflate_state *s)
  85020. {
  85021. send_bits(s, STATIC_TREES<<1, 3);
  85022. send_code(s, END_BLOCK, static_ltree);
  85023. #ifdef DEBUG
  85024. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85025. #endif
  85026. bi_flush(s);
  85027. /* Of the 10 bits for the empty block, we have already sent
  85028. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85029. * the EOB of the previous block) was thus at least one plus the length
  85030. * of the EOB plus what we have just sent of the empty static block.
  85031. */
  85032. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85033. send_bits(s, STATIC_TREES<<1, 3);
  85034. send_code(s, END_BLOCK, static_ltree);
  85035. #ifdef DEBUG
  85036. s->compressed_len += 10L;
  85037. #endif
  85038. bi_flush(s);
  85039. }
  85040. s->last_eob_len = 7;
  85041. }
  85042. /* ===========================================================================
  85043. * Determine the best encoding for the current block: dynamic trees, static
  85044. * trees or store, and output the encoded block to the zip file.
  85045. */
  85046. void _tr_flush_block (deflate_state *s,
  85047. charf *buf, /* input block, or NULL if too old */
  85048. ulg stored_len, /* length of input block */
  85049. int eof) /* true if this is the last block for a file */
  85050. {
  85051. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85052. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85053. /* Build the Huffman trees unless a stored block is forced */
  85054. if (s->level > 0) {
  85055. /* Check if the file is binary or text */
  85056. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85057. set_data_type(s);
  85058. /* Construct the literal and distance trees */
  85059. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85060. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85061. s->static_len));
  85062. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85063. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85064. s->static_len));
  85065. /* At this point, opt_len and static_len are the total bit lengths of
  85066. * the compressed block data, excluding the tree representations.
  85067. */
  85068. /* Build the bit length tree for the above two trees, and get the index
  85069. * in bl_order of the last bit length code to send.
  85070. */
  85071. max_blindex = build_bl_tree(s);
  85072. /* Determine the best encoding. Compute the block lengths in bytes. */
  85073. opt_lenb = (s->opt_len+3+7)>>3;
  85074. static_lenb = (s->static_len+3+7)>>3;
  85075. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85076. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85077. s->last_lit));
  85078. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85079. } else {
  85080. Assert(buf != (char*)0, "lost buf");
  85081. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85082. }
  85083. #ifdef FORCE_STORED
  85084. if (buf != (char*)0) { /* force stored block */
  85085. #else
  85086. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85087. /* 4: two words for the lengths */
  85088. #endif
  85089. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85090. * Otherwise we can't have processed more than WSIZE input bytes since
  85091. * the last block flush, because compression would have been
  85092. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85093. * transform a block into a stored block.
  85094. */
  85095. _tr_stored_block(s, buf, stored_len, eof);
  85096. #ifdef FORCE_STATIC
  85097. } else if (static_lenb >= 0) { /* force static trees */
  85098. #else
  85099. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85100. #endif
  85101. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85102. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85103. #ifdef DEBUG
  85104. s->compressed_len += 3 + s->static_len;
  85105. #endif
  85106. } else {
  85107. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85108. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85109. max_blindex+1);
  85110. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85111. #ifdef DEBUG
  85112. s->compressed_len += 3 + s->opt_len;
  85113. #endif
  85114. }
  85115. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85116. /* The above check is made mod 2^32, for files larger than 512 MB
  85117. * and uLong implemented on 32 bits.
  85118. */
  85119. init_block(s);
  85120. if (eof) {
  85121. bi_windup(s);
  85122. #ifdef DEBUG
  85123. s->compressed_len += 7; /* align on byte boundary */
  85124. #endif
  85125. }
  85126. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85127. s->compressed_len-7*eof));
  85128. }
  85129. /* ===========================================================================
  85130. * Save the match info and tally the frequency counts. Return true if
  85131. * the current block must be flushed.
  85132. */
  85133. int _tr_tally (deflate_state *s,
  85134. unsigned dist, /* distance of matched string */
  85135. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85136. {
  85137. s->d_buf[s->last_lit] = (ush)dist;
  85138. s->l_buf[s->last_lit++] = (uch)lc;
  85139. if (dist == 0) {
  85140. /* lc is the unmatched char */
  85141. s->dyn_ltree[lc].Freq++;
  85142. } else {
  85143. s->matches++;
  85144. /* Here, lc is the match length - MIN_MATCH */
  85145. dist--; /* dist = match distance - 1 */
  85146. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85147. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85148. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85149. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85150. s->dyn_dtree[d_code(dist)].Freq++;
  85151. }
  85152. #ifdef TRUNCATE_BLOCK
  85153. /* Try to guess if it is profitable to stop the current block here */
  85154. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85155. /* Compute an upper bound for the compressed length */
  85156. ulg out_length = (ulg)s->last_lit*8L;
  85157. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85158. int dcode;
  85159. for (dcode = 0; dcode < D_CODES; dcode++) {
  85160. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85161. (5L+extra_dbits[dcode]);
  85162. }
  85163. out_length >>= 3;
  85164. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85165. s->last_lit, in_length, out_length,
  85166. 100L - out_length*100L/in_length));
  85167. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85168. }
  85169. #endif
  85170. return (s->last_lit == s->lit_bufsize-1);
  85171. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85172. * on 16 bit machines and because stored blocks are restricted to
  85173. * 64K-1 bytes.
  85174. */
  85175. }
  85176. /* ===========================================================================
  85177. * Send the block data compressed using the given Huffman trees
  85178. */
  85179. local void compress_block (deflate_state *s,
  85180. ct_data *ltree, /* literal tree */
  85181. ct_data *dtree) /* distance tree */
  85182. {
  85183. unsigned dist; /* distance of matched string */
  85184. int lc; /* match length or unmatched char (if dist == 0) */
  85185. unsigned lx = 0; /* running index in l_buf */
  85186. unsigned code; /* the code to send */
  85187. int extra; /* number of extra bits to send */
  85188. if (s->last_lit != 0) do {
  85189. dist = s->d_buf[lx];
  85190. lc = s->l_buf[lx++];
  85191. if (dist == 0) {
  85192. send_code(s, lc, ltree); /* send a literal byte */
  85193. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85194. } else {
  85195. /* Here, lc is the match length - MIN_MATCH */
  85196. code = _length_code[lc];
  85197. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85198. extra = extra_lbits[code];
  85199. if (extra != 0) {
  85200. lc -= base_length[code];
  85201. send_bits(s, lc, extra); /* send the extra length bits */
  85202. }
  85203. dist--; /* dist is now the match distance - 1 */
  85204. code = d_code(dist);
  85205. Assert (code < D_CODES, "bad d_code");
  85206. send_code(s, code, dtree); /* send the distance code */
  85207. extra = extra_dbits[code];
  85208. if (extra != 0) {
  85209. dist -= base_dist[code];
  85210. send_bits(s, dist, extra); /* send the extra distance bits */
  85211. }
  85212. } /* literal or match pair ? */
  85213. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85214. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85215. "pendingBuf overflow");
  85216. } while (lx < s->last_lit);
  85217. send_code(s, END_BLOCK, ltree);
  85218. s->last_eob_len = ltree[END_BLOCK].Len;
  85219. }
  85220. /* ===========================================================================
  85221. * Set the data type to BINARY or TEXT, using a crude approximation:
  85222. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85223. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85224. * IN assertion: the fields Freq of dyn_ltree are set.
  85225. */
  85226. local void set_data_type (deflate_state *s)
  85227. {
  85228. int n;
  85229. for (n = 0; n < 9; n++)
  85230. if (s->dyn_ltree[n].Freq != 0)
  85231. break;
  85232. if (n == 9)
  85233. for (n = 14; n < 32; n++)
  85234. if (s->dyn_ltree[n].Freq != 0)
  85235. break;
  85236. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85237. }
  85238. /* ===========================================================================
  85239. * Reverse the first len bits of a code, using straightforward code (a faster
  85240. * method would use a table)
  85241. * IN assertion: 1 <= len <= 15
  85242. */
  85243. local unsigned bi_reverse (unsigned code, int len)
  85244. {
  85245. register unsigned res = 0;
  85246. do {
  85247. res |= code & 1;
  85248. code >>= 1, res <<= 1;
  85249. } while (--len > 0);
  85250. return res >> 1;
  85251. }
  85252. /* ===========================================================================
  85253. * Flush the bit buffer, keeping at most 7 bits in it.
  85254. */
  85255. local void bi_flush (deflate_state *s)
  85256. {
  85257. if (s->bi_valid == 16) {
  85258. put_short(s, s->bi_buf);
  85259. s->bi_buf = 0;
  85260. s->bi_valid = 0;
  85261. } else if (s->bi_valid >= 8) {
  85262. put_byte(s, (Byte)s->bi_buf);
  85263. s->bi_buf >>= 8;
  85264. s->bi_valid -= 8;
  85265. }
  85266. }
  85267. /* ===========================================================================
  85268. * Flush the bit buffer and align the output on a byte boundary
  85269. */
  85270. local void bi_windup (deflate_state *s)
  85271. {
  85272. if (s->bi_valid > 8) {
  85273. put_short(s, s->bi_buf);
  85274. } else if (s->bi_valid > 0) {
  85275. put_byte(s, (Byte)s->bi_buf);
  85276. }
  85277. s->bi_buf = 0;
  85278. s->bi_valid = 0;
  85279. #ifdef DEBUG
  85280. s->bits_sent = (s->bits_sent+7) & ~7;
  85281. #endif
  85282. }
  85283. /* ===========================================================================
  85284. * Copy a stored block, storing first the length and its
  85285. * one's complement if requested.
  85286. */
  85287. local void copy_block(deflate_state *s,
  85288. charf *buf, /* the input data */
  85289. unsigned len, /* its length */
  85290. int header) /* true if block header must be written */
  85291. {
  85292. bi_windup(s); /* align on byte boundary */
  85293. s->last_eob_len = 8; /* enough lookahead for inflate */
  85294. if (header) {
  85295. put_short(s, (ush)len);
  85296. put_short(s, (ush)~len);
  85297. #ifdef DEBUG
  85298. s->bits_sent += 2*16;
  85299. #endif
  85300. }
  85301. #ifdef DEBUG
  85302. s->bits_sent += (ulg)len<<3;
  85303. #endif
  85304. while (len--) {
  85305. put_byte(s, *buf++);
  85306. }
  85307. }
  85308. /*** End of inlined file: trees.c ***/
  85309. /*** Start of inlined file: zutil.c ***/
  85310. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85311. #ifndef NO_DUMMY_DECL
  85312. struct internal_state {int dummy;}; /* for buggy compilers */
  85313. #endif
  85314. const char * const z_errmsg[10] = {
  85315. "need dictionary", /* Z_NEED_DICT 2 */
  85316. "stream end", /* Z_STREAM_END 1 */
  85317. "", /* Z_OK 0 */
  85318. "file error", /* Z_ERRNO (-1) */
  85319. "stream error", /* Z_STREAM_ERROR (-2) */
  85320. "data error", /* Z_DATA_ERROR (-3) */
  85321. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85322. "buffer error", /* Z_BUF_ERROR (-5) */
  85323. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85324. ""};
  85325. /*const char * ZEXPORT zlibVersion()
  85326. {
  85327. return ZLIB_VERSION;
  85328. }
  85329. uLong ZEXPORT zlibCompileFlags()
  85330. {
  85331. uLong flags;
  85332. flags = 0;
  85333. switch (sizeof(uInt)) {
  85334. case 2: break;
  85335. case 4: flags += 1; break;
  85336. case 8: flags += 2; break;
  85337. default: flags += 3;
  85338. }
  85339. switch (sizeof(uLong)) {
  85340. case 2: break;
  85341. case 4: flags += 1 << 2; break;
  85342. case 8: flags += 2 << 2; break;
  85343. default: flags += 3 << 2;
  85344. }
  85345. switch (sizeof(voidpf)) {
  85346. case 2: break;
  85347. case 4: flags += 1 << 4; break;
  85348. case 8: flags += 2 << 4; break;
  85349. default: flags += 3 << 4;
  85350. }
  85351. switch (sizeof(z_off_t)) {
  85352. case 2: break;
  85353. case 4: flags += 1 << 6; break;
  85354. case 8: flags += 2 << 6; break;
  85355. default: flags += 3 << 6;
  85356. }
  85357. #ifdef DEBUG
  85358. flags += 1 << 8;
  85359. #endif
  85360. #if defined(ASMV) || defined(ASMINF)
  85361. flags += 1 << 9;
  85362. #endif
  85363. #ifdef ZLIB_WINAPI
  85364. flags += 1 << 10;
  85365. #endif
  85366. #ifdef BUILDFIXED
  85367. flags += 1 << 12;
  85368. #endif
  85369. #ifdef DYNAMIC_CRC_TABLE
  85370. flags += 1 << 13;
  85371. #endif
  85372. #ifdef NO_GZCOMPRESS
  85373. flags += 1L << 16;
  85374. #endif
  85375. #ifdef NO_GZIP
  85376. flags += 1L << 17;
  85377. #endif
  85378. #ifdef PKZIP_BUG_WORKAROUND
  85379. flags += 1L << 20;
  85380. #endif
  85381. #ifdef FASTEST
  85382. flags += 1L << 21;
  85383. #endif
  85384. #ifdef STDC
  85385. # ifdef NO_vsnprintf
  85386. flags += 1L << 25;
  85387. # ifdef HAS_vsprintf_void
  85388. flags += 1L << 26;
  85389. # endif
  85390. # else
  85391. # ifdef HAS_vsnprintf_void
  85392. flags += 1L << 26;
  85393. # endif
  85394. # endif
  85395. #else
  85396. flags += 1L << 24;
  85397. # ifdef NO_snprintf
  85398. flags += 1L << 25;
  85399. # ifdef HAS_sprintf_void
  85400. flags += 1L << 26;
  85401. # endif
  85402. # else
  85403. # ifdef HAS_snprintf_void
  85404. flags += 1L << 26;
  85405. # endif
  85406. # endif
  85407. #endif
  85408. return flags;
  85409. }*/
  85410. #ifdef DEBUG
  85411. # ifndef verbose
  85412. # define verbose 0
  85413. # endif
  85414. int z_verbose = verbose;
  85415. void z_error (const char *m)
  85416. {
  85417. fprintf(stderr, "%s\n", m);
  85418. exit(1);
  85419. }
  85420. #endif
  85421. /* exported to allow conversion of error code to string for compress() and
  85422. * uncompress()
  85423. */
  85424. const char * ZEXPORT zError(int err)
  85425. {
  85426. return ERR_MSG(err);
  85427. }
  85428. #if defined(_WIN32_WCE)
  85429. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85430. * errno. We define it as a global variable to simplify porting.
  85431. * Its value is always 0 and should not be used.
  85432. */
  85433. int errno = 0;
  85434. #endif
  85435. #ifndef HAVE_MEMCPY
  85436. void zmemcpy(dest, source, len)
  85437. Bytef* dest;
  85438. const Bytef* source;
  85439. uInt len;
  85440. {
  85441. if (len == 0) return;
  85442. do {
  85443. *dest++ = *source++; /* ??? to be unrolled */
  85444. } while (--len != 0);
  85445. }
  85446. int zmemcmp(s1, s2, len)
  85447. const Bytef* s1;
  85448. const Bytef* s2;
  85449. uInt len;
  85450. {
  85451. uInt j;
  85452. for (j = 0; j < len; j++) {
  85453. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85454. }
  85455. return 0;
  85456. }
  85457. void zmemzero(dest, len)
  85458. Bytef* dest;
  85459. uInt len;
  85460. {
  85461. if (len == 0) return;
  85462. do {
  85463. *dest++ = 0; /* ??? to be unrolled */
  85464. } while (--len != 0);
  85465. }
  85466. #endif
  85467. #ifdef SYS16BIT
  85468. #ifdef __TURBOC__
  85469. /* Turbo C in 16-bit mode */
  85470. # define MY_ZCALLOC
  85471. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85472. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85473. * must fix the pointer. Warning: the pointer must be put back to its
  85474. * original form in order to free it, use zcfree().
  85475. */
  85476. #define MAX_PTR 10
  85477. /* 10*64K = 640K */
  85478. local int next_ptr = 0;
  85479. typedef struct ptr_table_s {
  85480. voidpf org_ptr;
  85481. voidpf new_ptr;
  85482. } ptr_table;
  85483. local ptr_table table[MAX_PTR];
  85484. /* This table is used to remember the original form of pointers
  85485. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85486. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85487. * protected from concurrent access. This hack doesn't work anyway on
  85488. * a protected system like OS/2. Use Microsoft C instead.
  85489. */
  85490. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85491. {
  85492. voidpf buf = opaque; /* just to make some compilers happy */
  85493. ulg bsize = (ulg)items*size;
  85494. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85495. * will return a usable pointer which doesn't have to be normalized.
  85496. */
  85497. if (bsize < 65520L) {
  85498. buf = farmalloc(bsize);
  85499. if (*(ush*)&buf != 0) return buf;
  85500. } else {
  85501. buf = farmalloc(bsize + 16L);
  85502. }
  85503. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85504. table[next_ptr].org_ptr = buf;
  85505. /* Normalize the pointer to seg:0 */
  85506. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85507. *(ush*)&buf = 0;
  85508. table[next_ptr++].new_ptr = buf;
  85509. return buf;
  85510. }
  85511. void zcfree (voidpf opaque, voidpf ptr)
  85512. {
  85513. int n;
  85514. if (*(ush*)&ptr != 0) { /* object < 64K */
  85515. farfree(ptr);
  85516. return;
  85517. }
  85518. /* Find the original pointer */
  85519. for (n = 0; n < next_ptr; n++) {
  85520. if (ptr != table[n].new_ptr) continue;
  85521. farfree(table[n].org_ptr);
  85522. while (++n < next_ptr) {
  85523. table[n-1] = table[n];
  85524. }
  85525. next_ptr--;
  85526. return;
  85527. }
  85528. ptr = opaque; /* just to make some compilers happy */
  85529. Assert(0, "zcfree: ptr not found");
  85530. }
  85531. #endif /* __TURBOC__ */
  85532. #ifdef M_I86
  85533. /* Microsoft C in 16-bit mode */
  85534. # define MY_ZCALLOC
  85535. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85536. # define _halloc halloc
  85537. # define _hfree hfree
  85538. #endif
  85539. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85540. {
  85541. if (opaque) opaque = 0; /* to make compiler happy */
  85542. return _halloc((long)items, size);
  85543. }
  85544. void zcfree (voidpf opaque, voidpf ptr)
  85545. {
  85546. if (opaque) opaque = 0; /* to make compiler happy */
  85547. _hfree(ptr);
  85548. }
  85549. #endif /* M_I86 */
  85550. #endif /* SYS16BIT */
  85551. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85552. #ifndef STDC
  85553. extern voidp malloc OF((uInt size));
  85554. extern voidp calloc OF((uInt items, uInt size));
  85555. extern void free OF((voidpf ptr));
  85556. #endif
  85557. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85558. {
  85559. if (opaque) items += size - size; /* make compiler happy */
  85560. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85561. (voidpf)calloc(items, size);
  85562. }
  85563. void zcfree (voidpf opaque, voidpf ptr)
  85564. {
  85565. free(ptr);
  85566. if (opaque) return; /* make compiler happy */
  85567. }
  85568. #endif /* MY_ZCALLOC */
  85569. /*** End of inlined file: zutil.c ***/
  85570. #undef Byte
  85571. }
  85572. #else
  85573. #include <zlib.h>
  85574. #endif
  85575. }
  85576. #if JUCE_MSVC
  85577. #pragma warning (pop)
  85578. #endif
  85579. BEGIN_JUCE_NAMESPACE
  85580. // internal helper object that holds the zlib structures so they don't have to be
  85581. // included publicly.
  85582. class GZIPDecompressHelper
  85583. {
  85584. public:
  85585. GZIPDecompressHelper (const bool noWrap)
  85586. : finished (true),
  85587. needsDictionary (false),
  85588. error (true),
  85589. streamIsValid (false),
  85590. data (0),
  85591. dataSize (0)
  85592. {
  85593. using namespace zlibNamespace;
  85594. zerostruct (stream);
  85595. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85596. finished = error = ! streamIsValid;
  85597. }
  85598. ~GZIPDecompressHelper()
  85599. {
  85600. using namespace zlibNamespace;
  85601. if (streamIsValid)
  85602. inflateEnd (&stream);
  85603. }
  85604. bool needsInput() const throw() { return dataSize <= 0; }
  85605. void setInput (uint8* const data_, const int size) throw()
  85606. {
  85607. data = data_;
  85608. dataSize = size;
  85609. }
  85610. int doNextBlock (uint8* const dest, const int destSize)
  85611. {
  85612. using namespace zlibNamespace;
  85613. if (streamIsValid && data != 0 && ! finished)
  85614. {
  85615. stream.next_in = data;
  85616. stream.next_out = dest;
  85617. stream.avail_in = dataSize;
  85618. stream.avail_out = destSize;
  85619. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85620. {
  85621. case Z_STREAM_END:
  85622. finished = true;
  85623. // deliberate fall-through
  85624. case Z_OK:
  85625. data += dataSize - stream.avail_in;
  85626. dataSize = stream.avail_in;
  85627. return destSize - stream.avail_out;
  85628. case Z_NEED_DICT:
  85629. needsDictionary = true;
  85630. data += dataSize - stream.avail_in;
  85631. dataSize = stream.avail_in;
  85632. break;
  85633. case Z_DATA_ERROR:
  85634. case Z_MEM_ERROR:
  85635. error = true;
  85636. default:
  85637. break;
  85638. }
  85639. }
  85640. return 0;
  85641. }
  85642. bool finished, needsDictionary, error, streamIsValid;
  85643. private:
  85644. zlibNamespace::z_stream stream;
  85645. uint8* data;
  85646. int dataSize;
  85647. GZIPDecompressHelper (const GZIPDecompressHelper&);
  85648. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  85649. };
  85650. const int gzipDecompBufferSize = 32768;
  85651. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85652. const bool deleteSourceWhenDestroyed,
  85653. const bool noWrap_,
  85654. const int64 uncompressedStreamLength_)
  85655. : sourceStream (sourceStream_),
  85656. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85657. uncompressedStreamLength (uncompressedStreamLength_),
  85658. noWrap (noWrap_),
  85659. isEof (false),
  85660. activeBufferSize (0),
  85661. originalSourcePos (sourceStream_->getPosition()),
  85662. currentPos (0),
  85663. buffer (gzipDecompBufferSize),
  85664. helper (new GZIPDecompressHelper (noWrap_))
  85665. {
  85666. }
  85667. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85668. {
  85669. }
  85670. int64 GZIPDecompressorInputStream::getTotalLength()
  85671. {
  85672. return uncompressedStreamLength;
  85673. }
  85674. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85675. {
  85676. if ((howMany > 0) && ! isEof)
  85677. {
  85678. jassert (destBuffer != 0);
  85679. if (destBuffer != 0)
  85680. {
  85681. int numRead = 0;
  85682. uint8* d = static_cast <uint8*> (destBuffer);
  85683. while (! helper->error)
  85684. {
  85685. const int n = helper->doNextBlock (d, howMany);
  85686. currentPos += n;
  85687. if (n == 0)
  85688. {
  85689. if (helper->finished || helper->needsDictionary)
  85690. {
  85691. isEof = true;
  85692. return numRead;
  85693. }
  85694. if (helper->needsInput())
  85695. {
  85696. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  85697. if (activeBufferSize > 0)
  85698. {
  85699. helper->setInput (buffer, activeBufferSize);
  85700. }
  85701. else
  85702. {
  85703. isEof = true;
  85704. return numRead;
  85705. }
  85706. }
  85707. }
  85708. else
  85709. {
  85710. numRead += n;
  85711. howMany -= n;
  85712. d += n;
  85713. if (howMany <= 0)
  85714. return numRead;
  85715. }
  85716. }
  85717. }
  85718. }
  85719. return 0;
  85720. }
  85721. bool GZIPDecompressorInputStream::isExhausted()
  85722. {
  85723. return helper->error || isEof;
  85724. }
  85725. int64 GZIPDecompressorInputStream::getPosition()
  85726. {
  85727. return currentPos;
  85728. }
  85729. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85730. {
  85731. if (newPos < currentPos)
  85732. {
  85733. // to go backwards, reset the stream and start again..
  85734. isEof = false;
  85735. activeBufferSize = 0;
  85736. currentPos = 0;
  85737. helper = new GZIPDecompressHelper (noWrap);
  85738. sourceStream->setPosition (originalSourcePos);
  85739. }
  85740. skipNextBytes (newPos - currentPos);
  85741. return true;
  85742. }
  85743. END_JUCE_NAMESPACE
  85744. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85745. #endif
  85746. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85747. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85748. #if JUCE_USE_FLAC
  85749. #if JUCE_WINDOWS
  85750. #include <windows.h>
  85751. #endif
  85752. namespace FlacNamespace
  85753. {
  85754. #if JUCE_INCLUDE_FLAC_CODE
  85755. #if JUCE_MSVC
  85756. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  85757. #endif
  85758. #define FLAC__NO_DLL 1
  85759. #if ! defined (SIZE_MAX)
  85760. #define SIZE_MAX 0xffffffff
  85761. #endif
  85762. #define __STDC_LIMIT_MACROS 1
  85763. /*** Start of inlined file: all.h ***/
  85764. #ifndef FLAC__ALL_H
  85765. #define FLAC__ALL_H
  85766. /*** Start of inlined file: export.h ***/
  85767. #ifndef FLAC__EXPORT_H
  85768. #define FLAC__EXPORT_H
  85769. /** \file include/FLAC/export.h
  85770. *
  85771. * \brief
  85772. * This module contains #defines and symbols for exporting function
  85773. * calls, and providing version information and compiled-in features.
  85774. *
  85775. * See the \link flac_export export \endlink module.
  85776. */
  85777. /** \defgroup flac_export FLAC/export.h: export symbols
  85778. * \ingroup flac
  85779. *
  85780. * \brief
  85781. * This module contains #defines and symbols for exporting function
  85782. * calls, and providing version information and compiled-in features.
  85783. *
  85784. * If you are compiling with MSVC and will link to the static library
  85785. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85786. * make sure the symbols are exported properly.
  85787. *
  85788. * \{
  85789. */
  85790. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85791. #define FLAC_API
  85792. #else
  85793. #ifdef FLAC_API_EXPORTS
  85794. #define FLAC_API _declspec(dllexport)
  85795. #else
  85796. #define FLAC_API _declspec(dllimport)
  85797. #endif
  85798. #endif
  85799. /** These #defines will mirror the libtool-based library version number, see
  85800. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  85801. */
  85802. #define FLAC_API_VERSION_CURRENT 10
  85803. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  85804. #define FLAC_API_VERSION_AGE 2 /**< see above */
  85805. #ifdef __cplusplus
  85806. extern "C" {
  85807. #endif
  85808. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  85809. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  85810. #ifdef __cplusplus
  85811. }
  85812. #endif
  85813. /* \} */
  85814. #endif
  85815. /*** End of inlined file: export.h ***/
  85816. /*** Start of inlined file: assert.h ***/
  85817. #ifndef FLAC__ASSERT_H
  85818. #define FLAC__ASSERT_H
  85819. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  85820. #ifdef DEBUG
  85821. #include <assert.h>
  85822. #define FLAC__ASSERT(x) assert(x)
  85823. #define FLAC__ASSERT_DECLARATION(x) x
  85824. #else
  85825. #define FLAC__ASSERT(x)
  85826. #define FLAC__ASSERT_DECLARATION(x)
  85827. #endif
  85828. #endif
  85829. /*** End of inlined file: assert.h ***/
  85830. /*** Start of inlined file: callback.h ***/
  85831. #ifndef FLAC__CALLBACK_H
  85832. #define FLAC__CALLBACK_H
  85833. /*** Start of inlined file: ordinals.h ***/
  85834. #ifndef FLAC__ORDINALS_H
  85835. #define FLAC__ORDINALS_H
  85836. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  85837. #include <inttypes.h>
  85838. #endif
  85839. typedef signed char FLAC__int8;
  85840. typedef unsigned char FLAC__uint8;
  85841. #if defined(_MSC_VER) || defined(__BORLANDC__)
  85842. typedef __int16 FLAC__int16;
  85843. typedef __int32 FLAC__int32;
  85844. typedef __int64 FLAC__int64;
  85845. typedef unsigned __int16 FLAC__uint16;
  85846. typedef unsigned __int32 FLAC__uint32;
  85847. typedef unsigned __int64 FLAC__uint64;
  85848. #elif defined(__EMX__)
  85849. typedef short FLAC__int16;
  85850. typedef long FLAC__int32;
  85851. typedef long long FLAC__int64;
  85852. typedef unsigned short FLAC__uint16;
  85853. typedef unsigned long FLAC__uint32;
  85854. typedef unsigned long long FLAC__uint64;
  85855. #else
  85856. typedef int16_t FLAC__int16;
  85857. typedef int32_t FLAC__int32;
  85858. typedef int64_t FLAC__int64;
  85859. typedef uint16_t FLAC__uint16;
  85860. typedef uint32_t FLAC__uint32;
  85861. typedef uint64_t FLAC__uint64;
  85862. #endif
  85863. typedef int FLAC__bool;
  85864. typedef FLAC__uint8 FLAC__byte;
  85865. #ifdef true
  85866. #undef true
  85867. #endif
  85868. #ifdef false
  85869. #undef false
  85870. #endif
  85871. #ifndef __cplusplus
  85872. #define true 1
  85873. #define false 0
  85874. #endif
  85875. #endif
  85876. /*** End of inlined file: ordinals.h ***/
  85877. #include <stdlib.h> /* for size_t */
  85878. /** \file include/FLAC/callback.h
  85879. *
  85880. * \brief
  85881. * This module defines the structures for describing I/O callbacks
  85882. * to the other FLAC interfaces.
  85883. *
  85884. * See the detailed documentation for callbacks in the
  85885. * \link flac_callbacks callbacks \endlink module.
  85886. */
  85887. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  85888. * \ingroup flac
  85889. *
  85890. * \brief
  85891. * This module defines the structures for describing I/O callbacks
  85892. * to the other FLAC interfaces.
  85893. *
  85894. * The purpose of the I/O callback functions is to create a common way
  85895. * for the metadata interfaces to handle I/O.
  85896. *
  85897. * Originally the metadata interfaces required filenames as the way of
  85898. * specifying FLAC files to operate on. This is problematic in some
  85899. * environments so there is an additional option to specify a set of
  85900. * callbacks for doing I/O on the FLAC file, instead of the filename.
  85901. *
  85902. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  85903. * opaque structure for a data source.
  85904. *
  85905. * The callback function prototypes are similar (but not identical) to the
  85906. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  85907. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  85908. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  85909. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  85910. * is required. \warning You generally CANNOT directly use fseek or ftell
  85911. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  85912. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  85913. * large files. You will have to find an equivalent function (e.g. ftello),
  85914. * or write a wrapper. The same is true for feof() since this is usually
  85915. * implemented as a macro, not as a function whose address can be taken.
  85916. *
  85917. * \{
  85918. */
  85919. #ifdef __cplusplus
  85920. extern "C" {
  85921. #endif
  85922. /** This is the opaque handle type used by the callbacks. Typically
  85923. * this is a \c FILE* or address of a file descriptor.
  85924. */
  85925. typedef void* FLAC__IOHandle;
  85926. /** Signature for the read callback.
  85927. * The signature and semantics match POSIX fread() implementations
  85928. * and can generally be used interchangeably.
  85929. *
  85930. * \param ptr The address of the read buffer.
  85931. * \param size The size of the records to be read.
  85932. * \param nmemb The number of records to be read.
  85933. * \param handle The handle to the data source.
  85934. * \retval size_t
  85935. * The number of records read.
  85936. */
  85937. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85938. /** Signature for the write callback.
  85939. * The signature and semantics match POSIX fwrite() implementations
  85940. * and can generally be used interchangeably.
  85941. *
  85942. * \param ptr The address of the write buffer.
  85943. * \param size The size of the records to be written.
  85944. * \param nmemb The number of records to be written.
  85945. * \param handle The handle to the data source.
  85946. * \retval size_t
  85947. * The number of records written.
  85948. */
  85949. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85950. /** Signature for the seek callback.
  85951. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  85952. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  85953. * and 32-bits wide.
  85954. *
  85955. * \param handle The handle to the data source.
  85956. * \param offset The new position, relative to \a whence
  85957. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  85958. * \retval int
  85959. * \c 0 on success, \c -1 on error.
  85960. */
  85961. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  85962. /** Signature for the tell callback.
  85963. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  85964. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  85965. * and 32-bits wide.
  85966. *
  85967. * \param handle The handle to the data source.
  85968. * \retval FLAC__int64
  85969. * The current position on success, \c -1 on error.
  85970. */
  85971. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  85972. /** Signature for the EOF callback.
  85973. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  85974. * on many systems, feof() is a macro, so in this case a wrapper function
  85975. * must be provided instead.
  85976. *
  85977. * \param handle The handle to the data source.
  85978. * \retval int
  85979. * \c 0 if not at end of file, nonzero if at end of file.
  85980. */
  85981. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  85982. /** Signature for the close callback.
  85983. * The signature and semantics match POSIX fclose() implementations
  85984. * and can generally be used interchangeably.
  85985. *
  85986. * \param handle The handle to the data source.
  85987. * \retval int
  85988. * \c 0 on success, \c EOF on error.
  85989. */
  85990. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  85991. /** A structure for holding a set of callbacks.
  85992. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  85993. * describe which of the callbacks are required. The ones that are not
  85994. * required may be set to NULL.
  85995. *
  85996. * If the seek requirement for an interface is optional, you can signify that
  85997. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  85998. */
  85999. typedef struct {
  86000. FLAC__IOCallback_Read read;
  86001. FLAC__IOCallback_Write write;
  86002. FLAC__IOCallback_Seek seek;
  86003. FLAC__IOCallback_Tell tell;
  86004. FLAC__IOCallback_Eof eof;
  86005. FLAC__IOCallback_Close close;
  86006. } FLAC__IOCallbacks;
  86007. /* \} */
  86008. #ifdef __cplusplus
  86009. }
  86010. #endif
  86011. #endif
  86012. /*** End of inlined file: callback.h ***/
  86013. /*** Start of inlined file: format.h ***/
  86014. #ifndef FLAC__FORMAT_H
  86015. #define FLAC__FORMAT_H
  86016. #ifdef __cplusplus
  86017. extern "C" {
  86018. #endif
  86019. /** \file include/FLAC/format.h
  86020. *
  86021. * \brief
  86022. * This module contains structure definitions for the representation
  86023. * of FLAC format components in memory. These are the basic
  86024. * structures used by the rest of the interfaces.
  86025. *
  86026. * See the detailed documentation in the
  86027. * \link flac_format format \endlink module.
  86028. */
  86029. /** \defgroup flac_format FLAC/format.h: format components
  86030. * \ingroup flac
  86031. *
  86032. * \brief
  86033. * This module contains structure definitions for the representation
  86034. * of FLAC format components in memory. These are the basic
  86035. * structures used by the rest of the interfaces.
  86036. *
  86037. * First, you should be familiar with the
  86038. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86039. * follow directly from the specification. As a user of libFLAC, the
  86040. * interesting parts really are the structures that describe the frame
  86041. * header and metadata blocks.
  86042. *
  86043. * The format structures here are very primitive, designed to store
  86044. * information in an efficient way. Reading information from the
  86045. * structures is easy but creating or modifying them directly is
  86046. * more complex. For the most part, as a user of a library, editing
  86047. * is not necessary; however, for metadata blocks it is, so there are
  86048. * convenience functions provided in the \link flac_metadata metadata
  86049. * module \endlink to simplify the manipulation of metadata blocks.
  86050. *
  86051. * \note
  86052. * It's not the best convention, but symbols ending in _LEN are in bits
  86053. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86054. * global variables because they are usually used when declaring byte
  86055. * arrays and some compilers require compile-time knowledge of array
  86056. * sizes when declared on the stack.
  86057. *
  86058. * \{
  86059. */
  86060. /*
  86061. Most of the values described in this file are defined by the FLAC
  86062. format specification. There is nothing to tune here.
  86063. */
  86064. /** The largest legal metadata type code. */
  86065. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86066. /** The minimum block size, in samples, permitted by the format. */
  86067. #define FLAC__MIN_BLOCK_SIZE (16u)
  86068. /** The maximum block size, in samples, permitted by the format. */
  86069. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86070. /** The maximum block size, in samples, permitted by the FLAC subset for
  86071. * sample rates up to 48kHz. */
  86072. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86073. /** The maximum number of channels permitted by the format. */
  86074. #define FLAC__MAX_CHANNELS (8u)
  86075. /** The minimum sample resolution permitted by the format. */
  86076. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86077. /** The maximum sample resolution permitted by the format. */
  86078. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86079. /** The maximum sample resolution permitted by libFLAC.
  86080. *
  86081. * \warning
  86082. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86083. * the reference encoder/decoder is currently limited to 24 bits because
  86084. * of prevalent 32-bit math, so make sure and use this value when
  86085. * appropriate.
  86086. */
  86087. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86088. /** The maximum sample rate permitted by the format. The value is
  86089. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86090. * as to why.
  86091. */
  86092. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86093. /** The maximum LPC order permitted by the format. */
  86094. #define FLAC__MAX_LPC_ORDER (32u)
  86095. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86096. * up to 48kHz. */
  86097. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86098. /** The minimum quantized linear predictor coefficient precision
  86099. * permitted by the format.
  86100. */
  86101. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86102. /** The maximum quantized linear predictor coefficient precision
  86103. * permitted by the format.
  86104. */
  86105. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86106. /** The maximum order of the fixed predictors permitted by the format. */
  86107. #define FLAC__MAX_FIXED_ORDER (4u)
  86108. /** The maximum Rice partition order permitted by the format. */
  86109. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86110. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86111. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86112. /** The version string of the release, stamped onto the libraries and binaries.
  86113. *
  86114. * \note
  86115. * This does not correspond to the shared library version number, which
  86116. * is used to determine binary compatibility.
  86117. */
  86118. extern FLAC_API const char *FLAC__VERSION_STRING;
  86119. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86120. * This is a NUL-terminated ASCII string; when inserted into the
  86121. * VORBIS_COMMENT the trailing null is stripped.
  86122. */
  86123. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86124. /** The byte string representation of the beginning of a FLAC stream. */
  86125. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86126. /** The 32-bit integer big-endian representation of the beginning of
  86127. * a FLAC stream.
  86128. */
  86129. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86130. /** The length of the FLAC signature in bits. */
  86131. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86132. /** The length of the FLAC signature in bytes. */
  86133. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86134. /*****************************************************************************
  86135. *
  86136. * Subframe structures
  86137. *
  86138. *****************************************************************************/
  86139. /*****************************************************************************/
  86140. /** An enumeration of the available entropy coding methods. */
  86141. typedef enum {
  86142. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86143. /**< Residual is coded by partitioning into contexts, each with it's own
  86144. * 4-bit Rice parameter. */
  86145. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86146. /**< Residual is coded by partitioning into contexts, each with it's own
  86147. * 5-bit Rice parameter. */
  86148. } FLAC__EntropyCodingMethodType;
  86149. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86150. *
  86151. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86152. * give the string equivalent. The contents should not be modified.
  86153. */
  86154. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86155. /** Contents of a Rice partitioned residual
  86156. */
  86157. typedef struct {
  86158. unsigned *parameters;
  86159. /**< The Rice parameters for each context. */
  86160. unsigned *raw_bits;
  86161. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86162. * partitions and zero for unescaped partitions.
  86163. */
  86164. unsigned capacity_by_order;
  86165. /**< The capacity of the \a parameters and \a raw_bits arrays
  86166. * specified as an order, i.e. the number of array elements
  86167. * allocated is 2 ^ \a capacity_by_order.
  86168. */
  86169. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86170. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86171. */
  86172. typedef struct {
  86173. unsigned order;
  86174. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86175. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86176. /**< The context's Rice parameters and/or raw bits. */
  86177. } FLAC__EntropyCodingMethod_PartitionedRice;
  86178. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86179. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86180. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86181. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86182. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86183. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86184. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86185. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86186. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86187. */
  86188. typedef struct {
  86189. FLAC__EntropyCodingMethodType type;
  86190. union {
  86191. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86192. } data;
  86193. } FLAC__EntropyCodingMethod;
  86194. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86195. /*****************************************************************************/
  86196. /** An enumeration of the available subframe types. */
  86197. typedef enum {
  86198. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86199. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86200. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86201. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86202. } FLAC__SubframeType;
  86203. /** Maps a FLAC__SubframeType to a C string.
  86204. *
  86205. * Using a FLAC__SubframeType as the index to this array will
  86206. * give the string equivalent. The contents should not be modified.
  86207. */
  86208. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86209. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86210. */
  86211. typedef struct {
  86212. FLAC__int32 value; /**< The constant signal value. */
  86213. } FLAC__Subframe_Constant;
  86214. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86215. */
  86216. typedef struct {
  86217. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86218. } FLAC__Subframe_Verbatim;
  86219. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86220. */
  86221. typedef struct {
  86222. FLAC__EntropyCodingMethod entropy_coding_method;
  86223. /**< The residual coding method. */
  86224. unsigned order;
  86225. /**< The polynomial order. */
  86226. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86227. /**< Warmup samples to prime the predictor, length == order. */
  86228. const FLAC__int32 *residual;
  86229. /**< The residual signal, length == (blocksize minus order) samples. */
  86230. } FLAC__Subframe_Fixed;
  86231. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86232. */
  86233. typedef struct {
  86234. FLAC__EntropyCodingMethod entropy_coding_method;
  86235. /**< The residual coding method. */
  86236. unsigned order;
  86237. /**< The FIR order. */
  86238. unsigned qlp_coeff_precision;
  86239. /**< Quantized FIR filter coefficient precision in bits. */
  86240. int quantization_level;
  86241. /**< The qlp coeff shift needed. */
  86242. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86243. /**< FIR filter coefficients. */
  86244. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86245. /**< Warmup samples to prime the predictor, length == order. */
  86246. const FLAC__int32 *residual;
  86247. /**< The residual signal, length == (blocksize minus order) samples. */
  86248. } FLAC__Subframe_LPC;
  86249. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86250. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86251. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86252. */
  86253. typedef struct {
  86254. FLAC__SubframeType type;
  86255. union {
  86256. FLAC__Subframe_Constant constant;
  86257. FLAC__Subframe_Fixed fixed;
  86258. FLAC__Subframe_LPC lpc;
  86259. FLAC__Subframe_Verbatim verbatim;
  86260. } data;
  86261. unsigned wasted_bits;
  86262. } FLAC__Subframe;
  86263. /** == 1 (bit)
  86264. *
  86265. * This used to be a zero-padding bit (hence the name
  86266. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86267. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86268. * to mean something else.
  86269. */
  86270. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86271. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86272. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86273. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86274. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86275. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86276. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86277. /*****************************************************************************/
  86278. /*****************************************************************************
  86279. *
  86280. * Frame structures
  86281. *
  86282. *****************************************************************************/
  86283. /** An enumeration of the available channel assignments. */
  86284. typedef enum {
  86285. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86286. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86287. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86288. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86289. } FLAC__ChannelAssignment;
  86290. /** Maps a FLAC__ChannelAssignment to a C string.
  86291. *
  86292. * Using a FLAC__ChannelAssignment as the index to this array will
  86293. * give the string equivalent. The contents should not be modified.
  86294. */
  86295. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86296. /** An enumeration of the possible frame numbering methods. */
  86297. typedef enum {
  86298. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86299. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86300. } FLAC__FrameNumberType;
  86301. /** Maps a FLAC__FrameNumberType to a C string.
  86302. *
  86303. * Using a FLAC__FrameNumberType as the index to this array will
  86304. * give the string equivalent. The contents should not be modified.
  86305. */
  86306. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86307. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86308. */
  86309. typedef struct {
  86310. unsigned blocksize;
  86311. /**< The number of samples per subframe. */
  86312. unsigned sample_rate;
  86313. /**< The sample rate in Hz. */
  86314. unsigned channels;
  86315. /**< The number of channels (== number of subframes). */
  86316. FLAC__ChannelAssignment channel_assignment;
  86317. /**< The channel assignment for the frame. */
  86318. unsigned bits_per_sample;
  86319. /**< The sample resolution. */
  86320. FLAC__FrameNumberType number_type;
  86321. /**< The numbering scheme used for the frame. As a convenience, the
  86322. * decoder will always convert a frame number to a sample number because
  86323. * the rules are complex. */
  86324. union {
  86325. FLAC__uint32 frame_number;
  86326. FLAC__uint64 sample_number;
  86327. } number;
  86328. /**< The frame number or sample number of first sample in frame;
  86329. * use the \a number_type value to determine which to use. */
  86330. FLAC__uint8 crc;
  86331. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86332. * of the raw frame header bytes, meaning everything before the CRC byte
  86333. * including the sync code.
  86334. */
  86335. } FLAC__FrameHeader;
  86336. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86337. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86338. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86339. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86340. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86341. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86342. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86343. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86344. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86345. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86346. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86347. */
  86348. typedef struct {
  86349. FLAC__uint16 crc;
  86350. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86351. * 0) of the bytes before the crc, back to and including the frame header
  86352. * sync code.
  86353. */
  86354. } FLAC__FrameFooter;
  86355. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86356. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86357. */
  86358. typedef struct {
  86359. FLAC__FrameHeader header;
  86360. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86361. FLAC__FrameFooter footer;
  86362. } FLAC__Frame;
  86363. /*****************************************************************************/
  86364. /*****************************************************************************
  86365. *
  86366. * Meta-data structures
  86367. *
  86368. *****************************************************************************/
  86369. /** An enumeration of the available metadata block types. */
  86370. typedef enum {
  86371. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86372. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86373. FLAC__METADATA_TYPE_PADDING = 1,
  86374. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86375. FLAC__METADATA_TYPE_APPLICATION = 2,
  86376. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86377. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86378. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86379. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86380. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86381. FLAC__METADATA_TYPE_CUESHEET = 5,
  86382. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86383. FLAC__METADATA_TYPE_PICTURE = 6,
  86384. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86385. FLAC__METADATA_TYPE_UNDEFINED = 7
  86386. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86387. } FLAC__MetadataType;
  86388. /** Maps a FLAC__MetadataType to a C string.
  86389. *
  86390. * Using a FLAC__MetadataType as the index to this array will
  86391. * give the string equivalent. The contents should not be modified.
  86392. */
  86393. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86394. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86395. */
  86396. typedef struct {
  86397. unsigned min_blocksize, max_blocksize;
  86398. unsigned min_framesize, max_framesize;
  86399. unsigned sample_rate;
  86400. unsigned channels;
  86401. unsigned bits_per_sample;
  86402. FLAC__uint64 total_samples;
  86403. FLAC__byte md5sum[16];
  86404. } FLAC__StreamMetadata_StreamInfo;
  86405. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86406. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86407. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86408. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86409. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86410. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86411. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86412. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86413. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86414. /** The total stream length of the STREAMINFO block in bytes. */
  86415. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86416. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86417. */
  86418. typedef struct {
  86419. int dummy;
  86420. /**< Conceptually this is an empty struct since we don't store the
  86421. * padding bytes. Empty structs are not allowed by some C compilers,
  86422. * hence the dummy.
  86423. */
  86424. } FLAC__StreamMetadata_Padding;
  86425. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86426. */
  86427. typedef struct {
  86428. FLAC__byte id[4];
  86429. FLAC__byte *data;
  86430. } FLAC__StreamMetadata_Application;
  86431. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86432. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86433. */
  86434. typedef struct {
  86435. FLAC__uint64 sample_number;
  86436. /**< The sample number of the target frame. */
  86437. FLAC__uint64 stream_offset;
  86438. /**< The offset, in bytes, of the target frame with respect to
  86439. * beginning of the first frame. */
  86440. unsigned frame_samples;
  86441. /**< The number of samples in the target frame. */
  86442. } FLAC__StreamMetadata_SeekPoint;
  86443. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86444. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86445. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86446. /** The total stream length of a seek point in bytes. */
  86447. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86448. /** The value used in the \a sample_number field of
  86449. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86450. * point (== 0xffffffffffffffff).
  86451. */
  86452. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86453. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86454. *
  86455. * \note From the format specification:
  86456. * - The seek points must be sorted by ascending sample number.
  86457. * - Each seek point's sample number must be the first sample of the
  86458. * target frame.
  86459. * - Each seek point's sample number must be unique within the table.
  86460. * - Existence of a SEEKTABLE block implies a correct setting of
  86461. * total_samples in the stream_info block.
  86462. * - Behavior is undefined when more than one SEEKTABLE block is
  86463. * present in a stream.
  86464. */
  86465. typedef struct {
  86466. unsigned num_points;
  86467. FLAC__StreamMetadata_SeekPoint *points;
  86468. } FLAC__StreamMetadata_SeekTable;
  86469. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86470. *
  86471. * For convenience, the APIs maintain a trailing NUL character at the end of
  86472. * \a entry which is not counted toward \a length, i.e.
  86473. * \code strlen(entry) == length \endcode
  86474. */
  86475. typedef struct {
  86476. FLAC__uint32 length;
  86477. FLAC__byte *entry;
  86478. } FLAC__StreamMetadata_VorbisComment_Entry;
  86479. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86480. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86481. */
  86482. typedef struct {
  86483. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86484. FLAC__uint32 num_comments;
  86485. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86486. } FLAC__StreamMetadata_VorbisComment;
  86487. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86488. /** FLAC CUESHEET track index structure. (See the
  86489. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86490. * the full description of each field.)
  86491. */
  86492. typedef struct {
  86493. FLAC__uint64 offset;
  86494. /**< Offset in samples, relative to the track offset, of the index
  86495. * point.
  86496. */
  86497. FLAC__byte number;
  86498. /**< The index point number. */
  86499. } FLAC__StreamMetadata_CueSheet_Index;
  86500. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86501. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86502. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86503. /** FLAC CUESHEET track structure. (See the
  86504. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86505. * the full description of each field.)
  86506. */
  86507. typedef struct {
  86508. FLAC__uint64 offset;
  86509. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86510. FLAC__byte number;
  86511. /**< The track number. */
  86512. char isrc[13];
  86513. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86514. unsigned type:1;
  86515. /**< The track type: 0 for audio, 1 for non-audio. */
  86516. unsigned pre_emphasis:1;
  86517. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86518. FLAC__byte num_indices;
  86519. /**< The number of track index points. */
  86520. FLAC__StreamMetadata_CueSheet_Index *indices;
  86521. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86522. } FLAC__StreamMetadata_CueSheet_Track;
  86523. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86524. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86525. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86526. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86527. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86528. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86529. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86530. /** FLAC CUESHEET structure. (See the
  86531. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86532. * for the full description of each field.)
  86533. */
  86534. typedef struct {
  86535. char media_catalog_number[129];
  86536. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86537. * general, the media catalog number may be 0 to 128 bytes long; any
  86538. * unused characters should be right-padded with NUL characters.
  86539. */
  86540. FLAC__uint64 lead_in;
  86541. /**< The number of lead-in samples. */
  86542. FLAC__bool is_cd;
  86543. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86544. unsigned num_tracks;
  86545. /**< The number of tracks. */
  86546. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86547. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86548. } FLAC__StreamMetadata_CueSheet;
  86549. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86550. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86551. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86552. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86553. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86554. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86555. typedef enum {
  86556. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86557. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86558. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86559. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86560. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86561. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86562. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86563. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86564. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86565. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86566. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86567. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86568. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86569. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86570. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86571. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86572. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86573. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86574. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86575. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86576. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86577. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86578. } FLAC__StreamMetadata_Picture_Type;
  86579. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86580. *
  86581. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86582. * will give the string equivalent. The contents should not be
  86583. * modified.
  86584. */
  86585. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86586. /** FLAC PICTURE structure. (See the
  86587. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86588. * for the full description of each field.)
  86589. */
  86590. typedef struct {
  86591. FLAC__StreamMetadata_Picture_Type type;
  86592. /**< The kind of picture stored. */
  86593. char *mime_type;
  86594. /**< Picture data's MIME type, in ASCII printable characters
  86595. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86596. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86597. * MIME type of '-->' is also allowed, in which case the picture
  86598. * data should be a complete URL. In file storage, the MIME type is
  86599. * stored as a 32-bit length followed by the ASCII string with no NUL
  86600. * terminator, but is converted to a plain C string in this structure
  86601. * for convenience.
  86602. */
  86603. FLAC__byte *description;
  86604. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86605. * the description is stored as a 32-bit length followed by the UTF-8
  86606. * string with no NUL terminator, but is converted to a plain C string
  86607. * in this structure for convenience.
  86608. */
  86609. FLAC__uint32 width;
  86610. /**< Picture's width in pixels. */
  86611. FLAC__uint32 height;
  86612. /**< Picture's height in pixels. */
  86613. FLAC__uint32 depth;
  86614. /**< Picture's color depth in bits-per-pixel. */
  86615. FLAC__uint32 colors;
  86616. /**< For indexed palettes (like GIF), picture's number of colors (the
  86617. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86618. */
  86619. FLAC__uint32 data_length;
  86620. /**< Length of binary picture data in bytes. */
  86621. FLAC__byte *data;
  86622. /**< Binary picture data. */
  86623. } FLAC__StreamMetadata_Picture;
  86624. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86625. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86626. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86627. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86628. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86629. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86630. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86631. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86632. /** Structure that is used when a metadata block of unknown type is loaded.
  86633. * The contents are opaque. The structure is used only internally to
  86634. * correctly handle unknown metadata.
  86635. */
  86636. typedef struct {
  86637. FLAC__byte *data;
  86638. } FLAC__StreamMetadata_Unknown;
  86639. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86640. */
  86641. typedef struct {
  86642. FLAC__MetadataType type;
  86643. /**< The type of the metadata block; used determine which member of the
  86644. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86645. * then \a data.unknown must be used. */
  86646. FLAC__bool is_last;
  86647. /**< \c true if this metadata block is the last, else \a false */
  86648. unsigned length;
  86649. /**< Length, in bytes, of the block data as it appears in the stream. */
  86650. union {
  86651. FLAC__StreamMetadata_StreamInfo stream_info;
  86652. FLAC__StreamMetadata_Padding padding;
  86653. FLAC__StreamMetadata_Application application;
  86654. FLAC__StreamMetadata_SeekTable seek_table;
  86655. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86656. FLAC__StreamMetadata_CueSheet cue_sheet;
  86657. FLAC__StreamMetadata_Picture picture;
  86658. FLAC__StreamMetadata_Unknown unknown;
  86659. } data;
  86660. /**< Polymorphic block data; use the \a type value to determine which
  86661. * to use. */
  86662. } FLAC__StreamMetadata;
  86663. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86664. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86665. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86666. /** The total stream length of a metadata block header in bytes. */
  86667. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86668. /*****************************************************************************/
  86669. /*****************************************************************************
  86670. *
  86671. * Utility functions
  86672. *
  86673. *****************************************************************************/
  86674. /** Tests that a sample rate is valid for FLAC.
  86675. *
  86676. * \param sample_rate The sample rate to test for compliance.
  86677. * \retval FLAC__bool
  86678. * \c true if the given sample rate conforms to the specification, else
  86679. * \c false.
  86680. */
  86681. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86682. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86683. * for valid sample rates are slightly more complex since the rate has to
  86684. * be expressible completely in the frame header.
  86685. *
  86686. * \param sample_rate The sample rate to test for compliance.
  86687. * \retval FLAC__bool
  86688. * \c true if the given sample rate conforms to the specification for the
  86689. * subset, else \c false.
  86690. */
  86691. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86692. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86693. * comment specification.
  86694. *
  86695. * Vorbis comment names must be composed only of characters from
  86696. * [0x20-0x3C,0x3E-0x7D].
  86697. *
  86698. * \param name A NUL-terminated string to be checked.
  86699. * \assert
  86700. * \code name != NULL \endcode
  86701. * \retval FLAC__bool
  86702. * \c false if entry name is illegal, else \c true.
  86703. */
  86704. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86705. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86706. * comment specification.
  86707. *
  86708. * Vorbis comment values must be valid UTF-8 sequences.
  86709. *
  86710. * \param value A string to be checked.
  86711. * \param length A the length of \a value in bytes. May be
  86712. * \c (unsigned)(-1) to indicate that \a value is a plain
  86713. * UTF-8 NUL-terminated string.
  86714. * \assert
  86715. * \code value != NULL \endcode
  86716. * \retval FLAC__bool
  86717. * \c false if entry name is illegal, else \c true.
  86718. */
  86719. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86720. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86721. * comment specification.
  86722. *
  86723. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86724. * 'value' must be legal according to
  86725. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86726. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86727. *
  86728. * \param entry An entry to be checked.
  86729. * \param length The length of \a entry in bytes.
  86730. * \assert
  86731. * \code value != NULL \endcode
  86732. * \retval FLAC__bool
  86733. * \c false if entry name is illegal, else \c true.
  86734. */
  86735. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86736. /** Check a seek table to see if it conforms to the FLAC specification.
  86737. * See the format specification for limits on the contents of the
  86738. * seek table.
  86739. *
  86740. * \param seek_table A pointer to a seek table to be checked.
  86741. * \assert
  86742. * \code seek_table != NULL \endcode
  86743. * \retval FLAC__bool
  86744. * \c false if seek table is illegal, else \c true.
  86745. */
  86746. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86747. /** Sort a seek table's seek points according to the format specification.
  86748. * This includes a "unique-ification" step to remove duplicates, i.e.
  86749. * seek points with identical \a sample_number values. Duplicate seek
  86750. * points are converted into placeholder points and sorted to the end of
  86751. * the table.
  86752. *
  86753. * \param seek_table A pointer to a seek table to be sorted.
  86754. * \assert
  86755. * \code seek_table != NULL \endcode
  86756. * \retval unsigned
  86757. * The number of duplicate seek points converted into placeholders.
  86758. */
  86759. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86760. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86761. * See the format specification for limits on the contents of the
  86762. * cue sheet.
  86763. *
  86764. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86765. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86766. * stringent requirements for a CD-DA (audio) disc.
  86767. * \param violation Address of a pointer to a string. If there is a
  86768. * violation, a pointer to a string explanation of the
  86769. * violation will be returned here. \a violation may be
  86770. * \c NULL if you don't need the returned string. Do not
  86771. * free the returned string; it will always point to static
  86772. * data.
  86773. * \assert
  86774. * \code cue_sheet != NULL \endcode
  86775. * \retval FLAC__bool
  86776. * \c false if cue sheet is illegal, else \c true.
  86777. */
  86778. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86779. /** Check picture data to see if it conforms to the FLAC specification.
  86780. * See the format specification for limits on the contents of the
  86781. * PICTURE block.
  86782. *
  86783. * \param picture A pointer to existing picture data to be checked.
  86784. * \param violation Address of a pointer to a string. If there is a
  86785. * violation, a pointer to a string explanation of the
  86786. * violation will be returned here. \a violation may be
  86787. * \c NULL if you don't need the returned string. Do not
  86788. * free the returned string; it will always point to static
  86789. * data.
  86790. * \assert
  86791. * \code picture != NULL \endcode
  86792. * \retval FLAC__bool
  86793. * \c false if picture data is illegal, else \c true.
  86794. */
  86795. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  86796. /* \} */
  86797. #ifdef __cplusplus
  86798. }
  86799. #endif
  86800. #endif
  86801. /*** End of inlined file: format.h ***/
  86802. /*** Start of inlined file: metadata.h ***/
  86803. #ifndef FLAC__METADATA_H
  86804. #define FLAC__METADATA_H
  86805. #include <sys/types.h> /* for off_t */
  86806. /* --------------------------------------------------------------------
  86807. (For an example of how all these routines are used, see the source
  86808. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  86809. metaflac in src/metaflac/)
  86810. ------------------------------------------------------------------*/
  86811. /** \file include/FLAC/metadata.h
  86812. *
  86813. * \brief
  86814. * This module provides functions for creating and manipulating FLAC
  86815. * metadata blocks in memory, and three progressively more powerful
  86816. * interfaces for traversing and editing metadata in FLAC files.
  86817. *
  86818. * See the detailed documentation for each interface in the
  86819. * \link flac_metadata metadata \endlink module.
  86820. */
  86821. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  86822. * \ingroup flac
  86823. *
  86824. * \brief
  86825. * This module provides functions for creating and manipulating FLAC
  86826. * metadata blocks in memory, and three progressively more powerful
  86827. * interfaces for traversing and editing metadata in native FLAC files.
  86828. * Note that currently only the Chain interface (level 2) supports Ogg
  86829. * FLAC files, and it is read-only i.e. no writing back changed
  86830. * metadata to file.
  86831. *
  86832. * There are three metadata interfaces of increasing complexity:
  86833. *
  86834. * Level 0:
  86835. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  86836. * PICTURE blocks.
  86837. *
  86838. * Level 1:
  86839. * Read-write access to all metadata blocks. This level is write-
  86840. * efficient in most cases (more on this below), and uses less memory
  86841. * than level 2.
  86842. *
  86843. * Level 2:
  86844. * Read-write access to all metadata blocks. This level is write-
  86845. * efficient in all cases, but uses more memory since all metadata for
  86846. * the whole file is read into memory and manipulated before writing
  86847. * out again.
  86848. *
  86849. * What do we mean by efficient? Since FLAC metadata appears at the
  86850. * beginning of the file, when writing metadata back to a FLAC file
  86851. * it is possible to grow or shrink the metadata such that the entire
  86852. * file must be rewritten. However, if the size remains the same during
  86853. * changes or PADDING blocks are utilized, only the metadata needs to be
  86854. * overwritten, which is much faster.
  86855. *
  86856. * Efficient means the whole file is rewritten at most one time, and only
  86857. * when necessary. Level 1 is not efficient only in the case that you
  86858. * cause more than one metadata block to grow or shrink beyond what can
  86859. * be accomodated by padding. In this case you should probably use level
  86860. * 2, which allows you to edit all the metadata for a file in memory and
  86861. * write it out all at once.
  86862. *
  86863. * All levels know how to skip over and not disturb an ID3v2 tag at the
  86864. * front of the file.
  86865. *
  86866. * All levels access files via their filenames. In addition, level 2
  86867. * has additional alternative read and write functions that take an I/O
  86868. * handle and callbacks, for situations where access by filename is not
  86869. * possible.
  86870. *
  86871. * In addition to the three interfaces, this module defines functions for
  86872. * creating and manipulating various metadata objects in memory. As we see
  86873. * from the Format module, FLAC metadata blocks in memory are very primitive
  86874. * structures for storing information in an efficient way. Reading
  86875. * information from the structures is easy but creating or modifying them
  86876. * directly is more complex. The metadata object routines here facilitate
  86877. * this by taking care of the consistency and memory management drudgery.
  86878. *
  86879. * Unless you will be using the level 1 or 2 interfaces to modify existing
  86880. * metadata however, you will not probably not need these.
  86881. *
  86882. * From a dependency standpoint, none of the encoders or decoders require
  86883. * the metadata module. This is so that embedded users can strip out the
  86884. * metadata module from libFLAC to reduce the size and complexity.
  86885. */
  86886. #ifdef __cplusplus
  86887. extern "C" {
  86888. #endif
  86889. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  86890. * \ingroup flac_metadata
  86891. *
  86892. * \brief
  86893. * The level 0 interface consists of individual routines to read the
  86894. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  86895. * only a filename.
  86896. *
  86897. * They try to skip any ID3v2 tag at the head of the file.
  86898. *
  86899. * \{
  86900. */
  86901. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  86902. * will try to skip any ID3v2 tag at the head of the file.
  86903. *
  86904. * \param filename The path to the FLAC file to read.
  86905. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  86906. * FLAC__StreamMetadata is a simple structure with no
  86907. * memory allocation involved, you pass the address of
  86908. * an existing structure. It need not be initialized.
  86909. * \assert
  86910. * \code filename != NULL \endcode
  86911. * \code streaminfo != NULL \endcode
  86912. * \retval FLAC__bool
  86913. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  86914. * \c false if there was a memory allocation error, a file decoder error,
  86915. * or the file contained no STREAMINFO block. (A memory allocation error
  86916. * is possible because this function must set up a file decoder.)
  86917. */
  86918. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  86919. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  86920. * function will try to skip any ID3v2 tag at the head of the file.
  86921. *
  86922. * \param filename The path to the FLAC file to read.
  86923. * \param tags The address where the returned pointer will be
  86924. * stored. The \a tags object must be deleted by
  86925. * the caller using FLAC__metadata_object_delete().
  86926. * \assert
  86927. * \code filename != NULL \endcode
  86928. * \code tags != NULL \endcode
  86929. * \retval FLAC__bool
  86930. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  86931. * and \a *tags will be set to the address of the metadata structure.
  86932. * Returns \c false if there was a memory allocation error, a file
  86933. * decoder error, or the file contained no VORBIS_COMMENT block, and
  86934. * \a *tags will be set to \c NULL.
  86935. */
  86936. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  86937. /** Read the CUESHEET metadata block of the given FLAC file. This
  86938. * function will try to skip any ID3v2 tag at the head of the file.
  86939. *
  86940. * \param filename The path to the FLAC file to read.
  86941. * \param cuesheet The address where the returned pointer will be
  86942. * stored. The \a cuesheet object must be deleted by
  86943. * the caller using FLAC__metadata_object_delete().
  86944. * \assert
  86945. * \code filename != NULL \endcode
  86946. * \code cuesheet != NULL \endcode
  86947. * \retval FLAC__bool
  86948. * \c true if a valid CUESHEET block was read from \a filename,
  86949. * and \a *cuesheet will be set to the address of the metadata
  86950. * structure. Returns \c false if there was a memory allocation
  86951. * error, a file decoder error, or the file contained no CUESHEET
  86952. * block, and \a *cuesheet will be set to \c NULL.
  86953. */
  86954. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  86955. /** Read a PICTURE metadata block of the given FLAC file. This
  86956. * function will try to skip any ID3v2 tag at the head of the file.
  86957. * Since there can be more than one PICTURE block in a file, this
  86958. * function takes a number of parameters that act as constraints to
  86959. * the search. The PICTURE block with the largest area matching all
  86960. * the constraints will be returned, or \a *picture will be set to
  86961. * \c NULL if there was no such block.
  86962. *
  86963. * \param filename The path to the FLAC file to read.
  86964. * \param picture The address where the returned pointer will be
  86965. * stored. The \a picture object must be deleted by
  86966. * the caller using FLAC__metadata_object_delete().
  86967. * \param type The desired picture type. Use \c -1 to mean
  86968. * "any type".
  86969. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  86970. * string will be matched exactly. Use \c NULL to
  86971. * mean "any MIME type".
  86972. * \param description The desired description. The string will be
  86973. * matched exactly. Use \c NULL to mean "any
  86974. * description".
  86975. * \param max_width The maximum width in pixels desired. Use
  86976. * \c (unsigned)(-1) to mean "any width".
  86977. * \param max_height The maximum height in pixels desired. Use
  86978. * \c (unsigned)(-1) to mean "any height".
  86979. * \param max_depth The maximum color depth in bits-per-pixel desired.
  86980. * Use \c (unsigned)(-1) to mean "any depth".
  86981. * \param max_colors The maximum number of colors desired. Use
  86982. * \c (unsigned)(-1) to mean "any number of colors".
  86983. * \assert
  86984. * \code filename != NULL \endcode
  86985. * \code picture != NULL \endcode
  86986. * \retval FLAC__bool
  86987. * \c true if a valid PICTURE block was read from \a filename,
  86988. * and \a *picture will be set to the address of the metadata
  86989. * structure. Returns \c false if there was a memory allocation
  86990. * error, a file decoder error, or the file contained no PICTURE
  86991. * block, and \a *picture will be set to \c NULL.
  86992. */
  86993. 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);
  86994. /* \} */
  86995. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  86996. * \ingroup flac_metadata
  86997. *
  86998. * \brief
  86999. * The level 1 interface provides read-write access to FLAC file metadata and
  87000. * operates directly on the FLAC file.
  87001. *
  87002. * The general usage of this interface is:
  87003. *
  87004. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87005. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87006. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87007. * see if the file is writable, or only read access is allowed.
  87008. * - Use FLAC__metadata_simple_iterator_next() and
  87009. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87010. * This is does not read the actual blocks themselves.
  87011. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87012. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87013. * forward from the front of the file.
  87014. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87015. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87016. * the current iterator position. The returned object is yours to modify
  87017. * and free.
  87018. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87019. * back. You must have write permission to the original file. Make sure to
  87020. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87021. * below.
  87022. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87023. * Use the object creation functions from
  87024. * \link flac_metadata_object here \endlink to generate new objects.
  87025. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87026. * currently referred to by the iterator, or replace it with padding.
  87027. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87028. * finished.
  87029. *
  87030. * \note
  87031. * The FLAC file remains open the whole time between
  87032. * FLAC__metadata_simple_iterator_init() and
  87033. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87034. * the file during this time.
  87035. *
  87036. * \note
  87037. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87038. * FLAC__StreamMetadata objects. These are managed automatically.
  87039. *
  87040. * \note
  87041. * If any of the modification functions
  87042. * (FLAC__metadata_simple_iterator_set_block(),
  87043. * FLAC__metadata_simple_iterator_delete_block(),
  87044. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87045. * you should delete the iterator as it may no longer be valid.
  87046. *
  87047. * \{
  87048. */
  87049. struct FLAC__Metadata_SimpleIterator;
  87050. /** The opaque structure definition for the level 1 iterator type.
  87051. * See the
  87052. * \link flac_metadata_level1 metadata level 1 module \endlink
  87053. * for a detailed description.
  87054. */
  87055. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87056. /** Status type for FLAC__Metadata_SimpleIterator.
  87057. *
  87058. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87059. */
  87060. typedef enum {
  87061. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87062. /**< The iterator is in the normal OK state */
  87063. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87064. /**< The data passed into a function violated the function's usage criteria */
  87065. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87066. /**< The iterator could not open the target file */
  87067. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87068. /**< The iterator could not find the FLAC signature at the start of the file */
  87069. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87070. /**< The iterator tried to write to a file that was not writable */
  87071. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87072. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87073. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87074. /**< The iterator encountered an error while reading the FLAC file */
  87075. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87076. /**< The iterator encountered an error while seeking in the FLAC file */
  87077. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87078. /**< The iterator encountered an error while writing the FLAC file */
  87079. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87080. /**< The iterator encountered an error renaming the FLAC file */
  87081. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87082. /**< The iterator encountered an error removing the temporary file */
  87083. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87084. /**< Memory allocation failed */
  87085. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87086. /**< The caller violated an assertion or an unexpected error occurred */
  87087. } FLAC__Metadata_SimpleIteratorStatus;
  87088. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87089. *
  87090. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87091. * will give the string equivalent. The contents should not be modified.
  87092. */
  87093. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87094. /** Create a new iterator instance.
  87095. *
  87096. * \retval FLAC__Metadata_SimpleIterator*
  87097. * \c NULL if there was an error allocating memory, else the new instance.
  87098. */
  87099. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87100. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87101. *
  87102. * \param iterator A pointer to an existing iterator.
  87103. * \assert
  87104. * \code iterator != NULL \endcode
  87105. */
  87106. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87107. /** Get the current status of the iterator. Call this after a function
  87108. * returns \c false to get the reason for the error. Also resets the status
  87109. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87110. *
  87111. * \param iterator A pointer to an existing iterator.
  87112. * \assert
  87113. * \code iterator != NULL \endcode
  87114. * \retval FLAC__Metadata_SimpleIteratorStatus
  87115. * The current status of the iterator.
  87116. */
  87117. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87118. /** Initialize the iterator to point to the first metadata block in the
  87119. * given FLAC file.
  87120. *
  87121. * \param iterator A pointer to an existing iterator.
  87122. * \param filename The path to the FLAC file.
  87123. * \param read_only If \c true, the FLAC file will be opened
  87124. * in read-only mode; if \c false, the FLAC
  87125. * file will be opened for edit even if no
  87126. * edits are performed.
  87127. * \param preserve_file_stats If \c true, the owner and modification
  87128. * time will be preserved even if the FLAC
  87129. * file is written to.
  87130. * \assert
  87131. * \code iterator != NULL \endcode
  87132. * \code filename != NULL \endcode
  87133. * \retval FLAC__bool
  87134. * \c false if a memory allocation error occurs, the file can't be
  87135. * opened, or another error occurs, else \c true.
  87136. */
  87137. 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);
  87138. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87139. * FLAC__metadata_simple_iterator_set_block() and
  87140. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87141. *
  87142. * \param iterator A pointer to an existing iterator.
  87143. * \assert
  87144. * \code iterator != NULL \endcode
  87145. * \retval FLAC__bool
  87146. * See above.
  87147. */
  87148. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87149. /** Moves the iterator forward one metadata block, returning \c false if
  87150. * already at the end.
  87151. *
  87152. * \param iterator A pointer to an existing initialized iterator.
  87153. * \assert
  87154. * \code iterator != NULL \endcode
  87155. * \a iterator has been successfully initialized with
  87156. * FLAC__metadata_simple_iterator_init()
  87157. * \retval FLAC__bool
  87158. * \c false if already at the last metadata block of the chain, else
  87159. * \c true.
  87160. */
  87161. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87162. /** Moves the iterator backward one metadata block, returning \c false if
  87163. * already at the beginning.
  87164. *
  87165. * \param iterator A pointer to an existing initialized iterator.
  87166. * \assert
  87167. * \code iterator != NULL \endcode
  87168. * \a iterator has been successfully initialized with
  87169. * FLAC__metadata_simple_iterator_init()
  87170. * \retval FLAC__bool
  87171. * \c false if already at the first metadata block of the chain, else
  87172. * \c true.
  87173. */
  87174. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87175. /** Returns a flag telling if the current metadata block is the last.
  87176. *
  87177. * \param iterator A pointer to an existing initialized iterator.
  87178. * \assert
  87179. * \code iterator != NULL \endcode
  87180. * \a iterator has been successfully initialized with
  87181. * FLAC__metadata_simple_iterator_init()
  87182. * \retval FLAC__bool
  87183. * \c true if the current metadata block is the last in the file,
  87184. * else \c false.
  87185. */
  87186. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87187. /** Get the offset of the metadata block at the current position. This
  87188. * avoids reading the actual block data which can save time for large
  87189. * blocks.
  87190. *
  87191. * \param iterator A pointer to an existing initialized iterator.
  87192. * \assert
  87193. * \code iterator != NULL \endcode
  87194. * \a iterator has been successfully initialized with
  87195. * FLAC__metadata_simple_iterator_init()
  87196. * \retval off_t
  87197. * The offset of the metadata block at the current iterator position.
  87198. * This is the byte offset relative to the beginning of the file of
  87199. * the current metadata block's header.
  87200. */
  87201. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87202. /** Get the type of the metadata block at the current position. This
  87203. * avoids reading the actual block data which can save time for large
  87204. * blocks.
  87205. *
  87206. * \param iterator A pointer to an existing initialized iterator.
  87207. * \assert
  87208. * \code iterator != NULL \endcode
  87209. * \a iterator has been successfully initialized with
  87210. * FLAC__metadata_simple_iterator_init()
  87211. * \retval FLAC__MetadataType
  87212. * The type of the metadata block at the current iterator position.
  87213. */
  87214. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87215. /** Get the length of the metadata block at the current position. This
  87216. * avoids reading the actual block data which can save time for large
  87217. * blocks.
  87218. *
  87219. * \param iterator A pointer to an existing initialized iterator.
  87220. * \assert
  87221. * \code iterator != NULL \endcode
  87222. * \a iterator has been successfully initialized with
  87223. * FLAC__metadata_simple_iterator_init()
  87224. * \retval unsigned
  87225. * The length of the metadata block at the current iterator position.
  87226. * The is same length as that in the
  87227. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87228. * i.e. the length of the metadata body that follows the header.
  87229. */
  87230. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87231. /** Get the application ID of the \c APPLICATION block at the current
  87232. * position. This avoids reading the actual block data which can save
  87233. * time for large blocks.
  87234. *
  87235. * \param iterator A pointer to an existing initialized iterator.
  87236. * \param id A pointer to a buffer of at least \c 4 bytes where
  87237. * the ID will be stored.
  87238. * \assert
  87239. * \code iterator != NULL \endcode
  87240. * \code id != NULL \endcode
  87241. * \a iterator has been successfully initialized with
  87242. * FLAC__metadata_simple_iterator_init()
  87243. * \retval FLAC__bool
  87244. * \c true if the ID was successfully read, else \c false, in which
  87245. * case you should check FLAC__metadata_simple_iterator_status() to
  87246. * find out why. If the status is
  87247. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87248. * current metadata block is not an \c APPLICATION block. Otherwise
  87249. * if the status is
  87250. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87251. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87252. * occurred and the iterator can no longer be used.
  87253. */
  87254. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87255. /** Get the metadata block at the current position. You can modify the
  87256. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87257. * write it back to the FLAC file.
  87258. *
  87259. * You must call FLAC__metadata_object_delete() on the returned object
  87260. * when you are finished with it.
  87261. *
  87262. * \param iterator A pointer to an existing initialized iterator.
  87263. * \assert
  87264. * \code iterator != NULL \endcode
  87265. * \a iterator has been successfully initialized with
  87266. * FLAC__metadata_simple_iterator_init()
  87267. * \retval FLAC__StreamMetadata*
  87268. * The current metadata block, or \c NULL if there was a memory
  87269. * allocation error.
  87270. */
  87271. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87272. /** Write a block back to the FLAC file. This function tries to be
  87273. * as efficient as possible; how the block is actually written is
  87274. * shown by the following:
  87275. *
  87276. * Existing block is a STREAMINFO block and the new block is a
  87277. * STREAMINFO block: the new block is written in place. Make sure
  87278. * you know what you're doing when changing the values of a
  87279. * STREAMINFO block.
  87280. *
  87281. * Existing block is a STREAMINFO block and the new block is a
  87282. * not a STREAMINFO block: this is an error since the first block
  87283. * must be a STREAMINFO block. Returns \c false without altering the
  87284. * file.
  87285. *
  87286. * Existing block is not a STREAMINFO block and the new block is a
  87287. * STREAMINFO block: this is an error since there may be only one
  87288. * STREAMINFO block. Returns \c false without altering the file.
  87289. *
  87290. * Existing block and new block are the same length: the existing
  87291. * block will be replaced by the new block, written in place.
  87292. *
  87293. * Existing block is longer than new block: if use_padding is \c true,
  87294. * the existing block will be overwritten in place with the new
  87295. * block followed by a PADDING block, if possible, to make the total
  87296. * size the same as the existing block. Remember that a padding
  87297. * block requires at least four bytes so if the difference in size
  87298. * between the new block and existing block is less than that, the
  87299. * entire file will have to be rewritten, using the new block's
  87300. * exact size. If use_padding is \c false, the entire file will be
  87301. * rewritten, replacing the existing block by the new block.
  87302. *
  87303. * Existing block is shorter than new block: if use_padding is \c true,
  87304. * the function will try and expand the new block into the following
  87305. * PADDING block, if it exists and doing so won't shrink the PADDING
  87306. * block to less than 4 bytes. If there is no following PADDING
  87307. * block, or it will shrink to less than 4 bytes, or use_padding is
  87308. * \c false, the entire file is rewritten, replacing the existing block
  87309. * with the new block. Note that in this case any following PADDING
  87310. * block is preserved as is.
  87311. *
  87312. * After writing the block, the iterator will remain in the same
  87313. * place, i.e. pointing to the new block.
  87314. *
  87315. * \param iterator A pointer to an existing initialized iterator.
  87316. * \param block The block to set.
  87317. * \param use_padding See above.
  87318. * \assert
  87319. * \code iterator != NULL \endcode
  87320. * \a iterator has been successfully initialized with
  87321. * FLAC__metadata_simple_iterator_init()
  87322. * \code block != NULL \endcode
  87323. * \retval FLAC__bool
  87324. * \c true if successful, else \c false.
  87325. */
  87326. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87327. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87328. * except that instead of writing over an existing block, it appends
  87329. * a block after the existing block. \a use_padding is again used to
  87330. * tell the function to try an expand into following padding in an
  87331. * attempt to avoid rewriting the entire file.
  87332. *
  87333. * This function will fail and return \c false if given a STREAMINFO
  87334. * block.
  87335. *
  87336. * After writing the block, the iterator will be pointing to the
  87337. * new block.
  87338. *
  87339. * \param iterator A pointer to an existing initialized iterator.
  87340. * \param block The block to set.
  87341. * \param use_padding See above.
  87342. * \assert
  87343. * \code iterator != NULL \endcode
  87344. * \a iterator has been successfully initialized with
  87345. * FLAC__metadata_simple_iterator_init()
  87346. * \code block != NULL \endcode
  87347. * \retval FLAC__bool
  87348. * \c true if successful, else \c false.
  87349. */
  87350. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87351. /** Deletes the block at the current position. This will cause the
  87352. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87353. * in which case the block will be replaced by an equal-sized PADDING
  87354. * block. The iterator will be left pointing to the block before the
  87355. * one just deleted.
  87356. *
  87357. * You may not delete the STREAMINFO block.
  87358. *
  87359. * \param iterator A pointer to an existing initialized iterator.
  87360. * \param use_padding See above.
  87361. * \assert
  87362. * \code iterator != NULL \endcode
  87363. * \a iterator has been successfully initialized with
  87364. * FLAC__metadata_simple_iterator_init()
  87365. * \retval FLAC__bool
  87366. * \c true if successful, else \c false.
  87367. */
  87368. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87369. /* \} */
  87370. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87371. * \ingroup flac_metadata
  87372. *
  87373. * \brief
  87374. * The level 2 interface provides read-write access to FLAC file metadata;
  87375. * all metadata is read into memory, operated on in memory, and then written
  87376. * to file, which is more efficient than level 1 when editing multiple blocks.
  87377. *
  87378. * Currently Ogg FLAC is supported for read only, via
  87379. * FLAC__metadata_chain_read_ogg() but a subsequent
  87380. * FLAC__metadata_chain_write() will fail.
  87381. *
  87382. * The general usage of this interface is:
  87383. *
  87384. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87385. * linked list of FLAC metadata blocks.
  87386. * - Read all metadata into the the chain from a FLAC file using
  87387. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87388. * check the status.
  87389. * - Optionally, consolidate the padding using
  87390. * FLAC__metadata_chain_merge_padding() or
  87391. * FLAC__metadata_chain_sort_padding().
  87392. * - Create a new iterator using FLAC__metadata_iterator_new()
  87393. * - Initialize the iterator to point to the first element in the chain
  87394. * using FLAC__metadata_iterator_init()
  87395. * - Traverse the chain using FLAC__metadata_iterator_next and
  87396. * FLAC__metadata_iterator_prev().
  87397. * - Get a block for reading or modification using
  87398. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87399. * inside the chain is returned, so the block is yours to modify.
  87400. * Changes will be reflected in the FLAC file when you write the
  87401. * chain. You can also add and delete blocks (see functions below).
  87402. * - When done, write out the chain using FLAC__metadata_chain_write().
  87403. * Make sure to read the whole comment to the function below.
  87404. * - Delete the chain using FLAC__metadata_chain_delete().
  87405. *
  87406. * \note
  87407. * Even though the FLAC file is not open while the chain is being
  87408. * manipulated, you must not alter the file externally during
  87409. * this time. The chain assumes the FLAC file will not change
  87410. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87411. * and FLAC__metadata_chain_write().
  87412. *
  87413. * \note
  87414. * Do not modify the is_last, length, or type fields of returned
  87415. * FLAC__StreamMetadata objects. These are managed automatically.
  87416. *
  87417. * \note
  87418. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87419. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87420. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87421. * become owned by the chain and they will be deleted when the chain is
  87422. * deleted.
  87423. *
  87424. * \{
  87425. */
  87426. struct FLAC__Metadata_Chain;
  87427. /** The opaque structure definition for the level 2 chain type.
  87428. */
  87429. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87430. struct FLAC__Metadata_Iterator;
  87431. /** The opaque structure definition for the level 2 iterator type.
  87432. */
  87433. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87434. typedef enum {
  87435. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87436. /**< The chain is in the normal OK state */
  87437. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87438. /**< The data passed into a function violated the function's usage criteria */
  87439. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87440. /**< The chain could not open the target file */
  87441. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87442. /**< The chain could not find the FLAC signature at the start of the file */
  87443. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87444. /**< The chain tried to write to a file that was not writable */
  87445. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87446. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87447. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87448. /**< The chain encountered an error while reading the FLAC file */
  87449. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87450. /**< The chain encountered an error while seeking in the FLAC file */
  87451. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87452. /**< The chain encountered an error while writing the FLAC file */
  87453. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87454. /**< The chain encountered an error renaming the FLAC file */
  87455. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87456. /**< The chain encountered an error removing the temporary file */
  87457. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87458. /**< Memory allocation failed */
  87459. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87460. /**< The caller violated an assertion or an unexpected error occurred */
  87461. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87462. /**< One or more of the required callbacks was NULL */
  87463. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87464. /**< FLAC__metadata_chain_write() was called on a chain read by
  87465. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87466. * or
  87467. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87468. * was called on a chain read by
  87469. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87470. * Matching read/write methods must always be used. */
  87471. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87472. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87473. * chain write requires a tempfile; use
  87474. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87475. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87476. * called when the chain write does not require a tempfile; use
  87477. * FLAC__metadata_chain_write_with_callbacks() instead.
  87478. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87479. * before writing via callbacks. */
  87480. } FLAC__Metadata_ChainStatus;
  87481. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87482. *
  87483. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87484. * will give the string equivalent. The contents should not be modified.
  87485. */
  87486. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87487. /*********** FLAC__Metadata_Chain ***********/
  87488. /** Create a new chain instance.
  87489. *
  87490. * \retval FLAC__Metadata_Chain*
  87491. * \c NULL if there was an error allocating memory, else the new instance.
  87492. */
  87493. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87494. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87495. *
  87496. * \param chain A pointer to an existing chain.
  87497. * \assert
  87498. * \code chain != NULL \endcode
  87499. */
  87500. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87501. /** Get the current status of the chain. Call this after a function
  87502. * returns \c false to get the reason for the error. Also resets the
  87503. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87504. *
  87505. * \param chain A pointer to an existing chain.
  87506. * \assert
  87507. * \code chain != NULL \endcode
  87508. * \retval FLAC__Metadata_ChainStatus
  87509. * The current status of the chain.
  87510. */
  87511. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87512. /** Read all metadata from a FLAC file into the chain.
  87513. *
  87514. * \param chain A pointer to an existing chain.
  87515. * \param filename The path to the FLAC file to read.
  87516. * \assert
  87517. * \code chain != NULL \endcode
  87518. * \code filename != NULL \endcode
  87519. * \retval FLAC__bool
  87520. * \c true if a valid list of metadata blocks was read from
  87521. * \a filename, else \c false. On failure, check the status with
  87522. * FLAC__metadata_chain_status().
  87523. */
  87524. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87525. /** Read all metadata from an Ogg FLAC file into the chain.
  87526. *
  87527. * \note Ogg FLAC metadata data writing is not supported yet and
  87528. * FLAC__metadata_chain_write() will fail.
  87529. *
  87530. * \param chain A pointer to an existing chain.
  87531. * \param filename The path to the Ogg FLAC file to read.
  87532. * \assert
  87533. * \code chain != NULL \endcode
  87534. * \code filename != NULL \endcode
  87535. * \retval FLAC__bool
  87536. * \c true if a valid list of metadata blocks was read from
  87537. * \a filename, else \c false. On failure, check the status with
  87538. * FLAC__metadata_chain_status().
  87539. */
  87540. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87541. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87542. *
  87543. * The \a handle need only be open for reading, but must be seekable.
  87544. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87545. * for Windows).
  87546. *
  87547. * \param chain A pointer to an existing chain.
  87548. * \param handle The I/O handle of the FLAC stream to read. The
  87549. * handle will NOT be closed after the metadata is read;
  87550. * that is the duty of the caller.
  87551. * \param callbacks
  87552. * A set of callbacks to use for I/O. The mandatory
  87553. * callbacks are \a read, \a seek, and \a tell.
  87554. * \assert
  87555. * \code chain != NULL \endcode
  87556. * \retval FLAC__bool
  87557. * \c true if a valid list of metadata blocks was read from
  87558. * \a handle, else \c false. On failure, check the status with
  87559. * FLAC__metadata_chain_status().
  87560. */
  87561. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87562. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87563. *
  87564. * The \a handle need only be open for reading, but must be seekable.
  87565. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87566. * for Windows).
  87567. *
  87568. * \note Ogg FLAC metadata data writing is not supported yet and
  87569. * FLAC__metadata_chain_write() will fail.
  87570. *
  87571. * \param chain A pointer to an existing chain.
  87572. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87573. * handle will NOT be closed after the metadata is read;
  87574. * that is the duty of the caller.
  87575. * \param callbacks
  87576. * A set of callbacks to use for I/O. The mandatory
  87577. * callbacks are \a read, \a seek, and \a tell.
  87578. * \assert
  87579. * \code chain != NULL \endcode
  87580. * \retval FLAC__bool
  87581. * \c true if a valid list of metadata blocks was read from
  87582. * \a handle, else \c false. On failure, check the status with
  87583. * FLAC__metadata_chain_status().
  87584. */
  87585. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87586. /** Checks if writing the given chain would require the use of a
  87587. * temporary file, or if it could be written in place.
  87588. *
  87589. * Under certain conditions, padding can be utilized so that writing
  87590. * edited metadata back to the FLAC file does not require rewriting the
  87591. * entire file. If rewriting is required, then a temporary workfile is
  87592. * required. When writing metadata using callbacks, you must check
  87593. * this function to know whether to call
  87594. * FLAC__metadata_chain_write_with_callbacks() or
  87595. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87596. * writing with FLAC__metadata_chain_write(), the temporary file is
  87597. * handled internally.
  87598. *
  87599. * \param chain A pointer to an existing chain.
  87600. * \param use_padding
  87601. * Whether or not padding will be allowed to be used
  87602. * during the write. The value of \a use_padding given
  87603. * here must match the value later passed to
  87604. * FLAC__metadata_chain_write_with_callbacks() or
  87605. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87606. * \assert
  87607. * \code chain != NULL \endcode
  87608. * \retval FLAC__bool
  87609. * \c true if writing the current chain would require a tempfile, or
  87610. * \c false if metadata can be written in place.
  87611. */
  87612. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87613. /** Write all metadata out to the FLAC file. This function tries to be as
  87614. * efficient as possible; how the metadata is actually written is shown by
  87615. * the following:
  87616. *
  87617. * If the current chain is the same size as the existing metadata, the new
  87618. * data is written in place.
  87619. *
  87620. * If the current chain is longer than the existing metadata, and
  87621. * \a use_padding is \c true, and the last block is a PADDING block of
  87622. * sufficient length, the function will truncate the final padding block
  87623. * so that the overall size of the metadata is the same as the existing
  87624. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87625. * the above conditions are met, the entire FLAC file must be rewritten.
  87626. * If you want to use padding this way it is a good idea to call
  87627. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87628. * amount of padding to work with, unless you need to preserve ordering
  87629. * of the PADDING blocks for some reason.
  87630. *
  87631. * If the current chain is shorter than the existing metadata, and
  87632. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87633. * is extended to make the overall size the same as the existing data. If
  87634. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87635. * PADDING block is added to the end of the new data to make it the same
  87636. * size as the existing data (if possible, see the note to
  87637. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87638. * and the new data is written in place. If none of the above apply or
  87639. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87640. *
  87641. * If \a preserve_file_stats is \c true, the owner and modification time will
  87642. * be preserved even if the FLAC file is written.
  87643. *
  87644. * For this write function to be used, the chain must have been read with
  87645. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87646. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87647. *
  87648. * \param chain A pointer to an existing chain.
  87649. * \param use_padding See above.
  87650. * \param preserve_file_stats See above.
  87651. * \assert
  87652. * \code chain != NULL \endcode
  87653. * \retval FLAC__bool
  87654. * \c true if the write succeeded, else \c false. On failure,
  87655. * check the status with FLAC__metadata_chain_status().
  87656. */
  87657. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87658. /** Write all metadata out to a FLAC stream via callbacks.
  87659. *
  87660. * (See FLAC__metadata_chain_write() for the details on how padding is
  87661. * used to write metadata in place if possible.)
  87662. *
  87663. * The \a handle must be open for updating and be seekable. The
  87664. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87665. * for Windows).
  87666. *
  87667. * For this write function to be used, the chain must have been read with
  87668. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87669. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87670. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87671. * \c false.
  87672. *
  87673. * \param chain A pointer to an existing chain.
  87674. * \param use_padding See FLAC__metadata_chain_write()
  87675. * \param handle The I/O handle of the FLAC stream to write. The
  87676. * handle will NOT be closed after the metadata is
  87677. * written; that is the duty of the caller.
  87678. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87679. * callbacks are \a write and \a seek.
  87680. * \assert
  87681. * \code chain != NULL \endcode
  87682. * \retval FLAC__bool
  87683. * \c true if the write succeeded, else \c false. On failure,
  87684. * check the status with FLAC__metadata_chain_status().
  87685. */
  87686. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87687. /** Write all metadata out to a FLAC stream via callbacks.
  87688. *
  87689. * (See FLAC__metadata_chain_write() for the details on how padding is
  87690. * used to write metadata in place if possible.)
  87691. *
  87692. * This version of the write-with-callbacks function must be used when
  87693. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87694. * this function, you must supply an I/O handle corresponding to the
  87695. * FLAC file to edit, and a temporary handle to which the new FLAC
  87696. * file will be written. It is the caller's job to move this temporary
  87697. * FLAC file on top of the original FLAC file to complete the metadata
  87698. * edit.
  87699. *
  87700. * The \a handle must be open for reading and be seekable. The
  87701. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87702. * for Windows).
  87703. *
  87704. * The \a temp_handle must be open for writing. The
  87705. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87706. * for Windows). It should be an empty stream, or at least positioned
  87707. * at the start-of-file (in which case it is the caller's duty to
  87708. * truncate it on return).
  87709. *
  87710. * For this write function to be used, the chain must have been read with
  87711. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87712. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87713. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87714. * \c true.
  87715. *
  87716. * \param chain A pointer to an existing chain.
  87717. * \param use_padding See FLAC__metadata_chain_write()
  87718. * \param handle The I/O handle of the original FLAC stream to read.
  87719. * The handle will NOT be closed after the metadata is
  87720. * written; that is the duty of the caller.
  87721. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87722. * The mandatory callbacks are \a read, \a seek, and
  87723. * \a eof.
  87724. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87725. * handle will NOT be closed after the metadata is
  87726. * written; that is the duty of the caller.
  87727. * \param temp_callbacks
  87728. * A set of callbacks to use for I/O on temp_handle.
  87729. * The only mandatory callback is \a write.
  87730. * \assert
  87731. * \code chain != NULL \endcode
  87732. * \retval FLAC__bool
  87733. * \c true if the write succeeded, else \c false. On failure,
  87734. * check the status with FLAC__metadata_chain_status().
  87735. */
  87736. 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);
  87737. /** Merge adjacent PADDING blocks into a single block.
  87738. *
  87739. * \note This function does not write to the FLAC file, it only
  87740. * modifies the chain.
  87741. *
  87742. * \warning Any iterator on the current chain will become invalid after this
  87743. * call. You should delete the iterator and get a new one.
  87744. *
  87745. * \param chain A pointer to an existing chain.
  87746. * \assert
  87747. * \code chain != NULL \endcode
  87748. */
  87749. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87750. /** This function will move all PADDING blocks to the end on the metadata,
  87751. * then merge them into a single block.
  87752. *
  87753. * \note This function does not write to the FLAC file, it only
  87754. * modifies the chain.
  87755. *
  87756. * \warning Any iterator on the current chain will become invalid after this
  87757. * call. You should delete the iterator and get a new one.
  87758. *
  87759. * \param chain A pointer to an existing chain.
  87760. * \assert
  87761. * \code chain != NULL \endcode
  87762. */
  87763. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87764. /*********** FLAC__Metadata_Iterator ***********/
  87765. /** Create a new iterator instance.
  87766. *
  87767. * \retval FLAC__Metadata_Iterator*
  87768. * \c NULL if there was an error allocating memory, else the new instance.
  87769. */
  87770. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87771. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87772. *
  87773. * \param iterator A pointer to an existing iterator.
  87774. * \assert
  87775. * \code iterator != NULL \endcode
  87776. */
  87777. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87778. /** Initialize the iterator to point to the first metadata block in the
  87779. * given chain.
  87780. *
  87781. * \param iterator A pointer to an existing iterator.
  87782. * \param chain A pointer to an existing and initialized (read) chain.
  87783. * \assert
  87784. * \code iterator != NULL \endcode
  87785. * \code chain != NULL \endcode
  87786. */
  87787. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87788. /** Moves the iterator forward one metadata block, returning \c false if
  87789. * already at the end.
  87790. *
  87791. * \param iterator A pointer to an existing initialized iterator.
  87792. * \assert
  87793. * \code iterator != NULL \endcode
  87794. * \a iterator has been successfully initialized with
  87795. * FLAC__metadata_iterator_init()
  87796. * \retval FLAC__bool
  87797. * \c false if already at the last metadata block of the chain, else
  87798. * \c true.
  87799. */
  87800. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  87801. /** Moves the iterator backward one metadata block, returning \c false if
  87802. * already at the beginning.
  87803. *
  87804. * \param iterator A pointer to an existing initialized iterator.
  87805. * \assert
  87806. * \code iterator != NULL \endcode
  87807. * \a iterator has been successfully initialized with
  87808. * FLAC__metadata_iterator_init()
  87809. * \retval FLAC__bool
  87810. * \c false if already at the first metadata block of the chain, else
  87811. * \c true.
  87812. */
  87813. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  87814. /** Get the type of the metadata block at the current position.
  87815. *
  87816. * \param iterator A pointer to an existing initialized iterator.
  87817. * \assert
  87818. * \code iterator != NULL \endcode
  87819. * \a iterator has been successfully initialized with
  87820. * FLAC__metadata_iterator_init()
  87821. * \retval FLAC__MetadataType
  87822. * The type of the metadata block at the current iterator position.
  87823. */
  87824. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  87825. /** Get the metadata block at the current position. You can modify
  87826. * the block in place but must write the chain before the changes
  87827. * are reflected to the FLAC file. You do not need to call
  87828. * FLAC__metadata_iterator_set_block() to reflect the changes;
  87829. * the pointer returned by FLAC__metadata_iterator_get_block()
  87830. * points directly into the chain.
  87831. *
  87832. * \warning
  87833. * Do not call FLAC__metadata_object_delete() on the returned object;
  87834. * to delete a block use FLAC__metadata_iterator_delete_block().
  87835. *
  87836. * \param iterator A pointer to an existing initialized iterator.
  87837. * \assert
  87838. * \code iterator != NULL \endcode
  87839. * \a iterator has been successfully initialized with
  87840. * FLAC__metadata_iterator_init()
  87841. * \retval FLAC__StreamMetadata*
  87842. * The current metadata block.
  87843. */
  87844. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  87845. /** Set the metadata block at the current position, replacing the existing
  87846. * block. The new block passed in becomes owned by the chain and it will be
  87847. * deleted when the chain is deleted.
  87848. *
  87849. * \param iterator A pointer to an existing initialized iterator.
  87850. * \param block A pointer to a metadata block.
  87851. * \assert
  87852. * \code iterator != NULL \endcode
  87853. * \a iterator has been successfully initialized with
  87854. * FLAC__metadata_iterator_init()
  87855. * \code block != NULL \endcode
  87856. * \retval FLAC__bool
  87857. * \c false if the conditions in the above description are not met, or
  87858. * a memory allocation error occurs, otherwise \c true.
  87859. */
  87860. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87861. /** Removes the current block from the chain. If \a replace_with_padding is
  87862. * \c true, the block will instead be replaced with a padding block of equal
  87863. * size. You can not delete the STREAMINFO block. The iterator will be
  87864. * left pointing to the block before the one just "deleted", even if
  87865. * \a replace_with_padding is \c true.
  87866. *
  87867. * \param iterator A pointer to an existing initialized iterator.
  87868. * \param replace_with_padding See above.
  87869. * \assert
  87870. * \code iterator != NULL \endcode
  87871. * \a iterator has been successfully initialized with
  87872. * FLAC__metadata_iterator_init()
  87873. * \retval FLAC__bool
  87874. * \c false if the conditions in the above description are not met,
  87875. * otherwise \c true.
  87876. */
  87877. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  87878. /** Insert a new block before the current block. You cannot insert a block
  87879. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  87880. * as there can be only one, the one that already exists at the head when you
  87881. * read in a chain. The chain takes ownership of the new block and it will be
  87882. * deleted when the chain is deleted. The iterator will be left pointing to
  87883. * the new block.
  87884. *
  87885. * \param iterator A pointer to an existing initialized iterator.
  87886. * \param block A pointer to a metadata block to insert.
  87887. * \assert
  87888. * \code iterator != NULL \endcode
  87889. * \a iterator has been successfully initialized with
  87890. * FLAC__metadata_iterator_init()
  87891. * \retval FLAC__bool
  87892. * \c false if the conditions in the above description are not met, or
  87893. * a memory allocation error occurs, otherwise \c true.
  87894. */
  87895. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87896. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  87897. * block as there can be only one, the one that already exists at the head when
  87898. * you read in a chain. The chain takes ownership of the new block and it will
  87899. * be deleted when the chain is deleted. The iterator will be left pointing to
  87900. * the new block.
  87901. *
  87902. * \param iterator A pointer to an existing initialized iterator.
  87903. * \param block A pointer to a metadata block to insert.
  87904. * \assert
  87905. * \code iterator != NULL \endcode
  87906. * \a iterator has been successfully initialized with
  87907. * FLAC__metadata_iterator_init()
  87908. * \retval FLAC__bool
  87909. * \c false if the conditions in the above description are not met, or
  87910. * a memory allocation error occurs, otherwise \c true.
  87911. */
  87912. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87913. /* \} */
  87914. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  87915. * \ingroup flac_metadata
  87916. *
  87917. * \brief
  87918. * This module contains methods for manipulating FLAC metadata objects.
  87919. *
  87920. * Since many are variable length we have to be careful about the memory
  87921. * management. We decree that all pointers to data in the object are
  87922. * owned by the object and memory-managed by the object.
  87923. *
  87924. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  87925. * functions to create all instances. When using the
  87926. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  87927. * \a copy to \c true to have the function make it's own copy of the data, or
  87928. * to \c false to give the object ownership of your data. In the latter case
  87929. * your pointer must be freeable by free() and will be free()d when the object
  87930. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  87931. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  87932. * the length argument is 0 and the \a copy argument is \c false.
  87933. *
  87934. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  87935. * will return \c NULL in the case of a memory allocation error, otherwise a new
  87936. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  87937. * case of a memory allocation error.
  87938. *
  87939. * We don't have the convenience of C++ here, so note that the library relies
  87940. * on you to keep the types straight. In other words, if you pass, for
  87941. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  87942. * FLAC__metadata_object_application_set_data(), you will get an assertion
  87943. * failure.
  87944. *
  87945. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  87946. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  87947. * toward the length or stored in the stream, but it can make working with plain
  87948. * comments (those that don't contain embedded-NULs in the value) easier.
  87949. * Entries passed into these functions have trailing NULs added if missing, and
  87950. * returned entries are guaranteed to have a trailing NUL.
  87951. *
  87952. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  87953. * comment entry/name/value will first validate that it complies with the Vorbis
  87954. * comment specification and return false if it does not.
  87955. *
  87956. * There is no need to recalculate the length field on metadata blocks you
  87957. * have modified. They will be calculated automatically before they are
  87958. * written back to a file.
  87959. *
  87960. * \{
  87961. */
  87962. /** Create a new metadata object instance of the given type.
  87963. *
  87964. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  87965. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  87966. * the vendor string set (but zero comments).
  87967. *
  87968. * Do not pass in a value greater than or equal to
  87969. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  87970. * doing.
  87971. *
  87972. * \param type Type of object to create
  87973. * \retval FLAC__StreamMetadata*
  87974. * \c NULL if there was an error allocating memory or the type code is
  87975. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  87976. */
  87977. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  87978. /** Create a copy of an existing metadata object.
  87979. *
  87980. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  87981. * object is also copied. The caller takes ownership of the new block and
  87982. * is responsible for freeing it with FLAC__metadata_object_delete().
  87983. *
  87984. * \param object Pointer to object to copy.
  87985. * \assert
  87986. * \code object != NULL \endcode
  87987. * \retval FLAC__StreamMetadata*
  87988. * \c NULL if there was an error allocating memory, else the new instance.
  87989. */
  87990. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  87991. /** Free a metadata object. Deletes the object pointed to by \a object.
  87992. *
  87993. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  87994. * object is also deleted.
  87995. *
  87996. * \param object A pointer to an existing object.
  87997. * \assert
  87998. * \code object != NULL \endcode
  87999. */
  88000. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88001. /** Compares two metadata objects.
  88002. *
  88003. * The compare is "deep", i.e. dynamically allocated data within the
  88004. * object is also compared.
  88005. *
  88006. * \param block1 A pointer to an existing object.
  88007. * \param block2 A pointer to an existing object.
  88008. * \assert
  88009. * \code block1 != NULL \endcode
  88010. * \code block2 != NULL \endcode
  88011. * \retval FLAC__bool
  88012. * \c true if objects are identical, else \c false.
  88013. */
  88014. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88015. /** Sets the application data of an APPLICATION block.
  88016. *
  88017. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88018. * takes ownership of the pointer. The existing data will be freed if this
  88019. * function is successful, otherwise the original data will remain if \a copy
  88020. * is \c true and malloc() fails.
  88021. *
  88022. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88023. *
  88024. * \param object A pointer to an existing APPLICATION object.
  88025. * \param data A pointer to the data to set.
  88026. * \param length The length of \a data in bytes.
  88027. * \param copy See above.
  88028. * \assert
  88029. * \code object != NULL \endcode
  88030. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88031. * \code (data != NULL && length > 0) ||
  88032. * (data == NULL && length == 0 && copy == false) \endcode
  88033. * \retval FLAC__bool
  88034. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88035. */
  88036. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88037. /** Resize the seekpoint array.
  88038. *
  88039. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88040. * points will be added to the end.
  88041. *
  88042. * \param object A pointer to an existing SEEKTABLE object.
  88043. * \param new_num_points The desired length of the array; may be \c 0.
  88044. * \assert
  88045. * \code object != NULL \endcode
  88046. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88047. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88048. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88049. * \retval FLAC__bool
  88050. * \c false if memory allocation error, else \c true.
  88051. */
  88052. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88053. /** Set a seekpoint in a seektable.
  88054. *
  88055. * \param object A pointer to an existing SEEKTABLE object.
  88056. * \param point_num Index into seekpoint array to set.
  88057. * \param point The point to set.
  88058. * \assert
  88059. * \code object != NULL \endcode
  88060. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88061. * \code object->data.seek_table.num_points > point_num \endcode
  88062. */
  88063. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88064. /** Insert a seekpoint into a seektable.
  88065. *
  88066. * \param object A pointer to an existing SEEKTABLE object.
  88067. * \param point_num Index into seekpoint array to set.
  88068. * \param point The point to set.
  88069. * \assert
  88070. * \code object != NULL \endcode
  88071. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88072. * \code object->data.seek_table.num_points >= point_num \endcode
  88073. * \retval FLAC__bool
  88074. * \c false if memory allocation error, else \c true.
  88075. */
  88076. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88077. /** Delete a seekpoint from a seektable.
  88078. *
  88079. * \param object A pointer to an existing SEEKTABLE object.
  88080. * \param point_num Index into seekpoint array to set.
  88081. * \assert
  88082. * \code object != NULL \endcode
  88083. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88084. * \code object->data.seek_table.num_points > point_num \endcode
  88085. * \retval FLAC__bool
  88086. * \c false if memory allocation error, else \c true.
  88087. */
  88088. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88089. /** Check a seektable to see if it conforms to the FLAC specification.
  88090. * See the format specification for limits on the contents of the
  88091. * seektable.
  88092. *
  88093. * \param object A pointer to an existing SEEKTABLE object.
  88094. * \assert
  88095. * \code object != NULL \endcode
  88096. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88097. * \retval FLAC__bool
  88098. * \c false if seek table is illegal, else \c true.
  88099. */
  88100. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88101. /** Append a number of placeholder points to the end of a seek table.
  88102. *
  88103. * \note
  88104. * As with the other ..._seektable_template_... functions, you should
  88105. * call FLAC__metadata_object_seektable_template_sort() when finished
  88106. * to make the seek table legal.
  88107. *
  88108. * \param object A pointer to an existing SEEKTABLE object.
  88109. * \param num The number of placeholder points to append.
  88110. * \assert
  88111. * \code object != NULL \endcode
  88112. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88113. * \retval FLAC__bool
  88114. * \c false if memory allocation fails, else \c true.
  88115. */
  88116. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88117. /** Append a specific seek point template to the end of a seek table.
  88118. *
  88119. * \note
  88120. * As with the other ..._seektable_template_... functions, you should
  88121. * call FLAC__metadata_object_seektable_template_sort() when finished
  88122. * to make the seek table legal.
  88123. *
  88124. * \param object A pointer to an existing SEEKTABLE object.
  88125. * \param sample_number The sample number of the seek point template.
  88126. * \assert
  88127. * \code object != NULL \endcode
  88128. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88129. * \retval FLAC__bool
  88130. * \c false if memory allocation fails, else \c true.
  88131. */
  88132. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88133. /** Append specific seek point templates to the end of a seek table.
  88134. *
  88135. * \note
  88136. * As with the other ..._seektable_template_... functions, you should
  88137. * call FLAC__metadata_object_seektable_template_sort() when finished
  88138. * to make the seek table legal.
  88139. *
  88140. * \param object A pointer to an existing SEEKTABLE object.
  88141. * \param sample_numbers An array of sample numbers for the seek points.
  88142. * \param num The number of seek point templates to append.
  88143. * \assert
  88144. * \code object != NULL \endcode
  88145. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88146. * \retval FLAC__bool
  88147. * \c false if memory allocation fails, else \c true.
  88148. */
  88149. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88150. /** Append a set of evenly-spaced seek point templates to the end of a
  88151. * seek table.
  88152. *
  88153. * \note
  88154. * As with the other ..._seektable_template_... functions, you should
  88155. * call FLAC__metadata_object_seektable_template_sort() when finished
  88156. * to make the seek table legal.
  88157. *
  88158. * \param object A pointer to an existing SEEKTABLE object.
  88159. * \param num The number of placeholder points to append.
  88160. * \param total_samples The total number of samples to be encoded;
  88161. * the seekpoints will be spaced approximately
  88162. * \a total_samples / \a num samples apart.
  88163. * \assert
  88164. * \code object != NULL \endcode
  88165. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88166. * \code total_samples > 0 \endcode
  88167. * \retval FLAC__bool
  88168. * \c false if memory allocation fails, else \c true.
  88169. */
  88170. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88171. /** Append a set of evenly-spaced seek point templates to the end of a
  88172. * seek table.
  88173. *
  88174. * \note
  88175. * As with the other ..._seektable_template_... functions, you should
  88176. * call FLAC__metadata_object_seektable_template_sort() when finished
  88177. * to make the seek table legal.
  88178. *
  88179. * \param object A pointer to an existing SEEKTABLE object.
  88180. * \param samples The number of samples apart to space the placeholder
  88181. * points. The first point will be at sample \c 0, the
  88182. * second at sample \a samples, then 2*\a samples, and
  88183. * so on. As long as \a samples and \a total_samples
  88184. * are greater than \c 0, there will always be at least
  88185. * one seekpoint at sample \c 0.
  88186. * \param total_samples The total number of samples to be encoded;
  88187. * the seekpoints will be spaced
  88188. * \a samples samples apart.
  88189. * \assert
  88190. * \code object != NULL \endcode
  88191. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88192. * \code samples > 0 \endcode
  88193. * \code total_samples > 0 \endcode
  88194. * \retval FLAC__bool
  88195. * \c false if memory allocation fails, else \c true.
  88196. */
  88197. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88198. /** Sort a seek table's seek points according to the format specification,
  88199. * removing duplicates.
  88200. *
  88201. * \param object A pointer to a seek table to be sorted.
  88202. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88203. * If \c true, duplicates are deleted and the seek table is
  88204. * shrunk appropriately; the number of placeholder points
  88205. * present in the seek table will be the same after the call
  88206. * as before.
  88207. * \assert
  88208. * \code object != NULL \endcode
  88209. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88210. * \retval FLAC__bool
  88211. * \c false if realloc() fails, else \c true.
  88212. */
  88213. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88214. /** Sets the vendor string in a VORBIS_COMMENT block.
  88215. *
  88216. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88217. * one already.
  88218. *
  88219. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88220. * takes ownership of the \c entry.entry pointer.
  88221. *
  88222. * \note If this function returns \c false, the caller still owns the
  88223. * pointer.
  88224. *
  88225. * \param object A pointer to an existing VORBIS_COMMENT object.
  88226. * \param entry The entry to set the vendor string to.
  88227. * \param copy See above.
  88228. * \assert
  88229. * \code object != NULL \endcode
  88230. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88231. * \code (entry.entry != NULL && entry.length > 0) ||
  88232. * (entry.entry == NULL && entry.length == 0) \endcode
  88233. * \retval FLAC__bool
  88234. * \c false if memory allocation fails or \a entry does not comply with the
  88235. * Vorbis comment specification, else \c true.
  88236. */
  88237. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88238. /** Resize the comment array.
  88239. *
  88240. * If the size shrinks, elements will truncated; if it grows, new empty
  88241. * fields will be added to the end.
  88242. *
  88243. * \param object A pointer to an existing VORBIS_COMMENT object.
  88244. * \param new_num_comments The desired length of the array; may be \c 0.
  88245. * \assert
  88246. * \code object != NULL \endcode
  88247. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88248. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88249. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88250. * \retval FLAC__bool
  88251. * \c false if memory allocation fails, else \c true.
  88252. */
  88253. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88254. /** Sets a comment in a VORBIS_COMMENT block.
  88255. *
  88256. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88257. * one already.
  88258. *
  88259. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88260. * takes ownership of the \c entry.entry pointer.
  88261. *
  88262. * \note If this function returns \c false, the caller still owns the
  88263. * pointer.
  88264. *
  88265. * \param object A pointer to an existing VORBIS_COMMENT object.
  88266. * \param comment_num Index into comment array to set.
  88267. * \param entry The entry to set the comment to.
  88268. * \param copy See above.
  88269. * \assert
  88270. * \code object != NULL \endcode
  88271. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88272. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88273. * \code (entry.entry != NULL && entry.length > 0) ||
  88274. * (entry.entry == NULL && entry.length == 0) \endcode
  88275. * \retval FLAC__bool
  88276. * \c false if memory allocation fails or \a entry does not comply with the
  88277. * Vorbis comment specification, else \c true.
  88278. */
  88279. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88280. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88281. *
  88282. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88283. * one already.
  88284. *
  88285. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88286. * takes ownership of the \c entry.entry pointer.
  88287. *
  88288. * \note If this function returns \c false, the caller still owns the
  88289. * pointer.
  88290. *
  88291. * \param object A pointer to an existing VORBIS_COMMENT object.
  88292. * \param comment_num The index at which to insert the comment. The comments
  88293. * at and after \a comment_num move right one position.
  88294. * To append a comment to the end, set \a comment_num to
  88295. * \c object->data.vorbis_comment.num_comments .
  88296. * \param entry The comment to insert.
  88297. * \param copy See above.
  88298. * \assert
  88299. * \code object != NULL \endcode
  88300. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88301. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88302. * \code (entry.entry != NULL && entry.length > 0) ||
  88303. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88304. * \retval FLAC__bool
  88305. * \c false if memory allocation fails or \a entry does not comply with the
  88306. * Vorbis comment specification, else \c true.
  88307. */
  88308. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88309. /** Appends a comment to a VORBIS_COMMENT block.
  88310. *
  88311. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88312. * one already.
  88313. *
  88314. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88315. * takes ownership of the \c entry.entry pointer.
  88316. *
  88317. * \note If this function returns \c false, the caller still owns the
  88318. * pointer.
  88319. *
  88320. * \param object A pointer to an existing VORBIS_COMMENT object.
  88321. * \param entry The comment to insert.
  88322. * \param copy See above.
  88323. * \assert
  88324. * \code object != NULL \endcode
  88325. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88326. * \code (entry.entry != NULL && entry.length > 0) ||
  88327. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88328. * \retval FLAC__bool
  88329. * \c false if memory allocation fails or \a entry does not comply with the
  88330. * Vorbis comment specification, else \c true.
  88331. */
  88332. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88333. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88334. *
  88335. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88336. * one already.
  88337. *
  88338. * Depending on the the value of \a all, either all or just the first comment
  88339. * whose field name(s) match the given entry's name will be replaced by the
  88340. * given entry. If no comments match, \a entry will simply be appended.
  88341. *
  88342. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88343. * takes ownership of the \c entry.entry pointer.
  88344. *
  88345. * \note If this function returns \c false, the caller still owns the
  88346. * pointer.
  88347. *
  88348. * \param object A pointer to an existing VORBIS_COMMENT object.
  88349. * \param entry The comment to insert.
  88350. * \param all If \c true, all comments whose field name matches
  88351. * \a entry's field name will be removed, and \a entry will
  88352. * be inserted at the position of the first matching
  88353. * comment. If \c false, only the first comment whose
  88354. * field name matches \a entry's field name will be
  88355. * replaced with \a entry.
  88356. * \param copy See above.
  88357. * \assert
  88358. * \code object != NULL \endcode
  88359. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88360. * \code (entry.entry != NULL && entry.length > 0) ||
  88361. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88362. * \retval FLAC__bool
  88363. * \c false if memory allocation fails or \a entry does not comply with the
  88364. * Vorbis comment specification, else \c true.
  88365. */
  88366. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88367. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88368. *
  88369. * \param object A pointer to an existing VORBIS_COMMENT object.
  88370. * \param comment_num The index of the comment to delete.
  88371. * \assert
  88372. * \code object != NULL \endcode
  88373. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88374. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88375. * \retval FLAC__bool
  88376. * \c false if realloc() fails, else \c true.
  88377. */
  88378. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88379. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88380. *
  88381. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88382. * memory and shall be owned by the caller. For convenience the entry will
  88383. * have a terminating NUL.
  88384. *
  88385. * \param entry A pointer to a Vorbis comment entry. The entry's
  88386. * \c entry pointer should not point to allocated
  88387. * memory as it will be overwritten.
  88388. * \param field_name The field name in ASCII, \c NUL terminated.
  88389. * \param field_value The field value in UTF-8, \c NUL terminated.
  88390. * \assert
  88391. * \code entry != NULL \endcode
  88392. * \code field_name != NULL \endcode
  88393. * \code field_value != NULL \endcode
  88394. * \retval FLAC__bool
  88395. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88396. * not comply with the Vorbis comment specification, else \c true.
  88397. */
  88398. 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);
  88399. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88400. *
  88401. * The returned pointers to name and value will be allocated by malloc()
  88402. * and shall be owned by the caller.
  88403. *
  88404. * \param entry An existing Vorbis comment entry.
  88405. * \param field_name The address of where the returned pointer to the
  88406. * field name will be stored.
  88407. * \param field_value The address of where the returned pointer to the
  88408. * field value will be stored.
  88409. * \assert
  88410. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88411. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88412. * \code field_name != NULL \endcode
  88413. * \code field_value != NULL \endcode
  88414. * \retval FLAC__bool
  88415. * \c false if memory allocation fails or \a entry does not comply with the
  88416. * Vorbis comment specification, else \c true.
  88417. */
  88418. 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);
  88419. /** Check if the given Vorbis comment entry's field name matches the given
  88420. * field name.
  88421. *
  88422. * \param entry An existing Vorbis comment entry.
  88423. * \param field_name The field name to check.
  88424. * \param field_name_length The length of \a field_name, not including the
  88425. * terminating \c NUL.
  88426. * \assert
  88427. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88428. * \retval FLAC__bool
  88429. * \c true if the field names match, else \c false
  88430. */
  88431. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88432. /** Find a Vorbis comment with the given field name.
  88433. *
  88434. * The search begins at entry number \a offset; use an offset of 0 to
  88435. * search from the beginning of the comment array.
  88436. *
  88437. * \param object A pointer to an existing VORBIS_COMMENT object.
  88438. * \param offset The offset into the comment array from where to start
  88439. * the search.
  88440. * \param field_name The field name of the comment to find.
  88441. * \assert
  88442. * \code object != NULL \endcode
  88443. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88444. * \code field_name != NULL \endcode
  88445. * \retval int
  88446. * The offset in the comment array of the first comment whose field
  88447. * name matches \a field_name, or \c -1 if no match was found.
  88448. */
  88449. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88450. /** Remove first Vorbis comment matching the given field name.
  88451. *
  88452. * \param object A pointer to an existing VORBIS_COMMENT object.
  88453. * \param field_name The field name of comment to delete.
  88454. * \assert
  88455. * \code object != NULL \endcode
  88456. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88457. * \retval int
  88458. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88459. * \c 1 for one matching entry deleted.
  88460. */
  88461. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88462. /** Remove all Vorbis comments matching the given field name.
  88463. *
  88464. * \param object A pointer to an existing VORBIS_COMMENT object.
  88465. * \param field_name The field name of comments to delete.
  88466. * \assert
  88467. * \code object != NULL \endcode
  88468. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88469. * \retval int
  88470. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88471. * else the number of matching entries deleted.
  88472. */
  88473. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88474. /** Create a new CUESHEET track instance.
  88475. *
  88476. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88477. *
  88478. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88479. * \c NULL if there was an error allocating memory, else the new instance.
  88480. */
  88481. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88482. /** Create a copy of an existing CUESHEET track object.
  88483. *
  88484. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88485. * object is also copied. The caller takes ownership of the new object and
  88486. * is responsible for freeing it with
  88487. * FLAC__metadata_object_cuesheet_track_delete().
  88488. *
  88489. * \param object Pointer to object to copy.
  88490. * \assert
  88491. * \code object != NULL \endcode
  88492. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88493. * \c NULL if there was an error allocating memory, else the new instance.
  88494. */
  88495. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88496. /** Delete a CUESHEET track object
  88497. *
  88498. * \param object A pointer to an existing CUESHEET track object.
  88499. * \assert
  88500. * \code object != NULL \endcode
  88501. */
  88502. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88503. /** Resize a track's index point array.
  88504. *
  88505. * If the size shrinks, elements will truncated; if it grows, new blank
  88506. * indices will be added to the end.
  88507. *
  88508. * \param object A pointer to an existing CUESHEET object.
  88509. * \param track_num The index of the track to modify. NOTE: this is not
  88510. * necessarily the same as the track's \a number field.
  88511. * \param new_num_indices The desired length of the array; may be \c 0.
  88512. * \assert
  88513. * \code object != NULL \endcode
  88514. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88515. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88516. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88517. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88518. * \retval FLAC__bool
  88519. * \c false if memory allocation error, else \c true.
  88520. */
  88521. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88522. /** Insert an index point in a CUESHEET track at the given index.
  88523. *
  88524. * \param object A pointer to an existing CUESHEET object.
  88525. * \param track_num The index of the track to modify. NOTE: this is not
  88526. * necessarily the same as the track's \a number field.
  88527. * \param index_num The index into the track's index array at which to
  88528. * insert the index point. NOTE: this is not necessarily
  88529. * the same as the index point's \a number field. The
  88530. * indices at and after \a index_num move right one
  88531. * position. To append an index point to the end, set
  88532. * \a index_num to
  88533. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88534. * \param index The index point to insert.
  88535. * \assert
  88536. * \code object != NULL \endcode
  88537. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88538. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88539. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88540. * \retval FLAC__bool
  88541. * \c false if realloc() fails, else \c true.
  88542. */
  88543. 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);
  88544. /** Insert a blank index point in a CUESHEET track at the given index.
  88545. *
  88546. * A blank index point is one in which all field values are zero.
  88547. *
  88548. * \param object A pointer to an existing CUESHEET object.
  88549. * \param track_num The index of the track to modify. NOTE: this is not
  88550. * necessarily the same as the track's \a number field.
  88551. * \param index_num The index into the track's index array at which to
  88552. * insert the index point. NOTE: this is not necessarily
  88553. * the same as the index point's \a number field. The
  88554. * indices at and after \a index_num move right one
  88555. * position. To append an index point to the end, set
  88556. * \a index_num to
  88557. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88558. * \assert
  88559. * \code object != NULL \endcode
  88560. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88561. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88562. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88563. * \retval FLAC__bool
  88564. * \c false if realloc() fails, else \c true.
  88565. */
  88566. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88567. /** Delete an index point in a CUESHEET track at the given index.
  88568. *
  88569. * \param object A pointer to an existing CUESHEET object.
  88570. * \param track_num The index into the track array of the track to
  88571. * modify. NOTE: this is not necessarily the same
  88572. * as the track's \a number field.
  88573. * \param index_num The index into the track's index array of the index
  88574. * to delete. NOTE: this is not necessarily the same
  88575. * as the index's \a number field.
  88576. * \assert
  88577. * \code object != NULL \endcode
  88578. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88579. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88580. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88581. * \retval FLAC__bool
  88582. * \c false if realloc() fails, else \c true.
  88583. */
  88584. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88585. /** Resize the track array.
  88586. *
  88587. * If the size shrinks, elements will truncated; if it grows, new blank
  88588. * tracks will be added to the end.
  88589. *
  88590. * \param object A pointer to an existing CUESHEET object.
  88591. * \param new_num_tracks The desired length of the array; may be \c 0.
  88592. * \assert
  88593. * \code object != NULL \endcode
  88594. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88595. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88596. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88597. * \retval FLAC__bool
  88598. * \c false if memory allocation error, else \c true.
  88599. */
  88600. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88601. /** Sets a track in a CUESHEET block.
  88602. *
  88603. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88604. * takes ownership of the \a track pointer.
  88605. *
  88606. * \param object A pointer to an existing CUESHEET object.
  88607. * \param track_num Index into track array to set. NOTE: this is not
  88608. * necessarily the same as the track's \a number field.
  88609. * \param track The track to set the track to. You may safely pass in
  88610. * a const pointer if \a copy is \c true.
  88611. * \param copy See above.
  88612. * \assert
  88613. * \code object != NULL \endcode
  88614. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88615. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88616. * \code (track->indices != NULL && track->num_indices > 0) ||
  88617. * (track->indices == NULL && track->num_indices == 0)
  88618. * \retval FLAC__bool
  88619. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88620. */
  88621. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88622. /** Insert a track in a CUESHEET block at the given index.
  88623. *
  88624. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88625. * takes ownership of the \a track pointer.
  88626. *
  88627. * \param object A pointer to an existing CUESHEET object.
  88628. * \param track_num The index at which to insert the track. NOTE: this
  88629. * is not necessarily the same as the track's \a number
  88630. * field. The tracks at and after \a track_num move right
  88631. * one position. To append a track to the end, set
  88632. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88633. * \param track The track to insert. You may safely pass in a const
  88634. * pointer if \a copy is \c true.
  88635. * \param copy See above.
  88636. * \assert
  88637. * \code object != NULL \endcode
  88638. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88639. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88640. * \retval FLAC__bool
  88641. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88642. */
  88643. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88644. /** Insert a blank track in a CUESHEET block at the given index.
  88645. *
  88646. * A blank track is one in which all field values are zero.
  88647. *
  88648. * \param object A pointer to an existing CUESHEET object.
  88649. * \param track_num The index at which to insert the track. NOTE: this
  88650. * is not necessarily the same as the track's \a number
  88651. * field. The tracks at and after \a track_num move right
  88652. * one position. To append a track to the end, set
  88653. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88654. * \assert
  88655. * \code object != NULL \endcode
  88656. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88657. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88658. * \retval FLAC__bool
  88659. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88660. */
  88661. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88662. /** Delete a track in a CUESHEET block at the given index.
  88663. *
  88664. * \param object A pointer to an existing CUESHEET object.
  88665. * \param track_num The index into the track array of the track to
  88666. * delete. NOTE: this is not necessarily the same
  88667. * as the track's \a number field.
  88668. * \assert
  88669. * \code object != NULL \endcode
  88670. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88671. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88672. * \retval FLAC__bool
  88673. * \c false if realloc() fails, else \c true.
  88674. */
  88675. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88676. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88677. * See the format specification for limits on the contents of the
  88678. * cue sheet.
  88679. *
  88680. * \param object A pointer to an existing CUESHEET object.
  88681. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88682. * stringent requirements for a CD-DA (audio) disc.
  88683. * \param violation Address of a pointer to a string. If there is a
  88684. * violation, a pointer to a string explanation of the
  88685. * violation will be returned here. \a violation may be
  88686. * \c NULL if you don't need the returned string. Do not
  88687. * free the returned string; it will always point to static
  88688. * data.
  88689. * \assert
  88690. * \code object != NULL \endcode
  88691. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88692. * \retval FLAC__bool
  88693. * \c false if cue sheet is illegal, else \c true.
  88694. */
  88695. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88696. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88697. * assumes the cue sheet corresponds to a CD; the result is undefined
  88698. * if the cuesheet's is_cd bit is not set.
  88699. *
  88700. * \param object A pointer to an existing CUESHEET object.
  88701. * \assert
  88702. * \code object != NULL \endcode
  88703. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88704. * \retval FLAC__uint32
  88705. * The unsigned integer representation of the CDDB/freedb ID
  88706. */
  88707. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88708. /** Sets the MIME type of a PICTURE block.
  88709. *
  88710. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88711. * takes ownership of the pointer. The existing string will be freed if this
  88712. * function is successful, otherwise the original string will remain if \a copy
  88713. * is \c true and malloc() fails.
  88714. *
  88715. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88716. *
  88717. * \param object A pointer to an existing PICTURE object.
  88718. * \param mime_type A pointer to the MIME type string. The string must be
  88719. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88720. * is done.
  88721. * \param copy See above.
  88722. * \assert
  88723. * \code object != NULL \endcode
  88724. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88725. * \code (mime_type != NULL) \endcode
  88726. * \retval FLAC__bool
  88727. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88728. */
  88729. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88730. /** Sets the description of a PICTURE block.
  88731. *
  88732. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88733. * takes ownership of the pointer. The existing string will be freed if this
  88734. * function is successful, otherwise the original string will remain if \a copy
  88735. * is \c true and malloc() fails.
  88736. *
  88737. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88738. *
  88739. * \param object A pointer to an existing PICTURE object.
  88740. * \param description A pointer to the description string. The string must be
  88741. * valid UTF-8, NUL-terminated. No validation is done.
  88742. * \param copy See above.
  88743. * \assert
  88744. * \code object != NULL \endcode
  88745. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88746. * \code (description != NULL) \endcode
  88747. * \retval FLAC__bool
  88748. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88749. */
  88750. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88751. /** Sets the picture data of a PICTURE block.
  88752. *
  88753. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88754. * takes ownership of the pointer. Also sets the \a data_length field of the
  88755. * metadata object to what is passed in as the \a length parameter. The
  88756. * existing data will be freed if this function is successful, otherwise the
  88757. * original data and data_length will remain if \a copy is \c true and
  88758. * malloc() fails.
  88759. *
  88760. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88761. *
  88762. * \param object A pointer to an existing PICTURE object.
  88763. * \param data A pointer to the data to set.
  88764. * \param length The length of \a data in bytes.
  88765. * \param copy See above.
  88766. * \assert
  88767. * \code object != NULL \endcode
  88768. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88769. * \code (data != NULL && length > 0) ||
  88770. * (data == NULL && length == 0 && copy == false) \endcode
  88771. * \retval FLAC__bool
  88772. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88773. */
  88774. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88775. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88776. * See the format specification for limits on the contents of the
  88777. * PICTURE block.
  88778. *
  88779. * \param object A pointer to existing PICTURE block to be checked.
  88780. * \param violation Address of a pointer to a string. If there is a
  88781. * violation, a pointer to a string explanation of the
  88782. * violation will be returned here. \a violation may be
  88783. * \c NULL if you don't need the returned string. Do not
  88784. * free the returned string; it will always point to static
  88785. * data.
  88786. * \assert
  88787. * \code object != NULL \endcode
  88788. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88789. * \retval FLAC__bool
  88790. * \c false if PICTURE block is illegal, else \c true.
  88791. */
  88792. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  88793. /* \} */
  88794. #ifdef __cplusplus
  88795. }
  88796. #endif
  88797. #endif
  88798. /*** End of inlined file: metadata.h ***/
  88799. /*** Start of inlined file: stream_decoder.h ***/
  88800. #ifndef FLAC__STREAM_DECODER_H
  88801. #define FLAC__STREAM_DECODER_H
  88802. #include <stdio.h> /* for FILE */
  88803. #ifdef __cplusplus
  88804. extern "C" {
  88805. #endif
  88806. /** \file include/FLAC/stream_decoder.h
  88807. *
  88808. * \brief
  88809. * This module contains the functions which implement the stream
  88810. * decoder.
  88811. *
  88812. * See the detailed documentation in the
  88813. * \link flac_stream_decoder stream decoder \endlink module.
  88814. */
  88815. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  88816. * \ingroup flac
  88817. *
  88818. * \brief
  88819. * This module describes the decoder layers provided by libFLAC.
  88820. *
  88821. * The stream decoder can be used to decode complete streams either from
  88822. * the client via callbacks, or directly from a file, depending on how
  88823. * it is initialized. When decoding via callbacks, the client provides
  88824. * callbacks for reading FLAC data and writing decoded samples, and
  88825. * handling metadata and errors. If the client also supplies seek-related
  88826. * callback, the decoder function for sample-accurate seeking within the
  88827. * FLAC input is also available. When decoding from a file, the client
  88828. * needs only supply a filename or open \c FILE* and write/metadata/error
  88829. * callbacks; the rest of the callbacks are supplied internally. For more
  88830. * info see the \link flac_stream_decoder stream decoder \endlink module.
  88831. */
  88832. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  88833. * \ingroup flac_decoder
  88834. *
  88835. * \brief
  88836. * This module contains the functions which implement the stream
  88837. * decoder.
  88838. *
  88839. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  88840. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  88841. *
  88842. * The basic usage of this decoder is as follows:
  88843. * - The program creates an instance of a decoder using
  88844. * FLAC__stream_decoder_new().
  88845. * - The program overrides the default settings using
  88846. * FLAC__stream_decoder_set_*() functions.
  88847. * - The program initializes the instance to validate the settings and
  88848. * prepare for decoding using
  88849. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  88850. * or FLAC__stream_decoder_init_file() for native FLAC,
  88851. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  88852. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  88853. * - The program calls the FLAC__stream_decoder_process_*() functions
  88854. * to decode data, which subsequently calls the callbacks.
  88855. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  88856. * which flushes the input and output and resets the decoder to the
  88857. * uninitialized state.
  88858. * - The instance may be used again or deleted with
  88859. * FLAC__stream_decoder_delete().
  88860. *
  88861. * In more detail, the program will create a new instance by calling
  88862. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  88863. * functions to override the default decoder options, and call
  88864. * one of the FLAC__stream_decoder_init_*() functions.
  88865. *
  88866. * There are three initialization functions for native FLAC, one for
  88867. * setting up the decoder to decode FLAC data from the client via
  88868. * callbacks, and two for decoding directly from a FLAC file.
  88869. *
  88870. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  88871. * You must also supply several callbacks for handling I/O. Some (like
  88872. * seeking) are optional, depending on the capabilities of the input.
  88873. *
  88874. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  88875. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  88876. * \c FILE* or filename and fewer callbacks; the decoder will handle
  88877. * the other callbacks internally.
  88878. *
  88879. * There are three similarly-named init functions for decoding from Ogg
  88880. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88881. * library has been built with Ogg support.
  88882. *
  88883. * Once the decoder is initialized, your program will call one of several
  88884. * functions to start the decoding process:
  88885. *
  88886. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  88887. * most one metadata block or audio frame and return, calling either the
  88888. * metadata callback or write callback, respectively, once. If the decoder
  88889. * loses sync it will return with only the error callback being called.
  88890. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  88891. * to process the stream from the current location and stop upon reaching
  88892. * the first audio frame. The client will get one metadata, write, or error
  88893. * callback per metadata block, audio frame, or sync error, respectively.
  88894. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  88895. * to process the stream from the current location until the read callback
  88896. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  88897. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  88898. * write, or error callback per metadata block, audio frame, or sync error,
  88899. * respectively.
  88900. *
  88901. * When the decoder has finished decoding (normally or through an abort),
  88902. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  88903. * ensures the decoder is in the correct state and frees memory. Then the
  88904. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  88905. * again to decode another stream.
  88906. *
  88907. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  88908. * At any point after the stream decoder has been initialized, the client can
  88909. * call this function to seek to an exact sample within the stream.
  88910. * Subsequently, the first time the write callback is called it will be
  88911. * passed a (possibly partial) block starting at that sample.
  88912. *
  88913. * If the client cannot seek via the callback interface provided, but still
  88914. * has another way of seeking, it can flush the decoder using
  88915. * FLAC__stream_decoder_flush() and start feeding data from the new position
  88916. * through the read callback.
  88917. *
  88918. * The stream decoder also provides MD5 signature checking. If this is
  88919. * turned on before initialization, FLAC__stream_decoder_finish() will
  88920. * report when the decoded MD5 signature does not match the one stored
  88921. * in the STREAMINFO block. MD5 checking is automatically turned off
  88922. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  88923. * in the STREAMINFO block or when a seek is attempted.
  88924. *
  88925. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  88926. * attention. By default, the decoder only calls the metadata_callback for
  88927. * the STREAMINFO block. These functions allow you to tell the decoder
  88928. * explicitly which blocks to parse and return via the metadata_callback
  88929. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  88930. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  88931. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  88932. * which blocks to return. Remember that metadata blocks can potentially
  88933. * be big (for example, cover art) so filtering out the ones you don't
  88934. * use can reduce the memory requirements of the decoder. Also note the
  88935. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  88936. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  88937. * filtering APPLICATION blocks based on the application ID.
  88938. *
  88939. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  88940. * they still can legally be filtered from the metadata_callback.
  88941. *
  88942. * \note
  88943. * The "set" functions may only be called when the decoder is in the
  88944. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  88945. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  88946. * before FLAC__stream_decoder_init_*(). If this is the case they will
  88947. * return \c true, otherwise \c false.
  88948. *
  88949. * \note
  88950. * FLAC__stream_decoder_finish() resets all settings to the constructor
  88951. * defaults, including the callbacks.
  88952. *
  88953. * \{
  88954. */
  88955. /** State values for a FLAC__StreamDecoder
  88956. *
  88957. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  88958. */
  88959. typedef enum {
  88960. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  88961. /**< The decoder is ready to search for metadata. */
  88962. FLAC__STREAM_DECODER_READ_METADATA,
  88963. /**< The decoder is ready to or is in the process of reading metadata. */
  88964. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  88965. /**< The decoder is ready to or is in the process of searching for the
  88966. * frame sync code.
  88967. */
  88968. FLAC__STREAM_DECODER_READ_FRAME,
  88969. /**< The decoder is ready to or is in the process of reading a frame. */
  88970. FLAC__STREAM_DECODER_END_OF_STREAM,
  88971. /**< The decoder has reached the end of the stream. */
  88972. FLAC__STREAM_DECODER_OGG_ERROR,
  88973. /**< An error occurred in the underlying Ogg layer. */
  88974. FLAC__STREAM_DECODER_SEEK_ERROR,
  88975. /**< An error occurred while seeking. The decoder must be flushed
  88976. * with FLAC__stream_decoder_flush() or reset with
  88977. * FLAC__stream_decoder_reset() before decoding can continue.
  88978. */
  88979. FLAC__STREAM_DECODER_ABORTED,
  88980. /**< The decoder was aborted by the read callback. */
  88981. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  88982. /**< An error occurred allocating memory. The decoder is in an invalid
  88983. * state and can no longer be used.
  88984. */
  88985. FLAC__STREAM_DECODER_UNINITIALIZED
  88986. /**< The decoder is in the uninitialized state; one of the
  88987. * FLAC__stream_decoder_init_*() functions must be called before samples
  88988. * can be processed.
  88989. */
  88990. } FLAC__StreamDecoderState;
  88991. /** Maps a FLAC__StreamDecoderState to a C string.
  88992. *
  88993. * Using a FLAC__StreamDecoderState as the index to this array
  88994. * will give the string equivalent. The contents should not be modified.
  88995. */
  88996. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  88997. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  88998. */
  88999. typedef enum {
  89000. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89001. /**< Initialization was successful. */
  89002. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89003. /**< The library was not compiled with support for the given container
  89004. * format.
  89005. */
  89006. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89007. /**< A required callback was not supplied. */
  89008. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89009. /**< An error occurred allocating memory. */
  89010. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89011. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89012. * FLAC__stream_decoder_init_ogg_file(). */
  89013. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89014. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89015. * already initialized, usually because
  89016. * FLAC__stream_decoder_finish() was not called.
  89017. */
  89018. } FLAC__StreamDecoderInitStatus;
  89019. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89020. *
  89021. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89022. * will give the string equivalent. The contents should not be modified.
  89023. */
  89024. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89025. /** Return values for the FLAC__StreamDecoder read callback.
  89026. */
  89027. typedef enum {
  89028. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89029. /**< The read was OK and decoding can continue. */
  89030. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89031. /**< The read was attempted while at the end of the stream. Note that
  89032. * the client must only return this value when the read callback was
  89033. * called when already at the end of the stream. Otherwise, if the read
  89034. * itself moves to the end of the stream, the client should still return
  89035. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89036. * the next read callback it should return
  89037. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89038. * of \c 0.
  89039. */
  89040. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89041. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89042. } FLAC__StreamDecoderReadStatus;
  89043. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89044. *
  89045. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89046. * will give the string equivalent. The contents should not be modified.
  89047. */
  89048. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89049. /** Return values for the FLAC__StreamDecoder seek callback.
  89050. */
  89051. typedef enum {
  89052. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89053. /**< The seek was OK and decoding can continue. */
  89054. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89055. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89056. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89057. /**< Client does not support seeking. */
  89058. } FLAC__StreamDecoderSeekStatus;
  89059. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89060. *
  89061. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89062. * will give the string equivalent. The contents should not be modified.
  89063. */
  89064. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89065. /** Return values for the FLAC__StreamDecoder tell callback.
  89066. */
  89067. typedef enum {
  89068. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89069. /**< The tell was OK and decoding can continue. */
  89070. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89071. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89072. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89073. /**< Client does not support telling the position. */
  89074. } FLAC__StreamDecoderTellStatus;
  89075. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89076. *
  89077. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89078. * will give the string equivalent. The contents should not be modified.
  89079. */
  89080. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89081. /** Return values for the FLAC__StreamDecoder length callback.
  89082. */
  89083. typedef enum {
  89084. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89085. /**< The length call was OK and decoding can continue. */
  89086. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89087. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89088. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89089. /**< Client does not support reporting the length. */
  89090. } FLAC__StreamDecoderLengthStatus;
  89091. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89092. *
  89093. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89094. * will give the string equivalent. The contents should not be modified.
  89095. */
  89096. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89097. /** Return values for the FLAC__StreamDecoder write callback.
  89098. */
  89099. typedef enum {
  89100. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89101. /**< The write was OK and decoding can continue. */
  89102. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89103. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89104. } FLAC__StreamDecoderWriteStatus;
  89105. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89106. *
  89107. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89108. * will give the string equivalent. The contents should not be modified.
  89109. */
  89110. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89111. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89112. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89113. * all. The rest could be caused by bad sync (false synchronization on
  89114. * data that is not the start of a frame) or corrupted data. The error
  89115. * itself is the decoder's best guess at what happened assuming a correct
  89116. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89117. * could be caused by a correct sync on the start of a frame, but some
  89118. * data in the frame header was corrupted. Or it could be the result of
  89119. * syncing on a point the stream that looked like the starting of a frame
  89120. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89121. * could be because the decoder encountered a valid frame made by a future
  89122. * version of the encoder which it cannot parse, or because of a false
  89123. * sync making it appear as though an encountered frame was generated by
  89124. * a future encoder.
  89125. */
  89126. typedef enum {
  89127. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89128. /**< An error in the stream caused the decoder to lose synchronization. */
  89129. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89130. /**< The decoder encountered a corrupted frame header. */
  89131. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89132. /**< The frame's data did not match the CRC in the footer. */
  89133. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89134. /**< The decoder encountered reserved fields in use in the stream. */
  89135. } FLAC__StreamDecoderErrorStatus;
  89136. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89137. *
  89138. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89139. * will give the string equivalent. The contents should not be modified.
  89140. */
  89141. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89142. /***********************************************************************
  89143. *
  89144. * class FLAC__StreamDecoder
  89145. *
  89146. ***********************************************************************/
  89147. struct FLAC__StreamDecoderProtected;
  89148. struct FLAC__StreamDecoderPrivate;
  89149. /** The opaque structure definition for the stream decoder type.
  89150. * See the \link flac_stream_decoder stream decoder module \endlink
  89151. * for a detailed description.
  89152. */
  89153. typedef struct {
  89154. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89155. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89156. } FLAC__StreamDecoder;
  89157. /** Signature for the read callback.
  89158. *
  89159. * A function pointer matching this signature must be passed to
  89160. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89161. * called when the decoder needs more input data. The address of the
  89162. * buffer to be filled is supplied, along with the number of bytes the
  89163. * buffer can hold. The callback may choose to supply less data and
  89164. * modify the byte count but must be careful not to overflow the buffer.
  89165. * The callback then returns a status code chosen from
  89166. * FLAC__StreamDecoderReadStatus.
  89167. *
  89168. * Here is an example of a read callback for stdio streams:
  89169. * \code
  89170. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89171. * {
  89172. * FILE *file = ((MyClientData*)client_data)->file;
  89173. * if(*bytes > 0) {
  89174. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89175. * if(ferror(file))
  89176. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89177. * else if(*bytes == 0)
  89178. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89179. * else
  89180. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89181. * }
  89182. * else
  89183. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89184. * }
  89185. * \endcode
  89186. *
  89187. * \note In general, FLAC__StreamDecoder functions which change the
  89188. * state should not be called on the \a decoder while in the callback.
  89189. *
  89190. * \param decoder The decoder instance calling the callback.
  89191. * \param buffer A pointer to a location for the callee to store
  89192. * data to be decoded.
  89193. * \param bytes A pointer to the size of the buffer. On entry
  89194. * to the callback, it contains the maximum number
  89195. * of bytes that may be stored in \a buffer. The
  89196. * callee must set it to the actual number of bytes
  89197. * stored (0 in case of error or end-of-stream) before
  89198. * returning.
  89199. * \param client_data The callee's client data set through
  89200. * FLAC__stream_decoder_init_*().
  89201. * \retval FLAC__StreamDecoderReadStatus
  89202. * The callee's return status. Note that the callback should return
  89203. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89204. * zero bytes were read and there is no more data to be read.
  89205. */
  89206. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89207. /** Signature for the seek callback.
  89208. *
  89209. * A function pointer matching this signature may be passed to
  89210. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89211. * called when the decoder needs to seek the input stream. The decoder
  89212. * will pass the absolute byte offset to seek to, 0 meaning the
  89213. * beginning of the stream.
  89214. *
  89215. * Here is an example of a seek callback for stdio streams:
  89216. * \code
  89217. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89218. * {
  89219. * FILE *file = ((MyClientData*)client_data)->file;
  89220. * if(file == stdin)
  89221. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89222. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89223. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89224. * else
  89225. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89226. * }
  89227. * \endcode
  89228. *
  89229. * \note In general, FLAC__StreamDecoder functions which change the
  89230. * state should not be called on the \a decoder while in the callback.
  89231. *
  89232. * \param decoder The decoder instance calling the callback.
  89233. * \param absolute_byte_offset The offset from the beginning of the stream
  89234. * to seek to.
  89235. * \param client_data The callee's client data set through
  89236. * FLAC__stream_decoder_init_*().
  89237. * \retval FLAC__StreamDecoderSeekStatus
  89238. * The callee's return status.
  89239. */
  89240. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89241. /** Signature for the tell callback.
  89242. *
  89243. * A function pointer matching this signature may be passed to
  89244. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89245. * called when the decoder wants to know the current position of the
  89246. * stream. The callback should return the byte offset from the
  89247. * beginning of the stream.
  89248. *
  89249. * Here is an example of a tell callback for stdio streams:
  89250. * \code
  89251. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89252. * {
  89253. * FILE *file = ((MyClientData*)client_data)->file;
  89254. * off_t pos;
  89255. * if(file == stdin)
  89256. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89257. * else if((pos = ftello(file)) < 0)
  89258. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89259. * else {
  89260. * *absolute_byte_offset = (FLAC__uint64)pos;
  89261. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89262. * }
  89263. * }
  89264. * \endcode
  89265. *
  89266. * \note In general, FLAC__StreamDecoder functions which change the
  89267. * state should not be called on the \a decoder while in the callback.
  89268. *
  89269. * \param decoder The decoder instance calling the callback.
  89270. * \param absolute_byte_offset A pointer to storage for the current offset
  89271. * from the beginning of the stream.
  89272. * \param client_data The callee's client data set through
  89273. * FLAC__stream_decoder_init_*().
  89274. * \retval FLAC__StreamDecoderTellStatus
  89275. * The callee's return status.
  89276. */
  89277. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89278. /** Signature for the length callback.
  89279. *
  89280. * A function pointer matching this signature may be passed to
  89281. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89282. * called when the decoder wants to know the total length of the stream
  89283. * in bytes.
  89284. *
  89285. * Here is an example of a length callback for stdio streams:
  89286. * \code
  89287. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89288. * {
  89289. * FILE *file = ((MyClientData*)client_data)->file;
  89290. * struct stat filestats;
  89291. *
  89292. * if(file == stdin)
  89293. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89294. * else if(fstat(fileno(file), &filestats) != 0)
  89295. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89296. * else {
  89297. * *stream_length = (FLAC__uint64)filestats.st_size;
  89298. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89299. * }
  89300. * }
  89301. * \endcode
  89302. *
  89303. * \note In general, FLAC__StreamDecoder functions which change the
  89304. * state should not be called on the \a decoder while in the callback.
  89305. *
  89306. * \param decoder The decoder instance calling the callback.
  89307. * \param stream_length A pointer to storage for the length of the stream
  89308. * in bytes.
  89309. * \param client_data The callee's client data set through
  89310. * FLAC__stream_decoder_init_*().
  89311. * \retval FLAC__StreamDecoderLengthStatus
  89312. * The callee's return status.
  89313. */
  89314. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89315. /** Signature for the EOF callback.
  89316. *
  89317. * A function pointer matching this signature may be passed to
  89318. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89319. * called when the decoder needs to know if the end of the stream has
  89320. * been reached.
  89321. *
  89322. * Here is an example of a EOF callback for stdio streams:
  89323. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89324. * \code
  89325. * {
  89326. * FILE *file = ((MyClientData*)client_data)->file;
  89327. * return feof(file)? true : false;
  89328. * }
  89329. * \endcode
  89330. *
  89331. * \note In general, FLAC__StreamDecoder functions which change the
  89332. * state should not be called on the \a decoder while in the callback.
  89333. *
  89334. * \param decoder The decoder instance calling the callback.
  89335. * \param client_data The callee's client data set through
  89336. * FLAC__stream_decoder_init_*().
  89337. * \retval FLAC__bool
  89338. * \c true if the currently at the end of the stream, else \c false.
  89339. */
  89340. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89341. /** Signature for the write callback.
  89342. *
  89343. * A function pointer matching this signature must be passed to one of
  89344. * the FLAC__stream_decoder_init_*() functions.
  89345. * The supplied function will be called when the decoder has decoded a
  89346. * single audio frame. The decoder will pass the frame metadata as well
  89347. * as an array of pointers (one for each channel) pointing to the
  89348. * decoded audio.
  89349. *
  89350. * \note In general, FLAC__StreamDecoder functions which change the
  89351. * state should not be called on the \a decoder while in the callback.
  89352. *
  89353. * \param decoder The decoder instance calling the callback.
  89354. * \param frame The description of the decoded frame. See
  89355. * FLAC__Frame.
  89356. * \param buffer An array of pointers to decoded channels of data.
  89357. * Each pointer will point to an array of signed
  89358. * samples of length \a frame->header.blocksize.
  89359. * Channels will be ordered according to the FLAC
  89360. * specification; see the documentation for the
  89361. * <A HREF="../format.html#frame_header">frame header</A>.
  89362. * \param client_data The callee's client data set through
  89363. * FLAC__stream_decoder_init_*().
  89364. * \retval FLAC__StreamDecoderWriteStatus
  89365. * The callee's return status.
  89366. */
  89367. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89368. /** Signature for the metadata callback.
  89369. *
  89370. * A function pointer matching this signature must be passed to one of
  89371. * the FLAC__stream_decoder_init_*() functions.
  89372. * The supplied function will be called when the decoder has decoded a
  89373. * metadata block. In a valid FLAC file there will always be one
  89374. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89375. * These will be supplied by the decoder in the same order as they
  89376. * appear in the stream and always before the first audio frame (i.e.
  89377. * write callback). The metadata block that is passed in must not be
  89378. * modified, and it doesn't live beyond the callback, so you should make
  89379. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89380. * elsewhere. Since metadata blocks can potentially be large, by
  89381. * default the decoder only calls the metadata callback for the
  89382. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89383. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89384. *
  89385. * \note In general, FLAC__StreamDecoder functions which change the
  89386. * state should not be called on the \a decoder while in the callback.
  89387. *
  89388. * \param decoder The decoder instance calling the callback.
  89389. * \param metadata The decoded metadata block.
  89390. * \param client_data The callee's client data set through
  89391. * FLAC__stream_decoder_init_*().
  89392. */
  89393. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89394. /** Signature for the error callback.
  89395. *
  89396. * A function pointer matching this signature must be passed to one of
  89397. * the FLAC__stream_decoder_init_*() functions.
  89398. * The supplied function will be called whenever an error occurs during
  89399. * decoding.
  89400. *
  89401. * \note In general, FLAC__StreamDecoder functions which change the
  89402. * state should not be called on the \a decoder while in the callback.
  89403. *
  89404. * \param decoder The decoder instance calling the callback.
  89405. * \param status The error encountered by the decoder.
  89406. * \param client_data The callee's client data set through
  89407. * FLAC__stream_decoder_init_*().
  89408. */
  89409. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89410. /***********************************************************************
  89411. *
  89412. * Class constructor/destructor
  89413. *
  89414. ***********************************************************************/
  89415. /** Create a new stream decoder instance. The instance is created with
  89416. * default settings; see the individual FLAC__stream_decoder_set_*()
  89417. * functions for each setting's default.
  89418. *
  89419. * \retval FLAC__StreamDecoder*
  89420. * \c NULL if there was an error allocating memory, else the new instance.
  89421. */
  89422. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89423. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89424. *
  89425. * \param decoder A pointer to an existing decoder.
  89426. * \assert
  89427. * \code decoder != NULL \endcode
  89428. */
  89429. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89430. /***********************************************************************
  89431. *
  89432. * Public class method prototypes
  89433. *
  89434. ***********************************************************************/
  89435. /** Set the serial number for the FLAC stream within the Ogg container.
  89436. * The default behavior is to use the serial number of the first Ogg
  89437. * page. Setting a serial number here will explicitly specify which
  89438. * stream is to be decoded.
  89439. *
  89440. * \note
  89441. * This does not need to be set for native FLAC decoding.
  89442. *
  89443. * \default \c use serial number of first page
  89444. * \param decoder A decoder instance to set.
  89445. * \param serial_number See above.
  89446. * \assert
  89447. * \code decoder != NULL \endcode
  89448. * \retval FLAC__bool
  89449. * \c false if the decoder is already initialized, else \c true.
  89450. */
  89451. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89452. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89453. * compute the MD5 signature of the unencoded audio data while decoding
  89454. * and compare it to the signature from the STREAMINFO block, if it
  89455. * exists, during FLAC__stream_decoder_finish().
  89456. *
  89457. * MD5 signature checking will be turned off (until the next
  89458. * FLAC__stream_decoder_reset()) if there is no signature in the
  89459. * STREAMINFO block or when a seek is attempted.
  89460. *
  89461. * Clients that do not use the MD5 check should leave this off to speed
  89462. * up decoding.
  89463. *
  89464. * \default \c false
  89465. * \param decoder A decoder instance to set.
  89466. * \param value Flag value (see above).
  89467. * \assert
  89468. * \code decoder != NULL \endcode
  89469. * \retval FLAC__bool
  89470. * \c false if the decoder is already initialized, else \c true.
  89471. */
  89472. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89473. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89474. *
  89475. * \default By default, only the \c STREAMINFO block is returned via the
  89476. * metadata callback.
  89477. * \param decoder A decoder instance to set.
  89478. * \param type See above.
  89479. * \assert
  89480. * \code decoder != NULL \endcode
  89481. * \a type is valid
  89482. * \retval FLAC__bool
  89483. * \c false if the decoder is already initialized, else \c true.
  89484. */
  89485. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89486. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89487. * given \a id.
  89488. *
  89489. * \default By default, only the \c STREAMINFO block is returned via the
  89490. * metadata callback.
  89491. * \param decoder A decoder instance to set.
  89492. * \param id See above.
  89493. * \assert
  89494. * \code decoder != NULL \endcode
  89495. * \code id != NULL \endcode
  89496. * \retval FLAC__bool
  89497. * \c false if the decoder is already initialized, else \c true.
  89498. */
  89499. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89500. /** Direct the decoder to pass on all metadata blocks of any type.
  89501. *
  89502. * \default By default, only the \c STREAMINFO block is returned via the
  89503. * metadata callback.
  89504. * \param decoder A decoder instance to set.
  89505. * \assert
  89506. * \code decoder != NULL \endcode
  89507. * \retval FLAC__bool
  89508. * \c false if the decoder is already initialized, else \c true.
  89509. */
  89510. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89511. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89512. *
  89513. * \default By default, only the \c STREAMINFO block is returned via the
  89514. * metadata callback.
  89515. * \param decoder A decoder instance to set.
  89516. * \param type See above.
  89517. * \assert
  89518. * \code decoder != NULL \endcode
  89519. * \a type is valid
  89520. * \retval FLAC__bool
  89521. * \c false if the decoder is already initialized, else \c true.
  89522. */
  89523. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89524. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89525. * the given \a id.
  89526. *
  89527. * \default By default, only the \c STREAMINFO block is returned via the
  89528. * metadata callback.
  89529. * \param decoder A decoder instance to set.
  89530. * \param id See above.
  89531. * \assert
  89532. * \code decoder != NULL \endcode
  89533. * \code id != NULL \endcode
  89534. * \retval FLAC__bool
  89535. * \c false if the decoder is already initialized, else \c true.
  89536. */
  89537. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89538. /** Direct the decoder to filter out all metadata blocks of any type.
  89539. *
  89540. * \default By default, only the \c STREAMINFO block is returned via the
  89541. * metadata callback.
  89542. * \param decoder A decoder instance to set.
  89543. * \assert
  89544. * \code decoder != NULL \endcode
  89545. * \retval FLAC__bool
  89546. * \c false if the decoder is already initialized, else \c true.
  89547. */
  89548. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89549. /** Get the current decoder state.
  89550. *
  89551. * \param decoder A decoder instance to query.
  89552. * \assert
  89553. * \code decoder != NULL \endcode
  89554. * \retval FLAC__StreamDecoderState
  89555. * The current decoder state.
  89556. */
  89557. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89558. /** Get the current decoder state as a C string.
  89559. *
  89560. * \param decoder A decoder instance to query.
  89561. * \assert
  89562. * \code decoder != NULL \endcode
  89563. * \retval const char *
  89564. * The decoder state as a C string. Do not modify the contents.
  89565. */
  89566. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89567. /** Get the "MD5 signature checking" flag.
  89568. * This is the value of the setting, not whether or not the decoder is
  89569. * currently checking the MD5 (remember, it can be turned off automatically
  89570. * by a seek). When the decoder is reset the flag will be restored to the
  89571. * value returned by this function.
  89572. *
  89573. * \param decoder A decoder instance to query.
  89574. * \assert
  89575. * \code decoder != NULL \endcode
  89576. * \retval FLAC__bool
  89577. * See above.
  89578. */
  89579. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89580. /** Get the total number of samples in the stream being decoded.
  89581. * Will only be valid after decoding has started and will contain the
  89582. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89583. *
  89584. * \param decoder A decoder instance to query.
  89585. * \assert
  89586. * \code decoder != NULL \endcode
  89587. * \retval unsigned
  89588. * See above.
  89589. */
  89590. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89591. /** Get the current number of channels in the stream being decoded.
  89592. * Will only be valid after decoding has started and will contain the
  89593. * value from the most recently decoded frame header.
  89594. *
  89595. * \param decoder A decoder instance to query.
  89596. * \assert
  89597. * \code decoder != NULL \endcode
  89598. * \retval unsigned
  89599. * See above.
  89600. */
  89601. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89602. /** Get the current channel assignment in the stream being decoded.
  89603. * Will only be valid after decoding has started and will contain the
  89604. * value from the most recently decoded frame header.
  89605. *
  89606. * \param decoder A decoder instance to query.
  89607. * \assert
  89608. * \code decoder != NULL \endcode
  89609. * \retval FLAC__ChannelAssignment
  89610. * See above.
  89611. */
  89612. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89613. /** Get the current sample resolution in the stream being decoded.
  89614. * Will only be valid after decoding has started and will contain the
  89615. * value from the most recently decoded frame header.
  89616. *
  89617. * \param decoder A decoder instance to query.
  89618. * \assert
  89619. * \code decoder != NULL \endcode
  89620. * \retval unsigned
  89621. * See above.
  89622. */
  89623. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89624. /** Get the current sample rate in Hz of the stream being decoded.
  89625. * Will only be valid after decoding has started and will contain the
  89626. * value from the most recently decoded frame header.
  89627. *
  89628. * \param decoder A decoder instance to query.
  89629. * \assert
  89630. * \code decoder != NULL \endcode
  89631. * \retval unsigned
  89632. * See above.
  89633. */
  89634. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89635. /** Get the current blocksize of the stream being decoded.
  89636. * Will only be valid after decoding has started and will contain the
  89637. * value from the most recently decoded frame header.
  89638. *
  89639. * \param decoder A decoder instance to query.
  89640. * \assert
  89641. * \code decoder != NULL \endcode
  89642. * \retval unsigned
  89643. * See above.
  89644. */
  89645. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89646. /** Returns the decoder's current read position within the stream.
  89647. * The position is the byte offset from the start of the stream.
  89648. * Bytes before this position have been fully decoded. Note that
  89649. * there may still be undecoded bytes in the decoder's read FIFO.
  89650. * The returned position is correct even after a seek.
  89651. *
  89652. * \warning This function currently only works for native FLAC,
  89653. * not Ogg FLAC streams.
  89654. *
  89655. * \param decoder A decoder instance to query.
  89656. * \param position Address at which to return the desired position.
  89657. * \assert
  89658. * \code decoder != NULL \endcode
  89659. * \code position != NULL \endcode
  89660. * \retval FLAC__bool
  89661. * \c true if successful, \c false if the stream is not native FLAC,
  89662. * or there was an error from the 'tell' callback or it returned
  89663. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89664. */
  89665. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89666. /** Initialize the decoder instance to decode native FLAC streams.
  89667. *
  89668. * This flavor of initialization sets up the decoder to decode from a
  89669. * native FLAC stream. I/O is performed via callbacks to the client.
  89670. * For decoding from a plain file via filename or open FILE*,
  89671. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89672. * provide a simpler interface.
  89673. *
  89674. * This function should be called after FLAC__stream_decoder_new() and
  89675. * FLAC__stream_decoder_set_*() but before any of the
  89676. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89677. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89678. * if initialization succeeded.
  89679. *
  89680. * \param decoder An uninitialized decoder instance.
  89681. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89682. * pointer must not be \c NULL.
  89683. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89684. * pointer may be \c NULL if seeking is not
  89685. * supported. If \a seek_callback is not \c NULL then a
  89686. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89687. * Alternatively, a dummy seek callback that just
  89688. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89689. * may also be supplied, all though this is slightly
  89690. * less efficient for the decoder.
  89691. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89692. * pointer may be \c NULL if not supported by the client. If
  89693. * \a seek_callback is not \c NULL then a
  89694. * \a tell_callback must also be supplied.
  89695. * Alternatively, a dummy tell callback that just
  89696. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89697. * may also be supplied, all though this is slightly
  89698. * less efficient for the decoder.
  89699. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89700. * pointer may be \c NULL if not supported by the client. If
  89701. * \a seek_callback is not \c NULL then a
  89702. * \a length_callback must also be supplied.
  89703. * Alternatively, a dummy length callback that just
  89704. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89705. * may also be supplied, all though this is slightly
  89706. * less efficient for the decoder.
  89707. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89708. * pointer may be \c NULL if not supported by the client. If
  89709. * \a seek_callback is not \c NULL then a
  89710. * \a eof_callback must also be supplied.
  89711. * Alternatively, a dummy length callback that just
  89712. * returns \c false
  89713. * may also be supplied, all though this is slightly
  89714. * less efficient for the decoder.
  89715. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89716. * pointer must not be \c NULL.
  89717. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89718. * pointer may be \c NULL if the callback is not
  89719. * desired.
  89720. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89721. * pointer must not be \c NULL.
  89722. * \param client_data This value will be supplied to callbacks in their
  89723. * \a client_data argument.
  89724. * \assert
  89725. * \code decoder != NULL \endcode
  89726. * \retval FLAC__StreamDecoderInitStatus
  89727. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89728. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89729. */
  89730. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89731. FLAC__StreamDecoder *decoder,
  89732. FLAC__StreamDecoderReadCallback read_callback,
  89733. FLAC__StreamDecoderSeekCallback seek_callback,
  89734. FLAC__StreamDecoderTellCallback tell_callback,
  89735. FLAC__StreamDecoderLengthCallback length_callback,
  89736. FLAC__StreamDecoderEofCallback eof_callback,
  89737. FLAC__StreamDecoderWriteCallback write_callback,
  89738. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89739. FLAC__StreamDecoderErrorCallback error_callback,
  89740. void *client_data
  89741. );
  89742. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89743. *
  89744. * This flavor of initialization sets up the decoder to decode from a
  89745. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89746. * client. For decoding from a plain file via filename or open FILE*,
  89747. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89748. * provide a simpler interface.
  89749. *
  89750. * This function should be called after FLAC__stream_decoder_new() and
  89751. * FLAC__stream_decoder_set_*() but before any of the
  89752. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89753. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89754. * if initialization succeeded.
  89755. *
  89756. * \note Support for Ogg FLAC in the library is optional. If this
  89757. * library has been built without support for Ogg FLAC, this function
  89758. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89759. *
  89760. * \param decoder An uninitialized decoder instance.
  89761. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89762. * pointer must not be \c NULL.
  89763. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89764. * pointer may be \c NULL if seeking is not
  89765. * supported. If \a seek_callback is not \c NULL then a
  89766. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89767. * Alternatively, a dummy seek callback that just
  89768. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89769. * may also be supplied, all though this is slightly
  89770. * less efficient for the decoder.
  89771. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89772. * pointer may be \c NULL if not supported by the client. If
  89773. * \a seek_callback is not \c NULL then a
  89774. * \a tell_callback must also be supplied.
  89775. * Alternatively, a dummy tell callback that just
  89776. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89777. * may also be supplied, all though this is slightly
  89778. * less efficient for the decoder.
  89779. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89780. * pointer may be \c NULL if not supported by the client. If
  89781. * \a seek_callback is not \c NULL then a
  89782. * \a length_callback must also be supplied.
  89783. * Alternatively, a dummy length callback that just
  89784. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89785. * may also be supplied, all though this is slightly
  89786. * less efficient for the decoder.
  89787. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89788. * pointer may be \c NULL if not supported by the client. If
  89789. * \a seek_callback is not \c NULL then a
  89790. * \a eof_callback must also be supplied.
  89791. * Alternatively, a dummy length callback that just
  89792. * returns \c false
  89793. * may also be supplied, all though this is slightly
  89794. * less efficient for the decoder.
  89795. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89796. * pointer must not be \c NULL.
  89797. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89798. * pointer may be \c NULL if the callback is not
  89799. * desired.
  89800. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89801. * pointer must not be \c NULL.
  89802. * \param client_data This value will be supplied to callbacks in their
  89803. * \a client_data argument.
  89804. * \assert
  89805. * \code decoder != NULL \endcode
  89806. * \retval FLAC__StreamDecoderInitStatus
  89807. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89808. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89809. */
  89810. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  89811. FLAC__StreamDecoder *decoder,
  89812. FLAC__StreamDecoderReadCallback read_callback,
  89813. FLAC__StreamDecoderSeekCallback seek_callback,
  89814. FLAC__StreamDecoderTellCallback tell_callback,
  89815. FLAC__StreamDecoderLengthCallback length_callback,
  89816. FLAC__StreamDecoderEofCallback eof_callback,
  89817. FLAC__StreamDecoderWriteCallback write_callback,
  89818. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89819. FLAC__StreamDecoderErrorCallback error_callback,
  89820. void *client_data
  89821. );
  89822. /** Initialize the decoder instance to decode native FLAC files.
  89823. *
  89824. * This flavor of initialization sets up the decoder to decode from a
  89825. * plain native FLAC file. For non-stdio streams, you must use
  89826. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  89827. *
  89828. * This function should be called after FLAC__stream_decoder_new() and
  89829. * FLAC__stream_decoder_set_*() but before any of the
  89830. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89831. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89832. * if initialization succeeded.
  89833. *
  89834. * \param decoder An uninitialized decoder instance.
  89835. * \param file An open FLAC file. The file should have been
  89836. * opened with mode \c "rb" and rewound. The file
  89837. * becomes owned by the decoder and should not be
  89838. * manipulated by the client while decoding.
  89839. * Unless \a file is \c stdin, it will be closed
  89840. * when FLAC__stream_decoder_finish() is called.
  89841. * Note however that seeking will not work when
  89842. * decoding from \c stdout since it is not seekable.
  89843. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89844. * pointer must not be \c NULL.
  89845. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89846. * pointer may be \c NULL if the callback is not
  89847. * desired.
  89848. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89849. * pointer must not be \c NULL.
  89850. * \param client_data This value will be supplied to callbacks in their
  89851. * \a client_data argument.
  89852. * \assert
  89853. * \code decoder != NULL \endcode
  89854. * \code file != NULL \endcode
  89855. * \retval FLAC__StreamDecoderInitStatus
  89856. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89857. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89858. */
  89859. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  89860. FLAC__StreamDecoder *decoder,
  89861. FILE *file,
  89862. FLAC__StreamDecoderWriteCallback write_callback,
  89863. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89864. FLAC__StreamDecoderErrorCallback error_callback,
  89865. void *client_data
  89866. );
  89867. /** Initialize the decoder instance to decode Ogg FLAC files.
  89868. *
  89869. * This flavor of initialization sets up the decoder to decode from a
  89870. * plain Ogg FLAC file. For non-stdio streams, you must use
  89871. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  89872. *
  89873. * This function should be called after FLAC__stream_decoder_new() and
  89874. * FLAC__stream_decoder_set_*() but before any of the
  89875. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89876. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89877. * if initialization succeeded.
  89878. *
  89879. * \note Support for Ogg FLAC in the library is optional. If this
  89880. * library has been built without support for Ogg FLAC, this function
  89881. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89882. *
  89883. * \param decoder An uninitialized decoder instance.
  89884. * \param file An open FLAC file. The file should have been
  89885. * opened with mode \c "rb" and rewound. The file
  89886. * becomes owned by the decoder and should not be
  89887. * manipulated by the client while decoding.
  89888. * Unless \a file is \c stdin, it will be closed
  89889. * when FLAC__stream_decoder_finish() is called.
  89890. * Note however that seeking will not work when
  89891. * decoding from \c stdout since it is not seekable.
  89892. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89893. * pointer must not be \c NULL.
  89894. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89895. * pointer may be \c NULL if the callback is not
  89896. * desired.
  89897. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89898. * pointer must not be \c NULL.
  89899. * \param client_data This value will be supplied to callbacks in their
  89900. * \a client_data argument.
  89901. * \assert
  89902. * \code decoder != NULL \endcode
  89903. * \code file != NULL \endcode
  89904. * \retval FLAC__StreamDecoderInitStatus
  89905. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89906. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89907. */
  89908. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  89909. FLAC__StreamDecoder *decoder,
  89910. FILE *file,
  89911. FLAC__StreamDecoderWriteCallback write_callback,
  89912. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89913. FLAC__StreamDecoderErrorCallback error_callback,
  89914. void *client_data
  89915. );
  89916. /** Initialize the decoder instance to decode native FLAC files.
  89917. *
  89918. * This flavor of initialization sets up the decoder to decode from a plain
  89919. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89920. * example, with Unicode filenames on Windows), you must use
  89921. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  89922. * and provide callbacks for the I/O.
  89923. *
  89924. * This function should be called after FLAC__stream_decoder_new() and
  89925. * FLAC__stream_decoder_set_*() but before any of the
  89926. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89927. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89928. * if initialization succeeded.
  89929. *
  89930. * \param decoder An uninitialized decoder instance.
  89931. * \param filename The name of the file to decode from. The file will
  89932. * be opened with fopen(). Use \c NULL to decode from
  89933. * \c stdin. Note that \c stdin is not seekable.
  89934. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89935. * pointer must not be \c NULL.
  89936. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89937. * pointer may be \c NULL if the callback is not
  89938. * desired.
  89939. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89940. * pointer must not be \c NULL.
  89941. * \param client_data This value will be supplied to callbacks in their
  89942. * \a client_data argument.
  89943. * \assert
  89944. * \code decoder != NULL \endcode
  89945. * \retval FLAC__StreamDecoderInitStatus
  89946. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89947. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89948. */
  89949. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  89950. FLAC__StreamDecoder *decoder,
  89951. const char *filename,
  89952. FLAC__StreamDecoderWriteCallback write_callback,
  89953. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89954. FLAC__StreamDecoderErrorCallback error_callback,
  89955. void *client_data
  89956. );
  89957. /** Initialize the decoder instance to decode Ogg FLAC files.
  89958. *
  89959. * This flavor of initialization sets up the decoder to decode from a plain
  89960. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89961. * example, with Unicode filenames on Windows), you must use
  89962. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  89963. * and provide callbacks for the I/O.
  89964. *
  89965. * This function should be called after FLAC__stream_decoder_new() and
  89966. * FLAC__stream_decoder_set_*() but before any of the
  89967. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89968. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89969. * if initialization succeeded.
  89970. *
  89971. * \note Support for Ogg FLAC in the library is optional. If this
  89972. * library has been built without support for Ogg FLAC, this function
  89973. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89974. *
  89975. * \param decoder An uninitialized decoder instance.
  89976. * \param filename The name of the file to decode from. The file will
  89977. * be opened with fopen(). Use \c NULL to decode from
  89978. * \c stdin. Note that \c stdin is not seekable.
  89979. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89980. * pointer must not be \c NULL.
  89981. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89982. * pointer may be \c NULL if the callback is not
  89983. * desired.
  89984. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89985. * pointer must not be \c NULL.
  89986. * \param client_data This value will be supplied to callbacks in their
  89987. * \a client_data argument.
  89988. * \assert
  89989. * \code decoder != NULL \endcode
  89990. * \retval FLAC__StreamDecoderInitStatus
  89991. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89992. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89993. */
  89994. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  89995. FLAC__StreamDecoder *decoder,
  89996. const char *filename,
  89997. FLAC__StreamDecoderWriteCallback write_callback,
  89998. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89999. FLAC__StreamDecoderErrorCallback error_callback,
  90000. void *client_data
  90001. );
  90002. /** Finish the decoding process.
  90003. * Flushes the decoding buffer, releases resources, resets the decoder
  90004. * settings to their defaults, and returns the decoder state to
  90005. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90006. *
  90007. * In the event of a prematurely-terminated decode, it is not strictly
  90008. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90009. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90010. * with a FLAC__stream_decoder_finish().
  90011. *
  90012. * \param decoder An uninitialized decoder instance.
  90013. * \assert
  90014. * \code decoder != NULL \endcode
  90015. * \retval FLAC__bool
  90016. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90017. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90018. * signature does not match the one computed by the decoder; else
  90019. * \c true.
  90020. */
  90021. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90022. /** Flush the stream input.
  90023. * The decoder's input buffer will be cleared and the state set to
  90024. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90025. * off MD5 checking.
  90026. *
  90027. * \param decoder A decoder instance.
  90028. * \assert
  90029. * \code decoder != NULL \endcode
  90030. * \retval FLAC__bool
  90031. * \c true if successful, else \c false if a memory allocation
  90032. * error occurs (in which case the state will be set to
  90033. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90034. */
  90035. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90036. /** Reset the decoding process.
  90037. * The decoder's input buffer will be cleared and the state set to
  90038. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90039. * FLAC__stream_decoder_finish() except that the settings are
  90040. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90041. * before decoding again. MD5 checking will be restored to its original
  90042. * setting.
  90043. *
  90044. * If the decoder is seekable, or was initialized with
  90045. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90046. * the decoder will also attempt to seek to the beginning of the file.
  90047. * If this rewind fails, this function will return \c false. It follows
  90048. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90049. * \c stdin.
  90050. *
  90051. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90052. * and is not seekable (i.e. no seek callback was provided or the seek
  90053. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90054. * is the duty of the client to start feeding data from the beginning of
  90055. * the stream on the next FLAC__stream_decoder_process() or
  90056. * FLAC__stream_decoder_process_interleaved() call.
  90057. *
  90058. * \param decoder A decoder instance.
  90059. * \assert
  90060. * \code decoder != NULL \endcode
  90061. * \retval FLAC__bool
  90062. * \c true if successful, else \c false if a memory allocation occurs
  90063. * (in which case the state will be set to
  90064. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90065. * occurs (the state will be unchanged).
  90066. */
  90067. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90068. /** Decode one metadata block or audio frame.
  90069. * This version instructs the decoder to decode a either a single metadata
  90070. * block or a single frame and stop, unless the callbacks return a fatal
  90071. * error or the read callback returns
  90072. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90073. *
  90074. * As the decoder needs more input it will call the read callback.
  90075. * Depending on what was decoded, the metadata or write callback will be
  90076. * called with the decoded metadata block or audio frame.
  90077. *
  90078. * Unless there is a fatal read error or end of stream, this function
  90079. * will return once one whole frame is decoded. In other words, if the
  90080. * stream is not synchronized or points to a corrupt frame header, the
  90081. * decoder will continue to try and resync until it gets to a valid
  90082. * frame, then decode one frame, then return. If the decoder points to
  90083. * a frame whose frame CRC in the frame footer does not match the
  90084. * computed frame CRC, this function will issue a
  90085. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90086. * error callback, and return, having decoded one complete, although
  90087. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90088. * correct length to the write callback.)
  90089. *
  90090. * \param decoder An initialized decoder instance.
  90091. * \assert
  90092. * \code decoder != NULL \endcode
  90093. * \retval FLAC__bool
  90094. * \c false if any fatal read, write, or memory allocation error
  90095. * occurred (meaning decoding must stop), else \c true; for more
  90096. * information about the decoder, check the decoder state with
  90097. * FLAC__stream_decoder_get_state().
  90098. */
  90099. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90100. /** Decode until the end of the metadata.
  90101. * This version instructs the decoder to decode from the current position
  90102. * and continue until all the metadata has been read, or until the
  90103. * callbacks return a fatal error or the read callback returns
  90104. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90105. *
  90106. * As the decoder needs more input it will call the read callback.
  90107. * As each metadata block is decoded, the metadata callback will be called
  90108. * with the decoded metadata.
  90109. *
  90110. * \param decoder An initialized decoder instance.
  90111. * \assert
  90112. * \code decoder != NULL \endcode
  90113. * \retval FLAC__bool
  90114. * \c false if any fatal read, write, or memory allocation error
  90115. * occurred (meaning decoding must stop), else \c true; for more
  90116. * information about the decoder, check the decoder state with
  90117. * FLAC__stream_decoder_get_state().
  90118. */
  90119. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90120. /** Decode until the end of the stream.
  90121. * This version instructs the decoder to decode from the current position
  90122. * and continue until the end of stream (the read callback returns
  90123. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90124. * callbacks return a fatal error.
  90125. *
  90126. * As the decoder needs more input it will call the read callback.
  90127. * As each metadata block and frame is decoded, the metadata or write
  90128. * callback will be called with the decoded metadata or frame.
  90129. *
  90130. * \param decoder An initialized decoder instance.
  90131. * \assert
  90132. * \code decoder != NULL \endcode
  90133. * \retval FLAC__bool
  90134. * \c false if any fatal read, write, or memory allocation error
  90135. * occurred (meaning decoding must stop), else \c true; for more
  90136. * information about the decoder, check the decoder state with
  90137. * FLAC__stream_decoder_get_state().
  90138. */
  90139. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90140. /** Skip one audio frame.
  90141. * This version instructs the decoder to 'skip' a single frame and stop,
  90142. * unless the callbacks return a fatal error or the read callback returns
  90143. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90144. *
  90145. * The decoding flow is the same as what occurs when
  90146. * FLAC__stream_decoder_process_single() is called to process an audio
  90147. * frame, except that this function does not decode the parsed data into
  90148. * PCM or call the write callback. The integrity of the frame is still
  90149. * checked the same way as in the other process functions.
  90150. *
  90151. * This function will return once one whole frame is skipped, in the
  90152. * same way that FLAC__stream_decoder_process_single() will return once
  90153. * one whole frame is decoded.
  90154. *
  90155. * This function can be used in more quickly determining FLAC frame
  90156. * boundaries when decoding of the actual data is not needed, for
  90157. * example when an application is separating a FLAC stream into frames
  90158. * for editing or storing in a container. To do this, the application
  90159. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90160. * to the next frame, then use
  90161. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90162. * boundary.
  90163. *
  90164. * This function should only be called when the stream has advanced
  90165. * past all the metadata, otherwise it will return \c false.
  90166. *
  90167. * \param decoder An initialized decoder instance not in a metadata
  90168. * state.
  90169. * \assert
  90170. * \code decoder != NULL \endcode
  90171. * \retval FLAC__bool
  90172. * \c false if any fatal read, write, or memory allocation error
  90173. * occurred (meaning decoding must stop), or if the decoder
  90174. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90175. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90176. * information about the decoder, check the decoder state with
  90177. * FLAC__stream_decoder_get_state().
  90178. */
  90179. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90180. /** Flush the input and seek to an absolute sample.
  90181. * Decoding will resume at the given sample. Note that because of
  90182. * this, the next write callback may contain a partial block. The
  90183. * client must support seeking the input or this function will fail
  90184. * and return \c false. Furthermore, if the decoder state is
  90185. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90186. * with FLAC__stream_decoder_flush() or reset with
  90187. * FLAC__stream_decoder_reset() before decoding can continue.
  90188. *
  90189. * \param decoder A decoder instance.
  90190. * \param sample The target sample number to seek to.
  90191. * \assert
  90192. * \code decoder != NULL \endcode
  90193. * \retval FLAC__bool
  90194. * \c true if successful, else \c false.
  90195. */
  90196. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90197. /* \} */
  90198. #ifdef __cplusplus
  90199. }
  90200. #endif
  90201. #endif
  90202. /*** End of inlined file: stream_decoder.h ***/
  90203. /*** Start of inlined file: stream_encoder.h ***/
  90204. #ifndef FLAC__STREAM_ENCODER_H
  90205. #define FLAC__STREAM_ENCODER_H
  90206. #include <stdio.h> /* for FILE */
  90207. #ifdef __cplusplus
  90208. extern "C" {
  90209. #endif
  90210. /** \file include/FLAC/stream_encoder.h
  90211. *
  90212. * \brief
  90213. * This module contains the functions which implement the stream
  90214. * encoder.
  90215. *
  90216. * See the detailed documentation in the
  90217. * \link flac_stream_encoder stream encoder \endlink module.
  90218. */
  90219. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90220. * \ingroup flac
  90221. *
  90222. * \brief
  90223. * This module describes the encoder layers provided by libFLAC.
  90224. *
  90225. * The stream encoder can be used to encode complete streams either to the
  90226. * client via callbacks, or directly to a file, depending on how it is
  90227. * initialized. When encoding via callbacks, the client provides a write
  90228. * callback which will be called whenever FLAC data is ready to be written.
  90229. * If the client also supplies a seek callback, the encoder will also
  90230. * automatically handle the writing back of metadata discovered while
  90231. * encoding, like stream info, seek points offsets, etc. When encoding to
  90232. * a file, the client needs only supply a filename or open \c FILE* and an
  90233. * optional progress callback for periodic notification of progress; the
  90234. * write and seek callbacks are supplied internally. For more info see the
  90235. * \link flac_stream_encoder stream encoder \endlink module.
  90236. */
  90237. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90238. * \ingroup flac_encoder
  90239. *
  90240. * \brief
  90241. * This module contains the functions which implement the stream
  90242. * encoder.
  90243. *
  90244. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90245. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90246. *
  90247. * The basic usage of this encoder is as follows:
  90248. * - The program creates an instance of an encoder using
  90249. * FLAC__stream_encoder_new().
  90250. * - The program overrides the default settings using
  90251. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90252. * functions should be called:
  90253. * - FLAC__stream_encoder_set_channels()
  90254. * - FLAC__stream_encoder_set_bits_per_sample()
  90255. * - FLAC__stream_encoder_set_sample_rate()
  90256. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90257. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90258. * - If the application wants to control the compression level or set its own
  90259. * metadata, then the following should also be called:
  90260. * - FLAC__stream_encoder_set_compression_level()
  90261. * - FLAC__stream_encoder_set_verify()
  90262. * - FLAC__stream_encoder_set_metadata()
  90263. * - The rest of the set functions should only be called if the client needs
  90264. * exact control over how the audio is compressed; thorough understanding
  90265. * of the FLAC format is necessary to achieve good results.
  90266. * - The program initializes the instance to validate the settings and
  90267. * prepare for encoding using
  90268. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90269. * or FLAC__stream_encoder_init_file() for native FLAC
  90270. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90271. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90272. * - The program calls FLAC__stream_encoder_process() or
  90273. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90274. * subsequently calls the callbacks when there is encoder data ready
  90275. * to be written.
  90276. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90277. * which causes the encoder to encode any data still in its input pipe,
  90278. * update the metadata with the final encoding statistics if output
  90279. * seeking is possible, and finally reset the encoder to the
  90280. * uninitialized state.
  90281. * - The instance may be used again or deleted with
  90282. * FLAC__stream_encoder_delete().
  90283. *
  90284. * In more detail, the stream encoder functions similarly to the
  90285. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90286. * callbacks and more options. Typically the client will create a new
  90287. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90288. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90289. * calling one of the FLAC__stream_encoder_init_*() functions.
  90290. *
  90291. * Unlike the decoders, the stream encoder has many options that can
  90292. * affect the speed and compression ratio. When setting these parameters
  90293. * you should have some basic knowledge of the format (see the
  90294. * <A HREF="../documentation.html#format">user-level documentation</A>
  90295. * or the <A HREF="../format.html">formal description</A>). The
  90296. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90297. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90298. * functions will do this, so make sure to pay attention to the state
  90299. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90300. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90301. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90302. * the constructor.
  90303. *
  90304. * There are three initialization functions for native FLAC, one for
  90305. * setting up the encoder to encode FLAC data to the client via
  90306. * callbacks, and two for encoding directly to a file.
  90307. *
  90308. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90309. * You must also supply a write callback which will be called anytime
  90310. * there is raw encoded data to write. If the client can seek the output
  90311. * it is best to also supply seek and tell callbacks, as this allows the
  90312. * encoder to go back after encoding is finished to write back
  90313. * information that was collected while encoding, like seek point offsets,
  90314. * frame sizes, etc.
  90315. *
  90316. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90317. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90318. * filename or open \c FILE*; the encoder will handle all the callbacks
  90319. * internally. You may also supply a progress callback for periodic
  90320. * notification of the encoding progress.
  90321. *
  90322. * There are three similarly-named init functions for encoding to Ogg
  90323. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90324. * library has been built with Ogg support.
  90325. *
  90326. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90327. * call the write callback several times, once with the \c fLaC signature,
  90328. * and once for each encoded metadata block. Note that for Ogg FLAC
  90329. * encoding you will usually get at least twice the number of callbacks than
  90330. * with native FLAC, one for the Ogg page header and one for the page body.
  90331. *
  90332. * After initializing the instance, the client may feed audio data to the
  90333. * encoder in one of two ways:
  90334. *
  90335. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90336. * will pass an array of pointers to buffers, one for each channel, to
  90337. * the encoder, each of the same length. The samples need not be
  90338. * block-aligned, but each channel should have the same number of samples.
  90339. * - Channel interleaved, through
  90340. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90341. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90342. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90343. * Again, the samples need not be block-aligned but they must be
  90344. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90345. * the last value channelN_sampleM.
  90346. *
  90347. * Note that for either process call, each sample in the buffers should be a
  90348. * signed integer, right-justified to the resolution set by
  90349. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90350. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90351. *
  90352. * When the client is finished encoding data, it calls
  90353. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90354. * data still in its input pipe, and call the metadata callback with the
  90355. * final encoding statistics. Then the instance may be deleted with
  90356. * FLAC__stream_encoder_delete() or initialized again to encode another
  90357. * stream.
  90358. *
  90359. * For programs that write their own metadata, but that do not know the
  90360. * actual metadata until after encoding, it is advantageous to instruct
  90361. * the encoder to write a PADDING block of the correct size, so that
  90362. * instead of rewriting the whole stream after encoding, the program can
  90363. * just overwrite the PADDING block. If only the maximum size of the
  90364. * metadata is known, the program can write a slightly larger padding
  90365. * block, then split it after encoding.
  90366. *
  90367. * Make sure you understand how lengths are calculated. All FLAC metadata
  90368. * blocks have a 4 byte header which contains the type and length. This
  90369. * length does not include the 4 bytes of the header. See the format page
  90370. * for the specification of metadata blocks and their lengths.
  90371. *
  90372. * \note
  90373. * If you are writing the FLAC data to a file via callbacks, make sure it
  90374. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90375. * after the first encoding pass, the encoder will try to seek back to the
  90376. * beginning of the stream, to the STREAMINFO block, to write some data
  90377. * there. (If using FLAC__stream_encoder_init*_file() or
  90378. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90379. *
  90380. * \note
  90381. * The "set" functions may only be called when the encoder is in the
  90382. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90383. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90384. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90385. * return \c true, otherwise \c false.
  90386. *
  90387. * \note
  90388. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90389. * defaults.
  90390. *
  90391. * \{
  90392. */
  90393. /** State values for a FLAC__StreamEncoder.
  90394. *
  90395. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90396. *
  90397. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90398. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90399. * must be deleted with FLAC__stream_encoder_delete().
  90400. */
  90401. typedef enum {
  90402. FLAC__STREAM_ENCODER_OK = 0,
  90403. /**< The encoder is in the normal OK state and samples can be processed. */
  90404. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90405. /**< The encoder is in the uninitialized state; one of the
  90406. * FLAC__stream_encoder_init_*() functions must be called before samples
  90407. * can be processed.
  90408. */
  90409. FLAC__STREAM_ENCODER_OGG_ERROR,
  90410. /**< An error occurred in the underlying Ogg layer. */
  90411. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90412. /**< An error occurred in the underlying verify stream decoder;
  90413. * check FLAC__stream_encoder_get_verify_decoder_state().
  90414. */
  90415. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90416. /**< The verify decoder detected a mismatch between the original
  90417. * audio signal and the decoded audio signal.
  90418. */
  90419. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90420. /**< One of the callbacks returned a fatal error. */
  90421. FLAC__STREAM_ENCODER_IO_ERROR,
  90422. /**< An I/O error occurred while opening/reading/writing a file.
  90423. * Check \c errno.
  90424. */
  90425. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90426. /**< An error occurred while writing the stream; usually, the
  90427. * write_callback returned an error.
  90428. */
  90429. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90430. /**< Memory allocation failed. */
  90431. } FLAC__StreamEncoderState;
  90432. /** Maps a FLAC__StreamEncoderState to a C string.
  90433. *
  90434. * Using a FLAC__StreamEncoderState as the index to this array
  90435. * will give the string equivalent. The contents should not be modified.
  90436. */
  90437. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90438. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90439. */
  90440. typedef enum {
  90441. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90442. /**< Initialization was successful. */
  90443. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90444. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90445. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90446. /**< The library was not compiled with support for the given container
  90447. * format.
  90448. */
  90449. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90450. /**< A required callback was not supplied. */
  90451. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90452. /**< The encoder has an invalid setting for number of channels. */
  90453. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90454. /**< The encoder has an invalid setting for bits-per-sample.
  90455. * FLAC supports 4-32 bps but the reference encoder currently supports
  90456. * only up to 24 bps.
  90457. */
  90458. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90459. /**< The encoder has an invalid setting for the input sample rate. */
  90460. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90461. /**< The encoder has an invalid setting for the block size. */
  90462. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90463. /**< The encoder has an invalid setting for the maximum LPC order. */
  90464. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90465. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90466. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90467. /**< The specified block size is less than the maximum LPC order. */
  90468. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90469. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90470. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90471. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90472. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90473. * - One of the metadata blocks contains an undefined type
  90474. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90475. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90476. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90477. */
  90478. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90479. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90480. * already initialized, usually because
  90481. * FLAC__stream_encoder_finish() was not called.
  90482. */
  90483. } FLAC__StreamEncoderInitStatus;
  90484. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90485. *
  90486. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90487. * will give the string equivalent. The contents should not be modified.
  90488. */
  90489. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90490. /** Return values for the FLAC__StreamEncoder read callback.
  90491. */
  90492. typedef enum {
  90493. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90494. /**< The read was OK and decoding can continue. */
  90495. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90496. /**< The read was attempted at the end of the stream. */
  90497. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90498. /**< An unrecoverable error occurred. */
  90499. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90500. /**< Client does not support reading back from the output. */
  90501. } FLAC__StreamEncoderReadStatus;
  90502. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90503. *
  90504. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90505. * will give the string equivalent. The contents should not be modified.
  90506. */
  90507. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90508. /** Return values for the FLAC__StreamEncoder write callback.
  90509. */
  90510. typedef enum {
  90511. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90512. /**< The write was OK and encoding can continue. */
  90513. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90514. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90515. } FLAC__StreamEncoderWriteStatus;
  90516. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90517. *
  90518. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90519. * will give the string equivalent. The contents should not be modified.
  90520. */
  90521. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90522. /** Return values for the FLAC__StreamEncoder seek callback.
  90523. */
  90524. typedef enum {
  90525. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90526. /**< The seek was OK and encoding can continue. */
  90527. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90528. /**< An unrecoverable error occurred. */
  90529. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90530. /**< Client does not support seeking. */
  90531. } FLAC__StreamEncoderSeekStatus;
  90532. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90533. *
  90534. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90535. * will give the string equivalent. The contents should not be modified.
  90536. */
  90537. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90538. /** Return values for the FLAC__StreamEncoder tell callback.
  90539. */
  90540. typedef enum {
  90541. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90542. /**< The tell was OK and encoding can continue. */
  90543. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90544. /**< An unrecoverable error occurred. */
  90545. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90546. /**< Client does not support seeking. */
  90547. } FLAC__StreamEncoderTellStatus;
  90548. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90549. *
  90550. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90551. * will give the string equivalent. The contents should not be modified.
  90552. */
  90553. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90554. /***********************************************************************
  90555. *
  90556. * class FLAC__StreamEncoder
  90557. *
  90558. ***********************************************************************/
  90559. struct FLAC__StreamEncoderProtected;
  90560. struct FLAC__StreamEncoderPrivate;
  90561. /** The opaque structure definition for the stream encoder type.
  90562. * See the \link flac_stream_encoder stream encoder module \endlink
  90563. * for a detailed description.
  90564. */
  90565. typedef struct {
  90566. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90567. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90568. } FLAC__StreamEncoder;
  90569. /** Signature for the read callback.
  90570. *
  90571. * A function pointer matching this signature must be passed to
  90572. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90573. * The supplied function will be called when the encoder needs to read back
  90574. * encoded data. This happens during the metadata callback, when the encoder
  90575. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90576. * while encoding. The address of the buffer to be filled is supplied, along
  90577. * with the number of bytes the buffer can hold. The callback may choose to
  90578. * supply less data and modify the byte count but must be careful not to
  90579. * overflow the buffer. The callback then returns a status code chosen from
  90580. * FLAC__StreamEncoderReadStatus.
  90581. *
  90582. * Here is an example of a read callback for stdio streams:
  90583. * \code
  90584. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90585. * {
  90586. * FILE *file = ((MyClientData*)client_data)->file;
  90587. * if(*bytes > 0) {
  90588. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90589. * if(ferror(file))
  90590. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90591. * else if(*bytes == 0)
  90592. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90593. * else
  90594. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90595. * }
  90596. * else
  90597. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90598. * }
  90599. * \endcode
  90600. *
  90601. * \note In general, FLAC__StreamEncoder functions which change the
  90602. * state should not be called on the \a encoder while in the callback.
  90603. *
  90604. * \param encoder The encoder instance calling the callback.
  90605. * \param buffer A pointer to a location for the callee to store
  90606. * data to be encoded.
  90607. * \param bytes A pointer to the size of the buffer. On entry
  90608. * to the callback, it contains the maximum number
  90609. * of bytes that may be stored in \a buffer. The
  90610. * callee must set it to the actual number of bytes
  90611. * stored (0 in case of error or end-of-stream) before
  90612. * returning.
  90613. * \param client_data The callee's client data set through
  90614. * FLAC__stream_encoder_set_client_data().
  90615. * \retval FLAC__StreamEncoderReadStatus
  90616. * The callee's return status.
  90617. */
  90618. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90619. /** Signature for the write callback.
  90620. *
  90621. * A function pointer matching this signature must be passed to
  90622. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90623. * by the encoder anytime there is raw encoded data ready to write. It may
  90624. * include metadata mixed with encoded audio frames and the data is not
  90625. * guaranteed to be aligned on frame or metadata block boundaries.
  90626. *
  90627. * The only duty of the callback is to write out the \a bytes worth of data
  90628. * in \a buffer to the current position in the output stream. The arguments
  90629. * \a samples and \a current_frame are purely informational. If \a samples
  90630. * is greater than \c 0, then \a current_frame will hold the current frame
  90631. * number that is being written; otherwise it indicates that the write
  90632. * callback is being called to write metadata.
  90633. *
  90634. * \note
  90635. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90636. * write callback will be called twice when writing each audio
  90637. * frame; once for the page header, and once for the page body.
  90638. * When writing the page header, the \a samples argument to the
  90639. * write callback will be \c 0.
  90640. *
  90641. * \note In general, FLAC__StreamEncoder functions which change the
  90642. * state should not be called on the \a encoder while in the callback.
  90643. *
  90644. * \param encoder The encoder instance calling the callback.
  90645. * \param buffer An array of encoded data of length \a bytes.
  90646. * \param bytes The byte length of \a buffer.
  90647. * \param samples The number of samples encoded by \a buffer.
  90648. * \c 0 has a special meaning; see above.
  90649. * \param current_frame The number of the current frame being encoded.
  90650. * \param client_data The callee's client data set through
  90651. * FLAC__stream_encoder_init_*().
  90652. * \retval FLAC__StreamEncoderWriteStatus
  90653. * The callee's return status.
  90654. */
  90655. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90656. /** Signature for the seek callback.
  90657. *
  90658. * A function pointer matching this signature may be passed to
  90659. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90660. * when the encoder needs to seek the output stream. The encoder will pass
  90661. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90662. *
  90663. * Here is an example of a seek callback for stdio streams:
  90664. * \code
  90665. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90666. * {
  90667. * FILE *file = ((MyClientData*)client_data)->file;
  90668. * if(file == stdin)
  90669. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90670. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90671. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90672. * else
  90673. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90674. * }
  90675. * \endcode
  90676. *
  90677. * \note In general, FLAC__StreamEncoder functions which change the
  90678. * state should not be called on the \a encoder while in the callback.
  90679. *
  90680. * \param encoder The encoder instance calling the callback.
  90681. * \param absolute_byte_offset The offset from the beginning of the stream
  90682. * to seek to.
  90683. * \param client_data The callee's client data set through
  90684. * FLAC__stream_encoder_init_*().
  90685. * \retval FLAC__StreamEncoderSeekStatus
  90686. * The callee's return status.
  90687. */
  90688. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90689. /** Signature for the tell callback.
  90690. *
  90691. * A function pointer matching this signature may be passed to
  90692. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90693. * when the encoder needs to know the current position of the output stream.
  90694. *
  90695. * \warning
  90696. * The callback must return the true current byte offset of the output to
  90697. * which the encoder is writing. If you are buffering the output, make
  90698. * sure and take this into account. If you are writing directly to a
  90699. * FILE* from your write callback, ftell() is sufficient. If you are
  90700. * writing directly to a file descriptor from your write callback, you
  90701. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90702. * these points to rewrite metadata after encoding.
  90703. *
  90704. * Here is an example of a tell callback for stdio streams:
  90705. * \code
  90706. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90707. * {
  90708. * FILE *file = ((MyClientData*)client_data)->file;
  90709. * off_t pos;
  90710. * if(file == stdin)
  90711. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90712. * else if((pos = ftello(file)) < 0)
  90713. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90714. * else {
  90715. * *absolute_byte_offset = (FLAC__uint64)pos;
  90716. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90717. * }
  90718. * }
  90719. * \endcode
  90720. *
  90721. * \note In general, FLAC__StreamEncoder functions which change the
  90722. * state should not be called on the \a encoder while in the callback.
  90723. *
  90724. * \param encoder The encoder instance calling the callback.
  90725. * \param absolute_byte_offset The address at which to store the current
  90726. * position of the output.
  90727. * \param client_data The callee's client data set through
  90728. * FLAC__stream_encoder_init_*().
  90729. * \retval FLAC__StreamEncoderTellStatus
  90730. * The callee's return status.
  90731. */
  90732. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90733. /** Signature for the metadata callback.
  90734. *
  90735. * A function pointer matching this signature may be passed to
  90736. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90737. * once at the end of encoding with the populated STREAMINFO structure. This
  90738. * is so the client can seek back to the beginning of the file and write the
  90739. * STREAMINFO block with the correct statistics after encoding (like
  90740. * minimum/maximum frame size and total samples).
  90741. *
  90742. * \note In general, FLAC__StreamEncoder functions which change the
  90743. * state should not be called on the \a encoder while in the callback.
  90744. *
  90745. * \param encoder The encoder instance calling the callback.
  90746. * \param metadata The final populated STREAMINFO block.
  90747. * \param client_data The callee's client data set through
  90748. * FLAC__stream_encoder_init_*().
  90749. */
  90750. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90751. /** Signature for the progress callback.
  90752. *
  90753. * A function pointer matching this signature may be passed to
  90754. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90755. * The supplied function will be called when the encoder has finished
  90756. * writing a frame. The \c total_frames_estimate argument to the
  90757. * callback will be based on the value from
  90758. * FLAC__stream_encoder_set_total_samples_estimate().
  90759. *
  90760. * \note In general, FLAC__StreamEncoder functions which change the
  90761. * state should not be called on the \a encoder while in the callback.
  90762. *
  90763. * \param encoder The encoder instance calling the callback.
  90764. * \param bytes_written Bytes written so far.
  90765. * \param samples_written Samples written so far.
  90766. * \param frames_written Frames written so far.
  90767. * \param total_frames_estimate The estimate of the total number of
  90768. * frames to be written.
  90769. * \param client_data The callee's client data set through
  90770. * FLAC__stream_encoder_init_*().
  90771. */
  90772. 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);
  90773. /***********************************************************************
  90774. *
  90775. * Class constructor/destructor
  90776. *
  90777. ***********************************************************************/
  90778. /** Create a new stream encoder instance. The instance is created with
  90779. * default settings; see the individual FLAC__stream_encoder_set_*()
  90780. * functions for each setting's default.
  90781. *
  90782. * \retval FLAC__StreamEncoder*
  90783. * \c NULL if there was an error allocating memory, else the new instance.
  90784. */
  90785. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90786. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90787. *
  90788. * \param encoder A pointer to an existing encoder.
  90789. * \assert
  90790. * \code encoder != NULL \endcode
  90791. */
  90792. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  90793. /***********************************************************************
  90794. *
  90795. * Public class method prototypes
  90796. *
  90797. ***********************************************************************/
  90798. /** Set the serial number for the FLAC stream to use in the Ogg container.
  90799. *
  90800. * \note
  90801. * This does not need to be set for native FLAC encoding.
  90802. *
  90803. * \note
  90804. * It is recommended to set a serial number explicitly as the default of '0'
  90805. * may collide with other streams.
  90806. *
  90807. * \default \c 0
  90808. * \param encoder An encoder instance to set.
  90809. * \param serial_number See above.
  90810. * \assert
  90811. * \code encoder != NULL \endcode
  90812. * \retval FLAC__bool
  90813. * \c false if the encoder is already initialized, else \c true.
  90814. */
  90815. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  90816. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  90817. * encoded output by feeding it through an internal decoder and comparing
  90818. * the original signal against the decoded signal. If a mismatch occurs,
  90819. * the process call will return \c false. Note that this will slow the
  90820. * encoding process by the extra time required for decoding and comparison.
  90821. *
  90822. * \default \c false
  90823. * \param encoder An encoder instance to set.
  90824. * \param value Flag value (see above).
  90825. * \assert
  90826. * \code encoder != NULL \endcode
  90827. * \retval FLAC__bool
  90828. * \c false if the encoder is already initialized, else \c true.
  90829. */
  90830. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90831. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  90832. * the encoder will comply with the Subset and will check the
  90833. * settings during FLAC__stream_encoder_init_*() to see if all settings
  90834. * comply. If \c false, the settings may take advantage of the full
  90835. * range that the format allows.
  90836. *
  90837. * Make sure you know what it entails before setting this to \c false.
  90838. *
  90839. * \default \c true
  90840. * \param encoder An encoder instance to set.
  90841. * \param value Flag value (see above).
  90842. * \assert
  90843. * \code encoder != NULL \endcode
  90844. * \retval FLAC__bool
  90845. * \c false if the encoder is already initialized, else \c true.
  90846. */
  90847. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90848. /** Set the number of channels to be encoded.
  90849. *
  90850. * \default \c 2
  90851. * \param encoder An encoder instance to set.
  90852. * \param value See above.
  90853. * \assert
  90854. * \code encoder != NULL \endcode
  90855. * \retval FLAC__bool
  90856. * \c false if the encoder is already initialized, else \c true.
  90857. */
  90858. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  90859. /** Set the sample resolution of the input to be encoded.
  90860. *
  90861. * \warning
  90862. * Do not feed the encoder data that is wider than the value you
  90863. * set here or you will generate an invalid stream.
  90864. *
  90865. * \default \c 16
  90866. * \param encoder An encoder instance to set.
  90867. * \param value See above.
  90868. * \assert
  90869. * \code encoder != NULL \endcode
  90870. * \retval FLAC__bool
  90871. * \c false if the encoder is already initialized, else \c true.
  90872. */
  90873. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  90874. /** Set the sample rate (in Hz) of the input to be encoded.
  90875. *
  90876. * \default \c 44100
  90877. * \param encoder An encoder instance to set.
  90878. * \param value See above.
  90879. * \assert
  90880. * \code encoder != NULL \endcode
  90881. * \retval FLAC__bool
  90882. * \c false if the encoder is already initialized, else \c true.
  90883. */
  90884. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  90885. /** Set the compression level
  90886. *
  90887. * The compression level is roughly proportional to the amount of effort
  90888. * the encoder expends to compress the file. A higher level usually
  90889. * means more computation but higher compression. The default level is
  90890. * suitable for most applications.
  90891. *
  90892. * Currently the levels range from \c 0 (fastest, least compression) to
  90893. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  90894. * treated as \c 8.
  90895. *
  90896. * This function automatically calls the following other \c _set_
  90897. * functions with appropriate values, so the client does not need to
  90898. * unless it specifically wants to override them:
  90899. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  90900. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  90901. * - FLAC__stream_encoder_set_apodization()
  90902. * - FLAC__stream_encoder_set_max_lpc_order()
  90903. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  90904. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  90905. * - FLAC__stream_encoder_set_do_escape_coding()
  90906. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  90907. * - FLAC__stream_encoder_set_min_residual_partition_order()
  90908. * - FLAC__stream_encoder_set_max_residual_partition_order()
  90909. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  90910. *
  90911. * The actual values set for each level are:
  90912. * <table>
  90913. * <tr>
  90914. * <td><b>level</b><td>
  90915. * <td>do mid-side stereo<td>
  90916. * <td>loose mid-side stereo<td>
  90917. * <td>apodization<td>
  90918. * <td>max lpc order<td>
  90919. * <td>qlp coeff precision<td>
  90920. * <td>qlp coeff prec search<td>
  90921. * <td>escape coding<td>
  90922. * <td>exhaustive model search<td>
  90923. * <td>min residual partition order<td>
  90924. * <td>max residual partition order<td>
  90925. * <td>rice parameter search dist<td>
  90926. * </tr>
  90927. * <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>
  90928. * <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>
  90929. * <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>
  90930. * <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>
  90931. * <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>
  90932. * <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>
  90933. * <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>
  90934. * <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>
  90935. * <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>
  90936. * </table>
  90937. *
  90938. * \default \c 5
  90939. * \param encoder An encoder instance to set.
  90940. * \param value See above.
  90941. * \assert
  90942. * \code encoder != NULL \endcode
  90943. * \retval FLAC__bool
  90944. * \c false if the encoder is already initialized, else \c true.
  90945. */
  90946. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  90947. /** Set the blocksize to use while encoding.
  90948. *
  90949. * The number of samples to use per frame. Use \c 0 to let the encoder
  90950. * estimate a blocksize; this is usually best.
  90951. *
  90952. * \default \c 0
  90953. * \param encoder An encoder instance to set.
  90954. * \param value See above.
  90955. * \assert
  90956. * \code encoder != NULL \endcode
  90957. * \retval FLAC__bool
  90958. * \c false if the encoder is already initialized, else \c true.
  90959. */
  90960. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  90961. /** Set to \c true to enable mid-side encoding on stereo input. The
  90962. * number of channels must be 2 for this to have any effect. Set to
  90963. * \c false to use only independent channel coding.
  90964. *
  90965. * \default \c false
  90966. * \param encoder An encoder instance to set.
  90967. * \param value Flag value (see above).
  90968. * \assert
  90969. * \code encoder != NULL \endcode
  90970. * \retval FLAC__bool
  90971. * \c false if the encoder is already initialized, else \c true.
  90972. */
  90973. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90974. /** Set to \c true to enable adaptive switching between mid-side and
  90975. * left-right encoding on stereo input. Set to \c false to use
  90976. * exhaustive searching. Setting this to \c true requires
  90977. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  90978. * \c true in order to have any effect.
  90979. *
  90980. * \default \c false
  90981. * \param encoder An encoder instance to set.
  90982. * \param value Flag value (see above).
  90983. * \assert
  90984. * \code encoder != NULL \endcode
  90985. * \retval FLAC__bool
  90986. * \c false if the encoder is already initialized, else \c true.
  90987. */
  90988. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90989. /** Sets the apodization function(s) the encoder will use when windowing
  90990. * audio data for LPC analysis.
  90991. *
  90992. * The \a specification is a plain ASCII string which specifies exactly
  90993. * which functions to use. There may be more than one (up to 32),
  90994. * separated by \c ';' characters. Some functions take one or more
  90995. * comma-separated arguments in parentheses.
  90996. *
  90997. * The available functions are \c bartlett, \c bartlett_hann,
  90998. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  90999. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91000. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91001. *
  91002. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91003. * (0<STDDEV<=0.5).
  91004. *
  91005. * For \c tukey(P), P specifies the fraction of the window that is
  91006. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91007. * corresponds to \c hann.
  91008. *
  91009. * Example specifications are \c "blackman" or
  91010. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91011. *
  91012. * Any function that is specified erroneously is silently dropped. Up
  91013. * to 32 functions are kept, the rest are dropped. If the specification
  91014. * is empty the encoder defaults to \c "tukey(0.5)".
  91015. *
  91016. * When more than one function is specified, then for every subframe the
  91017. * encoder will try each of them separately and choose the window that
  91018. * results in the smallest compressed subframe.
  91019. *
  91020. * Note that each function specified causes the encoder to occupy a
  91021. * floating point array in which to store the window.
  91022. *
  91023. * \default \c "tukey(0.5)"
  91024. * \param encoder An encoder instance to set.
  91025. * \param specification See above.
  91026. * \assert
  91027. * \code encoder != NULL \endcode
  91028. * \code specification != NULL \endcode
  91029. * \retval FLAC__bool
  91030. * \c false if the encoder is already initialized, else \c true.
  91031. */
  91032. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91033. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91034. *
  91035. * \default \c 0
  91036. * \param encoder An encoder instance to set.
  91037. * \param value See above.
  91038. * \assert
  91039. * \code encoder != NULL \endcode
  91040. * \retval FLAC__bool
  91041. * \c false if the encoder is already initialized, else \c true.
  91042. */
  91043. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91044. /** Set the precision, in bits, of the quantized linear predictor
  91045. * coefficients, or \c 0 to let the encoder select it based on the
  91046. * blocksize.
  91047. *
  91048. * \note
  91049. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91050. * be less than 32.
  91051. *
  91052. * \default \c 0
  91053. * \param encoder An encoder instance to set.
  91054. * \param value See above.
  91055. * \assert
  91056. * \code encoder != NULL \endcode
  91057. * \retval FLAC__bool
  91058. * \c false if the encoder is already initialized, else \c true.
  91059. */
  91060. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91061. /** Set to \c false to use only the specified quantized linear predictor
  91062. * coefficient precision, or \c true to search neighboring precision
  91063. * values and use the best one.
  91064. *
  91065. * \default \c false
  91066. * \param encoder An encoder instance to set.
  91067. * \param value See above.
  91068. * \assert
  91069. * \code encoder != NULL \endcode
  91070. * \retval FLAC__bool
  91071. * \c false if the encoder is already initialized, else \c true.
  91072. */
  91073. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91074. /** Deprecated. Setting this value has no effect.
  91075. *
  91076. * \default \c false
  91077. * \param encoder An encoder instance to set.
  91078. * \param value See above.
  91079. * \assert
  91080. * \code encoder != NULL \endcode
  91081. * \retval FLAC__bool
  91082. * \c false if the encoder is already initialized, else \c true.
  91083. */
  91084. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91085. /** Set to \c false to let the encoder estimate the best model order
  91086. * based on the residual signal energy, or \c true to force the
  91087. * encoder to evaluate all order models and select the best.
  91088. *
  91089. * \default \c false
  91090. * \param encoder An encoder instance to set.
  91091. * \param value See above.
  91092. * \assert
  91093. * \code encoder != NULL \endcode
  91094. * \retval FLAC__bool
  91095. * \c false if the encoder is already initialized, else \c true.
  91096. */
  91097. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91098. /** Set the minimum partition order to search when coding the residual.
  91099. * This is used in tandem with
  91100. * FLAC__stream_encoder_set_max_residual_partition_order().
  91101. *
  91102. * The partition order determines the context size in the residual.
  91103. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91104. *
  91105. * Set both min and max values to \c 0 to force a single context,
  91106. * whose Rice parameter is based on the residual signal variance.
  91107. * Otherwise, set a min and max order, and the encoder will search
  91108. * all orders, using the mean of each context for its Rice parameter,
  91109. * and use the best.
  91110. *
  91111. * \default \c 0
  91112. * \param encoder An encoder instance to set.
  91113. * \param value See above.
  91114. * \assert
  91115. * \code encoder != NULL \endcode
  91116. * \retval FLAC__bool
  91117. * \c false if the encoder is already initialized, else \c true.
  91118. */
  91119. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91120. /** Set the maximum partition order to search when coding the residual.
  91121. * This is used in tandem with
  91122. * FLAC__stream_encoder_set_min_residual_partition_order().
  91123. *
  91124. * The partition order determines the context size in the residual.
  91125. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91126. *
  91127. * Set both min and max values to \c 0 to force a single context,
  91128. * whose Rice parameter is based on the residual signal variance.
  91129. * Otherwise, set a min and max order, and the encoder will search
  91130. * all orders, using the mean of each context for its Rice parameter,
  91131. * and use the best.
  91132. *
  91133. * \default \c 0
  91134. * \param encoder An encoder instance to set.
  91135. * \param value See above.
  91136. * \assert
  91137. * \code encoder != NULL \endcode
  91138. * \retval FLAC__bool
  91139. * \c false if the encoder is already initialized, else \c true.
  91140. */
  91141. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91142. /** Deprecated. Setting this value has no effect.
  91143. *
  91144. * \default \c 0
  91145. * \param encoder An encoder instance to set.
  91146. * \param value See above.
  91147. * \assert
  91148. * \code encoder != NULL \endcode
  91149. * \retval FLAC__bool
  91150. * \c false if the encoder is already initialized, else \c true.
  91151. */
  91152. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91153. /** Set an estimate of the total samples that will be encoded.
  91154. * This is merely an estimate and may be set to \c 0 if unknown.
  91155. * This value will be written to the STREAMINFO block before encoding,
  91156. * and can remove the need for the caller to rewrite the value later
  91157. * if the value is known before encoding.
  91158. *
  91159. * \default \c 0
  91160. * \param encoder An encoder instance to set.
  91161. * \param value See above.
  91162. * \assert
  91163. * \code encoder != NULL \endcode
  91164. * \retval FLAC__bool
  91165. * \c false if the encoder is already initialized, else \c true.
  91166. */
  91167. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91168. /** Set the metadata blocks to be emitted to the stream before encoding.
  91169. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91170. * array of pointers to metadata blocks. The array is non-const since
  91171. * the encoder may need to change the \a is_last flag inside them, and
  91172. * in some cases update seek point offsets. Otherwise, the encoder will
  91173. * not modify or free the blocks. It is up to the caller to free the
  91174. * metadata blocks after encoding finishes.
  91175. *
  91176. * \note
  91177. * The encoder stores only copies of the pointers in the \a metadata array;
  91178. * the metadata blocks themselves must survive at least until after
  91179. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91180. *
  91181. * \note
  91182. * The STREAMINFO block is always written and no STREAMINFO block may
  91183. * occur in the supplied array.
  91184. *
  91185. * \note
  91186. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91187. * in the \a metadata array, but the client has specified that it does not
  91188. * support seeking, then the SEEKTABLE will be written verbatim. However
  91189. * by itself this is not very useful as the client will not know the stream
  91190. * offsets for the seekpoints ahead of time. In order to get a proper
  91191. * seektable the client must support seeking. See next note.
  91192. *
  91193. * \note
  91194. * SEEKTABLE blocks are handled specially. Since you will not know
  91195. * the values for the seek point stream offsets, you should pass in
  91196. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91197. * required sample numbers (or placeholder points), with \c 0 for the
  91198. * \a frame_samples and \a stream_offset fields for each point. If the
  91199. * client has specified that it supports seeking by providing a seek
  91200. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91201. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91202. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91203. * then while it is encoding the encoder will fill the stream offsets in
  91204. * for you and when encoding is finished, it will seek back and write the
  91205. * real values into the SEEKTABLE block in the stream. There are helper
  91206. * routines for manipulating seektable template blocks; see metadata.h:
  91207. * FLAC__metadata_object_seektable_template_*(). If the client does
  91208. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91209. * will slow down or remove the ability to seek in the FLAC stream.
  91210. *
  91211. * \note
  91212. * The encoder instance \b will modify the first \c SEEKTABLE block
  91213. * as it transforms the template to a valid seektable while encoding,
  91214. * but it is still up to the caller to free all metadata blocks after
  91215. * encoding.
  91216. *
  91217. * \note
  91218. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91219. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91220. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91221. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91222. * block is present in the \a metadata array, libFLAC will write an
  91223. * empty one, containing only the vendor string.
  91224. *
  91225. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91226. * the second metadata block of the stream. The encoder already supplies
  91227. * the STREAMINFO block automatically. If \a metadata does not contain a
  91228. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91229. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91230. * first, the init function will reorder \a metadata by moving the
  91231. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91232. * blocks will remain as they were.
  91233. *
  91234. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91235. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91236. * return \c false.
  91237. *
  91238. * \default \c NULL, 0
  91239. * \param encoder An encoder instance to set.
  91240. * \param metadata See above.
  91241. * \param num_blocks See above.
  91242. * \assert
  91243. * \code encoder != NULL \endcode
  91244. * \retval FLAC__bool
  91245. * \c false if the encoder is already initialized, else \c true.
  91246. * \c false if the encoder is already initialized, or if
  91247. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91248. */
  91249. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91250. /** Get the current encoder state.
  91251. *
  91252. * \param encoder An encoder instance to query.
  91253. * \assert
  91254. * \code encoder != NULL \endcode
  91255. * \retval FLAC__StreamEncoderState
  91256. * The current encoder state.
  91257. */
  91258. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91259. /** Get the state of the verify stream decoder.
  91260. * Useful when the stream encoder state is
  91261. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91262. *
  91263. * \param encoder An encoder instance to query.
  91264. * \assert
  91265. * \code encoder != NULL \endcode
  91266. * \retval FLAC__StreamDecoderState
  91267. * The verify stream decoder state.
  91268. */
  91269. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91270. /** Get the current encoder state as a C string.
  91271. * This version automatically resolves
  91272. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91273. * verify decoder's state.
  91274. *
  91275. * \param encoder A encoder instance to query.
  91276. * \assert
  91277. * \code encoder != NULL \endcode
  91278. * \retval const char *
  91279. * The encoder state as a C string. Do not modify the contents.
  91280. */
  91281. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91282. /** Get relevant values about the nature of a verify decoder error.
  91283. * Useful when the stream encoder state is
  91284. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91285. * be addresses in which the stats will be returned, or NULL if value
  91286. * is not desired.
  91287. *
  91288. * \param encoder An encoder instance to query.
  91289. * \param absolute_sample The absolute sample number of the mismatch.
  91290. * \param frame_number The number of the frame in which the mismatch occurred.
  91291. * \param channel The channel in which the mismatch occurred.
  91292. * \param sample The number of the sample (relative to the frame) in
  91293. * which the mismatch occurred.
  91294. * \param expected The expected value for the sample in question.
  91295. * \param got The actual value returned by the decoder.
  91296. * \assert
  91297. * \code encoder != NULL \endcode
  91298. */
  91299. 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);
  91300. /** Get the "verify" flag.
  91301. *
  91302. * \param encoder An encoder instance to query.
  91303. * \assert
  91304. * \code encoder != NULL \endcode
  91305. * \retval FLAC__bool
  91306. * See FLAC__stream_encoder_set_verify().
  91307. */
  91308. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91309. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91310. *
  91311. * \param encoder An encoder instance to query.
  91312. * \assert
  91313. * \code encoder != NULL \endcode
  91314. * \retval FLAC__bool
  91315. * See FLAC__stream_encoder_set_streamable_subset().
  91316. */
  91317. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91318. /** Get the number of input channels being processed.
  91319. *
  91320. * \param encoder An encoder instance to query.
  91321. * \assert
  91322. * \code encoder != NULL \endcode
  91323. * \retval unsigned
  91324. * See FLAC__stream_encoder_set_channels().
  91325. */
  91326. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91327. /** Get the input sample resolution setting.
  91328. *
  91329. * \param encoder An encoder instance to query.
  91330. * \assert
  91331. * \code encoder != NULL \endcode
  91332. * \retval unsigned
  91333. * See FLAC__stream_encoder_set_bits_per_sample().
  91334. */
  91335. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91336. /** Get the input sample rate setting.
  91337. *
  91338. * \param encoder An encoder instance to query.
  91339. * \assert
  91340. * \code encoder != NULL \endcode
  91341. * \retval unsigned
  91342. * See FLAC__stream_encoder_set_sample_rate().
  91343. */
  91344. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91345. /** Get the blocksize setting.
  91346. *
  91347. * \param encoder An encoder instance to query.
  91348. * \assert
  91349. * \code encoder != NULL \endcode
  91350. * \retval unsigned
  91351. * See FLAC__stream_encoder_set_blocksize().
  91352. */
  91353. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91354. /** Get the "mid/side stereo coding" flag.
  91355. *
  91356. * \param encoder An encoder instance to query.
  91357. * \assert
  91358. * \code encoder != NULL \endcode
  91359. * \retval FLAC__bool
  91360. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91361. */
  91362. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91363. /** Get the "adaptive mid/side switching" flag.
  91364. *
  91365. * \param encoder An encoder instance to query.
  91366. * \assert
  91367. * \code encoder != NULL \endcode
  91368. * \retval FLAC__bool
  91369. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91370. */
  91371. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91372. /** Get the maximum LPC order setting.
  91373. *
  91374. * \param encoder An encoder instance to query.
  91375. * \assert
  91376. * \code encoder != NULL \endcode
  91377. * \retval unsigned
  91378. * See FLAC__stream_encoder_set_max_lpc_order().
  91379. */
  91380. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91381. /** Get the quantized linear predictor coefficient precision setting.
  91382. *
  91383. * \param encoder An encoder instance to query.
  91384. * \assert
  91385. * \code encoder != NULL \endcode
  91386. * \retval unsigned
  91387. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91388. */
  91389. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91390. /** Get the qlp coefficient precision search flag.
  91391. *
  91392. * \param encoder An encoder instance to query.
  91393. * \assert
  91394. * \code encoder != NULL \endcode
  91395. * \retval FLAC__bool
  91396. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91397. */
  91398. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91399. /** Get the "escape coding" flag.
  91400. *
  91401. * \param encoder An encoder instance to query.
  91402. * \assert
  91403. * \code encoder != NULL \endcode
  91404. * \retval FLAC__bool
  91405. * See FLAC__stream_encoder_set_do_escape_coding().
  91406. */
  91407. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91408. /** Get the exhaustive model search flag.
  91409. *
  91410. * \param encoder An encoder instance to query.
  91411. * \assert
  91412. * \code encoder != NULL \endcode
  91413. * \retval FLAC__bool
  91414. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91415. */
  91416. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91417. /** Get the minimum residual partition order setting.
  91418. *
  91419. * \param encoder An encoder instance to query.
  91420. * \assert
  91421. * \code encoder != NULL \endcode
  91422. * \retval unsigned
  91423. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91424. */
  91425. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91426. /** Get maximum residual partition order setting.
  91427. *
  91428. * \param encoder An encoder instance to query.
  91429. * \assert
  91430. * \code encoder != NULL \endcode
  91431. * \retval unsigned
  91432. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91433. */
  91434. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91435. /** Get the Rice parameter search distance setting.
  91436. *
  91437. * \param encoder An encoder instance to query.
  91438. * \assert
  91439. * \code encoder != NULL \endcode
  91440. * \retval unsigned
  91441. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91442. */
  91443. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91444. /** Get the previously set estimate of the total samples to be encoded.
  91445. * The encoder merely mimics back the value given to
  91446. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91447. * other way of knowing how many samples the client will encode.
  91448. *
  91449. * \param encoder An encoder instance to set.
  91450. * \assert
  91451. * \code encoder != NULL \endcode
  91452. * \retval FLAC__uint64
  91453. * See FLAC__stream_encoder_get_total_samples_estimate().
  91454. */
  91455. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91456. /** Initialize the encoder instance to encode native FLAC streams.
  91457. *
  91458. * This flavor of initialization sets up the encoder to encode to a
  91459. * native FLAC stream. I/O is performed via callbacks to the client.
  91460. * For encoding to a plain file via filename or open \c FILE*,
  91461. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91462. * provide a simpler interface.
  91463. *
  91464. * This function should be called after FLAC__stream_encoder_new() and
  91465. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91466. * or FLAC__stream_encoder_process_interleaved().
  91467. * initialization succeeded.
  91468. *
  91469. * The call to FLAC__stream_encoder_init_stream() currently will also
  91470. * immediately call the write callback several times, once with the \c fLaC
  91471. * signature, and once for each encoded metadata block.
  91472. *
  91473. * \param encoder An uninitialized encoder instance.
  91474. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91475. * pointer must not be \c NULL.
  91476. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91477. * pointer may be \c NULL if seeking is not
  91478. * supported. The encoder uses seeking to go back
  91479. * and write some some stream statistics to the
  91480. * STREAMINFO block; this is recommended but not
  91481. * necessary to create a valid FLAC stream. If
  91482. * \a seek_callback is not \c NULL then a
  91483. * \a tell_callback must also be supplied.
  91484. * Alternatively, a dummy seek callback that just
  91485. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91486. * may also be supplied, all though this is slightly
  91487. * less efficient for the encoder.
  91488. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91489. * pointer may be \c NULL if seeking is not
  91490. * supported. If \a seek_callback is \c NULL then
  91491. * this argument will be ignored. If
  91492. * \a seek_callback is not \c NULL then a
  91493. * \a tell_callback must also be supplied.
  91494. * Alternatively, a dummy tell callback that just
  91495. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91496. * may also be supplied, all though this is slightly
  91497. * less efficient for the encoder.
  91498. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91499. * pointer may be \c NULL if the callback is not
  91500. * desired. If the client provides a seek callback,
  91501. * this function is not necessary as the encoder
  91502. * will automatically seek back and update the
  91503. * STREAMINFO block. It may also be \c NULL if the
  91504. * client does not support seeking, since it will
  91505. * have no way of going back to update the
  91506. * STREAMINFO. However the client can still supply
  91507. * a callback if it would like to know the details
  91508. * from the STREAMINFO.
  91509. * \param client_data This value will be supplied to callbacks in their
  91510. * \a client_data argument.
  91511. * \assert
  91512. * \code encoder != NULL \endcode
  91513. * \retval FLAC__StreamEncoderInitStatus
  91514. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91515. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91516. */
  91517. 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);
  91518. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91519. *
  91520. * This flavor of initialization sets up the encoder to encode to a FLAC
  91521. * stream in an Ogg container. I/O is performed via callbacks to the
  91522. * client. For encoding to a plain file via filename or open \c FILE*,
  91523. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91524. * provide a simpler interface.
  91525. *
  91526. * This function should be called after FLAC__stream_encoder_new() and
  91527. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91528. * or FLAC__stream_encoder_process_interleaved().
  91529. * initialization succeeded.
  91530. *
  91531. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91532. * immediately call the write callback several times to write the metadata
  91533. * packets.
  91534. *
  91535. * \param encoder An uninitialized encoder instance.
  91536. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91537. * pointer must not be \c NULL if \a seek_callback
  91538. * is non-NULL since they are both needed to be
  91539. * able to write data back to the Ogg FLAC stream
  91540. * in the post-encode phase.
  91541. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91542. * pointer must not be \c NULL.
  91543. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91544. * pointer may be \c NULL if seeking is not
  91545. * supported. The encoder uses seeking to go back
  91546. * and write some some stream statistics to the
  91547. * STREAMINFO block; this is recommended but not
  91548. * necessary to create a valid FLAC stream. If
  91549. * \a seek_callback is not \c NULL then a
  91550. * \a tell_callback must also be supplied.
  91551. * Alternatively, a dummy seek callback that just
  91552. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91553. * may also be supplied, all though this is slightly
  91554. * less efficient for the encoder.
  91555. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91556. * pointer may be \c NULL if seeking is not
  91557. * supported. If \a seek_callback is \c NULL then
  91558. * this argument will be ignored. If
  91559. * \a seek_callback is not \c NULL then a
  91560. * \a tell_callback must also be supplied.
  91561. * Alternatively, a dummy tell callback that just
  91562. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91563. * may also be supplied, all though this is slightly
  91564. * less efficient for the encoder.
  91565. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91566. * pointer may be \c NULL if the callback is not
  91567. * desired. If the client provides a seek callback,
  91568. * this function is not necessary as the encoder
  91569. * will automatically seek back and update the
  91570. * STREAMINFO block. It may also be \c NULL if the
  91571. * client does not support seeking, since it will
  91572. * have no way of going back to update the
  91573. * STREAMINFO. However the client can still supply
  91574. * a callback if it would like to know the details
  91575. * from the STREAMINFO.
  91576. * \param client_data This value will be supplied to callbacks in their
  91577. * \a client_data argument.
  91578. * \assert
  91579. * \code encoder != NULL \endcode
  91580. * \retval FLAC__StreamEncoderInitStatus
  91581. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91582. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91583. */
  91584. 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);
  91585. /** Initialize the encoder instance to encode native FLAC files.
  91586. *
  91587. * This flavor of initialization sets up the encoder to encode to a
  91588. * plain native FLAC file. For non-stdio streams, you must use
  91589. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91590. *
  91591. * This function should be called after FLAC__stream_encoder_new() and
  91592. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91593. * or FLAC__stream_encoder_process_interleaved().
  91594. * initialization succeeded.
  91595. *
  91596. * \param encoder An uninitialized encoder instance.
  91597. * \param file An open file. The file should have been opened
  91598. * with mode \c "w+b" and rewound. The file
  91599. * becomes owned by the encoder and should not be
  91600. * manipulated by the client while encoding.
  91601. * Unless \a file is \c stdout, it will be closed
  91602. * when FLAC__stream_encoder_finish() is called.
  91603. * Note however that a proper SEEKTABLE cannot be
  91604. * created when encoding to \c stdout since it is
  91605. * not seekable.
  91606. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91607. * pointer may be \c NULL if the callback is not
  91608. * desired.
  91609. * \param client_data This value will be supplied to callbacks in their
  91610. * \a client_data argument.
  91611. * \assert
  91612. * \code encoder != NULL \endcode
  91613. * \code file != NULL \endcode
  91614. * \retval FLAC__StreamEncoderInitStatus
  91615. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91616. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91617. */
  91618. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91619. /** Initialize the encoder instance to encode Ogg FLAC files.
  91620. *
  91621. * This flavor of initialization sets up the encoder to encode to a
  91622. * plain Ogg FLAC file. For non-stdio streams, you must use
  91623. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91624. *
  91625. * This function should be called after FLAC__stream_encoder_new() and
  91626. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91627. * or FLAC__stream_encoder_process_interleaved().
  91628. * initialization succeeded.
  91629. *
  91630. * \param encoder An uninitialized encoder instance.
  91631. * \param file An open file. The file should have been opened
  91632. * with mode \c "w+b" and rewound. The file
  91633. * becomes owned by the encoder and should not be
  91634. * manipulated by the client while encoding.
  91635. * Unless \a file is \c stdout, it will be closed
  91636. * when FLAC__stream_encoder_finish() is called.
  91637. * Note however that a proper SEEKTABLE cannot be
  91638. * created when encoding to \c stdout since it is
  91639. * not seekable.
  91640. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91641. * pointer may be \c NULL if the callback is not
  91642. * desired.
  91643. * \param client_data This value will be supplied to callbacks in their
  91644. * \a client_data argument.
  91645. * \assert
  91646. * \code encoder != NULL \endcode
  91647. * \code file != NULL \endcode
  91648. * \retval FLAC__StreamEncoderInitStatus
  91649. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91650. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91651. */
  91652. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91653. /** Initialize the encoder instance to encode native FLAC files.
  91654. *
  91655. * This flavor of initialization sets up the encoder to encode to a plain
  91656. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91657. * with Unicode filenames on Windows), you must use
  91658. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91659. * and provide callbacks for the I/O.
  91660. *
  91661. * This function should be called after FLAC__stream_encoder_new() and
  91662. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91663. * or FLAC__stream_encoder_process_interleaved().
  91664. * initialization succeeded.
  91665. *
  91666. * \param encoder An uninitialized encoder instance.
  91667. * \param filename The name of the file to encode to. The file will
  91668. * be opened with fopen(). Use \c NULL to encode to
  91669. * \c stdout. Note however that a proper SEEKTABLE
  91670. * cannot be created when encoding to \c stdout since
  91671. * it is not seekable.
  91672. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91673. * pointer may be \c NULL if the callback is not
  91674. * desired.
  91675. * \param client_data This value will be supplied to callbacks in their
  91676. * \a client_data argument.
  91677. * \assert
  91678. * \code encoder != NULL \endcode
  91679. * \retval FLAC__StreamEncoderInitStatus
  91680. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91681. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91682. */
  91683. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91684. /** Initialize the encoder instance to encode Ogg FLAC files.
  91685. *
  91686. * This flavor of initialization sets up the encoder to encode to a plain
  91687. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91688. * with Unicode filenames on Windows), you must use
  91689. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91690. * and provide callbacks for the I/O.
  91691. *
  91692. * This function should be called after FLAC__stream_encoder_new() and
  91693. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91694. * or FLAC__stream_encoder_process_interleaved().
  91695. * initialization succeeded.
  91696. *
  91697. * \param encoder An uninitialized encoder instance.
  91698. * \param filename The name of the file to encode to. The file will
  91699. * be opened with fopen(). Use \c NULL to encode to
  91700. * \c stdout. Note however that a proper SEEKTABLE
  91701. * cannot be created when encoding to \c stdout since
  91702. * it is not seekable.
  91703. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91704. * pointer may be \c NULL if the callback is not
  91705. * desired.
  91706. * \param client_data This value will be supplied to callbacks in their
  91707. * \a client_data argument.
  91708. * \assert
  91709. * \code encoder != NULL \endcode
  91710. * \retval FLAC__StreamEncoderInitStatus
  91711. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91712. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91713. */
  91714. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91715. /** Finish the encoding process.
  91716. * Flushes the encoding buffer, releases resources, resets the encoder
  91717. * settings to their defaults, and returns the encoder state to
  91718. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91719. * one or more write callbacks before returning, and will generate
  91720. * a metadata callback.
  91721. *
  91722. * Note that in the course of processing the last frame, errors can
  91723. * occur, so the caller should be sure to check the return value to
  91724. * ensure the file was encoded properly.
  91725. *
  91726. * In the event of a prematurely-terminated encode, it is not strictly
  91727. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91728. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91729. * with a FLAC__stream_encoder_finish().
  91730. *
  91731. * \param encoder An uninitialized encoder instance.
  91732. * \assert
  91733. * \code encoder != NULL \endcode
  91734. * \retval FLAC__bool
  91735. * \c false if an error occurred processing the last frame; or if verify
  91736. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91737. * verify mismatch; else \c true. If \c false, caller should check the
  91738. * state with FLAC__stream_encoder_get_state() for more information
  91739. * about the error.
  91740. */
  91741. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91742. /** Submit data for encoding.
  91743. * This version allows you to supply the input data via an array of
  91744. * pointers, each pointer pointing to an array of \a samples samples
  91745. * representing one channel. The samples need not be block-aligned,
  91746. * but each channel should have the same number of samples. Each sample
  91747. * should be a signed integer, right-justified to the resolution set by
  91748. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91749. * resolution is 16 bits per sample, the samples should all be in the
  91750. * range [-32768,32767].
  91751. *
  91752. * For applications where channel order is important, channels must
  91753. * follow the order as described in the
  91754. * <A HREF="../format.html#frame_header">frame header</A>.
  91755. *
  91756. * \param encoder An initialized encoder instance in the OK state.
  91757. * \param buffer An array of pointers to each channel's signal.
  91758. * \param samples The number of samples in one channel.
  91759. * \assert
  91760. * \code encoder != NULL \endcode
  91761. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91762. * \retval FLAC__bool
  91763. * \c true if successful, else \c false; in this case, check the
  91764. * encoder state with FLAC__stream_encoder_get_state() to see what
  91765. * went wrong.
  91766. */
  91767. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91768. /** Submit data for encoding.
  91769. * This version allows you to supply the input data where the channels
  91770. * are interleaved into a single array (i.e. channel0_sample0,
  91771. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91772. * The samples need not be block-aligned but they must be
  91773. * sample-aligned, i.e. the first value should be channel0_sample0
  91774. * and the last value channelN_sampleM. Each sample should be a signed
  91775. * integer, right-justified to the resolution set by
  91776. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91777. * resolution is 16 bits per sample, the samples should all be in the
  91778. * range [-32768,32767].
  91779. *
  91780. * For applications where channel order is important, channels must
  91781. * follow the order as described in the
  91782. * <A HREF="../format.html#frame_header">frame header</A>.
  91783. *
  91784. * \param encoder An initialized encoder instance in the OK state.
  91785. * \param buffer An array of channel-interleaved data (see above).
  91786. * \param samples The number of samples in one channel, the same as for
  91787. * FLAC__stream_encoder_process(). For example, if
  91788. * encoding two channels, \c 1000 \a samples corresponds
  91789. * to a \a buffer of 2000 values.
  91790. * \assert
  91791. * \code encoder != NULL \endcode
  91792. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91793. * \retval FLAC__bool
  91794. * \c true if successful, else \c false; in this case, check the
  91795. * encoder state with FLAC__stream_encoder_get_state() to see what
  91796. * went wrong.
  91797. */
  91798. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  91799. /* \} */
  91800. #ifdef __cplusplus
  91801. }
  91802. #endif
  91803. #endif
  91804. /*** End of inlined file: stream_encoder.h ***/
  91805. #ifdef _MSC_VER
  91806. /* OPT: an MSVC built-in would be better */
  91807. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  91808. {
  91809. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  91810. return (x>>16) | (x<<16);
  91811. }
  91812. #endif
  91813. #if defined(_MSC_VER) && defined(_X86_)
  91814. /* OPT: an MSVC built-in would be better */
  91815. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  91816. {
  91817. __asm {
  91818. mov edx, start
  91819. mov ecx, len
  91820. test ecx, ecx
  91821. loop1:
  91822. jz done1
  91823. mov eax, [edx]
  91824. bswap eax
  91825. mov [edx], eax
  91826. add edx, 4
  91827. dec ecx
  91828. jmp short loop1
  91829. done1:
  91830. }
  91831. }
  91832. #endif
  91833. /** \mainpage
  91834. *
  91835. * \section intro Introduction
  91836. *
  91837. * This is the documentation for the FLAC C and C++ APIs. It is
  91838. * highly interconnected; this introduction should give you a top
  91839. * level idea of the structure and how to find the information you
  91840. * need. As a prerequisite you should have at least a basic
  91841. * knowledge of the FLAC format, documented
  91842. * <A HREF="../format.html">here</A>.
  91843. *
  91844. * \section c_api FLAC C API
  91845. *
  91846. * The FLAC C API is the interface to libFLAC, a set of structures
  91847. * describing the components of FLAC streams, and functions for
  91848. * encoding and decoding streams, as well as manipulating FLAC
  91849. * metadata in files. The public include files will be installed
  91850. * in your include area (for example /usr/include/FLAC/...).
  91851. *
  91852. * By writing a little code and linking against libFLAC, it is
  91853. * relatively easy to add FLAC support to another program. The
  91854. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  91855. * Complete source code of libFLAC as well as the command-line
  91856. * encoder and plugins is available and is a useful source of
  91857. * examples.
  91858. *
  91859. * Aside from encoders and decoders, libFLAC provides a powerful
  91860. * metadata interface for manipulating metadata in FLAC files. It
  91861. * allows the user to add, delete, and modify FLAC metadata blocks
  91862. * and it can automatically take advantage of PADDING blocks to avoid
  91863. * rewriting the entire FLAC file when changing the size of the
  91864. * metadata.
  91865. *
  91866. * libFLAC usually only requires the standard C library and C math
  91867. * library. In particular, threading is not used so there is no
  91868. * dependency on a thread library. However, libFLAC does not use
  91869. * global variables and should be thread-safe.
  91870. *
  91871. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  91872. * However the metadata editing interfaces currently have limited
  91873. * read-only support for Ogg FLAC files.
  91874. *
  91875. * \section cpp_api FLAC C++ API
  91876. *
  91877. * The FLAC C++ API is a set of classes that encapsulate the
  91878. * structures and functions in libFLAC. They provide slightly more
  91879. * functionality with respect to metadata but are otherwise
  91880. * equivalent. For the most part, they share the same usage as
  91881. * their counterparts in libFLAC, and the FLAC C API documentation
  91882. * can be used as a supplement. The public include files
  91883. * for the C++ API will be installed in your include area (for
  91884. * example /usr/include/FLAC++/...).
  91885. *
  91886. * libFLAC++ is also licensed under
  91887. * <A HREF="../license.html">Xiph's BSD license</A>.
  91888. *
  91889. * \section getting_started Getting Started
  91890. *
  91891. * A good starting point for learning the API is to browse through
  91892. * the <A HREF="modules.html">modules</A>. Modules are logical
  91893. * groupings of related functions or classes, which correspond roughly
  91894. * to header files or sections of header files. Each module includes a
  91895. * detailed description of the general usage of its functions or
  91896. * classes.
  91897. *
  91898. * From there you can go on to look at the documentation of
  91899. * individual functions. You can see different views of the individual
  91900. * functions through the links in top bar across this page.
  91901. *
  91902. * If you prefer a more hands-on approach, you can jump right to some
  91903. * <A HREF="../documentation_example_code.html">example code</A>.
  91904. *
  91905. * \section porting_guide Porting Guide
  91906. *
  91907. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  91908. * has been introduced which gives detailed instructions on how to
  91909. * port your code to newer versions of FLAC.
  91910. *
  91911. * \section embedded_developers Embedded Developers
  91912. *
  91913. * libFLAC has grown larger over time as more functionality has been
  91914. * included, but much of it may be unnecessary for a particular embedded
  91915. * implementation. Unused parts may be pruned by some simple editing of
  91916. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  91917. * metadata interface are all independent from each other.
  91918. *
  91919. * It is easiest to just describe the dependencies:
  91920. *
  91921. * - All modules depend on the \link flac_format Format \endlink module.
  91922. * - The decoders and encoders depend on the bitbuffer.
  91923. * - The decoder is independent of the encoder. The encoder uses the
  91924. * decoder because of the verify feature, but this can be removed if
  91925. * not needed.
  91926. * - Parts of the metadata interface require the stream decoder (but not
  91927. * the encoder).
  91928. * - Ogg support is selectable through the compile time macro
  91929. * \c FLAC__HAS_OGG.
  91930. *
  91931. * For example, if your application only requires the stream decoder, no
  91932. * encoder, and no metadata interface, you can remove the stream encoder
  91933. * and the metadata interface, which will greatly reduce the size of the
  91934. * library.
  91935. *
  91936. * Also, there are several places in the libFLAC code with comments marked
  91937. * with "OPT:" where a #define can be changed to enable code that might be
  91938. * faster on a specific platform. Experimenting with these can yield faster
  91939. * binaries.
  91940. */
  91941. /** \defgroup porting Porting Guide for New Versions
  91942. *
  91943. * This module describes differences in the library interfaces from
  91944. * version to version. It assists in the porting of code that uses
  91945. * the libraries to newer versions of FLAC.
  91946. *
  91947. * One simple facility for making porting easier that has been added
  91948. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  91949. * library's includes (e.g. \c include/FLAC/export.h). The
  91950. * \c #defines mirror the libraries'
  91951. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  91952. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  91953. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  91954. * These can be used to support multiple versions of an API during the
  91955. * transition phase, e.g.
  91956. *
  91957. * \code
  91958. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  91959. * legacy code
  91960. * #else
  91961. * new code
  91962. * #endif
  91963. * \endcode
  91964. *
  91965. * The the source will work for multiple versions and the legacy code can
  91966. * easily be removed when the transition is complete.
  91967. *
  91968. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  91969. * include/FLAC/export.h), which can be used to determine whether or not
  91970. * the library has been compiled with support for Ogg FLAC. This is
  91971. * simpler than trying to call an Ogg init function and catching the
  91972. * error.
  91973. */
  91974. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  91975. * \ingroup porting
  91976. *
  91977. * \brief
  91978. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  91979. *
  91980. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  91981. * been simplified. First, libOggFLAC has been merged into libFLAC and
  91982. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  91983. * decoding layers and three encoding layers have been merged into a
  91984. * single stream decoder and stream encoder. That is, the functionality
  91985. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  91986. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  91987. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  91988. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  91989. * is there is now a single API that can be used to encode or decode
  91990. * streams to/from native FLAC or Ogg FLAC and the single API can work
  91991. * on both seekable and non-seekable streams.
  91992. *
  91993. * Instead of creating an encoder or decoder of a certain layer, now the
  91994. * client will always create a FLAC__StreamEncoder or
  91995. * FLAC__StreamDecoder. The old layers are now differentiated by the
  91996. * initialization function. For example, for the decoder,
  91997. * FLAC__stream_decoder_init() has been replaced by
  91998. * FLAC__stream_decoder_init_stream(). This init function takes
  91999. * callbacks for the I/O, and the seeking callbacks are optional. This
  92000. * allows the client to use the same object for seekable and
  92001. * non-seekable streams. For decoding a FLAC file directly, the client
  92002. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92003. * and fewer callbacks; most of the other callbacks are supplied
  92004. * internally. For situations where fopen()ing by filename is not
  92005. * possible (e.g. Unicode filenames on Windows) the client can instead
  92006. * open the file itself and supply the FILE* to
  92007. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92008. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92009. * Since the callbacks and client data are now passed to the init
  92010. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92011. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92012. * rest of the calls to the decoder are the same as before.
  92013. *
  92014. * There are counterpart init functions for Ogg FLAC, e.g.
  92015. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92016. * and callbacks are the same as for native FLAC.
  92017. *
  92018. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92019. * been set up like so:
  92020. *
  92021. * \code
  92022. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92023. * if(decoder == NULL) do_something;
  92024. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92025. * [... other settings ...]
  92026. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92027. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92028. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92029. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92030. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92031. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92032. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92033. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92034. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92035. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92036. * \endcode
  92037. *
  92038. * In FLAC 1.1.3 it is like this:
  92039. *
  92040. * \code
  92041. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92042. * if(decoder == NULL) do_something;
  92043. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92044. * [... other settings ...]
  92045. * if(FLAC__stream_decoder_init_stream(
  92046. * decoder,
  92047. * my_read_callback,
  92048. * my_seek_callback, // or NULL
  92049. * my_tell_callback, // or NULL
  92050. * my_length_callback, // or NULL
  92051. * my_eof_callback, // or NULL
  92052. * my_write_callback,
  92053. * my_metadata_callback, // or NULL
  92054. * my_error_callback,
  92055. * my_client_data
  92056. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92057. * \endcode
  92058. *
  92059. * or you could do;
  92060. *
  92061. * \code
  92062. * [...]
  92063. * FILE *file = fopen("somefile.flac","rb");
  92064. * if(file == NULL) do_somthing;
  92065. * if(FLAC__stream_decoder_init_FILE(
  92066. * decoder,
  92067. * file,
  92068. * my_write_callback,
  92069. * my_metadata_callback, // or NULL
  92070. * my_error_callback,
  92071. * my_client_data
  92072. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92073. * \endcode
  92074. *
  92075. * or just:
  92076. *
  92077. * \code
  92078. * [...]
  92079. * if(FLAC__stream_decoder_init_file(
  92080. * decoder,
  92081. * "somefile.flac",
  92082. * my_write_callback,
  92083. * my_metadata_callback, // or NULL
  92084. * my_error_callback,
  92085. * my_client_data
  92086. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92087. * \endcode
  92088. *
  92089. * Another small change to the decoder is in how it handles unparseable
  92090. * streams. Before, when the decoder found an unparseable stream
  92091. * (reserved for when the decoder encounters a stream from a future
  92092. * encoder that it can't parse), it changed the state to
  92093. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92094. * drops sync and calls the error callback with a new error code
  92095. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92096. * more robust. If your error callback does not discriminate on the the
  92097. * error state, your code does not need to be changed.
  92098. *
  92099. * The encoder now has a new setting:
  92100. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92101. * method used to window the data before LPC analysis. You only need to
  92102. * add a call to this function if the default is not suitable. There
  92103. * are also two new convenience functions that may be useful:
  92104. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92105. * FLAC__metadata_get_cuesheet().
  92106. *
  92107. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92108. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92109. * is now \c size_t instead of \c unsigned.
  92110. */
  92111. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92112. * \ingroup porting
  92113. *
  92114. * \brief
  92115. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92116. *
  92117. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92118. * There was a slight change in the implementation of
  92119. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92120. * of the \a metadata array of pointers so the client no longer needs
  92121. * to maintain it after the call. The objects themselves that are
  92122. * pointed to by the array are still not copied though and must be
  92123. * maintained until the call to FLAC__stream_encoder_finish().
  92124. */
  92125. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92126. * \ingroup porting
  92127. *
  92128. * \brief
  92129. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92130. *
  92131. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92132. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92133. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92134. *
  92135. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92136. * has changed to reflect the conversion of one of the reserved bits
  92137. * into active use. It used to be \c 2 and now is \c 1. However the
  92138. * FLAC frame header length has not changed, so to skip the proper
  92139. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92140. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92141. */
  92142. /** \defgroup flac FLAC C API
  92143. *
  92144. * The FLAC C API is the interface to libFLAC, a set of structures
  92145. * describing the components of FLAC streams, and functions for
  92146. * encoding and decoding streams, as well as manipulating FLAC
  92147. * metadata in files.
  92148. *
  92149. * You should start with the format components as all other modules
  92150. * are dependent on it.
  92151. */
  92152. #endif
  92153. /*** End of inlined file: all.h ***/
  92154. /*** Start of inlined file: bitmath.c ***/
  92155. /*** Start of inlined file: juce_FlacHeader.h ***/
  92156. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92157. // tasks..
  92158. #define VERSION "1.2.1"
  92159. #define FLAC__NO_DLL 1
  92160. #if JUCE_MSVC
  92161. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92162. #endif
  92163. #if JUCE_MAC
  92164. #define FLAC__SYS_DARWIN 1
  92165. #endif
  92166. /*** End of inlined file: juce_FlacHeader.h ***/
  92167. #if JUCE_USE_FLAC
  92168. #if HAVE_CONFIG_H
  92169. # include <config.h>
  92170. #endif
  92171. /*** Start of inlined file: bitmath.h ***/
  92172. #ifndef FLAC__PRIVATE__BITMATH_H
  92173. #define FLAC__PRIVATE__BITMATH_H
  92174. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92175. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92176. unsigned FLAC__bitmath_silog2(int v);
  92177. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92178. #endif
  92179. /*** End of inlined file: bitmath.h ***/
  92180. /* An example of what FLAC__bitmath_ilog2() computes:
  92181. *
  92182. * ilog2( 0) = assertion failure
  92183. * ilog2( 1) = 0
  92184. * ilog2( 2) = 1
  92185. * ilog2( 3) = 1
  92186. * ilog2( 4) = 2
  92187. * ilog2( 5) = 2
  92188. * ilog2( 6) = 2
  92189. * ilog2( 7) = 2
  92190. * ilog2( 8) = 3
  92191. * ilog2( 9) = 3
  92192. * ilog2(10) = 3
  92193. * ilog2(11) = 3
  92194. * ilog2(12) = 3
  92195. * ilog2(13) = 3
  92196. * ilog2(14) = 3
  92197. * ilog2(15) = 3
  92198. * ilog2(16) = 4
  92199. * ilog2(17) = 4
  92200. * ilog2(18) = 4
  92201. */
  92202. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92203. {
  92204. unsigned l = 0;
  92205. FLAC__ASSERT(v > 0);
  92206. while(v >>= 1)
  92207. l++;
  92208. return l;
  92209. }
  92210. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92211. {
  92212. unsigned l = 0;
  92213. FLAC__ASSERT(v > 0);
  92214. while(v >>= 1)
  92215. l++;
  92216. return l;
  92217. }
  92218. /* An example of what FLAC__bitmath_silog2() computes:
  92219. *
  92220. * silog2(-10) = 5
  92221. * silog2(- 9) = 5
  92222. * silog2(- 8) = 4
  92223. * silog2(- 7) = 4
  92224. * silog2(- 6) = 4
  92225. * silog2(- 5) = 4
  92226. * silog2(- 4) = 3
  92227. * silog2(- 3) = 3
  92228. * silog2(- 2) = 2
  92229. * silog2(- 1) = 2
  92230. * silog2( 0) = 0
  92231. * silog2( 1) = 2
  92232. * silog2( 2) = 3
  92233. * silog2( 3) = 3
  92234. * silog2( 4) = 4
  92235. * silog2( 5) = 4
  92236. * silog2( 6) = 4
  92237. * silog2( 7) = 4
  92238. * silog2( 8) = 5
  92239. * silog2( 9) = 5
  92240. * silog2( 10) = 5
  92241. */
  92242. unsigned FLAC__bitmath_silog2(int v)
  92243. {
  92244. while(1) {
  92245. if(v == 0) {
  92246. return 0;
  92247. }
  92248. else if(v > 0) {
  92249. unsigned l = 0;
  92250. while(v) {
  92251. l++;
  92252. v >>= 1;
  92253. }
  92254. return l+1;
  92255. }
  92256. else if(v == -1) {
  92257. return 2;
  92258. }
  92259. else {
  92260. v++;
  92261. v = -v;
  92262. }
  92263. }
  92264. }
  92265. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92266. {
  92267. while(1) {
  92268. if(v == 0) {
  92269. return 0;
  92270. }
  92271. else if(v > 0) {
  92272. unsigned l = 0;
  92273. while(v) {
  92274. l++;
  92275. v >>= 1;
  92276. }
  92277. return l+1;
  92278. }
  92279. else if(v == -1) {
  92280. return 2;
  92281. }
  92282. else {
  92283. v++;
  92284. v = -v;
  92285. }
  92286. }
  92287. }
  92288. #endif
  92289. /*** End of inlined file: bitmath.c ***/
  92290. /*** Start of inlined file: bitreader.c ***/
  92291. /*** Start of inlined file: juce_FlacHeader.h ***/
  92292. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92293. // tasks..
  92294. #define VERSION "1.2.1"
  92295. #define FLAC__NO_DLL 1
  92296. #if JUCE_MSVC
  92297. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92298. #endif
  92299. #if JUCE_MAC
  92300. #define FLAC__SYS_DARWIN 1
  92301. #endif
  92302. /*** End of inlined file: juce_FlacHeader.h ***/
  92303. #if JUCE_USE_FLAC
  92304. #if HAVE_CONFIG_H
  92305. # include <config.h>
  92306. #endif
  92307. #include <stdlib.h> /* for malloc() */
  92308. #include <string.h> /* for memcpy(), memset() */
  92309. #ifdef _MSC_VER
  92310. #include <winsock.h> /* for ntohl() */
  92311. #elif defined FLAC__SYS_DARWIN
  92312. #include <machine/endian.h> /* for ntohl() */
  92313. #elif defined __MINGW32__
  92314. #include <winsock.h> /* for ntohl() */
  92315. #else
  92316. #include <netinet/in.h> /* for ntohl() */
  92317. #endif
  92318. /*** Start of inlined file: bitreader.h ***/
  92319. #ifndef FLAC__PRIVATE__BITREADER_H
  92320. #define FLAC__PRIVATE__BITREADER_H
  92321. #include <stdio.h> /* for FILE */
  92322. /*** Start of inlined file: cpu.h ***/
  92323. #ifndef FLAC__PRIVATE__CPU_H
  92324. #define FLAC__PRIVATE__CPU_H
  92325. #ifdef HAVE_CONFIG_H
  92326. #include <config.h>
  92327. #endif
  92328. typedef enum {
  92329. FLAC__CPUINFO_TYPE_IA32,
  92330. FLAC__CPUINFO_TYPE_PPC,
  92331. FLAC__CPUINFO_TYPE_UNKNOWN
  92332. } FLAC__CPUInfo_Type;
  92333. typedef struct {
  92334. FLAC__bool cpuid;
  92335. FLAC__bool bswap;
  92336. FLAC__bool cmov;
  92337. FLAC__bool mmx;
  92338. FLAC__bool fxsr;
  92339. FLAC__bool sse;
  92340. FLAC__bool sse2;
  92341. FLAC__bool sse3;
  92342. FLAC__bool ssse3;
  92343. FLAC__bool _3dnow;
  92344. FLAC__bool ext3dnow;
  92345. FLAC__bool extmmx;
  92346. } FLAC__CPUInfo_IA32;
  92347. typedef struct {
  92348. FLAC__bool altivec;
  92349. FLAC__bool ppc64;
  92350. } FLAC__CPUInfo_PPC;
  92351. typedef struct {
  92352. FLAC__bool use_asm;
  92353. FLAC__CPUInfo_Type type;
  92354. union {
  92355. FLAC__CPUInfo_IA32 ia32;
  92356. FLAC__CPUInfo_PPC ppc;
  92357. } data;
  92358. } FLAC__CPUInfo;
  92359. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92360. #ifndef FLAC__NO_ASM
  92361. #ifdef FLAC__CPU_IA32
  92362. #ifdef FLAC__HAS_NASM
  92363. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92364. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92365. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92366. #endif
  92367. #endif
  92368. #endif
  92369. #endif
  92370. /*** End of inlined file: cpu.h ***/
  92371. /*
  92372. * opaque structure definition
  92373. */
  92374. struct FLAC__BitReader;
  92375. typedef struct FLAC__BitReader FLAC__BitReader;
  92376. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92377. /*
  92378. * construction, deletion, initialization, etc functions
  92379. */
  92380. FLAC__BitReader *FLAC__bitreader_new(void);
  92381. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92382. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92383. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92384. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92385. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92386. /*
  92387. * CRC functions
  92388. */
  92389. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92390. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92391. /*
  92392. * info functions
  92393. */
  92394. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92395. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92396. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92397. /*
  92398. * read functions
  92399. */
  92400. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92401. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92402. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92403. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92404. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92405. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92406. 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! */
  92407. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92408. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92409. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92410. #ifndef FLAC__NO_ASM
  92411. # ifdef FLAC__CPU_IA32
  92412. # ifdef FLAC__HAS_NASM
  92413. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92414. # endif
  92415. # endif
  92416. #endif
  92417. #if 0 /* UNUSED */
  92418. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92419. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92420. #endif
  92421. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92422. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92423. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92424. #endif
  92425. /*** End of inlined file: bitreader.h ***/
  92426. /*** Start of inlined file: crc.h ***/
  92427. #ifndef FLAC__PRIVATE__CRC_H
  92428. #define FLAC__PRIVATE__CRC_H
  92429. /* 8 bit CRC generator, MSB shifted first
  92430. ** polynomial = x^8 + x^2 + x^1 + x^0
  92431. ** init = 0
  92432. */
  92433. extern FLAC__byte const FLAC__crc8_table[256];
  92434. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92435. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92436. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92437. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92438. /* 16 bit CRC generator, MSB shifted first
  92439. ** polynomial = x^16 + x^15 + x^2 + x^0
  92440. ** init = 0
  92441. */
  92442. extern unsigned FLAC__crc16_table[256];
  92443. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92444. /* this alternate may be faster on some systems/compilers */
  92445. #if 0
  92446. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92447. #endif
  92448. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92449. #endif
  92450. /*** End of inlined file: crc.h ***/
  92451. /* Things should be fastest when this matches the machine word size */
  92452. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92453. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92454. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92455. typedef FLAC__uint32 brword;
  92456. #define FLAC__BYTES_PER_WORD 4
  92457. #define FLAC__BITS_PER_WORD 32
  92458. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92459. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92460. #if WORDS_BIGENDIAN
  92461. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92462. #else
  92463. #if defined (_MSC_VER) && defined (_X86_)
  92464. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92465. #else
  92466. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92467. #endif
  92468. #endif
  92469. /* counts the # of zero MSBs in a word */
  92470. #define COUNT_ZERO_MSBS(word) ( \
  92471. (word) <= 0xffff ? \
  92472. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92473. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92474. )
  92475. /* this alternate might be slightly faster on some systems/compilers: */
  92476. #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])) )
  92477. /*
  92478. * This should be at least twice as large as the largest number of words
  92479. * required to represent any 'number' (in any encoding) you are going to
  92480. * read. With FLAC this is on the order of maybe a few hundred bits.
  92481. * If the buffer is smaller than that, the decoder won't be able to read
  92482. * in a whole number that is in a variable length encoding (e.g. Rice).
  92483. * But to be practical it should be at least 1K bytes.
  92484. *
  92485. * Increase this number to decrease the number of read callbacks, at the
  92486. * expense of using more memory. Or decrease for the reverse effect,
  92487. * keeping in mind the limit from the first paragraph. The optimal size
  92488. * also depends on the CPU cache size and other factors; some twiddling
  92489. * may be necessary to squeeze out the best performance.
  92490. */
  92491. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92492. static const unsigned char byte_to_unary_table[] = {
  92493. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92494. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92495. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92496. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92497. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92498. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92499. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92500. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92509. };
  92510. #ifdef min
  92511. #undef min
  92512. #endif
  92513. #define min(x,y) ((x)<(y)?(x):(y))
  92514. #ifdef max
  92515. #undef max
  92516. #endif
  92517. #define max(x,y) ((x)>(y)?(x):(y))
  92518. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92519. #ifdef _MSC_VER
  92520. #define FLAC__U64L(x) x
  92521. #else
  92522. #define FLAC__U64L(x) x##LLU
  92523. #endif
  92524. #ifndef FLaC__INLINE
  92525. #define FLaC__INLINE
  92526. #endif
  92527. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92528. struct FLAC__BitReader {
  92529. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92530. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92531. brword *buffer;
  92532. unsigned capacity; /* in words */
  92533. unsigned words; /* # of completed words in buffer */
  92534. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92535. unsigned consumed_words; /* #words ... */
  92536. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92537. unsigned read_crc16; /* the running frame CRC */
  92538. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92539. FLAC__BitReaderReadCallback read_callback;
  92540. void *client_data;
  92541. FLAC__CPUInfo cpu_info;
  92542. };
  92543. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92544. {
  92545. register unsigned crc = br->read_crc16;
  92546. #if FLAC__BYTES_PER_WORD == 4
  92547. switch(br->crc16_align) {
  92548. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92549. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92550. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92551. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92552. }
  92553. #elif FLAC__BYTES_PER_WORD == 8
  92554. switch(br->crc16_align) {
  92555. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92556. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92557. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92558. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92559. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92560. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92561. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92562. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92563. }
  92564. #else
  92565. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92566. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92567. br->read_crc16 = crc;
  92568. #endif
  92569. br->crc16_align = 0;
  92570. }
  92571. /* would be static except it needs to be called by asm routines */
  92572. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92573. {
  92574. unsigned start, end;
  92575. size_t bytes;
  92576. FLAC__byte *target;
  92577. /* first shift the unconsumed buffer data toward the front as much as possible */
  92578. if(br->consumed_words > 0) {
  92579. start = br->consumed_words;
  92580. end = br->words + (br->bytes? 1:0);
  92581. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92582. br->words -= start;
  92583. br->consumed_words = 0;
  92584. }
  92585. /*
  92586. * set the target for reading, taking into account word alignment and endianness
  92587. */
  92588. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92589. if(bytes == 0)
  92590. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92591. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92592. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92593. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92594. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92595. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92596. * ^^-------target, bytes=3
  92597. * on LE machines, have to byteswap the odd tail word so nothing is
  92598. * overwritten:
  92599. */
  92600. #if WORDS_BIGENDIAN
  92601. #else
  92602. if(br->bytes)
  92603. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92604. #endif
  92605. /* now it looks like:
  92606. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92607. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92608. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92609. * ^^-------target, bytes=3
  92610. */
  92611. /* read in the data; note that the callback may return a smaller number of bytes */
  92612. if(!br->read_callback(target, &bytes, br->client_data))
  92613. return false;
  92614. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92615. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92616. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92617. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92618. * now have to byteswap on LE machines:
  92619. */
  92620. #if WORDS_BIGENDIAN
  92621. #else
  92622. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92623. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92624. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92625. start = br->words;
  92626. local_swap32_block_(br->buffer + start, end - start);
  92627. }
  92628. else
  92629. # endif
  92630. for(start = br->words; start < end; start++)
  92631. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92632. #endif
  92633. /* now it looks like:
  92634. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92635. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92636. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92637. * finally we'll update the reader values:
  92638. */
  92639. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92640. br->words = end / FLAC__BYTES_PER_WORD;
  92641. br->bytes = end % FLAC__BYTES_PER_WORD;
  92642. return true;
  92643. }
  92644. /***********************************************************************
  92645. *
  92646. * Class constructor/destructor
  92647. *
  92648. ***********************************************************************/
  92649. FLAC__BitReader *FLAC__bitreader_new(void)
  92650. {
  92651. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92652. /* calloc() implies:
  92653. memset(br, 0, sizeof(FLAC__BitReader));
  92654. br->buffer = 0;
  92655. br->capacity = 0;
  92656. br->words = br->bytes = 0;
  92657. br->consumed_words = br->consumed_bits = 0;
  92658. br->read_callback = 0;
  92659. br->client_data = 0;
  92660. */
  92661. return br;
  92662. }
  92663. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92664. {
  92665. FLAC__ASSERT(0 != br);
  92666. FLAC__bitreader_free(br);
  92667. free(br);
  92668. }
  92669. /***********************************************************************
  92670. *
  92671. * Public class methods
  92672. *
  92673. ***********************************************************************/
  92674. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92675. {
  92676. FLAC__ASSERT(0 != br);
  92677. br->words = br->bytes = 0;
  92678. br->consumed_words = br->consumed_bits = 0;
  92679. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92680. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92681. if(br->buffer == 0)
  92682. return false;
  92683. br->read_callback = rcb;
  92684. br->client_data = cd;
  92685. br->cpu_info = cpu;
  92686. return true;
  92687. }
  92688. void FLAC__bitreader_free(FLAC__BitReader *br)
  92689. {
  92690. FLAC__ASSERT(0 != br);
  92691. if(0 != br->buffer)
  92692. free(br->buffer);
  92693. br->buffer = 0;
  92694. br->capacity = 0;
  92695. br->words = br->bytes = 0;
  92696. br->consumed_words = br->consumed_bits = 0;
  92697. br->read_callback = 0;
  92698. br->client_data = 0;
  92699. }
  92700. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92701. {
  92702. br->words = br->bytes = 0;
  92703. br->consumed_words = br->consumed_bits = 0;
  92704. return true;
  92705. }
  92706. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92707. {
  92708. unsigned i, j;
  92709. if(br == 0) {
  92710. fprintf(out, "bitreader is NULL\n");
  92711. }
  92712. else {
  92713. 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);
  92714. for(i = 0; i < br->words; i++) {
  92715. fprintf(out, "%08X: ", i);
  92716. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92717. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92718. fprintf(out, ".");
  92719. else
  92720. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92721. fprintf(out, "\n");
  92722. }
  92723. if(br->bytes > 0) {
  92724. fprintf(out, "%08X: ", i);
  92725. for(j = 0; j < br->bytes*8; j++)
  92726. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92727. fprintf(out, ".");
  92728. else
  92729. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92730. fprintf(out, "\n");
  92731. }
  92732. }
  92733. }
  92734. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92735. {
  92736. FLAC__ASSERT(0 != br);
  92737. FLAC__ASSERT(0 != br->buffer);
  92738. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92739. br->read_crc16 = (unsigned)seed;
  92740. br->crc16_align = br->consumed_bits;
  92741. }
  92742. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92743. {
  92744. FLAC__ASSERT(0 != br);
  92745. FLAC__ASSERT(0 != br->buffer);
  92746. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92747. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92748. /* CRC any tail bytes in a partially-consumed word */
  92749. if(br->consumed_bits) {
  92750. const brword tail = br->buffer[br->consumed_words];
  92751. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92752. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92753. }
  92754. return br->read_crc16;
  92755. }
  92756. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92757. {
  92758. return ((br->consumed_bits & 7) == 0);
  92759. }
  92760. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92761. {
  92762. return 8 - (br->consumed_bits & 7);
  92763. }
  92764. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92765. {
  92766. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92767. }
  92768. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92769. {
  92770. FLAC__ASSERT(0 != br);
  92771. FLAC__ASSERT(0 != br->buffer);
  92772. FLAC__ASSERT(bits <= 32);
  92773. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92774. FLAC__ASSERT(br->consumed_words <= br->words);
  92775. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92776. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92777. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92778. *val = 0;
  92779. return true;
  92780. }
  92781. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92782. if(!bitreader_read_from_client_(br))
  92783. return false;
  92784. }
  92785. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92786. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92787. if(br->consumed_bits) {
  92788. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92789. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92790. const brword word = br->buffer[br->consumed_words];
  92791. if(bits < n) {
  92792. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  92793. br->consumed_bits += bits;
  92794. return true;
  92795. }
  92796. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  92797. bits -= n;
  92798. crc16_update_word_(br, word);
  92799. br->consumed_words++;
  92800. br->consumed_bits = 0;
  92801. 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 */
  92802. *val <<= bits;
  92803. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  92804. br->consumed_bits = bits;
  92805. }
  92806. return true;
  92807. }
  92808. else {
  92809. const brword word = br->buffer[br->consumed_words];
  92810. if(bits < FLAC__BITS_PER_WORD) {
  92811. *val = word >> (FLAC__BITS_PER_WORD-bits);
  92812. br->consumed_bits = bits;
  92813. return true;
  92814. }
  92815. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  92816. *val = word;
  92817. crc16_update_word_(br, word);
  92818. br->consumed_words++;
  92819. return true;
  92820. }
  92821. }
  92822. else {
  92823. /* in this case we're starting our read at a partial tail word;
  92824. * the reader has guaranteed that we have at least 'bits' bits
  92825. * available to read, which makes this case simpler.
  92826. */
  92827. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92828. if(br->consumed_bits) {
  92829. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92830. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  92831. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  92832. br->consumed_bits += bits;
  92833. return true;
  92834. }
  92835. else {
  92836. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  92837. br->consumed_bits += bits;
  92838. return true;
  92839. }
  92840. }
  92841. }
  92842. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  92843. {
  92844. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  92845. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  92846. return false;
  92847. /* sign-extend: */
  92848. *val <<= (32-bits);
  92849. *val >>= (32-bits);
  92850. return true;
  92851. }
  92852. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  92853. {
  92854. FLAC__uint32 hi, lo;
  92855. if(bits > 32) {
  92856. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  92857. return false;
  92858. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  92859. return false;
  92860. *val = hi;
  92861. *val <<= 32;
  92862. *val |= lo;
  92863. }
  92864. else {
  92865. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  92866. return false;
  92867. *val = lo;
  92868. }
  92869. return true;
  92870. }
  92871. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  92872. {
  92873. FLAC__uint32 x8, x32 = 0;
  92874. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  92875. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  92876. return false;
  92877. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92878. return false;
  92879. x32 |= (x8 << 8);
  92880. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92881. return false;
  92882. x32 |= (x8 << 16);
  92883. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92884. return false;
  92885. x32 |= (x8 << 24);
  92886. *val = x32;
  92887. return true;
  92888. }
  92889. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  92890. {
  92891. /*
  92892. * OPT: a faster implementation is possible but probably not that useful
  92893. * since this is only called a couple of times in the metadata readers.
  92894. */
  92895. FLAC__ASSERT(0 != br);
  92896. FLAC__ASSERT(0 != br->buffer);
  92897. if(bits > 0) {
  92898. const unsigned n = br->consumed_bits & 7;
  92899. unsigned m;
  92900. FLAC__uint32 x;
  92901. if(n != 0) {
  92902. m = min(8-n, bits);
  92903. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  92904. return false;
  92905. bits -= m;
  92906. }
  92907. m = bits / 8;
  92908. if(m > 0) {
  92909. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  92910. return false;
  92911. bits %= 8;
  92912. }
  92913. if(bits > 0) {
  92914. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  92915. return false;
  92916. }
  92917. }
  92918. return true;
  92919. }
  92920. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  92921. {
  92922. FLAC__uint32 x;
  92923. FLAC__ASSERT(0 != br);
  92924. FLAC__ASSERT(0 != br->buffer);
  92925. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92926. /* step 1: skip over partial head word to get word aligned */
  92927. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92928. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92929. return false;
  92930. nvals--;
  92931. }
  92932. if(0 == nvals)
  92933. return true;
  92934. /* step 2: skip whole words in chunks */
  92935. while(nvals >= FLAC__BYTES_PER_WORD) {
  92936. if(br->consumed_words < br->words) {
  92937. br->consumed_words++;
  92938. nvals -= FLAC__BYTES_PER_WORD;
  92939. }
  92940. else if(!bitreader_read_from_client_(br))
  92941. return false;
  92942. }
  92943. /* step 3: skip any remainder from partial tail bytes */
  92944. while(nvals) {
  92945. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92946. return false;
  92947. nvals--;
  92948. }
  92949. return true;
  92950. }
  92951. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  92952. {
  92953. FLAC__uint32 x;
  92954. FLAC__ASSERT(0 != br);
  92955. FLAC__ASSERT(0 != br->buffer);
  92956. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92957. /* step 1: read from partial head word to get word aligned */
  92958. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92959. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92960. return false;
  92961. *val++ = (FLAC__byte)x;
  92962. nvals--;
  92963. }
  92964. if(0 == nvals)
  92965. return true;
  92966. /* step 2: read whole words in chunks */
  92967. while(nvals >= FLAC__BYTES_PER_WORD) {
  92968. if(br->consumed_words < br->words) {
  92969. const brword word = br->buffer[br->consumed_words++];
  92970. #if FLAC__BYTES_PER_WORD == 4
  92971. val[0] = (FLAC__byte)(word >> 24);
  92972. val[1] = (FLAC__byte)(word >> 16);
  92973. val[2] = (FLAC__byte)(word >> 8);
  92974. val[3] = (FLAC__byte)word;
  92975. #elif FLAC__BYTES_PER_WORD == 8
  92976. val[0] = (FLAC__byte)(word >> 56);
  92977. val[1] = (FLAC__byte)(word >> 48);
  92978. val[2] = (FLAC__byte)(word >> 40);
  92979. val[3] = (FLAC__byte)(word >> 32);
  92980. val[4] = (FLAC__byte)(word >> 24);
  92981. val[5] = (FLAC__byte)(word >> 16);
  92982. val[6] = (FLAC__byte)(word >> 8);
  92983. val[7] = (FLAC__byte)word;
  92984. #else
  92985. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  92986. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  92987. #endif
  92988. val += FLAC__BYTES_PER_WORD;
  92989. nvals -= FLAC__BYTES_PER_WORD;
  92990. }
  92991. else if(!bitreader_read_from_client_(br))
  92992. return false;
  92993. }
  92994. /* step 3: read any remainder from partial tail bytes */
  92995. while(nvals) {
  92996. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92997. return false;
  92998. *val++ = (FLAC__byte)x;
  92999. nvals--;
  93000. }
  93001. return true;
  93002. }
  93003. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93004. #if 0 /* slow but readable version */
  93005. {
  93006. unsigned bit;
  93007. FLAC__ASSERT(0 != br);
  93008. FLAC__ASSERT(0 != br->buffer);
  93009. *val = 0;
  93010. while(1) {
  93011. if(!FLAC__bitreader_read_bit(br, &bit))
  93012. return false;
  93013. if(bit)
  93014. break;
  93015. else
  93016. *val++;
  93017. }
  93018. return true;
  93019. }
  93020. #else
  93021. {
  93022. unsigned i;
  93023. FLAC__ASSERT(0 != br);
  93024. FLAC__ASSERT(0 != br->buffer);
  93025. *val = 0;
  93026. while(1) {
  93027. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93028. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93029. if(b) {
  93030. i = COUNT_ZERO_MSBS(b);
  93031. *val += i;
  93032. i++;
  93033. br->consumed_bits += i;
  93034. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93035. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93036. br->consumed_words++;
  93037. br->consumed_bits = 0;
  93038. }
  93039. return true;
  93040. }
  93041. else {
  93042. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93043. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93044. br->consumed_words++;
  93045. br->consumed_bits = 0;
  93046. /* didn't find stop bit yet, have to keep going... */
  93047. }
  93048. }
  93049. /* at this point we've eaten up all the whole words; have to try
  93050. * reading through any tail bytes before calling the read callback.
  93051. * this is a repeat of the above logic adjusted for the fact we
  93052. * don't have a whole word. note though if the client is feeding
  93053. * us data a byte at a time (unlikely), br->consumed_bits may not
  93054. * be zero.
  93055. */
  93056. if(br->bytes) {
  93057. const unsigned end = br->bytes * 8;
  93058. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93059. if(b) {
  93060. i = COUNT_ZERO_MSBS(b);
  93061. *val += i;
  93062. i++;
  93063. br->consumed_bits += i;
  93064. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93065. return true;
  93066. }
  93067. else {
  93068. *val += end - br->consumed_bits;
  93069. br->consumed_bits += end;
  93070. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93071. /* didn't find stop bit yet, have to keep going... */
  93072. }
  93073. }
  93074. if(!bitreader_read_from_client_(br))
  93075. return false;
  93076. }
  93077. }
  93078. #endif
  93079. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93080. {
  93081. FLAC__uint32 lsbs = 0, msbs = 0;
  93082. unsigned uval;
  93083. FLAC__ASSERT(0 != br);
  93084. FLAC__ASSERT(0 != br->buffer);
  93085. FLAC__ASSERT(parameter <= 31);
  93086. /* read the unary MSBs and end bit */
  93087. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93088. return false;
  93089. /* read the binary LSBs */
  93090. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93091. return false;
  93092. /* compose the value */
  93093. uval = (msbs << parameter) | lsbs;
  93094. if(uval & 1)
  93095. *val = -((int)(uval >> 1)) - 1;
  93096. else
  93097. *val = (int)(uval >> 1);
  93098. return true;
  93099. }
  93100. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93101. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93102. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93103. /* OPT: possibly faster version for use with MSVC */
  93104. #ifdef _MSC_VER
  93105. {
  93106. unsigned i;
  93107. unsigned uval = 0;
  93108. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93109. /* try and get br->consumed_words and br->consumed_bits into register;
  93110. * must remember to flush them back to *br before calling other
  93111. * bitwriter functions that use them, and before returning */
  93112. register unsigned cwords;
  93113. register unsigned cbits;
  93114. FLAC__ASSERT(0 != br);
  93115. FLAC__ASSERT(0 != br->buffer);
  93116. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93117. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93118. FLAC__ASSERT(parameter < 32);
  93119. /* 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 */
  93120. if(nvals == 0)
  93121. return true;
  93122. cbits = br->consumed_bits;
  93123. cwords = br->consumed_words;
  93124. while(1) {
  93125. /* read unary part */
  93126. while(1) {
  93127. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93128. brword b = br->buffer[cwords] << cbits;
  93129. if(b) {
  93130. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93131. __asm {
  93132. bsr eax, b
  93133. not eax
  93134. and eax, 31
  93135. mov i, eax
  93136. }
  93137. #else
  93138. i = COUNT_ZERO_MSBS(b);
  93139. #endif
  93140. uval += i;
  93141. bits = parameter;
  93142. i++;
  93143. cbits += i;
  93144. if(cbits == FLAC__BITS_PER_WORD) {
  93145. crc16_update_word_(br, br->buffer[cwords]);
  93146. cwords++;
  93147. cbits = 0;
  93148. }
  93149. goto break1;
  93150. }
  93151. else {
  93152. uval += FLAC__BITS_PER_WORD - cbits;
  93153. crc16_update_word_(br, br->buffer[cwords]);
  93154. cwords++;
  93155. cbits = 0;
  93156. /* didn't find stop bit yet, have to keep going... */
  93157. }
  93158. }
  93159. /* at this point we've eaten up all the whole words; have to try
  93160. * reading through any tail bytes before calling the read callback.
  93161. * this is a repeat of the above logic adjusted for the fact we
  93162. * don't have a whole word. note though if the client is feeding
  93163. * us data a byte at a time (unlikely), br->consumed_bits may not
  93164. * be zero.
  93165. */
  93166. if(br->bytes) {
  93167. const unsigned end = br->bytes * 8;
  93168. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93169. if(b) {
  93170. i = COUNT_ZERO_MSBS(b);
  93171. uval += i;
  93172. bits = parameter;
  93173. i++;
  93174. cbits += i;
  93175. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93176. goto break1;
  93177. }
  93178. else {
  93179. uval += end - cbits;
  93180. cbits += end;
  93181. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93182. /* didn't find stop bit yet, have to keep going... */
  93183. }
  93184. }
  93185. /* flush registers and read; bitreader_read_from_client_() does
  93186. * not touch br->consumed_bits at all but we still need to set
  93187. * it in case it fails and we have to return false.
  93188. */
  93189. br->consumed_bits = cbits;
  93190. br->consumed_words = cwords;
  93191. if(!bitreader_read_from_client_(br))
  93192. return false;
  93193. cwords = br->consumed_words;
  93194. }
  93195. break1:
  93196. /* read binary part */
  93197. FLAC__ASSERT(cwords <= br->words);
  93198. if(bits) {
  93199. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93200. /* flush registers and read; bitreader_read_from_client_() does
  93201. * not touch br->consumed_bits at all but we still need to set
  93202. * it in case it fails and we have to return false.
  93203. */
  93204. br->consumed_bits = cbits;
  93205. br->consumed_words = cwords;
  93206. if(!bitreader_read_from_client_(br))
  93207. return false;
  93208. cwords = br->consumed_words;
  93209. }
  93210. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93211. if(cbits) {
  93212. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93213. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93214. const brword word = br->buffer[cwords];
  93215. if(bits < n) {
  93216. uval <<= bits;
  93217. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93218. cbits += bits;
  93219. goto break2;
  93220. }
  93221. uval <<= n;
  93222. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93223. bits -= n;
  93224. crc16_update_word_(br, word);
  93225. cwords++;
  93226. cbits = 0;
  93227. 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 */
  93228. uval <<= bits;
  93229. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93230. cbits = bits;
  93231. }
  93232. goto break2;
  93233. }
  93234. else {
  93235. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93236. uval <<= bits;
  93237. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93238. cbits = bits;
  93239. goto break2;
  93240. }
  93241. }
  93242. else {
  93243. /* in this case we're starting our read at a partial tail word;
  93244. * the reader has guaranteed that we have at least 'bits' bits
  93245. * available to read, which makes this case simpler.
  93246. */
  93247. uval <<= bits;
  93248. if(cbits) {
  93249. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93250. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93251. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93252. cbits += bits;
  93253. goto break2;
  93254. }
  93255. else {
  93256. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93257. cbits += bits;
  93258. goto break2;
  93259. }
  93260. }
  93261. }
  93262. break2:
  93263. /* compose the value */
  93264. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93265. /* are we done? */
  93266. --nvals;
  93267. if(nvals == 0) {
  93268. br->consumed_bits = cbits;
  93269. br->consumed_words = cwords;
  93270. return true;
  93271. }
  93272. uval = 0;
  93273. ++vals;
  93274. }
  93275. }
  93276. #else
  93277. {
  93278. unsigned i;
  93279. unsigned uval = 0;
  93280. /* try and get br->consumed_words and br->consumed_bits into register;
  93281. * must remember to flush them back to *br before calling other
  93282. * bitwriter functions that use them, and before returning */
  93283. register unsigned cwords;
  93284. register unsigned cbits;
  93285. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93286. FLAC__ASSERT(0 != br);
  93287. FLAC__ASSERT(0 != br->buffer);
  93288. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93289. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93290. FLAC__ASSERT(parameter < 32);
  93291. /* 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 */
  93292. if(nvals == 0)
  93293. return true;
  93294. cbits = br->consumed_bits;
  93295. cwords = br->consumed_words;
  93296. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93297. while(1) {
  93298. /* read unary part */
  93299. while(1) {
  93300. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93301. brword b = br->buffer[cwords] << cbits;
  93302. if(b) {
  93303. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93304. asm volatile (
  93305. "bsrl %1, %0;"
  93306. "notl %0;"
  93307. "andl $31, %0;"
  93308. : "=r"(i)
  93309. : "r"(b)
  93310. );
  93311. #else
  93312. i = COUNT_ZERO_MSBS(b);
  93313. #endif
  93314. uval += i;
  93315. cbits += i;
  93316. cbits++; /* skip over stop bit */
  93317. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93318. crc16_update_word_(br, br->buffer[cwords]);
  93319. cwords++;
  93320. cbits = 0;
  93321. }
  93322. goto break1;
  93323. }
  93324. else {
  93325. uval += FLAC__BITS_PER_WORD - cbits;
  93326. crc16_update_word_(br, br->buffer[cwords]);
  93327. cwords++;
  93328. cbits = 0;
  93329. /* didn't find stop bit yet, have to keep going... */
  93330. }
  93331. }
  93332. /* at this point we've eaten up all the whole words; have to try
  93333. * reading through any tail bytes before calling the read callback.
  93334. * this is a repeat of the above logic adjusted for the fact we
  93335. * don't have a whole word. note though if the client is feeding
  93336. * us data a byte at a time (unlikely), br->consumed_bits may not
  93337. * be zero.
  93338. */
  93339. if(br->bytes) {
  93340. const unsigned end = br->bytes * 8;
  93341. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93342. if(b) {
  93343. i = COUNT_ZERO_MSBS(b);
  93344. uval += i;
  93345. cbits += i;
  93346. cbits++; /* skip over stop bit */
  93347. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93348. goto break1;
  93349. }
  93350. else {
  93351. uval += end - cbits;
  93352. cbits += end;
  93353. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93354. /* didn't find stop bit yet, have to keep going... */
  93355. }
  93356. }
  93357. /* flush registers and read; bitreader_read_from_client_() does
  93358. * not touch br->consumed_bits at all but we still need to set
  93359. * it in case it fails and we have to return false.
  93360. */
  93361. br->consumed_bits = cbits;
  93362. br->consumed_words = cwords;
  93363. if(!bitreader_read_from_client_(br))
  93364. return false;
  93365. cwords = br->consumed_words;
  93366. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93367. /* + uval to offset our count by the # of unary bits already
  93368. * consumed before the read, because we will add these back
  93369. * in all at once at break1
  93370. */
  93371. }
  93372. break1:
  93373. ucbits -= uval;
  93374. ucbits--; /* account for stop bit */
  93375. /* read binary part */
  93376. FLAC__ASSERT(cwords <= br->words);
  93377. if(parameter) {
  93378. while(ucbits < parameter) {
  93379. /* flush registers and read; bitreader_read_from_client_() does
  93380. * not touch br->consumed_bits at all but we still need to set
  93381. * it in case it fails and we have to return false.
  93382. */
  93383. br->consumed_bits = cbits;
  93384. br->consumed_words = cwords;
  93385. if(!bitreader_read_from_client_(br))
  93386. return false;
  93387. cwords = br->consumed_words;
  93388. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93389. }
  93390. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93391. if(cbits) {
  93392. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93393. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93394. const brword word = br->buffer[cwords];
  93395. if(parameter < n) {
  93396. uval <<= parameter;
  93397. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93398. cbits += parameter;
  93399. }
  93400. else {
  93401. uval <<= n;
  93402. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93403. crc16_update_word_(br, word);
  93404. cwords++;
  93405. cbits = parameter - n;
  93406. 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 */
  93407. uval <<= cbits;
  93408. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93409. }
  93410. }
  93411. }
  93412. else {
  93413. cbits = parameter;
  93414. uval <<= parameter;
  93415. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93416. }
  93417. }
  93418. else {
  93419. /* in this case we're starting our read at a partial tail word;
  93420. * the reader has guaranteed that we have at least 'parameter'
  93421. * bits available to read, which makes this case simpler.
  93422. */
  93423. uval <<= parameter;
  93424. if(cbits) {
  93425. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93426. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93427. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93428. cbits += parameter;
  93429. }
  93430. else {
  93431. cbits = parameter;
  93432. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93433. }
  93434. }
  93435. }
  93436. ucbits -= parameter;
  93437. /* compose the value */
  93438. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93439. /* are we done? */
  93440. --nvals;
  93441. if(nvals == 0) {
  93442. br->consumed_bits = cbits;
  93443. br->consumed_words = cwords;
  93444. return true;
  93445. }
  93446. uval = 0;
  93447. ++vals;
  93448. }
  93449. }
  93450. #endif
  93451. #if 0 /* UNUSED */
  93452. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93453. {
  93454. FLAC__uint32 lsbs = 0, msbs = 0;
  93455. unsigned bit, uval, k;
  93456. FLAC__ASSERT(0 != br);
  93457. FLAC__ASSERT(0 != br->buffer);
  93458. k = FLAC__bitmath_ilog2(parameter);
  93459. /* read the unary MSBs and end bit */
  93460. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93461. return false;
  93462. /* read the binary LSBs */
  93463. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93464. return false;
  93465. if(parameter == 1u<<k) {
  93466. /* compose the value */
  93467. uval = (msbs << k) | lsbs;
  93468. }
  93469. else {
  93470. unsigned d = (1 << (k+1)) - parameter;
  93471. if(lsbs >= d) {
  93472. if(!FLAC__bitreader_read_bit(br, &bit))
  93473. return false;
  93474. lsbs <<= 1;
  93475. lsbs |= bit;
  93476. lsbs -= d;
  93477. }
  93478. /* compose the value */
  93479. uval = msbs * parameter + lsbs;
  93480. }
  93481. /* unfold unsigned to signed */
  93482. if(uval & 1)
  93483. *val = -((int)(uval >> 1)) - 1;
  93484. else
  93485. *val = (int)(uval >> 1);
  93486. return true;
  93487. }
  93488. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93489. {
  93490. FLAC__uint32 lsbs, msbs = 0;
  93491. unsigned bit, k;
  93492. FLAC__ASSERT(0 != br);
  93493. FLAC__ASSERT(0 != br->buffer);
  93494. k = FLAC__bitmath_ilog2(parameter);
  93495. /* read the unary MSBs and end bit */
  93496. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93497. return false;
  93498. /* read the binary LSBs */
  93499. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93500. return false;
  93501. if(parameter == 1u<<k) {
  93502. /* compose the value */
  93503. *val = (msbs << k) | lsbs;
  93504. }
  93505. else {
  93506. unsigned d = (1 << (k+1)) - parameter;
  93507. if(lsbs >= d) {
  93508. if(!FLAC__bitreader_read_bit(br, &bit))
  93509. return false;
  93510. lsbs <<= 1;
  93511. lsbs |= bit;
  93512. lsbs -= d;
  93513. }
  93514. /* compose the value */
  93515. *val = msbs * parameter + lsbs;
  93516. }
  93517. return true;
  93518. }
  93519. #endif /* UNUSED */
  93520. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93521. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93522. {
  93523. FLAC__uint32 v = 0;
  93524. FLAC__uint32 x;
  93525. unsigned i;
  93526. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93527. return false;
  93528. if(raw)
  93529. raw[(*rawlen)++] = (FLAC__byte)x;
  93530. if(!(x & 0x80)) { /* 0xxxxxxx */
  93531. v = x;
  93532. i = 0;
  93533. }
  93534. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93535. v = x & 0x1F;
  93536. i = 1;
  93537. }
  93538. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93539. v = x & 0x0F;
  93540. i = 2;
  93541. }
  93542. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93543. v = x & 0x07;
  93544. i = 3;
  93545. }
  93546. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93547. v = x & 0x03;
  93548. i = 4;
  93549. }
  93550. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93551. v = x & 0x01;
  93552. i = 5;
  93553. }
  93554. else {
  93555. *val = 0xffffffff;
  93556. return true;
  93557. }
  93558. for( ; i; i--) {
  93559. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93560. return false;
  93561. if(raw)
  93562. raw[(*rawlen)++] = (FLAC__byte)x;
  93563. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93564. *val = 0xffffffff;
  93565. return true;
  93566. }
  93567. v <<= 6;
  93568. v |= (x & 0x3F);
  93569. }
  93570. *val = v;
  93571. return true;
  93572. }
  93573. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93574. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93575. {
  93576. FLAC__uint64 v = 0;
  93577. FLAC__uint32 x;
  93578. unsigned i;
  93579. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93580. return false;
  93581. if(raw)
  93582. raw[(*rawlen)++] = (FLAC__byte)x;
  93583. if(!(x & 0x80)) { /* 0xxxxxxx */
  93584. v = x;
  93585. i = 0;
  93586. }
  93587. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93588. v = x & 0x1F;
  93589. i = 1;
  93590. }
  93591. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93592. v = x & 0x0F;
  93593. i = 2;
  93594. }
  93595. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93596. v = x & 0x07;
  93597. i = 3;
  93598. }
  93599. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93600. v = x & 0x03;
  93601. i = 4;
  93602. }
  93603. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93604. v = x & 0x01;
  93605. i = 5;
  93606. }
  93607. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93608. v = 0;
  93609. i = 6;
  93610. }
  93611. else {
  93612. *val = FLAC__U64L(0xffffffffffffffff);
  93613. return true;
  93614. }
  93615. for( ; i; i--) {
  93616. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93617. return false;
  93618. if(raw)
  93619. raw[(*rawlen)++] = (FLAC__byte)x;
  93620. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93621. *val = FLAC__U64L(0xffffffffffffffff);
  93622. return true;
  93623. }
  93624. v <<= 6;
  93625. v |= (x & 0x3F);
  93626. }
  93627. *val = v;
  93628. return true;
  93629. }
  93630. #endif
  93631. /*** End of inlined file: bitreader.c ***/
  93632. /*** Start of inlined file: bitwriter.c ***/
  93633. /*** Start of inlined file: juce_FlacHeader.h ***/
  93634. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93635. // tasks..
  93636. #define VERSION "1.2.1"
  93637. #define FLAC__NO_DLL 1
  93638. #if JUCE_MSVC
  93639. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93640. #endif
  93641. #if JUCE_MAC
  93642. #define FLAC__SYS_DARWIN 1
  93643. #endif
  93644. /*** End of inlined file: juce_FlacHeader.h ***/
  93645. #if JUCE_USE_FLAC
  93646. #if HAVE_CONFIG_H
  93647. # include <config.h>
  93648. #endif
  93649. #include <stdlib.h> /* for malloc() */
  93650. #include <string.h> /* for memcpy(), memset() */
  93651. #ifdef _MSC_VER
  93652. #include <winsock.h> /* for ntohl() */
  93653. #elif defined FLAC__SYS_DARWIN
  93654. #include <machine/endian.h> /* for ntohl() */
  93655. #elif defined __MINGW32__
  93656. #include <winsock.h> /* for ntohl() */
  93657. #else
  93658. #include <netinet/in.h> /* for ntohl() */
  93659. #endif
  93660. #if 0 /* UNUSED */
  93661. #endif
  93662. /*** Start of inlined file: bitwriter.h ***/
  93663. #ifndef FLAC__PRIVATE__BITWRITER_H
  93664. #define FLAC__PRIVATE__BITWRITER_H
  93665. #include <stdio.h> /* for FILE */
  93666. /*
  93667. * opaque structure definition
  93668. */
  93669. struct FLAC__BitWriter;
  93670. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93671. /*
  93672. * construction, deletion, initialization, etc functions
  93673. */
  93674. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93675. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93676. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93677. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93678. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93679. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93680. /*
  93681. * CRC functions
  93682. *
  93683. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93684. */
  93685. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93686. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93687. /*
  93688. * info functions
  93689. */
  93690. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93691. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93692. /*
  93693. * direct buffer access
  93694. *
  93695. * there may be no calls on the bitwriter between get and release.
  93696. * the bitwriter continues to own the returned buffer.
  93697. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93698. */
  93699. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93700. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93701. /*
  93702. * write functions
  93703. */
  93704. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93705. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93706. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93707. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93708. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93709. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93710. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93711. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93712. #if 0 /* UNUSED */
  93713. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93714. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93715. #endif
  93716. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93717. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93718. #if 0 /* UNUSED */
  93719. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93720. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93721. #endif
  93722. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93723. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93724. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93725. #endif
  93726. /*** End of inlined file: bitwriter.h ***/
  93727. /*** Start of inlined file: alloc.h ***/
  93728. #ifndef FLAC__SHARE__ALLOC_H
  93729. #define FLAC__SHARE__ALLOC_H
  93730. #if HAVE_CONFIG_H
  93731. # include <config.h>
  93732. #endif
  93733. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93734. * before #including this file, otherwise SIZE_MAX might not be defined
  93735. */
  93736. #include <limits.h> /* for SIZE_MAX */
  93737. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93738. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93739. #endif
  93740. #include <stdlib.h> /* for size_t, malloc(), etc */
  93741. #ifndef SIZE_MAX
  93742. # ifndef SIZE_T_MAX
  93743. # ifdef _MSC_VER
  93744. # define SIZE_T_MAX UINT_MAX
  93745. # else
  93746. # error
  93747. # endif
  93748. # endif
  93749. # define SIZE_MAX SIZE_T_MAX
  93750. #endif
  93751. #ifndef FLaC__INLINE
  93752. #define FLaC__INLINE
  93753. #endif
  93754. /* avoid malloc()ing 0 bytes, see:
  93755. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93756. */
  93757. static FLaC__INLINE void *safe_malloc_(size_t size)
  93758. {
  93759. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93760. if(!size)
  93761. size++;
  93762. return malloc(size);
  93763. }
  93764. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93765. {
  93766. if(!nmemb || !size)
  93767. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93768. return calloc(nmemb, size);
  93769. }
  93770. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93771. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93772. {
  93773. size2 += size1;
  93774. if(size2 < size1)
  93775. return 0;
  93776. return safe_malloc_(size2);
  93777. }
  93778. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93779. {
  93780. size2 += size1;
  93781. if(size2 < size1)
  93782. return 0;
  93783. size3 += size2;
  93784. if(size3 < size2)
  93785. return 0;
  93786. return safe_malloc_(size3);
  93787. }
  93788. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93789. {
  93790. size2 += size1;
  93791. if(size2 < size1)
  93792. return 0;
  93793. size3 += size2;
  93794. if(size3 < size2)
  93795. return 0;
  93796. size4 += size3;
  93797. if(size4 < size3)
  93798. return 0;
  93799. return safe_malloc_(size4);
  93800. }
  93801. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  93802. #if 0
  93803. needs support for cases where sizeof(size_t) != 4
  93804. {
  93805. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  93806. if(sizeof(size_t) == 4) {
  93807. if ((double)size1 * (double)size2 < 4294967296.0)
  93808. return malloc(size1*size2);
  93809. }
  93810. return 0;
  93811. }
  93812. #else
  93813. /* better? */
  93814. {
  93815. if(!size1 || !size2)
  93816. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93817. if(size1 > SIZE_MAX / size2)
  93818. return 0;
  93819. return malloc(size1*size2);
  93820. }
  93821. #endif
  93822. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  93823. {
  93824. if(!size1 || !size2 || !size3)
  93825. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93826. if(size1 > SIZE_MAX / size2)
  93827. return 0;
  93828. size1 *= size2;
  93829. if(size1 > SIZE_MAX / size3)
  93830. return 0;
  93831. return malloc(size1*size3);
  93832. }
  93833. /* size1*size2 + size3 */
  93834. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  93835. {
  93836. if(!size1 || !size2)
  93837. return safe_malloc_(size3);
  93838. if(size1 > SIZE_MAX / size2)
  93839. return 0;
  93840. return safe_malloc_add_2op_(size1*size2, size3);
  93841. }
  93842. /* size1 * (size2 + size3) */
  93843. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  93844. {
  93845. if(!size1 || (!size2 && !size3))
  93846. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93847. size2 += size3;
  93848. if(size2 < size3)
  93849. return 0;
  93850. return safe_malloc_mul_2op_(size1, size2);
  93851. }
  93852. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  93853. {
  93854. size2 += size1;
  93855. if(size2 < size1)
  93856. return 0;
  93857. return realloc(ptr, size2);
  93858. }
  93859. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  93860. {
  93861. size2 += size1;
  93862. if(size2 < size1)
  93863. return 0;
  93864. size3 += size2;
  93865. if(size3 < size2)
  93866. return 0;
  93867. return realloc(ptr, size3);
  93868. }
  93869. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  93870. {
  93871. size2 += size1;
  93872. if(size2 < size1)
  93873. return 0;
  93874. size3 += size2;
  93875. if(size3 < size2)
  93876. return 0;
  93877. size4 += size3;
  93878. if(size4 < size3)
  93879. return 0;
  93880. return realloc(ptr, size4);
  93881. }
  93882. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  93883. {
  93884. if(!size1 || !size2)
  93885. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93886. if(size1 > SIZE_MAX / size2)
  93887. return 0;
  93888. return realloc(ptr, size1*size2);
  93889. }
  93890. /* size1 * (size2 + size3) */
  93891. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  93892. {
  93893. if(!size1 || (!size2 && !size3))
  93894. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93895. size2 += size3;
  93896. if(size2 < size3)
  93897. return 0;
  93898. return safe_realloc_mul_2op_(ptr, size1, size2);
  93899. }
  93900. #endif
  93901. /*** End of inlined file: alloc.h ***/
  93902. /* Things should be fastest when this matches the machine word size */
  93903. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  93904. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  93905. typedef FLAC__uint32 bwword;
  93906. #define FLAC__BYTES_PER_WORD 4
  93907. #define FLAC__BITS_PER_WORD 32
  93908. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93909. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  93910. #if WORDS_BIGENDIAN
  93911. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93912. #else
  93913. #ifdef _MSC_VER
  93914. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93915. #else
  93916. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93917. #endif
  93918. #endif
  93919. /*
  93920. * The default capacity here doesn't matter too much. The buffer always grows
  93921. * to hold whatever is written to it. Usually the encoder will stop adding at
  93922. * a frame or metadata block, then write that out and clear the buffer for the
  93923. * next one.
  93924. */
  93925. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  93926. /* When growing, increment 4K at a time */
  93927. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  93928. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  93929. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  93930. #ifdef min
  93931. #undef min
  93932. #endif
  93933. #define min(x,y) ((x)<(y)?(x):(y))
  93934. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93935. #ifdef _MSC_VER
  93936. #define FLAC__U64L(x) x
  93937. #else
  93938. #define FLAC__U64L(x) x##LLU
  93939. #endif
  93940. #ifndef FLaC__INLINE
  93941. #define FLaC__INLINE
  93942. #endif
  93943. struct FLAC__BitWriter {
  93944. bwword *buffer;
  93945. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  93946. unsigned capacity; /* capacity of buffer in words */
  93947. unsigned words; /* # of complete words in buffer */
  93948. unsigned bits; /* # of used bits in accum */
  93949. };
  93950. /* * WATCHOUT: The current implementation only grows the buffer. */
  93951. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  93952. {
  93953. unsigned new_capacity;
  93954. bwword *new_buffer;
  93955. FLAC__ASSERT(0 != bw);
  93956. FLAC__ASSERT(0 != bw->buffer);
  93957. /* calculate total words needed to store 'bits_to_add' additional bits */
  93958. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  93959. /* it's possible (due to pessimism in the growth estimation that
  93960. * leads to this call) that we don't actually need to grow
  93961. */
  93962. if(bw->capacity >= new_capacity)
  93963. return true;
  93964. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  93965. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  93966. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93967. /* make sure we got everything right */
  93968. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93969. FLAC__ASSERT(new_capacity > bw->capacity);
  93970. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  93971. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  93972. if(new_buffer == 0)
  93973. return false;
  93974. bw->buffer = new_buffer;
  93975. bw->capacity = new_capacity;
  93976. return true;
  93977. }
  93978. /***********************************************************************
  93979. *
  93980. * Class constructor/destructor
  93981. *
  93982. ***********************************************************************/
  93983. FLAC__BitWriter *FLAC__bitwriter_new(void)
  93984. {
  93985. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  93986. /* note that calloc() sets all members to 0 for us */
  93987. return bw;
  93988. }
  93989. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  93990. {
  93991. FLAC__ASSERT(0 != bw);
  93992. FLAC__bitwriter_free(bw);
  93993. free(bw);
  93994. }
  93995. /***********************************************************************
  93996. *
  93997. * Public class methods
  93998. *
  93999. ***********************************************************************/
  94000. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94001. {
  94002. FLAC__ASSERT(0 != bw);
  94003. bw->words = bw->bits = 0;
  94004. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94005. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94006. if(bw->buffer == 0)
  94007. return false;
  94008. return true;
  94009. }
  94010. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94011. {
  94012. FLAC__ASSERT(0 != bw);
  94013. if(0 != bw->buffer)
  94014. free(bw->buffer);
  94015. bw->buffer = 0;
  94016. bw->capacity = 0;
  94017. bw->words = bw->bits = 0;
  94018. }
  94019. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94020. {
  94021. bw->words = bw->bits = 0;
  94022. }
  94023. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94024. {
  94025. unsigned i, j;
  94026. if(bw == 0) {
  94027. fprintf(out, "bitwriter is NULL\n");
  94028. }
  94029. else {
  94030. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94031. for(i = 0; i < bw->words; i++) {
  94032. fprintf(out, "%08X: ", i);
  94033. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94034. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94035. fprintf(out, "\n");
  94036. }
  94037. if(bw->bits > 0) {
  94038. fprintf(out, "%08X: ", i);
  94039. for(j = 0; j < bw->bits; j++)
  94040. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94041. fprintf(out, "\n");
  94042. }
  94043. }
  94044. }
  94045. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94046. {
  94047. const FLAC__byte *buffer;
  94048. size_t bytes;
  94049. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94050. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94051. return false;
  94052. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94053. FLAC__bitwriter_release_buffer(bw);
  94054. return true;
  94055. }
  94056. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94057. {
  94058. const FLAC__byte *buffer;
  94059. size_t bytes;
  94060. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94061. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94062. return false;
  94063. *crc = FLAC__crc8(buffer, bytes);
  94064. FLAC__bitwriter_release_buffer(bw);
  94065. return true;
  94066. }
  94067. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94068. {
  94069. return ((bw->bits & 7) == 0);
  94070. }
  94071. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94072. {
  94073. return FLAC__TOTAL_BITS(bw);
  94074. }
  94075. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94076. {
  94077. FLAC__ASSERT((bw->bits & 7) == 0);
  94078. /* double protection */
  94079. if(bw->bits & 7)
  94080. return false;
  94081. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94082. if(bw->bits) {
  94083. FLAC__ASSERT(bw->words <= bw->capacity);
  94084. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94085. return false;
  94086. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94087. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94088. }
  94089. /* now we can just return what we have */
  94090. *buffer = (FLAC__byte*)bw->buffer;
  94091. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94092. return true;
  94093. }
  94094. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94095. {
  94096. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94097. * get-mode' flag could be added everywhere and then cleared here
  94098. */
  94099. (void)bw;
  94100. }
  94101. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94102. {
  94103. unsigned n;
  94104. FLAC__ASSERT(0 != bw);
  94105. FLAC__ASSERT(0 != bw->buffer);
  94106. if(bits == 0)
  94107. return true;
  94108. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94109. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94110. return false;
  94111. /* first part gets to word alignment */
  94112. if(bw->bits) {
  94113. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94114. bw->accum <<= n;
  94115. bits -= n;
  94116. bw->bits += n;
  94117. if(bw->bits == FLAC__BITS_PER_WORD) {
  94118. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94119. bw->bits = 0;
  94120. }
  94121. else
  94122. return true;
  94123. }
  94124. /* do whole words */
  94125. while(bits >= FLAC__BITS_PER_WORD) {
  94126. bw->buffer[bw->words++] = 0;
  94127. bits -= FLAC__BITS_PER_WORD;
  94128. }
  94129. /* do any leftovers */
  94130. if(bits > 0) {
  94131. bw->accum = 0;
  94132. bw->bits = bits;
  94133. }
  94134. return true;
  94135. }
  94136. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94137. {
  94138. register unsigned left;
  94139. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94140. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94141. FLAC__ASSERT(0 != bw);
  94142. FLAC__ASSERT(0 != bw->buffer);
  94143. FLAC__ASSERT(bits <= 32);
  94144. if(bits == 0)
  94145. return true;
  94146. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94147. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94148. return false;
  94149. left = FLAC__BITS_PER_WORD - bw->bits;
  94150. if(bits < left) {
  94151. bw->accum <<= bits;
  94152. bw->accum |= val;
  94153. bw->bits += bits;
  94154. }
  94155. 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 */
  94156. bw->accum <<= left;
  94157. bw->accum |= val >> (bw->bits = bits - left);
  94158. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94159. bw->accum = val;
  94160. }
  94161. else {
  94162. bw->accum = val;
  94163. bw->bits = 0;
  94164. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94165. }
  94166. return true;
  94167. }
  94168. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94169. {
  94170. /* zero-out unused bits */
  94171. if(bits < 32)
  94172. val &= (~(0xffffffff << bits));
  94173. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94174. }
  94175. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94176. {
  94177. /* this could be a little faster but it's not used for much */
  94178. if(bits > 32) {
  94179. return
  94180. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94181. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94182. }
  94183. else
  94184. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94185. }
  94186. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94187. {
  94188. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94189. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94190. return false;
  94191. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94192. return false;
  94193. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94194. return false;
  94195. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94196. return false;
  94197. return true;
  94198. }
  94199. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94200. {
  94201. unsigned i;
  94202. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94203. for(i = 0; i < nvals; i++) {
  94204. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94205. return false;
  94206. }
  94207. return true;
  94208. }
  94209. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94210. {
  94211. if(val < 32)
  94212. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94213. else
  94214. return
  94215. FLAC__bitwriter_write_zeroes(bw, val) &&
  94216. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94217. }
  94218. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94219. {
  94220. FLAC__uint32 uval;
  94221. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94222. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94223. uval = (val<<1) ^ (val>>31);
  94224. return 1 + parameter + (uval >> parameter);
  94225. }
  94226. #if 0 /* UNUSED */
  94227. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94228. {
  94229. unsigned bits, msbs, uval;
  94230. unsigned k;
  94231. FLAC__ASSERT(parameter > 0);
  94232. /* fold signed to unsigned */
  94233. if(val < 0)
  94234. uval = (unsigned)(((-(++val)) << 1) + 1);
  94235. else
  94236. uval = (unsigned)(val << 1);
  94237. k = FLAC__bitmath_ilog2(parameter);
  94238. if(parameter == 1u<<k) {
  94239. FLAC__ASSERT(k <= 30);
  94240. msbs = uval >> k;
  94241. bits = 1 + k + msbs;
  94242. }
  94243. else {
  94244. unsigned q, r, d;
  94245. d = (1 << (k+1)) - parameter;
  94246. q = uval / parameter;
  94247. r = uval - (q * parameter);
  94248. bits = 1 + q + k;
  94249. if(r >= d)
  94250. bits++;
  94251. }
  94252. return bits;
  94253. }
  94254. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94255. {
  94256. unsigned bits, msbs;
  94257. unsigned k;
  94258. FLAC__ASSERT(parameter > 0);
  94259. k = FLAC__bitmath_ilog2(parameter);
  94260. if(parameter == 1u<<k) {
  94261. FLAC__ASSERT(k <= 30);
  94262. msbs = uval >> k;
  94263. bits = 1 + k + msbs;
  94264. }
  94265. else {
  94266. unsigned q, r, d;
  94267. d = (1 << (k+1)) - parameter;
  94268. q = uval / parameter;
  94269. r = uval - (q * parameter);
  94270. bits = 1 + q + k;
  94271. if(r >= d)
  94272. bits++;
  94273. }
  94274. return bits;
  94275. }
  94276. #endif /* UNUSED */
  94277. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94278. {
  94279. unsigned total_bits, interesting_bits, msbs;
  94280. FLAC__uint32 uval, pattern;
  94281. FLAC__ASSERT(0 != bw);
  94282. FLAC__ASSERT(0 != bw->buffer);
  94283. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94284. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94285. uval = (val<<1) ^ (val>>31);
  94286. msbs = uval >> parameter;
  94287. interesting_bits = 1 + parameter;
  94288. total_bits = interesting_bits + msbs;
  94289. pattern = 1 << parameter; /* the unary end bit */
  94290. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94291. if(total_bits <= 32)
  94292. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94293. else
  94294. return
  94295. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94296. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94297. }
  94298. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94299. {
  94300. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94301. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94302. FLAC__uint32 uval;
  94303. unsigned left;
  94304. const unsigned lsbits = 1 + parameter;
  94305. unsigned msbits;
  94306. FLAC__ASSERT(0 != bw);
  94307. FLAC__ASSERT(0 != bw->buffer);
  94308. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94309. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94310. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94311. while(nvals) {
  94312. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94313. uval = (*vals<<1) ^ (*vals>>31);
  94314. msbits = uval >> parameter;
  94315. #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) */
  94316. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94317. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94318. bw->bits = bw->bits + msbits + lsbits;
  94319. uval |= mask1; /* set stop bit */
  94320. uval &= mask2; /* mask off unused top bits */
  94321. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94322. bw->accum <<= msbits;
  94323. bw->accum <<= lsbits;
  94324. bw->accum |= uval;
  94325. if(bw->bits == FLAC__BITS_PER_WORD) {
  94326. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94327. bw->bits = 0;
  94328. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94329. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94330. FLAC__ASSERT(bw->capacity == bw->words);
  94331. return false;
  94332. }
  94333. }
  94334. }
  94335. else {
  94336. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94337. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94338. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94339. bw->bits = bw->bits + msbits + lsbits;
  94340. uval |= mask1; /* set stop bit */
  94341. uval &= mask2; /* mask off unused top bits */
  94342. bw->accum <<= msbits + lsbits;
  94343. bw->accum |= uval;
  94344. }
  94345. else {
  94346. #endif
  94347. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94348. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94349. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94350. return false;
  94351. if(msbits) {
  94352. /* first part gets to word alignment */
  94353. if(bw->bits) {
  94354. left = FLAC__BITS_PER_WORD - bw->bits;
  94355. if(msbits < left) {
  94356. bw->accum <<= msbits;
  94357. bw->bits += msbits;
  94358. goto break1;
  94359. }
  94360. else {
  94361. bw->accum <<= left;
  94362. msbits -= left;
  94363. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94364. bw->bits = 0;
  94365. }
  94366. }
  94367. /* do whole words */
  94368. while(msbits >= FLAC__BITS_PER_WORD) {
  94369. bw->buffer[bw->words++] = 0;
  94370. msbits -= FLAC__BITS_PER_WORD;
  94371. }
  94372. /* do any leftovers */
  94373. if(msbits > 0) {
  94374. bw->accum = 0;
  94375. bw->bits = msbits;
  94376. }
  94377. }
  94378. break1:
  94379. uval |= mask1; /* set stop bit */
  94380. uval &= mask2; /* mask off unused top bits */
  94381. left = FLAC__BITS_PER_WORD - bw->bits;
  94382. if(lsbits < left) {
  94383. bw->accum <<= lsbits;
  94384. bw->accum |= uval;
  94385. bw->bits += lsbits;
  94386. }
  94387. else {
  94388. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94389. * be > lsbits (because of previous assertions) so it would have
  94390. * triggered the (lsbits<left) case above.
  94391. */
  94392. FLAC__ASSERT(bw->bits);
  94393. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94394. bw->accum <<= left;
  94395. bw->accum |= uval >> (bw->bits = lsbits - left);
  94396. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94397. bw->accum = uval;
  94398. }
  94399. #if 1
  94400. }
  94401. #endif
  94402. vals++;
  94403. nvals--;
  94404. }
  94405. return true;
  94406. }
  94407. #if 0 /* UNUSED */
  94408. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94409. {
  94410. unsigned total_bits, msbs, uval;
  94411. unsigned k;
  94412. FLAC__ASSERT(0 != bw);
  94413. FLAC__ASSERT(0 != bw->buffer);
  94414. FLAC__ASSERT(parameter > 0);
  94415. /* fold signed to unsigned */
  94416. if(val < 0)
  94417. uval = (unsigned)(((-(++val)) << 1) + 1);
  94418. else
  94419. uval = (unsigned)(val << 1);
  94420. k = FLAC__bitmath_ilog2(parameter);
  94421. if(parameter == 1u<<k) {
  94422. unsigned pattern;
  94423. FLAC__ASSERT(k <= 30);
  94424. msbs = uval >> k;
  94425. total_bits = 1 + k + msbs;
  94426. pattern = 1 << k; /* the unary end bit */
  94427. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94428. if(total_bits <= 32) {
  94429. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94430. return false;
  94431. }
  94432. else {
  94433. /* write the unary MSBs */
  94434. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94435. return false;
  94436. /* write the unary end bit and binary LSBs */
  94437. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94438. return false;
  94439. }
  94440. }
  94441. else {
  94442. unsigned q, r, d;
  94443. d = (1 << (k+1)) - parameter;
  94444. q = uval / parameter;
  94445. r = uval - (q * parameter);
  94446. /* write the unary MSBs */
  94447. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94448. return false;
  94449. /* write the unary end bit */
  94450. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94451. return false;
  94452. /* write the binary LSBs */
  94453. if(r >= d) {
  94454. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94455. return false;
  94456. }
  94457. else {
  94458. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94459. return false;
  94460. }
  94461. }
  94462. return true;
  94463. }
  94464. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94465. {
  94466. unsigned total_bits, msbs;
  94467. unsigned k;
  94468. FLAC__ASSERT(0 != bw);
  94469. FLAC__ASSERT(0 != bw->buffer);
  94470. FLAC__ASSERT(parameter > 0);
  94471. k = FLAC__bitmath_ilog2(parameter);
  94472. if(parameter == 1u<<k) {
  94473. unsigned pattern;
  94474. FLAC__ASSERT(k <= 30);
  94475. msbs = uval >> k;
  94476. total_bits = 1 + k + msbs;
  94477. pattern = 1 << k; /* the unary end bit */
  94478. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94479. if(total_bits <= 32) {
  94480. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94481. return false;
  94482. }
  94483. else {
  94484. /* write the unary MSBs */
  94485. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94486. return false;
  94487. /* write the unary end bit and binary LSBs */
  94488. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94489. return false;
  94490. }
  94491. }
  94492. else {
  94493. unsigned q, r, d;
  94494. d = (1 << (k+1)) - parameter;
  94495. q = uval / parameter;
  94496. r = uval - (q * parameter);
  94497. /* write the unary MSBs */
  94498. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94499. return false;
  94500. /* write the unary end bit */
  94501. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94502. return false;
  94503. /* write the binary LSBs */
  94504. if(r >= d) {
  94505. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94506. return false;
  94507. }
  94508. else {
  94509. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94510. return false;
  94511. }
  94512. }
  94513. return true;
  94514. }
  94515. #endif /* UNUSED */
  94516. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94517. {
  94518. FLAC__bool ok = 1;
  94519. FLAC__ASSERT(0 != bw);
  94520. FLAC__ASSERT(0 != bw->buffer);
  94521. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94522. if(val < 0x80) {
  94523. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94524. }
  94525. else if(val < 0x800) {
  94526. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94527. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94528. }
  94529. else if(val < 0x10000) {
  94530. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94531. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94532. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94533. }
  94534. else if(val < 0x200000) {
  94535. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94536. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94537. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94538. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94539. }
  94540. else if(val < 0x4000000) {
  94541. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94542. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94543. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94544. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94545. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94546. }
  94547. else {
  94548. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94549. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94550. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94551. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94552. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94553. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94554. }
  94555. return ok;
  94556. }
  94557. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94558. {
  94559. FLAC__bool ok = 1;
  94560. FLAC__ASSERT(0 != bw);
  94561. FLAC__ASSERT(0 != bw->buffer);
  94562. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94563. if(val < 0x80) {
  94564. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94565. }
  94566. else if(val < 0x800) {
  94567. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94568. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94569. }
  94570. else if(val < 0x10000) {
  94571. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94572. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94573. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94574. }
  94575. else if(val < 0x200000) {
  94576. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94577. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94578. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94579. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94580. }
  94581. else if(val < 0x4000000) {
  94582. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94583. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94584. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94585. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94586. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94587. }
  94588. else if(val < 0x80000000) {
  94589. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94590. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94591. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94592. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94593. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94594. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94595. }
  94596. else {
  94597. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94598. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94599. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94600. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94601. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94602. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94603. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94604. }
  94605. return ok;
  94606. }
  94607. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94608. {
  94609. /* 0-pad to byte boundary */
  94610. if(bw->bits & 7u)
  94611. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94612. else
  94613. return true;
  94614. }
  94615. #endif
  94616. /*** End of inlined file: bitwriter.c ***/
  94617. /*** Start of inlined file: cpu.c ***/
  94618. /*** Start of inlined file: juce_FlacHeader.h ***/
  94619. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94620. // tasks..
  94621. #define VERSION "1.2.1"
  94622. #define FLAC__NO_DLL 1
  94623. #if JUCE_MSVC
  94624. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94625. #endif
  94626. #if JUCE_MAC
  94627. #define FLAC__SYS_DARWIN 1
  94628. #endif
  94629. /*** End of inlined file: juce_FlacHeader.h ***/
  94630. #if JUCE_USE_FLAC
  94631. #if HAVE_CONFIG_H
  94632. # include <config.h>
  94633. #endif
  94634. #include <stdlib.h>
  94635. #include <stdio.h>
  94636. #if defined FLAC__CPU_IA32
  94637. # include <signal.h>
  94638. #elif defined FLAC__CPU_PPC
  94639. # if !defined FLAC__NO_ASM
  94640. # if defined FLAC__SYS_DARWIN
  94641. # include <sys/sysctl.h>
  94642. # include <mach/mach.h>
  94643. # include <mach/mach_host.h>
  94644. # include <mach/host_info.h>
  94645. # include <mach/machine.h>
  94646. # ifndef CPU_SUBTYPE_POWERPC_970
  94647. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94648. # endif
  94649. # else /* FLAC__SYS_DARWIN */
  94650. # include <signal.h>
  94651. # include <setjmp.h>
  94652. static sigjmp_buf jmpbuf;
  94653. static volatile sig_atomic_t canjump = 0;
  94654. static void sigill_handler (int sig)
  94655. {
  94656. if (!canjump) {
  94657. signal (sig, SIG_DFL);
  94658. raise (sig);
  94659. }
  94660. canjump = 0;
  94661. siglongjmp (jmpbuf, 1);
  94662. }
  94663. # endif /* FLAC__SYS_DARWIN */
  94664. # endif /* FLAC__NO_ASM */
  94665. #endif /* FLAC__CPU_PPC */
  94666. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94667. #include <sys/param.h>
  94668. #include <sys/sysctl.h>
  94669. #include <machine/cpu.h>
  94670. #endif
  94671. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94672. #include <sys/types.h>
  94673. #include <sys/sysctl.h>
  94674. #endif
  94675. #if defined(__APPLE__)
  94676. /* how to get sysctlbyname()? */
  94677. #endif
  94678. /* these are flags in EDX of CPUID AX=00000001 */
  94679. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94680. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94681. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94682. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94683. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94684. /* these are flags in ECX of CPUID AX=00000001 */
  94685. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94686. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94687. /* these are flags in EDX of CPUID AX=80000001 */
  94688. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94689. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94690. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94691. /*
  94692. * Extra stuff needed for detection of OS support for SSE on IA-32
  94693. */
  94694. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94695. # if defined(__linux__)
  94696. /*
  94697. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94698. * modify the return address to jump over the offending SSE instruction
  94699. * and also the operation following it that indicates the instruction
  94700. * executed successfully. In this way we use no global variables and
  94701. * stay thread-safe.
  94702. *
  94703. * 3 + 3 + 6:
  94704. * 3 bytes for "xorps xmm0,xmm0"
  94705. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94706. * 6 bytes extra in case our estimate is wrong
  94707. * 12 bytes puts us in the NOP "landing zone"
  94708. */
  94709. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94710. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94711. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94712. {
  94713. (void)signal;
  94714. sc.eip += 3 + 3 + 6;
  94715. }
  94716. # else
  94717. # include <sys/ucontext.h>
  94718. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94719. {
  94720. (void)signal, (void)si;
  94721. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94722. }
  94723. # endif
  94724. # elif defined(_MSC_VER)
  94725. # include <windows.h>
  94726. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94727. # ifdef USE_TRY_CATCH_FLAVOR
  94728. # else
  94729. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94730. {
  94731. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94732. ep->ContextRecord->Eip += 3 + 3 + 6;
  94733. return EXCEPTION_CONTINUE_EXECUTION;
  94734. }
  94735. return EXCEPTION_CONTINUE_SEARCH;
  94736. }
  94737. # endif
  94738. # endif
  94739. #endif
  94740. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94741. {
  94742. /*
  94743. * IA32-specific
  94744. */
  94745. #ifdef FLAC__CPU_IA32
  94746. info->type = FLAC__CPUINFO_TYPE_IA32;
  94747. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94748. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94749. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94750. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94751. info->data.ia32.cmov = false;
  94752. info->data.ia32.mmx = false;
  94753. info->data.ia32.fxsr = false;
  94754. info->data.ia32.sse = false;
  94755. info->data.ia32.sse2 = false;
  94756. info->data.ia32.sse3 = false;
  94757. info->data.ia32.ssse3 = false;
  94758. info->data.ia32._3dnow = false;
  94759. info->data.ia32.ext3dnow = false;
  94760. info->data.ia32.extmmx = false;
  94761. if(info->data.ia32.cpuid) {
  94762. /* http://www.sandpile.org/ia32/cpuid.htm */
  94763. FLAC__uint32 flags_edx, flags_ecx;
  94764. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94765. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94766. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94767. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94768. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94769. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94770. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94771. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94772. #ifdef FLAC__USE_3DNOW
  94773. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94774. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94775. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94776. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94777. #else
  94778. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94779. #endif
  94780. #ifdef DEBUG
  94781. fprintf(stderr, "CPU info (IA-32):\n");
  94782. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94783. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94784. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94785. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94786. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94787. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94788. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94789. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94790. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94791. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94792. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  94793. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  94794. #endif
  94795. /*
  94796. * now have to check for OS support of SSE/SSE2
  94797. */
  94798. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  94799. #if defined FLAC__NO_SSE_OS
  94800. /* assume user knows better than us; turn it off */
  94801. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94802. #elif defined FLAC__SSE_OS
  94803. /* assume user knows better than us; leave as detected above */
  94804. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  94805. int sse = 0;
  94806. size_t len;
  94807. /* at least one of these must work: */
  94808. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  94809. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  94810. if(!sse)
  94811. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94812. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  94813. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  94814. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  94815. size_t len = sizeof(val);
  94816. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94817. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94818. else { /* double-check SSE2 */
  94819. mib[1] = CPU_SSE2;
  94820. len = sizeof(val);
  94821. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94822. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94823. }
  94824. # else
  94825. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94826. # endif
  94827. #elif defined(__linux__)
  94828. int sse = 0;
  94829. struct sigaction sigill_save;
  94830. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94831. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  94832. #else
  94833. struct sigaction sigill_sse;
  94834. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  94835. __sigemptyset(&sigill_sse.sa_mask);
  94836. 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 */
  94837. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  94838. #endif
  94839. {
  94840. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  94841. /* see sigill_handler_sse_os() for an explanation of the following: */
  94842. asm volatile (
  94843. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  94844. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  94845. "incl %0\n\t" /* SIGILL handler will jump over this */
  94846. /* landing zone */
  94847. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  94848. "nop\n\t"
  94849. "nop\n\t"
  94850. "nop\n\t"
  94851. "nop\n\t"
  94852. "nop\n\t"
  94853. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  94854. "nop\n\t"
  94855. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  94856. : "=r"(sse)
  94857. : "r"(sse)
  94858. );
  94859. sigaction(SIGILL, &sigill_save, NULL);
  94860. }
  94861. if(!sse)
  94862. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94863. #elif defined(_MSC_VER)
  94864. # ifdef USE_TRY_CATCH_FLAVOR
  94865. _try {
  94866. __asm {
  94867. # if _MSC_VER <= 1200
  94868. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94869. _emit 0x0F
  94870. _emit 0x57
  94871. _emit 0xC0
  94872. # else
  94873. xorps xmm0,xmm0
  94874. # endif
  94875. }
  94876. }
  94877. _except(EXCEPTION_EXECUTE_HANDLER) {
  94878. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  94879. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94880. }
  94881. # else
  94882. int sse = 0;
  94883. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  94884. /* see GCC version above for explanation */
  94885. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  94886. /* http://www.codeproject.com/cpp/gccasm.asp */
  94887. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  94888. __asm {
  94889. # if _MSC_VER <= 1200
  94890. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94891. _emit 0x0F
  94892. _emit 0x57
  94893. _emit 0xC0
  94894. # else
  94895. xorps xmm0,xmm0
  94896. # endif
  94897. inc sse
  94898. nop
  94899. nop
  94900. nop
  94901. nop
  94902. nop
  94903. nop
  94904. nop
  94905. nop
  94906. nop
  94907. }
  94908. SetUnhandledExceptionFilter(save);
  94909. if(!sse)
  94910. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94911. # endif
  94912. #else
  94913. /* no way to test, disable to be safe */
  94914. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94915. #endif
  94916. #ifdef DEBUG
  94917. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94918. #endif
  94919. }
  94920. }
  94921. #else
  94922. info->use_asm = false;
  94923. #endif
  94924. /*
  94925. * PPC-specific
  94926. */
  94927. #elif defined FLAC__CPU_PPC
  94928. info->type = FLAC__CPUINFO_TYPE_PPC;
  94929. # if !defined FLAC__NO_ASM
  94930. info->use_asm = true;
  94931. # ifdef FLAC__USE_ALTIVEC
  94932. # if defined FLAC__SYS_DARWIN
  94933. {
  94934. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  94935. size_t len = sizeof(val);
  94936. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  94937. }
  94938. {
  94939. host_basic_info_data_t hostInfo;
  94940. mach_msg_type_number_t infoCount;
  94941. infoCount = HOST_BASIC_INFO_COUNT;
  94942. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  94943. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  94944. }
  94945. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  94946. {
  94947. /* no Darwin, do it the brute-force way */
  94948. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  94949. info->data.ppc.altivec = 0;
  94950. info->data.ppc.ppc64 = 0;
  94951. signal (SIGILL, sigill_handler);
  94952. canjump = 0;
  94953. if (!sigsetjmp (jmpbuf, 1)) {
  94954. canjump = 1;
  94955. asm volatile (
  94956. "mtspr 256, %0\n\t"
  94957. "vand %%v0, %%v0, %%v0"
  94958. :
  94959. : "r" (-1)
  94960. );
  94961. info->data.ppc.altivec = 1;
  94962. }
  94963. canjump = 0;
  94964. if (!sigsetjmp (jmpbuf, 1)) {
  94965. int x = 0;
  94966. canjump = 1;
  94967. /* PPC64 hardware implements the cntlzd instruction */
  94968. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  94969. info->data.ppc.ppc64 = 1;
  94970. }
  94971. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  94972. }
  94973. # endif
  94974. # else /* !FLAC__USE_ALTIVEC */
  94975. info->data.ppc.altivec = 0;
  94976. info->data.ppc.ppc64 = 0;
  94977. # endif
  94978. # else
  94979. info->use_asm = false;
  94980. # endif
  94981. /*
  94982. * unknown CPI
  94983. */
  94984. #else
  94985. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  94986. info->use_asm = false;
  94987. #endif
  94988. }
  94989. #endif
  94990. /*** End of inlined file: cpu.c ***/
  94991. /*** Start of inlined file: crc.c ***/
  94992. /*** Start of inlined file: juce_FlacHeader.h ***/
  94993. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94994. // tasks..
  94995. #define VERSION "1.2.1"
  94996. #define FLAC__NO_DLL 1
  94997. #if JUCE_MSVC
  94998. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94999. #endif
  95000. #if JUCE_MAC
  95001. #define FLAC__SYS_DARWIN 1
  95002. #endif
  95003. /*** End of inlined file: juce_FlacHeader.h ***/
  95004. #if JUCE_USE_FLAC
  95005. #if HAVE_CONFIG_H
  95006. # include <config.h>
  95007. #endif
  95008. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95009. FLAC__byte const FLAC__crc8_table[256] = {
  95010. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95011. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95012. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95013. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95014. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95015. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95016. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95017. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95018. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95019. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95020. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95021. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95022. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95023. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95024. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95025. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95026. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95027. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95028. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95029. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95030. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95031. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95032. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95033. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95034. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95035. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95036. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95037. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95038. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95039. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95040. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95041. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95042. };
  95043. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95044. unsigned FLAC__crc16_table[256] = {
  95045. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95046. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95047. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95048. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95049. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95050. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95051. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95052. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95053. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95054. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95055. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95056. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95057. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95058. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95059. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95060. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95061. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95062. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95063. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95064. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95065. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95066. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95067. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95068. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95069. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95070. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95071. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95072. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95073. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95074. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95075. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95076. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95077. };
  95078. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95079. {
  95080. *crc = FLAC__crc8_table[*crc ^ data];
  95081. }
  95082. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95083. {
  95084. while(len--)
  95085. *crc = FLAC__crc8_table[*crc ^ *data++];
  95086. }
  95087. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95088. {
  95089. FLAC__uint8 crc = 0;
  95090. while(len--)
  95091. crc = FLAC__crc8_table[crc ^ *data++];
  95092. return crc;
  95093. }
  95094. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95095. {
  95096. unsigned crc = 0;
  95097. while(len--)
  95098. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95099. return crc;
  95100. }
  95101. #endif
  95102. /*** End of inlined file: crc.c ***/
  95103. /*** Start of inlined file: fixed.c ***/
  95104. /*** Start of inlined file: juce_FlacHeader.h ***/
  95105. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95106. // tasks..
  95107. #define VERSION "1.2.1"
  95108. #define FLAC__NO_DLL 1
  95109. #if JUCE_MSVC
  95110. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95111. #endif
  95112. #if JUCE_MAC
  95113. #define FLAC__SYS_DARWIN 1
  95114. #endif
  95115. /*** End of inlined file: juce_FlacHeader.h ***/
  95116. #if JUCE_USE_FLAC
  95117. #if HAVE_CONFIG_H
  95118. # include <config.h>
  95119. #endif
  95120. #include <math.h>
  95121. #include <string.h>
  95122. /*** Start of inlined file: fixed.h ***/
  95123. #ifndef FLAC__PRIVATE__FIXED_H
  95124. #define FLAC__PRIVATE__FIXED_H
  95125. #ifdef HAVE_CONFIG_H
  95126. #include <config.h>
  95127. #endif
  95128. /*** Start of inlined file: float.h ***/
  95129. #ifndef FLAC__PRIVATE__FLOAT_H
  95130. #define FLAC__PRIVATE__FLOAT_H
  95131. #ifdef HAVE_CONFIG_H
  95132. #include <config.h>
  95133. #endif
  95134. /*
  95135. * These typedefs make it easier to ensure that integer versions of
  95136. * the library really only contain integer operations. All the code
  95137. * in libFLAC should use FLAC__float and FLAC__double in place of
  95138. * float and double, and be protected by checks of the macro
  95139. * FLAC__INTEGER_ONLY_LIBRARY.
  95140. *
  95141. * FLAC__real is the basic floating point type used in LPC analysis.
  95142. */
  95143. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95144. typedef double FLAC__double;
  95145. typedef float FLAC__float;
  95146. /*
  95147. * WATCHOUT: changing FLAC__real will change the signatures of many
  95148. * functions that have assembly language equivalents and break them.
  95149. */
  95150. typedef float FLAC__real;
  95151. #else
  95152. /*
  95153. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95154. * for the integer part and lower 16 bits for the fractional part.
  95155. */
  95156. typedef FLAC__int32 FLAC__fixedpoint;
  95157. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95158. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95159. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95160. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95161. extern const FLAC__fixedpoint FLAC__FP_E;
  95162. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95163. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95164. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95165. /*
  95166. * FLAC__fixedpoint_log2()
  95167. * --------------------------------------------------------------------
  95168. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95169. * algorithm by Knuth for x >= 1.0
  95170. *
  95171. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95172. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95173. *
  95174. * 'precision' roughly limits the number of iterations that are done;
  95175. * use (unsigned)(-1) for maximum precision.
  95176. *
  95177. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95178. * function will punt and return 0.
  95179. *
  95180. * The return value will also have 'fracbits' fractional bits.
  95181. */
  95182. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95183. #endif
  95184. #endif
  95185. /*** End of inlined file: float.h ***/
  95186. /*** Start of inlined file: format.h ***/
  95187. #ifndef FLAC__PRIVATE__FORMAT_H
  95188. #define FLAC__PRIVATE__FORMAT_H
  95189. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95190. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95191. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95192. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95193. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95194. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95195. #endif
  95196. /*** End of inlined file: format.h ***/
  95197. /*
  95198. * FLAC__fixed_compute_best_predictor()
  95199. * --------------------------------------------------------------------
  95200. * Compute the best fixed predictor and the expected bits-per-sample
  95201. * of the residual signal for each order. The _wide() version uses
  95202. * 64-bit integers which is statistically necessary when bits-per-
  95203. * sample + log2(blocksize) > 30
  95204. *
  95205. * IN data[0,data_len-1]
  95206. * IN data_len
  95207. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95208. */
  95209. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95210. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95211. # ifndef FLAC__NO_ASM
  95212. # ifdef FLAC__CPU_IA32
  95213. # ifdef FLAC__HAS_NASM
  95214. 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]);
  95215. # endif
  95216. # endif
  95217. # endif
  95218. 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]);
  95219. #else
  95220. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95221. 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]);
  95222. #endif
  95223. /*
  95224. * FLAC__fixed_compute_residual()
  95225. * --------------------------------------------------------------------
  95226. * Compute the residual signal obtained from sutracting the predicted
  95227. * signal from the original.
  95228. *
  95229. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95230. * IN data_len length of original signal
  95231. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95232. * OUT residual[0,data_len-1] residual signal
  95233. */
  95234. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95235. /*
  95236. * FLAC__fixed_restore_signal()
  95237. * --------------------------------------------------------------------
  95238. * Restore the original signal by summing the residual and the
  95239. * predictor.
  95240. *
  95241. * IN residual[0,data_len-1] residual signal
  95242. * IN data_len length of original signal
  95243. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95244. * *** IMPORTANT: the caller must pass in the historical samples:
  95245. * IN data[-order,-1] previously-reconstructed historical samples
  95246. * OUT data[0,data_len-1] original signal
  95247. */
  95248. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95249. #endif
  95250. /*** End of inlined file: fixed.h ***/
  95251. #ifndef M_LN2
  95252. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95253. #define M_LN2 0.69314718055994530942
  95254. #endif
  95255. #ifdef min
  95256. #undef min
  95257. #endif
  95258. #define min(x,y) ((x) < (y)? (x) : (y))
  95259. #ifdef local_abs
  95260. #undef local_abs
  95261. #endif
  95262. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95263. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95264. /* rbps stands for residual bits per sample
  95265. *
  95266. * (ln(2) * err)
  95267. * rbps = log (-----------)
  95268. * 2 ( n )
  95269. */
  95270. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95271. {
  95272. FLAC__uint32 rbps;
  95273. unsigned bits; /* the number of bits required to represent a number */
  95274. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95275. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95276. FLAC__ASSERT(err > 0);
  95277. FLAC__ASSERT(n > 0);
  95278. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95279. if(err <= n)
  95280. return 0;
  95281. /*
  95282. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95283. * These allow us later to know we won't lose too much precision in the
  95284. * fixed-point division (err<<fracbits)/n.
  95285. */
  95286. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95287. err <<= fracbits;
  95288. err /= n;
  95289. /* err now holds err/n with fracbits fractional bits */
  95290. /*
  95291. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95292. * our purposes.
  95293. */
  95294. FLAC__ASSERT(err > 0);
  95295. bits = FLAC__bitmath_ilog2(err)+1;
  95296. if(bits > 16) {
  95297. err >>= (bits-16);
  95298. fracbits -= (bits-16);
  95299. }
  95300. rbps = (FLAC__uint32)err;
  95301. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95302. rbps *= FLAC__FP_LN2;
  95303. fracbits += 16;
  95304. FLAC__ASSERT(fracbits >= 0);
  95305. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95306. {
  95307. const int f = fracbits & 3;
  95308. if(f) {
  95309. rbps >>= f;
  95310. fracbits -= f;
  95311. }
  95312. }
  95313. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95314. if(rbps == 0)
  95315. return 0;
  95316. /*
  95317. * The return value must have 16 fractional bits. Since the whole part
  95318. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95319. * must be >= -3, these assertion allows us to be able to shift rbps
  95320. * left if necessary to get 16 fracbits without losing any bits of the
  95321. * whole part of rbps.
  95322. *
  95323. * There is a slight chance due to accumulated error that the whole part
  95324. * will require 6 bits, so we use 6 in the assertion. Really though as
  95325. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95326. */
  95327. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95328. FLAC__ASSERT(fracbits >= -3);
  95329. /* now shift the decimal point into place */
  95330. if(fracbits < 16)
  95331. return rbps << (16-fracbits);
  95332. else if(fracbits > 16)
  95333. return rbps >> (fracbits-16);
  95334. else
  95335. return rbps;
  95336. }
  95337. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95338. {
  95339. FLAC__uint32 rbps;
  95340. unsigned bits; /* the number of bits required to represent a number */
  95341. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95342. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95343. FLAC__ASSERT(err > 0);
  95344. FLAC__ASSERT(n > 0);
  95345. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95346. if(err <= n)
  95347. return 0;
  95348. /*
  95349. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95350. * These allow us later to know we won't lose too much precision in the
  95351. * fixed-point division (err<<fracbits)/n.
  95352. */
  95353. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95354. err <<= fracbits;
  95355. err /= n;
  95356. /* err now holds err/n with fracbits fractional bits */
  95357. /*
  95358. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95359. * our purposes.
  95360. */
  95361. FLAC__ASSERT(err > 0);
  95362. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95363. if(bits > 16) {
  95364. err >>= (bits-16);
  95365. fracbits -= (bits-16);
  95366. }
  95367. rbps = (FLAC__uint32)err;
  95368. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95369. rbps *= FLAC__FP_LN2;
  95370. fracbits += 16;
  95371. FLAC__ASSERT(fracbits >= 0);
  95372. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95373. {
  95374. const int f = fracbits & 3;
  95375. if(f) {
  95376. rbps >>= f;
  95377. fracbits -= f;
  95378. }
  95379. }
  95380. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95381. if(rbps == 0)
  95382. return 0;
  95383. /*
  95384. * The return value must have 16 fractional bits. Since the whole part
  95385. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95386. * must be >= -3, these assertion allows us to be able to shift rbps
  95387. * left if necessary to get 16 fracbits without losing any bits of the
  95388. * whole part of rbps.
  95389. *
  95390. * There is a slight chance due to accumulated error that the whole part
  95391. * will require 6 bits, so we use 6 in the assertion. Really though as
  95392. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95393. */
  95394. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95395. FLAC__ASSERT(fracbits >= -3);
  95396. /* now shift the decimal point into place */
  95397. if(fracbits < 16)
  95398. return rbps << (16-fracbits);
  95399. else if(fracbits > 16)
  95400. return rbps >> (fracbits-16);
  95401. else
  95402. return rbps;
  95403. }
  95404. #endif
  95405. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95406. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95407. #else
  95408. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95409. #endif
  95410. {
  95411. FLAC__int32 last_error_0 = data[-1];
  95412. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95413. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95414. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95415. FLAC__int32 error, save;
  95416. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95417. unsigned i, order;
  95418. for(i = 0; i < data_len; i++) {
  95419. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95420. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95421. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95422. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95423. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95424. }
  95425. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95426. order = 0;
  95427. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95428. order = 1;
  95429. else if(total_error_2 < min(total_error_3, total_error_4))
  95430. order = 2;
  95431. else if(total_error_3 < total_error_4)
  95432. order = 3;
  95433. else
  95434. order = 4;
  95435. /* Estimate the expected number of bits per residual signal sample. */
  95436. /* 'total_error*' is linearly related to the variance of the residual */
  95437. /* signal, so we use it directly to compute E(|x|) */
  95438. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95439. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95440. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95441. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95442. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95443. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95444. 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);
  95445. 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);
  95446. 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);
  95447. 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);
  95448. 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);
  95449. #else
  95450. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95451. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95452. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95453. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95454. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95455. #endif
  95456. return order;
  95457. }
  95458. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95459. 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])
  95460. #else
  95461. 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])
  95462. #endif
  95463. {
  95464. FLAC__int32 last_error_0 = data[-1];
  95465. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95466. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95467. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95468. FLAC__int32 error, save;
  95469. /* total_error_* are 64-bits to avoid overflow when encoding
  95470. * erratic signals when the bits-per-sample and blocksize are
  95471. * large.
  95472. */
  95473. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95474. unsigned i, order;
  95475. for(i = 0; i < data_len; i++) {
  95476. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95477. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95478. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95479. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95480. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95481. }
  95482. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95483. order = 0;
  95484. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95485. order = 1;
  95486. else if(total_error_2 < min(total_error_3, total_error_4))
  95487. order = 2;
  95488. else if(total_error_3 < total_error_4)
  95489. order = 3;
  95490. else
  95491. order = 4;
  95492. /* Estimate the expected number of bits per residual signal sample. */
  95493. /* 'total_error*' is linearly related to the variance of the residual */
  95494. /* signal, so we use it directly to compute E(|x|) */
  95495. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95496. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95497. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95498. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95499. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95500. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95501. #if defined _MSC_VER || defined __MINGW32__
  95502. /* with MSVC you have to spoon feed it the casting */
  95503. 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);
  95504. 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);
  95505. 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);
  95506. 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);
  95507. 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);
  95508. #else
  95509. 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);
  95510. 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);
  95511. 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);
  95512. 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);
  95513. 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);
  95514. #endif
  95515. #else
  95516. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95517. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95518. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95519. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95520. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95521. #endif
  95522. return order;
  95523. }
  95524. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95525. {
  95526. const int idata_len = (int)data_len;
  95527. int i;
  95528. switch(order) {
  95529. case 0:
  95530. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95531. memcpy(residual, data, sizeof(residual[0])*data_len);
  95532. break;
  95533. case 1:
  95534. for(i = 0; i < idata_len; i++)
  95535. residual[i] = data[i] - data[i-1];
  95536. break;
  95537. case 2:
  95538. for(i = 0; i < idata_len; i++)
  95539. #if 1 /* OPT: may be faster with some compilers on some systems */
  95540. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95541. #else
  95542. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95543. #endif
  95544. break;
  95545. case 3:
  95546. for(i = 0; i < idata_len; i++)
  95547. #if 1 /* OPT: may be faster with some compilers on some systems */
  95548. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95549. #else
  95550. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95551. #endif
  95552. break;
  95553. case 4:
  95554. for(i = 0; i < idata_len; i++)
  95555. #if 1 /* OPT: may be faster with some compilers on some systems */
  95556. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95557. #else
  95558. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95559. #endif
  95560. break;
  95561. default:
  95562. FLAC__ASSERT(0);
  95563. }
  95564. }
  95565. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95566. {
  95567. int i, idata_len = (int)data_len;
  95568. switch(order) {
  95569. case 0:
  95570. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95571. memcpy(data, residual, sizeof(residual[0])*data_len);
  95572. break;
  95573. case 1:
  95574. for(i = 0; i < idata_len; i++)
  95575. data[i] = residual[i] + data[i-1];
  95576. break;
  95577. case 2:
  95578. for(i = 0; i < idata_len; i++)
  95579. #if 1 /* OPT: may be faster with some compilers on some systems */
  95580. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95581. #else
  95582. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95583. #endif
  95584. break;
  95585. case 3:
  95586. for(i = 0; i < idata_len; i++)
  95587. #if 1 /* OPT: may be faster with some compilers on some systems */
  95588. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95589. #else
  95590. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95591. #endif
  95592. break;
  95593. case 4:
  95594. for(i = 0; i < idata_len; i++)
  95595. #if 1 /* OPT: may be faster with some compilers on some systems */
  95596. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95597. #else
  95598. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95599. #endif
  95600. break;
  95601. default:
  95602. FLAC__ASSERT(0);
  95603. }
  95604. }
  95605. #endif
  95606. /*** End of inlined file: fixed.c ***/
  95607. /*** Start of inlined file: float.c ***/
  95608. /*** Start of inlined file: juce_FlacHeader.h ***/
  95609. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95610. // tasks..
  95611. #define VERSION "1.2.1"
  95612. #define FLAC__NO_DLL 1
  95613. #if JUCE_MSVC
  95614. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95615. #endif
  95616. #if JUCE_MAC
  95617. #define FLAC__SYS_DARWIN 1
  95618. #endif
  95619. /*** End of inlined file: juce_FlacHeader.h ***/
  95620. #if JUCE_USE_FLAC
  95621. #if HAVE_CONFIG_H
  95622. # include <config.h>
  95623. #endif
  95624. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95625. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95626. #ifdef _MSC_VER
  95627. #define FLAC__U64L(x) x
  95628. #else
  95629. #define FLAC__U64L(x) x##LLU
  95630. #endif
  95631. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95632. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95633. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95634. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95635. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95636. /* Lookup tables for Knuth's logarithm algorithm */
  95637. #define LOG2_LOOKUP_PRECISION 16
  95638. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95639. {
  95640. /*
  95641. * 0 fraction bits
  95642. */
  95643. /* undefined */ 0x00000000,
  95644. /* lg(2/1) = */ 0x00000001,
  95645. /* lg(4/3) = */ 0x00000000,
  95646. /* lg(8/7) = */ 0x00000000,
  95647. /* lg(16/15) = */ 0x00000000,
  95648. /* lg(32/31) = */ 0x00000000,
  95649. /* lg(64/63) = */ 0x00000000,
  95650. /* lg(128/127) = */ 0x00000000,
  95651. /* lg(256/255) = */ 0x00000000,
  95652. /* lg(512/511) = */ 0x00000000,
  95653. /* lg(1024/1023) = */ 0x00000000,
  95654. /* lg(2048/2047) = */ 0x00000000,
  95655. /* lg(4096/4095) = */ 0x00000000,
  95656. /* lg(8192/8191) = */ 0x00000000,
  95657. /* lg(16384/16383) = */ 0x00000000,
  95658. /* lg(32768/32767) = */ 0x00000000
  95659. },
  95660. {
  95661. /*
  95662. * 4 fraction bits
  95663. */
  95664. /* undefined */ 0x00000000,
  95665. /* lg(2/1) = */ 0x00000010,
  95666. /* lg(4/3) = */ 0x00000007,
  95667. /* lg(8/7) = */ 0x00000003,
  95668. /* lg(16/15) = */ 0x00000001,
  95669. /* lg(32/31) = */ 0x00000001,
  95670. /* lg(64/63) = */ 0x00000000,
  95671. /* lg(128/127) = */ 0x00000000,
  95672. /* lg(256/255) = */ 0x00000000,
  95673. /* lg(512/511) = */ 0x00000000,
  95674. /* lg(1024/1023) = */ 0x00000000,
  95675. /* lg(2048/2047) = */ 0x00000000,
  95676. /* lg(4096/4095) = */ 0x00000000,
  95677. /* lg(8192/8191) = */ 0x00000000,
  95678. /* lg(16384/16383) = */ 0x00000000,
  95679. /* lg(32768/32767) = */ 0x00000000
  95680. },
  95681. {
  95682. /*
  95683. * 8 fraction bits
  95684. */
  95685. /* undefined */ 0x00000000,
  95686. /* lg(2/1) = */ 0x00000100,
  95687. /* lg(4/3) = */ 0x0000006a,
  95688. /* lg(8/7) = */ 0x00000031,
  95689. /* lg(16/15) = */ 0x00000018,
  95690. /* lg(32/31) = */ 0x0000000c,
  95691. /* lg(64/63) = */ 0x00000006,
  95692. /* lg(128/127) = */ 0x00000003,
  95693. /* lg(256/255) = */ 0x00000001,
  95694. /* lg(512/511) = */ 0x00000001,
  95695. /* lg(1024/1023) = */ 0x00000000,
  95696. /* lg(2048/2047) = */ 0x00000000,
  95697. /* lg(4096/4095) = */ 0x00000000,
  95698. /* lg(8192/8191) = */ 0x00000000,
  95699. /* lg(16384/16383) = */ 0x00000000,
  95700. /* lg(32768/32767) = */ 0x00000000
  95701. },
  95702. {
  95703. /*
  95704. * 12 fraction bits
  95705. */
  95706. /* undefined */ 0x00000000,
  95707. /* lg(2/1) = */ 0x00001000,
  95708. /* lg(4/3) = */ 0x000006a4,
  95709. /* lg(8/7) = */ 0x00000315,
  95710. /* lg(16/15) = */ 0x0000017d,
  95711. /* lg(32/31) = */ 0x000000bc,
  95712. /* lg(64/63) = */ 0x0000005d,
  95713. /* lg(128/127) = */ 0x0000002e,
  95714. /* lg(256/255) = */ 0x00000017,
  95715. /* lg(512/511) = */ 0x0000000c,
  95716. /* lg(1024/1023) = */ 0x00000006,
  95717. /* lg(2048/2047) = */ 0x00000003,
  95718. /* lg(4096/4095) = */ 0x00000001,
  95719. /* lg(8192/8191) = */ 0x00000001,
  95720. /* lg(16384/16383) = */ 0x00000000,
  95721. /* lg(32768/32767) = */ 0x00000000
  95722. },
  95723. {
  95724. /*
  95725. * 16 fraction bits
  95726. */
  95727. /* undefined */ 0x00000000,
  95728. /* lg(2/1) = */ 0x00010000,
  95729. /* lg(4/3) = */ 0x00006a40,
  95730. /* lg(8/7) = */ 0x00003151,
  95731. /* lg(16/15) = */ 0x000017d6,
  95732. /* lg(32/31) = */ 0x00000bba,
  95733. /* lg(64/63) = */ 0x000005d1,
  95734. /* lg(128/127) = */ 0x000002e6,
  95735. /* lg(256/255) = */ 0x00000172,
  95736. /* lg(512/511) = */ 0x000000b9,
  95737. /* lg(1024/1023) = */ 0x0000005c,
  95738. /* lg(2048/2047) = */ 0x0000002e,
  95739. /* lg(4096/4095) = */ 0x00000017,
  95740. /* lg(8192/8191) = */ 0x0000000c,
  95741. /* lg(16384/16383) = */ 0x00000006,
  95742. /* lg(32768/32767) = */ 0x00000003
  95743. },
  95744. {
  95745. /*
  95746. * 20 fraction bits
  95747. */
  95748. /* undefined */ 0x00000000,
  95749. /* lg(2/1) = */ 0x00100000,
  95750. /* lg(4/3) = */ 0x0006a3fe,
  95751. /* lg(8/7) = */ 0x00031513,
  95752. /* lg(16/15) = */ 0x00017d60,
  95753. /* lg(32/31) = */ 0x0000bb9d,
  95754. /* lg(64/63) = */ 0x00005d10,
  95755. /* lg(128/127) = */ 0x00002e59,
  95756. /* lg(256/255) = */ 0x00001721,
  95757. /* lg(512/511) = */ 0x00000b8e,
  95758. /* lg(1024/1023) = */ 0x000005c6,
  95759. /* lg(2048/2047) = */ 0x000002e3,
  95760. /* lg(4096/4095) = */ 0x00000171,
  95761. /* lg(8192/8191) = */ 0x000000b9,
  95762. /* lg(16384/16383) = */ 0x0000005c,
  95763. /* lg(32768/32767) = */ 0x0000002e
  95764. },
  95765. {
  95766. /*
  95767. * 24 fraction bits
  95768. */
  95769. /* undefined */ 0x00000000,
  95770. /* lg(2/1) = */ 0x01000000,
  95771. /* lg(4/3) = */ 0x006a3fe6,
  95772. /* lg(8/7) = */ 0x00315130,
  95773. /* lg(16/15) = */ 0x0017d605,
  95774. /* lg(32/31) = */ 0x000bb9ca,
  95775. /* lg(64/63) = */ 0x0005d0fc,
  95776. /* lg(128/127) = */ 0x0002e58f,
  95777. /* lg(256/255) = */ 0x0001720e,
  95778. /* lg(512/511) = */ 0x0000b8d8,
  95779. /* lg(1024/1023) = */ 0x00005c61,
  95780. /* lg(2048/2047) = */ 0x00002e2d,
  95781. /* lg(4096/4095) = */ 0x00001716,
  95782. /* lg(8192/8191) = */ 0x00000b8b,
  95783. /* lg(16384/16383) = */ 0x000005c5,
  95784. /* lg(32768/32767) = */ 0x000002e3
  95785. },
  95786. {
  95787. /*
  95788. * 28 fraction bits
  95789. */
  95790. /* undefined */ 0x00000000,
  95791. /* lg(2/1) = */ 0x10000000,
  95792. /* lg(4/3) = */ 0x06a3fe5c,
  95793. /* lg(8/7) = */ 0x03151301,
  95794. /* lg(16/15) = */ 0x017d6049,
  95795. /* lg(32/31) = */ 0x00bb9ca6,
  95796. /* lg(64/63) = */ 0x005d0fba,
  95797. /* lg(128/127) = */ 0x002e58f7,
  95798. /* lg(256/255) = */ 0x001720da,
  95799. /* lg(512/511) = */ 0x000b8d87,
  95800. /* lg(1024/1023) = */ 0x0005c60b,
  95801. /* lg(2048/2047) = */ 0x0002e2d7,
  95802. /* lg(4096/4095) = */ 0x00017160,
  95803. /* lg(8192/8191) = */ 0x0000b8ad,
  95804. /* lg(16384/16383) = */ 0x00005c56,
  95805. /* lg(32768/32767) = */ 0x00002e2b
  95806. }
  95807. };
  95808. #if 0
  95809. static const FLAC__uint64 log2_lookup_wide[] = {
  95810. {
  95811. /*
  95812. * 32 fraction bits
  95813. */
  95814. /* undefined */ 0x00000000,
  95815. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  95816. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  95817. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  95818. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  95819. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  95820. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  95821. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  95822. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  95823. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  95824. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  95825. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  95826. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  95827. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  95828. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  95829. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  95830. },
  95831. {
  95832. /*
  95833. * 48 fraction bits
  95834. */
  95835. /* undefined */ 0x00000000,
  95836. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  95837. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  95838. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  95839. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  95840. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  95841. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  95842. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  95843. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  95844. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  95845. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  95846. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  95847. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  95848. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  95849. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  95850. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  95851. }
  95852. };
  95853. #endif
  95854. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  95855. {
  95856. const FLAC__uint32 ONE = (1u << fracbits);
  95857. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  95858. FLAC__ASSERT(fracbits < 32);
  95859. FLAC__ASSERT((fracbits & 0x3) == 0);
  95860. if(x < ONE)
  95861. return 0;
  95862. if(precision > LOG2_LOOKUP_PRECISION)
  95863. precision = LOG2_LOOKUP_PRECISION;
  95864. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  95865. {
  95866. FLAC__uint32 y = 0;
  95867. FLAC__uint32 z = x >> 1, k = 1;
  95868. while (x > ONE && k < precision) {
  95869. if (x - z >= ONE) {
  95870. x -= z;
  95871. z = x >> k;
  95872. y += table[k];
  95873. }
  95874. else {
  95875. z >>= 1;
  95876. k++;
  95877. }
  95878. }
  95879. return y;
  95880. }
  95881. }
  95882. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  95883. #endif
  95884. /*** End of inlined file: float.c ***/
  95885. /*** Start of inlined file: format.c ***/
  95886. /*** Start of inlined file: juce_FlacHeader.h ***/
  95887. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95888. // tasks..
  95889. #define VERSION "1.2.1"
  95890. #define FLAC__NO_DLL 1
  95891. #if JUCE_MSVC
  95892. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95893. #endif
  95894. #if JUCE_MAC
  95895. #define FLAC__SYS_DARWIN 1
  95896. #endif
  95897. /*** End of inlined file: juce_FlacHeader.h ***/
  95898. #if JUCE_USE_FLAC
  95899. #if HAVE_CONFIG_H
  95900. # include <config.h>
  95901. #endif
  95902. #include <stdio.h>
  95903. #include <stdlib.h> /* for qsort() */
  95904. #include <string.h> /* for memset() */
  95905. #ifndef FLaC__INLINE
  95906. #define FLaC__INLINE
  95907. #endif
  95908. #ifdef min
  95909. #undef min
  95910. #endif
  95911. #define min(a,b) ((a)<(b)?(a):(b))
  95912. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95913. #ifdef _MSC_VER
  95914. #define FLAC__U64L(x) x
  95915. #else
  95916. #define FLAC__U64L(x) x##LLU
  95917. #endif
  95918. /* VERSION should come from configure */
  95919. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  95920. ;
  95921. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  95922. /* yet one more hack because of MSVC6: */
  95923. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  95924. #else
  95925. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  95926. #endif
  95927. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  95928. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  95929. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  95930. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  95931. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  95932. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  95933. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  95934. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  95935. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  95936. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  95937. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  95938. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  95939. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  95940. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  95941. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  95942. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  95943. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  95944. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  95945. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  95946. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  95947. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  95948. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  95949. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  95950. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  95951. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  95952. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  95953. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  95954. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  95955. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  95956. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  95957. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  95958. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  95959. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  95960. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  95961. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  95962. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  95963. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  95964. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  95965. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  95966. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  95967. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  95968. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  95969. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  95970. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  95971. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  95972. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  95973. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  95974. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  95975. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  95976. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  95977. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  95978. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  95979. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  95980. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  95981. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  95982. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  95983. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  95984. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  95985. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  95986. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  95987. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  95988. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  95989. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  95990. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  95991. "PARTITIONED_RICE",
  95992. "PARTITIONED_RICE2"
  95993. };
  95994. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  95995. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  95996. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  95997. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  95998. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  95999. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96000. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96001. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96002. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96003. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96004. "CONSTANT",
  96005. "VERBATIM",
  96006. "FIXED",
  96007. "LPC"
  96008. };
  96009. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96010. "INDEPENDENT",
  96011. "LEFT_SIDE",
  96012. "RIGHT_SIDE",
  96013. "MID_SIDE"
  96014. };
  96015. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96016. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96017. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96018. };
  96019. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96020. "STREAMINFO",
  96021. "PADDING",
  96022. "APPLICATION",
  96023. "SEEKTABLE",
  96024. "VORBIS_COMMENT",
  96025. "CUESHEET",
  96026. "PICTURE"
  96027. };
  96028. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96029. "Other",
  96030. "32x32 pixels 'file icon' (PNG only)",
  96031. "Other file icon",
  96032. "Cover (front)",
  96033. "Cover (back)",
  96034. "Leaflet page",
  96035. "Media (e.g. label side of CD)",
  96036. "Lead artist/lead performer/soloist",
  96037. "Artist/performer",
  96038. "Conductor",
  96039. "Band/Orchestra",
  96040. "Composer",
  96041. "Lyricist/text writer",
  96042. "Recording Location",
  96043. "During recording",
  96044. "During performance",
  96045. "Movie/video screen capture",
  96046. "A bright coloured fish",
  96047. "Illustration",
  96048. "Band/artist logotype",
  96049. "Publisher/Studio logotype"
  96050. };
  96051. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96052. {
  96053. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96054. return false;
  96055. }
  96056. else
  96057. return true;
  96058. }
  96059. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96060. {
  96061. if(
  96062. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96063. (
  96064. sample_rate >= (1u << 16) &&
  96065. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96066. )
  96067. ) {
  96068. return false;
  96069. }
  96070. else
  96071. return true;
  96072. }
  96073. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96074. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96075. {
  96076. unsigned i;
  96077. FLAC__uint64 prev_sample_number = 0;
  96078. FLAC__bool got_prev = false;
  96079. FLAC__ASSERT(0 != seek_table);
  96080. for(i = 0; i < seek_table->num_points; i++) {
  96081. if(got_prev) {
  96082. if(
  96083. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96084. seek_table->points[i].sample_number <= prev_sample_number
  96085. )
  96086. return false;
  96087. }
  96088. prev_sample_number = seek_table->points[i].sample_number;
  96089. got_prev = true;
  96090. }
  96091. return true;
  96092. }
  96093. /* used as the sort predicate for qsort() */
  96094. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96095. {
  96096. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96097. if(l->sample_number == r->sample_number)
  96098. return 0;
  96099. else if(l->sample_number < r->sample_number)
  96100. return -1;
  96101. else
  96102. return 1;
  96103. }
  96104. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96105. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96106. {
  96107. unsigned i, j;
  96108. FLAC__bool first;
  96109. FLAC__ASSERT(0 != seek_table);
  96110. /* sort the seekpoints */
  96111. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96112. /* uniquify the seekpoints */
  96113. first = true;
  96114. for(i = j = 0; i < seek_table->num_points; i++) {
  96115. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96116. if(!first) {
  96117. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96118. continue;
  96119. }
  96120. }
  96121. first = false;
  96122. seek_table->points[j++] = seek_table->points[i];
  96123. }
  96124. for(i = j; i < seek_table->num_points; i++) {
  96125. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96126. seek_table->points[i].stream_offset = 0;
  96127. seek_table->points[i].frame_samples = 0;
  96128. }
  96129. return j;
  96130. }
  96131. /*
  96132. * also disallows non-shortest-form encodings, c.f.
  96133. * http://www.unicode.org/versions/corrigendum1.html
  96134. * and a more clear explanation at the end of this section:
  96135. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96136. */
  96137. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96138. {
  96139. FLAC__ASSERT(0 != utf8);
  96140. if ((utf8[0] & 0x80) == 0) {
  96141. return 1;
  96142. }
  96143. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96144. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96145. return 0;
  96146. return 2;
  96147. }
  96148. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96149. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96150. return 0;
  96151. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96152. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96153. return 0;
  96154. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96155. return 0;
  96156. return 3;
  96157. }
  96158. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96159. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96160. return 0;
  96161. return 4;
  96162. }
  96163. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96164. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96165. return 0;
  96166. return 5;
  96167. }
  96168. 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) {
  96169. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96170. return 0;
  96171. return 6;
  96172. }
  96173. else {
  96174. return 0;
  96175. }
  96176. }
  96177. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96178. {
  96179. char c;
  96180. for(c = *name; c; c = *(++name))
  96181. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96182. return false;
  96183. return true;
  96184. }
  96185. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96186. {
  96187. if(length == (unsigned)(-1)) {
  96188. while(*value) {
  96189. unsigned n = utf8len_(value);
  96190. if(n == 0)
  96191. return false;
  96192. value += n;
  96193. }
  96194. }
  96195. else {
  96196. const FLAC__byte *end = value + length;
  96197. while(value < end) {
  96198. unsigned n = utf8len_(value);
  96199. if(n == 0)
  96200. return false;
  96201. value += n;
  96202. }
  96203. if(value != end)
  96204. return false;
  96205. }
  96206. return true;
  96207. }
  96208. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96209. {
  96210. const FLAC__byte *s, *end;
  96211. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96212. if(*s < 0x20 || *s > 0x7D)
  96213. return false;
  96214. }
  96215. if(s == end)
  96216. return false;
  96217. s++; /* skip '=' */
  96218. while(s < end) {
  96219. unsigned n = utf8len_(s);
  96220. if(n == 0)
  96221. return false;
  96222. s += n;
  96223. }
  96224. if(s != end)
  96225. return false;
  96226. return true;
  96227. }
  96228. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96229. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96230. {
  96231. unsigned i, j;
  96232. if(check_cd_da_subset) {
  96233. if(cue_sheet->lead_in < 2 * 44100) {
  96234. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96235. return false;
  96236. }
  96237. if(cue_sheet->lead_in % 588 != 0) {
  96238. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96239. return false;
  96240. }
  96241. }
  96242. if(cue_sheet->num_tracks == 0) {
  96243. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96244. return false;
  96245. }
  96246. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96247. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96248. return false;
  96249. }
  96250. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96251. if(cue_sheet->tracks[i].number == 0) {
  96252. if(violation) *violation = "cue sheet may not have a track number 0";
  96253. return false;
  96254. }
  96255. if(check_cd_da_subset) {
  96256. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96257. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96258. return false;
  96259. }
  96260. }
  96261. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96262. if(violation) {
  96263. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96264. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96265. else
  96266. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96267. }
  96268. return false;
  96269. }
  96270. if(i < cue_sheet->num_tracks - 1) {
  96271. if(cue_sheet->tracks[i].num_indices == 0) {
  96272. if(violation) *violation = "cue sheet track must have at least one index point";
  96273. return false;
  96274. }
  96275. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96276. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96277. return false;
  96278. }
  96279. }
  96280. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96281. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96282. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96283. return false;
  96284. }
  96285. if(j > 0) {
  96286. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96287. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96288. return false;
  96289. }
  96290. }
  96291. }
  96292. }
  96293. return true;
  96294. }
  96295. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96296. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96297. {
  96298. char *p;
  96299. FLAC__byte *b;
  96300. for(p = picture->mime_type; *p; p++) {
  96301. if(*p < 0x20 || *p > 0x7e) {
  96302. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96303. return false;
  96304. }
  96305. }
  96306. for(b = picture->description; *b; ) {
  96307. unsigned n = utf8len_(b);
  96308. if(n == 0) {
  96309. if(violation) *violation = "description string must be valid UTF-8";
  96310. return false;
  96311. }
  96312. b += n;
  96313. }
  96314. return true;
  96315. }
  96316. /*
  96317. * These routines are private to libFLAC
  96318. */
  96319. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96320. {
  96321. return
  96322. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96323. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96324. blocksize,
  96325. predictor_order
  96326. );
  96327. }
  96328. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96329. {
  96330. unsigned max_rice_partition_order = 0;
  96331. while(!(blocksize & 1)) {
  96332. max_rice_partition_order++;
  96333. blocksize >>= 1;
  96334. }
  96335. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96336. }
  96337. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96338. {
  96339. unsigned max_rice_partition_order = limit;
  96340. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96341. max_rice_partition_order--;
  96342. FLAC__ASSERT(
  96343. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96344. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96345. );
  96346. return max_rice_partition_order;
  96347. }
  96348. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96349. {
  96350. FLAC__ASSERT(0 != object);
  96351. object->parameters = 0;
  96352. object->raw_bits = 0;
  96353. object->capacity_by_order = 0;
  96354. }
  96355. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96356. {
  96357. FLAC__ASSERT(0 != object);
  96358. if(0 != object->parameters)
  96359. free(object->parameters);
  96360. if(0 != object->raw_bits)
  96361. free(object->raw_bits);
  96362. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96363. }
  96364. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96365. {
  96366. FLAC__ASSERT(0 != object);
  96367. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96368. if(object->capacity_by_order < max_partition_order) {
  96369. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96370. return false;
  96371. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96372. return false;
  96373. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96374. object->capacity_by_order = max_partition_order;
  96375. }
  96376. return true;
  96377. }
  96378. #endif
  96379. /*** End of inlined file: format.c ***/
  96380. /*** Start of inlined file: lpc_flac.c ***/
  96381. /*** Start of inlined file: juce_FlacHeader.h ***/
  96382. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96383. // tasks..
  96384. #define VERSION "1.2.1"
  96385. #define FLAC__NO_DLL 1
  96386. #if JUCE_MSVC
  96387. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96388. #endif
  96389. #if JUCE_MAC
  96390. #define FLAC__SYS_DARWIN 1
  96391. #endif
  96392. /*** End of inlined file: juce_FlacHeader.h ***/
  96393. #if JUCE_USE_FLAC
  96394. #if HAVE_CONFIG_H
  96395. # include <config.h>
  96396. #endif
  96397. #include <math.h>
  96398. /*** Start of inlined file: lpc.h ***/
  96399. #ifndef FLAC__PRIVATE__LPC_H
  96400. #define FLAC__PRIVATE__LPC_H
  96401. #ifdef HAVE_CONFIG_H
  96402. #include <config.h>
  96403. #endif
  96404. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96405. /*
  96406. * FLAC__lpc_window_data()
  96407. * --------------------------------------------------------------------
  96408. * Applies the given window to the data.
  96409. * OPT: asm implementation
  96410. *
  96411. * IN in[0,data_len-1]
  96412. * IN window[0,data_len-1]
  96413. * OUT out[0,lag-1]
  96414. * IN data_len
  96415. */
  96416. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96417. /*
  96418. * FLAC__lpc_compute_autocorrelation()
  96419. * --------------------------------------------------------------------
  96420. * Compute the autocorrelation for lags between 0 and lag-1.
  96421. * Assumes data[] outside of [0,data_len-1] == 0.
  96422. * Asserts that lag > 0.
  96423. *
  96424. * IN data[0,data_len-1]
  96425. * IN data_len
  96426. * IN 0 < lag <= data_len
  96427. * OUT autoc[0,lag-1]
  96428. */
  96429. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96430. #ifndef FLAC__NO_ASM
  96431. # ifdef FLAC__CPU_IA32
  96432. # ifdef FLAC__HAS_NASM
  96433. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96434. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96435. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96436. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96437. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96438. # endif
  96439. # endif
  96440. #endif
  96441. /*
  96442. * FLAC__lpc_compute_lp_coefficients()
  96443. * --------------------------------------------------------------------
  96444. * Computes LP coefficients for orders 1..max_order.
  96445. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96446. * and there is no point in calculating a predictor.
  96447. *
  96448. * IN autoc[0,max_order] autocorrelation values
  96449. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96450. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96451. * *** IMPORTANT:
  96452. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96453. * OUT error[0,max_order-1] error for each order (more
  96454. * specifically, the variance of
  96455. * the error signal times # of
  96456. * samples in the signal)
  96457. *
  96458. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96459. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96460. * in lp_coeff[7][0,7], etc.
  96461. */
  96462. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96463. /*
  96464. * FLAC__lpc_quantize_coefficients()
  96465. * --------------------------------------------------------------------
  96466. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96467. * must be less than 32 (sizeof(FLAC__int32)*8).
  96468. *
  96469. * IN lp_coeff[0,order-1] LP coefficients
  96470. * IN order LP order
  96471. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96472. * desired precision (in bits, including sign
  96473. * bit) of largest coefficient
  96474. * OUT qlp_coeff[0,order-1] quantized coefficients
  96475. * OUT shift # of bits to shift right to get approximated
  96476. * LP coefficients. NOTE: could be negative.
  96477. * RETURN 0 => quantization OK
  96478. * 1 => coefficients require too much shifting for *shift to
  96479. * fit in the LPC subframe header. 'shift' is unset.
  96480. * 2 => coefficients are all zero, which is bad. 'shift' is
  96481. * unset.
  96482. */
  96483. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96484. /*
  96485. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96486. * --------------------------------------------------------------------
  96487. * Compute the residual signal obtained from sutracting the predicted
  96488. * signal from the original.
  96489. *
  96490. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96491. * IN data_len length of original signal
  96492. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96493. * IN order > 0 LP order
  96494. * IN lp_quantization quantization of LP coefficients in bits
  96495. * OUT residual[0,data_len-1] residual signal
  96496. */
  96497. 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[]);
  96498. 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[]);
  96499. #ifndef FLAC__NO_ASM
  96500. # ifdef FLAC__CPU_IA32
  96501. # ifdef FLAC__HAS_NASM
  96502. 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[]);
  96503. 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[]);
  96504. # endif
  96505. # endif
  96506. #endif
  96507. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96508. /*
  96509. * FLAC__lpc_restore_signal()
  96510. * --------------------------------------------------------------------
  96511. * Restore the original signal by summing the residual and the
  96512. * predictor.
  96513. *
  96514. * IN residual[0,data_len-1] residual signal
  96515. * IN data_len length of original signal
  96516. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96517. * IN order > 0 LP order
  96518. * IN lp_quantization quantization of LP coefficients in bits
  96519. * *** IMPORTANT: the caller must pass in the historical samples:
  96520. * IN data[-order,-1] previously-reconstructed historical samples
  96521. * OUT data[0,data_len-1] original signal
  96522. */
  96523. 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[]);
  96524. 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[]);
  96525. #ifndef FLAC__NO_ASM
  96526. # ifdef FLAC__CPU_IA32
  96527. # ifdef FLAC__HAS_NASM
  96528. 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[]);
  96529. 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[]);
  96530. # endif /* FLAC__HAS_NASM */
  96531. # elif defined FLAC__CPU_PPC
  96532. 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[]);
  96533. 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[]);
  96534. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96535. #endif /* FLAC__NO_ASM */
  96536. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96537. /*
  96538. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96539. * --------------------------------------------------------------------
  96540. * Compute the expected number of bits per residual signal sample
  96541. * based on the LP error (which is related to the residual variance).
  96542. *
  96543. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96544. * IN total_samples > 0 # of samples in residual signal
  96545. * RETURN expected bits per sample
  96546. */
  96547. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96548. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96549. /*
  96550. * FLAC__lpc_compute_best_order()
  96551. * --------------------------------------------------------------------
  96552. * Compute the best order from the array of signal errors returned
  96553. * during coefficient computation.
  96554. *
  96555. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96556. * IN max_order > 0 max LP order
  96557. * IN total_samples > 0 # of samples in residual signal
  96558. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96559. * (includes warmup sample size and quantized LP coefficient)
  96560. * RETURN [1,max_order] best order
  96561. */
  96562. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96563. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96564. #endif
  96565. /*** End of inlined file: lpc.h ***/
  96566. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96567. #include <stdio.h>
  96568. #endif
  96569. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96570. #ifndef M_LN2
  96571. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96572. #define M_LN2 0.69314718055994530942
  96573. #endif
  96574. /* OPT: #undef'ing this may improve the speed on some architectures */
  96575. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96576. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96577. {
  96578. unsigned i;
  96579. for(i = 0; i < data_len; i++)
  96580. out[i] = in[i] * window[i];
  96581. }
  96582. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96583. {
  96584. /* a readable, but slower, version */
  96585. #if 0
  96586. FLAC__real d;
  96587. unsigned i;
  96588. FLAC__ASSERT(lag > 0);
  96589. FLAC__ASSERT(lag <= data_len);
  96590. /*
  96591. * Technically we should subtract the mean first like so:
  96592. * for(i = 0; i < data_len; i++)
  96593. * data[i] -= mean;
  96594. * but it appears not to make enough of a difference to matter, and
  96595. * most signals are already closely centered around zero
  96596. */
  96597. while(lag--) {
  96598. for(i = lag, d = 0.0; i < data_len; i++)
  96599. d += data[i] * data[i - lag];
  96600. autoc[lag] = d;
  96601. }
  96602. #endif
  96603. /*
  96604. * this version tends to run faster because of better data locality
  96605. * ('data_len' is usually much larger than 'lag')
  96606. */
  96607. FLAC__real d;
  96608. unsigned sample, coeff;
  96609. const unsigned limit = data_len - lag;
  96610. FLAC__ASSERT(lag > 0);
  96611. FLAC__ASSERT(lag <= data_len);
  96612. for(coeff = 0; coeff < lag; coeff++)
  96613. autoc[coeff] = 0.0;
  96614. for(sample = 0; sample <= limit; sample++) {
  96615. d = data[sample];
  96616. for(coeff = 0; coeff < lag; coeff++)
  96617. autoc[coeff] += d * data[sample+coeff];
  96618. }
  96619. for(; sample < data_len; sample++) {
  96620. d = data[sample];
  96621. for(coeff = 0; coeff < data_len - sample; coeff++)
  96622. autoc[coeff] += d * data[sample+coeff];
  96623. }
  96624. }
  96625. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96626. {
  96627. unsigned i, j;
  96628. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96629. FLAC__ASSERT(0 != max_order);
  96630. FLAC__ASSERT(0 < *max_order);
  96631. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96632. FLAC__ASSERT(autoc[0] != 0.0);
  96633. err = autoc[0];
  96634. for(i = 0; i < *max_order; i++) {
  96635. /* Sum up this iteration's reflection coefficient. */
  96636. r = -autoc[i+1];
  96637. for(j = 0; j < i; j++)
  96638. r -= lpc[j] * autoc[i-j];
  96639. ref[i] = (r/=err);
  96640. /* Update LPC coefficients and total error. */
  96641. lpc[i]=r;
  96642. for(j = 0; j < (i>>1); j++) {
  96643. FLAC__double tmp = lpc[j];
  96644. lpc[j] += r * lpc[i-1-j];
  96645. lpc[i-1-j] += r * tmp;
  96646. }
  96647. if(i & 1)
  96648. lpc[j] += lpc[j] * r;
  96649. err *= (1.0 - r * r);
  96650. /* save this order */
  96651. for(j = 0; j <= i; j++)
  96652. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96653. error[i] = err;
  96654. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96655. if(err == 0.0) {
  96656. *max_order = i+1;
  96657. return;
  96658. }
  96659. }
  96660. }
  96661. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96662. {
  96663. unsigned i;
  96664. FLAC__double cmax;
  96665. FLAC__int32 qmax, qmin;
  96666. FLAC__ASSERT(precision > 0);
  96667. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96668. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96669. precision--;
  96670. qmax = 1 << precision;
  96671. qmin = -qmax;
  96672. qmax--;
  96673. /* calc cmax = max( |lp_coeff[i]| ) */
  96674. cmax = 0.0;
  96675. for(i = 0; i < order; i++) {
  96676. const FLAC__double d = fabs(lp_coeff[i]);
  96677. if(d > cmax)
  96678. cmax = d;
  96679. }
  96680. if(cmax <= 0.0) {
  96681. /* => coefficients are all 0, which means our constant-detect didn't work */
  96682. return 2;
  96683. }
  96684. else {
  96685. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96686. const int min_shiftlimit = -max_shiftlimit - 1;
  96687. int log2cmax;
  96688. (void)frexp(cmax, &log2cmax);
  96689. log2cmax--;
  96690. *shift = (int)precision - log2cmax - 1;
  96691. if(*shift > max_shiftlimit)
  96692. *shift = max_shiftlimit;
  96693. else if(*shift < min_shiftlimit)
  96694. return 1;
  96695. }
  96696. if(*shift >= 0) {
  96697. FLAC__double error = 0.0;
  96698. FLAC__int32 q;
  96699. for(i = 0; i < order; i++) {
  96700. error += lp_coeff[i] * (1 << *shift);
  96701. #if 1 /* unfortunately lround() is C99 */
  96702. if(error >= 0.0)
  96703. q = (FLAC__int32)(error + 0.5);
  96704. else
  96705. q = (FLAC__int32)(error - 0.5);
  96706. #else
  96707. q = lround(error);
  96708. #endif
  96709. #ifdef FLAC__OVERFLOW_DETECT
  96710. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96711. 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]);
  96712. else if(q < qmin)
  96713. 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]);
  96714. #endif
  96715. if(q > qmax)
  96716. q = qmax;
  96717. else if(q < qmin)
  96718. q = qmin;
  96719. error -= q;
  96720. qlp_coeff[i] = q;
  96721. }
  96722. }
  96723. /* negative shift is very rare but due to design flaw, negative shift is
  96724. * a NOP in the decoder, so it must be handled specially by scaling down
  96725. * coeffs
  96726. */
  96727. else {
  96728. const int nshift = -(*shift);
  96729. FLAC__double error = 0.0;
  96730. FLAC__int32 q;
  96731. #ifdef DEBUG
  96732. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96733. #endif
  96734. for(i = 0; i < order; i++) {
  96735. error += lp_coeff[i] / (1 << nshift);
  96736. #if 1 /* unfortunately lround() is C99 */
  96737. if(error >= 0.0)
  96738. q = (FLAC__int32)(error + 0.5);
  96739. else
  96740. q = (FLAC__int32)(error - 0.5);
  96741. #else
  96742. q = lround(error);
  96743. #endif
  96744. #ifdef FLAC__OVERFLOW_DETECT
  96745. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96746. 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]);
  96747. else if(q < qmin)
  96748. 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]);
  96749. #endif
  96750. if(q > qmax)
  96751. q = qmax;
  96752. else if(q < qmin)
  96753. q = qmin;
  96754. error -= q;
  96755. qlp_coeff[i] = q;
  96756. }
  96757. *shift = 0;
  96758. }
  96759. return 0;
  96760. }
  96761. 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[])
  96762. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96763. {
  96764. FLAC__int64 sumo;
  96765. unsigned i, j;
  96766. FLAC__int32 sum;
  96767. const FLAC__int32 *history;
  96768. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96769. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96770. for(i=0;i<order;i++)
  96771. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96772. fprintf(stderr,"\n");
  96773. #endif
  96774. FLAC__ASSERT(order > 0);
  96775. for(i = 0; i < data_len; i++) {
  96776. sumo = 0;
  96777. sum = 0;
  96778. history = data;
  96779. for(j = 0; j < order; j++) {
  96780. sum += qlp_coeff[j] * (*(--history));
  96781. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96782. #if defined _MSC_VER
  96783. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96784. 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);
  96785. #else
  96786. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96787. 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);
  96788. #endif
  96789. }
  96790. *(residual++) = *(data++) - (sum >> lp_quantization);
  96791. }
  96792. /* Here's a slower but clearer version:
  96793. for(i = 0; i < data_len; i++) {
  96794. sum = 0;
  96795. for(j = 0; j < order; j++)
  96796. sum += qlp_coeff[j] * data[i-j-1];
  96797. residual[i] = data[i] - (sum >> lp_quantization);
  96798. }
  96799. */
  96800. }
  96801. #else /* fully unrolled version for normal use */
  96802. {
  96803. int i;
  96804. FLAC__int32 sum;
  96805. FLAC__ASSERT(order > 0);
  96806. FLAC__ASSERT(order <= 32);
  96807. /*
  96808. * We do unique versions up to 12th order since that's the subset limit.
  96809. * Also they are roughly ordered to match frequency of occurrence to
  96810. * minimize branching.
  96811. */
  96812. if(order <= 12) {
  96813. if(order > 8) {
  96814. if(order > 10) {
  96815. if(order == 12) {
  96816. for(i = 0; i < (int)data_len; i++) {
  96817. sum = 0;
  96818. sum += qlp_coeff[11] * data[i-12];
  96819. sum += qlp_coeff[10] * data[i-11];
  96820. sum += qlp_coeff[9] * data[i-10];
  96821. sum += qlp_coeff[8] * data[i-9];
  96822. sum += qlp_coeff[7] * data[i-8];
  96823. sum += qlp_coeff[6] * data[i-7];
  96824. sum += qlp_coeff[5] * data[i-6];
  96825. sum += qlp_coeff[4] * data[i-5];
  96826. sum += qlp_coeff[3] * data[i-4];
  96827. sum += qlp_coeff[2] * data[i-3];
  96828. sum += qlp_coeff[1] * data[i-2];
  96829. sum += qlp_coeff[0] * data[i-1];
  96830. residual[i] = data[i] - (sum >> lp_quantization);
  96831. }
  96832. }
  96833. else { /* order == 11 */
  96834. for(i = 0; i < (int)data_len; i++) {
  96835. sum = 0;
  96836. sum += qlp_coeff[10] * data[i-11];
  96837. sum += qlp_coeff[9] * data[i-10];
  96838. sum += qlp_coeff[8] * data[i-9];
  96839. sum += qlp_coeff[7] * data[i-8];
  96840. sum += qlp_coeff[6] * data[i-7];
  96841. sum += qlp_coeff[5] * data[i-6];
  96842. sum += qlp_coeff[4] * data[i-5];
  96843. sum += qlp_coeff[3] * data[i-4];
  96844. sum += qlp_coeff[2] * data[i-3];
  96845. sum += qlp_coeff[1] * data[i-2];
  96846. sum += qlp_coeff[0] * data[i-1];
  96847. residual[i] = data[i] - (sum >> lp_quantization);
  96848. }
  96849. }
  96850. }
  96851. else {
  96852. if(order == 10) {
  96853. for(i = 0; i < (int)data_len; i++) {
  96854. sum = 0;
  96855. sum += qlp_coeff[9] * data[i-10];
  96856. sum += qlp_coeff[8] * data[i-9];
  96857. sum += qlp_coeff[7] * data[i-8];
  96858. sum += qlp_coeff[6] * data[i-7];
  96859. sum += qlp_coeff[5] * data[i-6];
  96860. sum += qlp_coeff[4] * data[i-5];
  96861. sum += qlp_coeff[3] * data[i-4];
  96862. sum += qlp_coeff[2] * data[i-3];
  96863. sum += qlp_coeff[1] * data[i-2];
  96864. sum += qlp_coeff[0] * data[i-1];
  96865. residual[i] = data[i] - (sum >> lp_quantization);
  96866. }
  96867. }
  96868. else { /* order == 9 */
  96869. for(i = 0; i < (int)data_len; i++) {
  96870. sum = 0;
  96871. sum += qlp_coeff[8] * data[i-9];
  96872. sum += qlp_coeff[7] * data[i-8];
  96873. sum += qlp_coeff[6] * data[i-7];
  96874. sum += qlp_coeff[5] * data[i-6];
  96875. sum += qlp_coeff[4] * data[i-5];
  96876. sum += qlp_coeff[3] * data[i-4];
  96877. sum += qlp_coeff[2] * data[i-3];
  96878. sum += qlp_coeff[1] * data[i-2];
  96879. sum += qlp_coeff[0] * data[i-1];
  96880. residual[i] = data[i] - (sum >> lp_quantization);
  96881. }
  96882. }
  96883. }
  96884. }
  96885. else if(order > 4) {
  96886. if(order > 6) {
  96887. if(order == 8) {
  96888. for(i = 0; i < (int)data_len; i++) {
  96889. sum = 0;
  96890. sum += qlp_coeff[7] * data[i-8];
  96891. sum += qlp_coeff[6] * data[i-7];
  96892. sum += qlp_coeff[5] * data[i-6];
  96893. sum += qlp_coeff[4] * data[i-5];
  96894. sum += qlp_coeff[3] * data[i-4];
  96895. sum += qlp_coeff[2] * data[i-3];
  96896. sum += qlp_coeff[1] * data[i-2];
  96897. sum += qlp_coeff[0] * data[i-1];
  96898. residual[i] = data[i] - (sum >> lp_quantization);
  96899. }
  96900. }
  96901. else { /* order == 7 */
  96902. for(i = 0; i < (int)data_len; i++) {
  96903. sum = 0;
  96904. sum += qlp_coeff[6] * data[i-7];
  96905. sum += qlp_coeff[5] * data[i-6];
  96906. sum += qlp_coeff[4] * data[i-5];
  96907. sum += qlp_coeff[3] * data[i-4];
  96908. sum += qlp_coeff[2] * data[i-3];
  96909. sum += qlp_coeff[1] * data[i-2];
  96910. sum += qlp_coeff[0] * data[i-1];
  96911. residual[i] = data[i] - (sum >> lp_quantization);
  96912. }
  96913. }
  96914. }
  96915. else {
  96916. if(order == 6) {
  96917. for(i = 0; i < (int)data_len; i++) {
  96918. sum = 0;
  96919. sum += qlp_coeff[5] * data[i-6];
  96920. sum += qlp_coeff[4] * data[i-5];
  96921. sum += qlp_coeff[3] * data[i-4];
  96922. sum += qlp_coeff[2] * data[i-3];
  96923. sum += qlp_coeff[1] * data[i-2];
  96924. sum += qlp_coeff[0] * data[i-1];
  96925. residual[i] = data[i] - (sum >> lp_quantization);
  96926. }
  96927. }
  96928. else { /* order == 5 */
  96929. for(i = 0; i < (int)data_len; i++) {
  96930. sum = 0;
  96931. sum += qlp_coeff[4] * data[i-5];
  96932. sum += qlp_coeff[3] * data[i-4];
  96933. sum += qlp_coeff[2] * data[i-3];
  96934. sum += qlp_coeff[1] * data[i-2];
  96935. sum += qlp_coeff[0] * data[i-1];
  96936. residual[i] = data[i] - (sum >> lp_quantization);
  96937. }
  96938. }
  96939. }
  96940. }
  96941. else {
  96942. if(order > 2) {
  96943. if(order == 4) {
  96944. for(i = 0; i < (int)data_len; i++) {
  96945. sum = 0;
  96946. sum += qlp_coeff[3] * data[i-4];
  96947. sum += qlp_coeff[2] * data[i-3];
  96948. sum += qlp_coeff[1] * data[i-2];
  96949. sum += qlp_coeff[0] * data[i-1];
  96950. residual[i] = data[i] - (sum >> lp_quantization);
  96951. }
  96952. }
  96953. else { /* order == 3 */
  96954. for(i = 0; i < (int)data_len; i++) {
  96955. sum = 0;
  96956. sum += qlp_coeff[2] * data[i-3];
  96957. sum += qlp_coeff[1] * data[i-2];
  96958. sum += qlp_coeff[0] * data[i-1];
  96959. residual[i] = data[i] - (sum >> lp_quantization);
  96960. }
  96961. }
  96962. }
  96963. else {
  96964. if(order == 2) {
  96965. for(i = 0; i < (int)data_len; i++) {
  96966. sum = 0;
  96967. sum += qlp_coeff[1] * data[i-2];
  96968. sum += qlp_coeff[0] * data[i-1];
  96969. residual[i] = data[i] - (sum >> lp_quantization);
  96970. }
  96971. }
  96972. else { /* order == 1 */
  96973. for(i = 0; i < (int)data_len; i++)
  96974. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  96975. }
  96976. }
  96977. }
  96978. }
  96979. else { /* order > 12 */
  96980. for(i = 0; i < (int)data_len; i++) {
  96981. sum = 0;
  96982. switch(order) {
  96983. case 32: sum += qlp_coeff[31] * data[i-32];
  96984. case 31: sum += qlp_coeff[30] * data[i-31];
  96985. case 30: sum += qlp_coeff[29] * data[i-30];
  96986. case 29: sum += qlp_coeff[28] * data[i-29];
  96987. case 28: sum += qlp_coeff[27] * data[i-28];
  96988. case 27: sum += qlp_coeff[26] * data[i-27];
  96989. case 26: sum += qlp_coeff[25] * data[i-26];
  96990. case 25: sum += qlp_coeff[24] * data[i-25];
  96991. case 24: sum += qlp_coeff[23] * data[i-24];
  96992. case 23: sum += qlp_coeff[22] * data[i-23];
  96993. case 22: sum += qlp_coeff[21] * data[i-22];
  96994. case 21: sum += qlp_coeff[20] * data[i-21];
  96995. case 20: sum += qlp_coeff[19] * data[i-20];
  96996. case 19: sum += qlp_coeff[18] * data[i-19];
  96997. case 18: sum += qlp_coeff[17] * data[i-18];
  96998. case 17: sum += qlp_coeff[16] * data[i-17];
  96999. case 16: sum += qlp_coeff[15] * data[i-16];
  97000. case 15: sum += qlp_coeff[14] * data[i-15];
  97001. case 14: sum += qlp_coeff[13] * data[i-14];
  97002. case 13: sum += qlp_coeff[12] * data[i-13];
  97003. sum += qlp_coeff[11] * data[i-12];
  97004. sum += qlp_coeff[10] * data[i-11];
  97005. sum += qlp_coeff[ 9] * data[i-10];
  97006. sum += qlp_coeff[ 8] * data[i- 9];
  97007. sum += qlp_coeff[ 7] * data[i- 8];
  97008. sum += qlp_coeff[ 6] * data[i- 7];
  97009. sum += qlp_coeff[ 5] * data[i- 6];
  97010. sum += qlp_coeff[ 4] * data[i- 5];
  97011. sum += qlp_coeff[ 3] * data[i- 4];
  97012. sum += qlp_coeff[ 2] * data[i- 3];
  97013. sum += qlp_coeff[ 1] * data[i- 2];
  97014. sum += qlp_coeff[ 0] * data[i- 1];
  97015. }
  97016. residual[i] = data[i] - (sum >> lp_quantization);
  97017. }
  97018. }
  97019. }
  97020. #endif
  97021. 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[])
  97022. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97023. {
  97024. unsigned i, j;
  97025. FLAC__int64 sum;
  97026. const FLAC__int32 *history;
  97027. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97028. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97029. for(i=0;i<order;i++)
  97030. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97031. fprintf(stderr,"\n");
  97032. #endif
  97033. FLAC__ASSERT(order > 0);
  97034. for(i = 0; i < data_len; i++) {
  97035. sum = 0;
  97036. history = data;
  97037. for(j = 0; j < order; j++)
  97038. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97039. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97040. #if defined _MSC_VER
  97041. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97042. #else
  97043. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97044. #endif
  97045. break;
  97046. }
  97047. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97048. #if defined _MSC_VER
  97049. 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));
  97050. #else
  97051. 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)));
  97052. #endif
  97053. break;
  97054. }
  97055. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97056. }
  97057. }
  97058. #else /* fully unrolled version for normal use */
  97059. {
  97060. int i;
  97061. FLAC__int64 sum;
  97062. FLAC__ASSERT(order > 0);
  97063. FLAC__ASSERT(order <= 32);
  97064. /*
  97065. * We do unique versions up to 12th order since that's the subset limit.
  97066. * Also they are roughly ordered to match frequency of occurrence to
  97067. * minimize branching.
  97068. */
  97069. if(order <= 12) {
  97070. if(order > 8) {
  97071. if(order > 10) {
  97072. if(order == 12) {
  97073. for(i = 0; i < (int)data_len; i++) {
  97074. sum = 0;
  97075. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97076. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97077. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97078. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97079. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97080. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97081. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97082. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97083. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97084. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97085. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97086. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97087. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97088. }
  97089. }
  97090. else { /* order == 11 */
  97091. for(i = 0; i < (int)data_len; i++) {
  97092. sum = 0;
  97093. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97094. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97095. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97096. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97097. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97098. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97099. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97100. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97101. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97102. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97103. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97104. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97105. }
  97106. }
  97107. }
  97108. else {
  97109. if(order == 10) {
  97110. for(i = 0; i < (int)data_len; i++) {
  97111. sum = 0;
  97112. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97113. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97114. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97115. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97116. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97117. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97118. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97119. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97120. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97121. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97122. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97123. }
  97124. }
  97125. else { /* order == 9 */
  97126. for(i = 0; i < (int)data_len; i++) {
  97127. sum = 0;
  97128. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97129. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97130. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97131. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97132. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97133. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97134. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97135. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97136. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97137. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97138. }
  97139. }
  97140. }
  97141. }
  97142. else if(order > 4) {
  97143. if(order > 6) {
  97144. if(order == 8) {
  97145. for(i = 0; i < (int)data_len; i++) {
  97146. sum = 0;
  97147. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97148. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97149. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97150. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97151. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97152. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97153. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97154. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97155. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97156. }
  97157. }
  97158. else { /* order == 7 */
  97159. for(i = 0; i < (int)data_len; i++) {
  97160. sum = 0;
  97161. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97162. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97163. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97164. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97165. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97166. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97167. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97168. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97169. }
  97170. }
  97171. }
  97172. else {
  97173. if(order == 6) {
  97174. for(i = 0; i < (int)data_len; i++) {
  97175. sum = 0;
  97176. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97177. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97178. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97179. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97180. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97181. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97182. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97183. }
  97184. }
  97185. else { /* order == 5 */
  97186. for(i = 0; i < (int)data_len; i++) {
  97187. sum = 0;
  97188. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97189. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97190. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97191. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97192. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97193. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97194. }
  97195. }
  97196. }
  97197. }
  97198. else {
  97199. if(order > 2) {
  97200. if(order == 4) {
  97201. for(i = 0; i < (int)data_len; i++) {
  97202. sum = 0;
  97203. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97204. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97205. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97206. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97207. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97208. }
  97209. }
  97210. else { /* order == 3 */
  97211. for(i = 0; i < (int)data_len; i++) {
  97212. sum = 0;
  97213. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97214. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97215. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97216. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97217. }
  97218. }
  97219. }
  97220. else {
  97221. if(order == 2) {
  97222. for(i = 0; i < (int)data_len; i++) {
  97223. sum = 0;
  97224. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97225. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97226. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97227. }
  97228. }
  97229. else { /* order == 1 */
  97230. for(i = 0; i < (int)data_len; i++)
  97231. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97232. }
  97233. }
  97234. }
  97235. }
  97236. else { /* order > 12 */
  97237. for(i = 0; i < (int)data_len; i++) {
  97238. sum = 0;
  97239. switch(order) {
  97240. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97241. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97242. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97243. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97244. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97245. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97246. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97247. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97248. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97249. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97250. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97251. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97252. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97253. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97254. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97255. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97256. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97257. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97258. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97259. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97260. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97261. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97262. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97263. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97264. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97265. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97266. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97267. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97268. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97269. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97270. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97271. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97272. }
  97273. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97274. }
  97275. }
  97276. }
  97277. #endif
  97278. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97279. 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[])
  97280. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97281. {
  97282. FLAC__int64 sumo;
  97283. unsigned i, j;
  97284. FLAC__int32 sum;
  97285. const FLAC__int32 *r = residual, *history;
  97286. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97287. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97288. for(i=0;i<order;i++)
  97289. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97290. fprintf(stderr,"\n");
  97291. #endif
  97292. FLAC__ASSERT(order > 0);
  97293. for(i = 0; i < data_len; i++) {
  97294. sumo = 0;
  97295. sum = 0;
  97296. history = data;
  97297. for(j = 0; j < order; j++) {
  97298. sum += qlp_coeff[j] * (*(--history));
  97299. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97300. #if defined _MSC_VER
  97301. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97302. 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);
  97303. #else
  97304. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97305. 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);
  97306. #endif
  97307. }
  97308. *(data++) = *(r++) + (sum >> lp_quantization);
  97309. }
  97310. /* Here's a slower but clearer version:
  97311. for(i = 0; i < data_len; i++) {
  97312. sum = 0;
  97313. for(j = 0; j < order; j++)
  97314. sum += qlp_coeff[j] * data[i-j-1];
  97315. data[i] = residual[i] + (sum >> lp_quantization);
  97316. }
  97317. */
  97318. }
  97319. #else /* fully unrolled version for normal use */
  97320. {
  97321. int i;
  97322. FLAC__int32 sum;
  97323. FLAC__ASSERT(order > 0);
  97324. FLAC__ASSERT(order <= 32);
  97325. /*
  97326. * We do unique versions up to 12th order since that's the subset limit.
  97327. * Also they are roughly ordered to match frequency of occurrence to
  97328. * minimize branching.
  97329. */
  97330. if(order <= 12) {
  97331. if(order > 8) {
  97332. if(order > 10) {
  97333. if(order == 12) {
  97334. for(i = 0; i < (int)data_len; i++) {
  97335. sum = 0;
  97336. sum += qlp_coeff[11] * data[i-12];
  97337. sum += qlp_coeff[10] * data[i-11];
  97338. sum += qlp_coeff[9] * data[i-10];
  97339. sum += qlp_coeff[8] * data[i-9];
  97340. sum += qlp_coeff[7] * data[i-8];
  97341. sum += qlp_coeff[6] * data[i-7];
  97342. sum += qlp_coeff[5] * data[i-6];
  97343. sum += qlp_coeff[4] * data[i-5];
  97344. sum += qlp_coeff[3] * data[i-4];
  97345. sum += qlp_coeff[2] * data[i-3];
  97346. sum += qlp_coeff[1] * data[i-2];
  97347. sum += qlp_coeff[0] * data[i-1];
  97348. data[i] = residual[i] + (sum >> lp_quantization);
  97349. }
  97350. }
  97351. else { /* order == 11 */
  97352. for(i = 0; i < (int)data_len; i++) {
  97353. sum = 0;
  97354. sum += qlp_coeff[10] * data[i-11];
  97355. sum += qlp_coeff[9] * data[i-10];
  97356. sum += qlp_coeff[8] * data[i-9];
  97357. sum += qlp_coeff[7] * data[i-8];
  97358. sum += qlp_coeff[6] * data[i-7];
  97359. sum += qlp_coeff[5] * data[i-6];
  97360. sum += qlp_coeff[4] * data[i-5];
  97361. sum += qlp_coeff[3] * data[i-4];
  97362. sum += qlp_coeff[2] * data[i-3];
  97363. sum += qlp_coeff[1] * data[i-2];
  97364. sum += qlp_coeff[0] * data[i-1];
  97365. data[i] = residual[i] + (sum >> lp_quantization);
  97366. }
  97367. }
  97368. }
  97369. else {
  97370. if(order == 10) {
  97371. for(i = 0; i < (int)data_len; i++) {
  97372. sum = 0;
  97373. sum += qlp_coeff[9] * data[i-10];
  97374. sum += qlp_coeff[8] * data[i-9];
  97375. sum += qlp_coeff[7] * data[i-8];
  97376. sum += qlp_coeff[6] * data[i-7];
  97377. sum += qlp_coeff[5] * data[i-6];
  97378. sum += qlp_coeff[4] * data[i-5];
  97379. sum += qlp_coeff[3] * data[i-4];
  97380. sum += qlp_coeff[2] * data[i-3];
  97381. sum += qlp_coeff[1] * data[i-2];
  97382. sum += qlp_coeff[0] * data[i-1];
  97383. data[i] = residual[i] + (sum >> lp_quantization);
  97384. }
  97385. }
  97386. else { /* order == 9 */
  97387. for(i = 0; i < (int)data_len; i++) {
  97388. sum = 0;
  97389. sum += qlp_coeff[8] * data[i-9];
  97390. sum += qlp_coeff[7] * data[i-8];
  97391. sum += qlp_coeff[6] * data[i-7];
  97392. sum += qlp_coeff[5] * data[i-6];
  97393. sum += qlp_coeff[4] * data[i-5];
  97394. sum += qlp_coeff[3] * data[i-4];
  97395. sum += qlp_coeff[2] * data[i-3];
  97396. sum += qlp_coeff[1] * data[i-2];
  97397. sum += qlp_coeff[0] * data[i-1];
  97398. data[i] = residual[i] + (sum >> lp_quantization);
  97399. }
  97400. }
  97401. }
  97402. }
  97403. else if(order > 4) {
  97404. if(order > 6) {
  97405. if(order == 8) {
  97406. for(i = 0; i < (int)data_len; i++) {
  97407. sum = 0;
  97408. sum += qlp_coeff[7] * data[i-8];
  97409. sum += qlp_coeff[6] * data[i-7];
  97410. sum += qlp_coeff[5] * data[i-6];
  97411. sum += qlp_coeff[4] * data[i-5];
  97412. sum += qlp_coeff[3] * data[i-4];
  97413. sum += qlp_coeff[2] * data[i-3];
  97414. sum += qlp_coeff[1] * data[i-2];
  97415. sum += qlp_coeff[0] * data[i-1];
  97416. data[i] = residual[i] + (sum >> lp_quantization);
  97417. }
  97418. }
  97419. else { /* order == 7 */
  97420. for(i = 0; i < (int)data_len; i++) {
  97421. sum = 0;
  97422. sum += qlp_coeff[6] * data[i-7];
  97423. sum += qlp_coeff[5] * data[i-6];
  97424. sum += qlp_coeff[4] * data[i-5];
  97425. sum += qlp_coeff[3] * data[i-4];
  97426. sum += qlp_coeff[2] * data[i-3];
  97427. sum += qlp_coeff[1] * data[i-2];
  97428. sum += qlp_coeff[0] * data[i-1];
  97429. data[i] = residual[i] + (sum >> lp_quantization);
  97430. }
  97431. }
  97432. }
  97433. else {
  97434. if(order == 6) {
  97435. for(i = 0; i < (int)data_len; i++) {
  97436. sum = 0;
  97437. sum += qlp_coeff[5] * data[i-6];
  97438. sum += qlp_coeff[4] * data[i-5];
  97439. sum += qlp_coeff[3] * data[i-4];
  97440. sum += qlp_coeff[2] * data[i-3];
  97441. sum += qlp_coeff[1] * data[i-2];
  97442. sum += qlp_coeff[0] * data[i-1];
  97443. data[i] = residual[i] + (sum >> lp_quantization);
  97444. }
  97445. }
  97446. else { /* order == 5 */
  97447. for(i = 0; i < (int)data_len; i++) {
  97448. sum = 0;
  97449. sum += qlp_coeff[4] * data[i-5];
  97450. sum += qlp_coeff[3] * data[i-4];
  97451. sum += qlp_coeff[2] * data[i-3];
  97452. sum += qlp_coeff[1] * data[i-2];
  97453. sum += qlp_coeff[0] * data[i-1];
  97454. data[i] = residual[i] + (sum >> lp_quantization);
  97455. }
  97456. }
  97457. }
  97458. }
  97459. else {
  97460. if(order > 2) {
  97461. if(order == 4) {
  97462. for(i = 0; i < (int)data_len; i++) {
  97463. sum = 0;
  97464. sum += qlp_coeff[3] * data[i-4];
  97465. sum += qlp_coeff[2] * data[i-3];
  97466. sum += qlp_coeff[1] * data[i-2];
  97467. sum += qlp_coeff[0] * data[i-1];
  97468. data[i] = residual[i] + (sum >> lp_quantization);
  97469. }
  97470. }
  97471. else { /* order == 3 */
  97472. for(i = 0; i < (int)data_len; i++) {
  97473. sum = 0;
  97474. sum += qlp_coeff[2] * data[i-3];
  97475. sum += qlp_coeff[1] * data[i-2];
  97476. sum += qlp_coeff[0] * data[i-1];
  97477. data[i] = residual[i] + (sum >> lp_quantization);
  97478. }
  97479. }
  97480. }
  97481. else {
  97482. if(order == 2) {
  97483. for(i = 0; i < (int)data_len; i++) {
  97484. sum = 0;
  97485. sum += qlp_coeff[1] * data[i-2];
  97486. sum += qlp_coeff[0] * data[i-1];
  97487. data[i] = residual[i] + (sum >> lp_quantization);
  97488. }
  97489. }
  97490. else { /* order == 1 */
  97491. for(i = 0; i < (int)data_len; i++)
  97492. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97493. }
  97494. }
  97495. }
  97496. }
  97497. else { /* order > 12 */
  97498. for(i = 0; i < (int)data_len; i++) {
  97499. sum = 0;
  97500. switch(order) {
  97501. case 32: sum += qlp_coeff[31] * data[i-32];
  97502. case 31: sum += qlp_coeff[30] * data[i-31];
  97503. case 30: sum += qlp_coeff[29] * data[i-30];
  97504. case 29: sum += qlp_coeff[28] * data[i-29];
  97505. case 28: sum += qlp_coeff[27] * data[i-28];
  97506. case 27: sum += qlp_coeff[26] * data[i-27];
  97507. case 26: sum += qlp_coeff[25] * data[i-26];
  97508. case 25: sum += qlp_coeff[24] * data[i-25];
  97509. case 24: sum += qlp_coeff[23] * data[i-24];
  97510. case 23: sum += qlp_coeff[22] * data[i-23];
  97511. case 22: sum += qlp_coeff[21] * data[i-22];
  97512. case 21: sum += qlp_coeff[20] * data[i-21];
  97513. case 20: sum += qlp_coeff[19] * data[i-20];
  97514. case 19: sum += qlp_coeff[18] * data[i-19];
  97515. case 18: sum += qlp_coeff[17] * data[i-18];
  97516. case 17: sum += qlp_coeff[16] * data[i-17];
  97517. case 16: sum += qlp_coeff[15] * data[i-16];
  97518. case 15: sum += qlp_coeff[14] * data[i-15];
  97519. case 14: sum += qlp_coeff[13] * data[i-14];
  97520. case 13: sum += qlp_coeff[12] * data[i-13];
  97521. sum += qlp_coeff[11] * data[i-12];
  97522. sum += qlp_coeff[10] * data[i-11];
  97523. sum += qlp_coeff[ 9] * data[i-10];
  97524. sum += qlp_coeff[ 8] * data[i- 9];
  97525. sum += qlp_coeff[ 7] * data[i- 8];
  97526. sum += qlp_coeff[ 6] * data[i- 7];
  97527. sum += qlp_coeff[ 5] * data[i- 6];
  97528. sum += qlp_coeff[ 4] * data[i- 5];
  97529. sum += qlp_coeff[ 3] * data[i- 4];
  97530. sum += qlp_coeff[ 2] * data[i- 3];
  97531. sum += qlp_coeff[ 1] * data[i- 2];
  97532. sum += qlp_coeff[ 0] * data[i- 1];
  97533. }
  97534. data[i] = residual[i] + (sum >> lp_quantization);
  97535. }
  97536. }
  97537. }
  97538. #endif
  97539. 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[])
  97540. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97541. {
  97542. unsigned i, j;
  97543. FLAC__int64 sum;
  97544. const FLAC__int32 *r = residual, *history;
  97545. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97546. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97547. for(i=0;i<order;i++)
  97548. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97549. fprintf(stderr,"\n");
  97550. #endif
  97551. FLAC__ASSERT(order > 0);
  97552. for(i = 0; i < data_len; i++) {
  97553. sum = 0;
  97554. history = data;
  97555. for(j = 0; j < order; j++)
  97556. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97557. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97558. #ifdef _MSC_VER
  97559. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97560. #else
  97561. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97562. #endif
  97563. break;
  97564. }
  97565. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97566. #ifdef _MSC_VER
  97567. 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));
  97568. #else
  97569. 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)));
  97570. #endif
  97571. break;
  97572. }
  97573. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97574. }
  97575. }
  97576. #else /* fully unrolled version for normal use */
  97577. {
  97578. int i;
  97579. FLAC__int64 sum;
  97580. FLAC__ASSERT(order > 0);
  97581. FLAC__ASSERT(order <= 32);
  97582. /*
  97583. * We do unique versions up to 12th order since that's the subset limit.
  97584. * Also they are roughly ordered to match frequency of occurrence to
  97585. * minimize branching.
  97586. */
  97587. if(order <= 12) {
  97588. if(order > 8) {
  97589. if(order > 10) {
  97590. if(order == 12) {
  97591. for(i = 0; i < (int)data_len; i++) {
  97592. sum = 0;
  97593. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97594. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97595. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97596. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97597. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97598. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97599. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97600. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97601. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97602. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97603. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97604. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97605. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97606. }
  97607. }
  97608. else { /* order == 11 */
  97609. for(i = 0; i < (int)data_len; i++) {
  97610. sum = 0;
  97611. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97612. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97613. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97614. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97615. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97616. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97617. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97618. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97619. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97620. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97621. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97622. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97623. }
  97624. }
  97625. }
  97626. else {
  97627. if(order == 10) {
  97628. for(i = 0; i < (int)data_len; i++) {
  97629. sum = 0;
  97630. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97631. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97632. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97633. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97634. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97635. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97636. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97637. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97638. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97639. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97640. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97641. }
  97642. }
  97643. else { /* order == 9 */
  97644. for(i = 0; i < (int)data_len; i++) {
  97645. sum = 0;
  97646. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97647. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97648. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97649. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97650. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97651. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97652. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97653. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97654. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97655. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97656. }
  97657. }
  97658. }
  97659. }
  97660. else if(order > 4) {
  97661. if(order > 6) {
  97662. if(order == 8) {
  97663. for(i = 0; i < (int)data_len; i++) {
  97664. sum = 0;
  97665. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97666. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97667. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97668. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97669. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97670. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97671. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97672. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97673. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97674. }
  97675. }
  97676. else { /* order == 7 */
  97677. for(i = 0; i < (int)data_len; i++) {
  97678. sum = 0;
  97679. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97680. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97681. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97682. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97683. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97684. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97685. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97686. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97687. }
  97688. }
  97689. }
  97690. else {
  97691. if(order == 6) {
  97692. for(i = 0; i < (int)data_len; i++) {
  97693. sum = 0;
  97694. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97695. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97696. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97697. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97698. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97699. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97700. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97701. }
  97702. }
  97703. else { /* order == 5 */
  97704. for(i = 0; i < (int)data_len; i++) {
  97705. sum = 0;
  97706. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97707. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97708. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97709. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97710. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97711. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97712. }
  97713. }
  97714. }
  97715. }
  97716. else {
  97717. if(order > 2) {
  97718. if(order == 4) {
  97719. for(i = 0; i < (int)data_len; i++) {
  97720. sum = 0;
  97721. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97722. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97723. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97724. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97725. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97726. }
  97727. }
  97728. else { /* order == 3 */
  97729. for(i = 0; i < (int)data_len; i++) {
  97730. sum = 0;
  97731. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97732. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97733. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97734. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97735. }
  97736. }
  97737. }
  97738. else {
  97739. if(order == 2) {
  97740. for(i = 0; i < (int)data_len; i++) {
  97741. sum = 0;
  97742. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97743. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97744. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97745. }
  97746. }
  97747. else { /* order == 1 */
  97748. for(i = 0; i < (int)data_len; i++)
  97749. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97750. }
  97751. }
  97752. }
  97753. }
  97754. else { /* order > 12 */
  97755. for(i = 0; i < (int)data_len; i++) {
  97756. sum = 0;
  97757. switch(order) {
  97758. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97759. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97760. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97761. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97762. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97763. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97764. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97765. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97766. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97767. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97768. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97769. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97770. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97771. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97772. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97773. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97774. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97775. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97776. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97777. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97778. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97779. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97780. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97781. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97782. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97783. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97784. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97785. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97786. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97787. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97788. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97789. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97790. }
  97791. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97792. }
  97793. }
  97794. }
  97795. #endif
  97796. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97797. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  97798. {
  97799. FLAC__double error_scale;
  97800. FLAC__ASSERT(total_samples > 0);
  97801. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97802. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  97803. }
  97804. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  97805. {
  97806. if(lpc_error > 0.0) {
  97807. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  97808. if(bps >= 0.0)
  97809. return bps;
  97810. else
  97811. return 0.0;
  97812. }
  97813. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  97814. return 1e32;
  97815. }
  97816. else {
  97817. return 0.0;
  97818. }
  97819. }
  97820. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  97821. {
  97822. 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 */
  97823. FLAC__double bits, best_bits, error_scale;
  97824. FLAC__ASSERT(max_order > 0);
  97825. FLAC__ASSERT(total_samples > 0);
  97826. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97827. best_index = 0;
  97828. best_bits = (unsigned)(-1);
  97829. for(index = 0, order = 1; index < max_order; index++, order++) {
  97830. 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);
  97831. if(bits < best_bits) {
  97832. best_index = index;
  97833. best_bits = bits;
  97834. }
  97835. }
  97836. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  97837. }
  97838. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97839. #endif
  97840. /*** End of inlined file: lpc_flac.c ***/
  97841. /*** Start of inlined file: md5.c ***/
  97842. /*** Start of inlined file: juce_FlacHeader.h ***/
  97843. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97844. // tasks..
  97845. #define VERSION "1.2.1"
  97846. #define FLAC__NO_DLL 1
  97847. #if JUCE_MSVC
  97848. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97849. #endif
  97850. #if JUCE_MAC
  97851. #define FLAC__SYS_DARWIN 1
  97852. #endif
  97853. /*** End of inlined file: juce_FlacHeader.h ***/
  97854. #if JUCE_USE_FLAC
  97855. #if HAVE_CONFIG_H
  97856. # include <config.h>
  97857. #endif
  97858. #include <stdlib.h> /* for malloc() */
  97859. #include <string.h> /* for memcpy() */
  97860. /*** Start of inlined file: md5.h ***/
  97861. #ifndef FLAC__PRIVATE__MD5_H
  97862. #define FLAC__PRIVATE__MD5_H
  97863. /*
  97864. * This is the header file for the MD5 message-digest algorithm.
  97865. * The algorithm is due to Ron Rivest. This code was
  97866. * written by Colin Plumb in 1993, no copyright is claimed.
  97867. * This code is in the public domain; do with it what you wish.
  97868. *
  97869. * Equivalent code is available from RSA Data Security, Inc.
  97870. * This code has been tested against that, and is equivalent,
  97871. * except that you don't need to include two pages of legalese
  97872. * with every copy.
  97873. *
  97874. * To compute the message digest of a chunk of bytes, declare an
  97875. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97876. * needed on buffers full of bytes, and then call MD5Final, which
  97877. * will fill a supplied 16-byte array with the digest.
  97878. *
  97879. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  97880. * header definitions; now uses stuff from dpkg's config.h
  97881. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97882. * Still in the public domain.
  97883. *
  97884. * Josh Coalson: made some changes to integrate with libFLAC.
  97885. * Still in the public domain, with no warranty.
  97886. */
  97887. typedef struct {
  97888. FLAC__uint32 in[16];
  97889. FLAC__uint32 buf[4];
  97890. FLAC__uint32 bytes[2];
  97891. FLAC__byte *internal_buf;
  97892. size_t capacity;
  97893. } FLAC__MD5Context;
  97894. void FLAC__MD5Init(FLAC__MD5Context *context);
  97895. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  97896. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  97897. #endif
  97898. /*** End of inlined file: md5.h ***/
  97899. #ifndef FLaC__INLINE
  97900. #define FLaC__INLINE
  97901. #endif
  97902. /*
  97903. * This code implements the MD5 message-digest algorithm.
  97904. * The algorithm is due to Ron Rivest. This code was
  97905. * written by Colin Plumb in 1993, no copyright is claimed.
  97906. * This code is in the public domain; do with it what you wish.
  97907. *
  97908. * Equivalent code is available from RSA Data Security, Inc.
  97909. * This code has been tested against that, and is equivalent,
  97910. * except that you don't need to include two pages of legalese
  97911. * with every copy.
  97912. *
  97913. * To compute the message digest of a chunk of bytes, declare an
  97914. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97915. * needed on buffers full of bytes, and then call MD5Final, which
  97916. * will fill a supplied 16-byte array with the digest.
  97917. *
  97918. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  97919. * definitions; now uses stuff from dpkg's config.h.
  97920. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97921. * Still in the public domain.
  97922. *
  97923. * Josh Coalson: made some changes to integrate with libFLAC.
  97924. * Still in the public domain.
  97925. */
  97926. /* The four core functions - F1 is optimized somewhat */
  97927. /* #define F1(x, y, z) (x & y | ~x & z) */
  97928. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  97929. #define F2(x, y, z) F1(z, x, y)
  97930. #define F3(x, y, z) (x ^ y ^ z)
  97931. #define F4(x, y, z) (y ^ (x | ~z))
  97932. /* This is the central step in the MD5 algorithm. */
  97933. #define MD5STEP(f,w,x,y,z,in,s) \
  97934. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  97935. /*
  97936. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  97937. * reflect the addition of 16 longwords of new data. MD5Update blocks
  97938. * the data and converts bytes into longwords for this routine.
  97939. */
  97940. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  97941. {
  97942. register FLAC__uint32 a, b, c, d;
  97943. a = buf[0];
  97944. b = buf[1];
  97945. c = buf[2];
  97946. d = buf[3];
  97947. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  97948. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  97949. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  97950. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  97951. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  97952. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  97953. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  97954. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  97955. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  97956. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  97957. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  97958. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  97959. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  97960. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  97961. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  97962. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  97963. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  97964. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  97965. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  97966. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  97967. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  97968. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  97969. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  97970. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  97971. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  97972. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  97973. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  97974. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  97975. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  97976. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  97977. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  97978. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  97979. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  97980. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  97981. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  97982. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  97983. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  97984. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  97985. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  97986. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  97987. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  97988. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  97989. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  97990. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  97991. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  97992. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  97993. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  97994. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  97995. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  97996. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  97997. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  97998. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  97999. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98000. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98001. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98002. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98003. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98004. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98005. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98006. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98007. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98008. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98009. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98010. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98011. buf[0] += a;
  98012. buf[1] += b;
  98013. buf[2] += c;
  98014. buf[3] += d;
  98015. }
  98016. #if WORDS_BIGENDIAN
  98017. //@@@@@@ OPT: use bswap/intrinsics
  98018. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98019. {
  98020. register FLAC__uint32 x;
  98021. do {
  98022. x = *buf;
  98023. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98024. *buf++ = (x >> 16) | (x << 16);
  98025. } while (--words);
  98026. }
  98027. static void byteSwapX16(FLAC__uint32 *buf)
  98028. {
  98029. register FLAC__uint32 x;
  98030. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98031. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98032. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98033. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98034. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98035. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98036. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98037. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98038. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98039. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98040. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98041. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98042. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98043. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98044. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98045. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98046. }
  98047. #else
  98048. #define byteSwap(buf, words)
  98049. #define byteSwapX16(buf)
  98050. #endif
  98051. /*
  98052. * Update context to reflect the concatenation of another buffer full
  98053. * of bytes.
  98054. */
  98055. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98056. {
  98057. FLAC__uint32 t;
  98058. /* Update byte count */
  98059. t = ctx->bytes[0];
  98060. if ((ctx->bytes[0] = t + len) < t)
  98061. ctx->bytes[1]++; /* Carry from low to high */
  98062. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98063. if (t > len) {
  98064. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98065. return;
  98066. }
  98067. /* First chunk is an odd size */
  98068. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98069. byteSwapX16(ctx->in);
  98070. FLAC__MD5Transform(ctx->buf, ctx->in);
  98071. buf += t;
  98072. len -= t;
  98073. /* Process data in 64-byte chunks */
  98074. while (len >= 64) {
  98075. memcpy(ctx->in, buf, 64);
  98076. byteSwapX16(ctx->in);
  98077. FLAC__MD5Transform(ctx->buf, ctx->in);
  98078. buf += 64;
  98079. len -= 64;
  98080. }
  98081. /* Handle any remaining bytes of data. */
  98082. memcpy(ctx->in, buf, len);
  98083. }
  98084. /*
  98085. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98086. * initialization constants.
  98087. */
  98088. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98089. {
  98090. ctx->buf[0] = 0x67452301;
  98091. ctx->buf[1] = 0xefcdab89;
  98092. ctx->buf[2] = 0x98badcfe;
  98093. ctx->buf[3] = 0x10325476;
  98094. ctx->bytes[0] = 0;
  98095. ctx->bytes[1] = 0;
  98096. ctx->internal_buf = 0;
  98097. ctx->capacity = 0;
  98098. }
  98099. /*
  98100. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98101. * 1 0* (64-bit count of bits processed, MSB-first)
  98102. */
  98103. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98104. {
  98105. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98106. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98107. /* Set the first char of padding to 0x80. There is always room. */
  98108. *p++ = 0x80;
  98109. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98110. count = 56 - 1 - count;
  98111. if (count < 0) { /* Padding forces an extra block */
  98112. memset(p, 0, count + 8);
  98113. byteSwapX16(ctx->in);
  98114. FLAC__MD5Transform(ctx->buf, ctx->in);
  98115. p = (FLAC__byte *)ctx->in;
  98116. count = 56;
  98117. }
  98118. memset(p, 0, count);
  98119. byteSwap(ctx->in, 14);
  98120. /* Append length in bits and transform */
  98121. ctx->in[14] = ctx->bytes[0] << 3;
  98122. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98123. FLAC__MD5Transform(ctx->buf, ctx->in);
  98124. byteSwap(ctx->buf, 4);
  98125. memcpy(digest, ctx->buf, 16);
  98126. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98127. if(0 != ctx->internal_buf) {
  98128. free(ctx->internal_buf);
  98129. ctx->internal_buf = 0;
  98130. ctx->capacity = 0;
  98131. }
  98132. }
  98133. /*
  98134. * Convert the incoming audio signal to a byte stream
  98135. */
  98136. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98137. {
  98138. unsigned channel, sample;
  98139. register FLAC__int32 a_word;
  98140. register FLAC__byte *buf_ = buf;
  98141. #if WORDS_BIGENDIAN
  98142. #else
  98143. if(channels == 2 && bytes_per_sample == 2) {
  98144. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98145. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98146. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98147. *buf1_ = (FLAC__int16)signal[1][sample];
  98148. }
  98149. else if(channels == 1 && bytes_per_sample == 2) {
  98150. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98151. for(sample = 0; sample < samples; sample++)
  98152. *buf1_++ = (FLAC__int16)signal[0][sample];
  98153. }
  98154. else
  98155. #endif
  98156. if(bytes_per_sample == 2) {
  98157. if(channels == 2) {
  98158. for(sample = 0; sample < samples; sample++) {
  98159. a_word = signal[0][sample];
  98160. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98161. *buf_++ = (FLAC__byte)a_word;
  98162. a_word = signal[1][sample];
  98163. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98164. *buf_++ = (FLAC__byte)a_word;
  98165. }
  98166. }
  98167. else if(channels == 1) {
  98168. for(sample = 0; sample < samples; sample++) {
  98169. a_word = signal[0][sample];
  98170. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98171. *buf_++ = (FLAC__byte)a_word;
  98172. }
  98173. }
  98174. else {
  98175. for(sample = 0; sample < samples; sample++) {
  98176. for(channel = 0; channel < channels; channel++) {
  98177. a_word = signal[channel][sample];
  98178. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98179. *buf_++ = (FLAC__byte)a_word;
  98180. }
  98181. }
  98182. }
  98183. }
  98184. else if(bytes_per_sample == 3) {
  98185. if(channels == 2) {
  98186. for(sample = 0; sample < samples; sample++) {
  98187. a_word = signal[0][sample];
  98188. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98189. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98190. *buf_++ = (FLAC__byte)a_word;
  98191. a_word = signal[1][sample];
  98192. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98193. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98194. *buf_++ = (FLAC__byte)a_word;
  98195. }
  98196. }
  98197. else if(channels == 1) {
  98198. for(sample = 0; sample < samples; sample++) {
  98199. a_word = signal[0][sample];
  98200. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98201. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98202. *buf_++ = (FLAC__byte)a_word;
  98203. }
  98204. }
  98205. else {
  98206. for(sample = 0; sample < samples; sample++) {
  98207. for(channel = 0; channel < channels; channel++) {
  98208. a_word = signal[channel][sample];
  98209. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98210. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98211. *buf_++ = (FLAC__byte)a_word;
  98212. }
  98213. }
  98214. }
  98215. }
  98216. else if(bytes_per_sample == 1) {
  98217. if(channels == 2) {
  98218. for(sample = 0; sample < samples; sample++) {
  98219. a_word = signal[0][sample];
  98220. *buf_++ = (FLAC__byte)a_word;
  98221. a_word = signal[1][sample];
  98222. *buf_++ = (FLAC__byte)a_word;
  98223. }
  98224. }
  98225. else if(channels == 1) {
  98226. for(sample = 0; sample < samples; sample++) {
  98227. a_word = signal[0][sample];
  98228. *buf_++ = (FLAC__byte)a_word;
  98229. }
  98230. }
  98231. else {
  98232. for(sample = 0; sample < samples; sample++) {
  98233. for(channel = 0; channel < channels; channel++) {
  98234. a_word = signal[channel][sample];
  98235. *buf_++ = (FLAC__byte)a_word;
  98236. }
  98237. }
  98238. }
  98239. }
  98240. else { /* bytes_per_sample == 4, maybe optimize more later */
  98241. for(sample = 0; sample < samples; sample++) {
  98242. for(channel = 0; channel < channels; channel++) {
  98243. a_word = signal[channel][sample];
  98244. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98245. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98246. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98247. *buf_++ = (FLAC__byte)a_word;
  98248. }
  98249. }
  98250. }
  98251. }
  98252. /*
  98253. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98254. */
  98255. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98256. {
  98257. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98258. /* overflow check */
  98259. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98260. return false;
  98261. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98262. return false;
  98263. if(ctx->capacity < bytes_needed) {
  98264. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98265. if(0 == tmp) {
  98266. free(ctx->internal_buf);
  98267. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98268. return false;
  98269. }
  98270. ctx->internal_buf = tmp;
  98271. ctx->capacity = bytes_needed;
  98272. }
  98273. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98274. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98275. return true;
  98276. }
  98277. #endif
  98278. /*** End of inlined file: md5.c ***/
  98279. /*** Start of inlined file: memory.c ***/
  98280. /*** Start of inlined file: juce_FlacHeader.h ***/
  98281. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98282. // tasks..
  98283. #define VERSION "1.2.1"
  98284. #define FLAC__NO_DLL 1
  98285. #if JUCE_MSVC
  98286. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98287. #endif
  98288. #if JUCE_MAC
  98289. #define FLAC__SYS_DARWIN 1
  98290. #endif
  98291. /*** End of inlined file: juce_FlacHeader.h ***/
  98292. #if JUCE_USE_FLAC
  98293. #if HAVE_CONFIG_H
  98294. # include <config.h>
  98295. #endif
  98296. /*** Start of inlined file: memory.h ***/
  98297. #ifndef FLAC__PRIVATE__MEMORY_H
  98298. #define FLAC__PRIVATE__MEMORY_H
  98299. #ifdef HAVE_CONFIG_H
  98300. #include <config.h>
  98301. #endif
  98302. #include <stdlib.h> /* for size_t */
  98303. /* Returns the unaligned address returned by malloc.
  98304. * Use free() on this address to deallocate.
  98305. */
  98306. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98307. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98308. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98309. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98310. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98311. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98312. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98313. #endif
  98314. #endif
  98315. /*** End of inlined file: memory.h ***/
  98316. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98317. {
  98318. void *x;
  98319. FLAC__ASSERT(0 != aligned_address);
  98320. #ifdef FLAC__ALIGN_MALLOC_DATA
  98321. /* align on 32-byte (256-bit) boundary */
  98322. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98323. #ifdef SIZEOF_VOIDP
  98324. #if SIZEOF_VOIDP == 4
  98325. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98326. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98327. #elif SIZEOF_VOIDP == 8
  98328. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98329. #else
  98330. # error Unsupported sizeof(void*)
  98331. #endif
  98332. #else
  98333. /* there's got to be a better way to do this right for all archs */
  98334. if(sizeof(void*) == sizeof(unsigned))
  98335. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98336. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98337. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98338. else
  98339. return 0;
  98340. #endif
  98341. #else
  98342. x = safe_malloc_(bytes);
  98343. *aligned_address = x;
  98344. #endif
  98345. return x;
  98346. }
  98347. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98348. {
  98349. FLAC__int32 *pu; /* unaligned pointer */
  98350. union { /* union needed to comply with C99 pointer aliasing rules */
  98351. FLAC__int32 *pa; /* aligned pointer */
  98352. void *pv; /* aligned pointer alias */
  98353. } u;
  98354. FLAC__ASSERT(elements > 0);
  98355. FLAC__ASSERT(0 != unaligned_pointer);
  98356. FLAC__ASSERT(0 != aligned_pointer);
  98357. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98358. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98359. if(0 == pu) {
  98360. return false;
  98361. }
  98362. else {
  98363. if(*unaligned_pointer != 0)
  98364. free(*unaligned_pointer);
  98365. *unaligned_pointer = pu;
  98366. *aligned_pointer = u.pa;
  98367. return true;
  98368. }
  98369. }
  98370. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98371. {
  98372. FLAC__uint32 *pu; /* unaligned pointer */
  98373. union { /* union needed to comply with C99 pointer aliasing rules */
  98374. FLAC__uint32 *pa; /* aligned pointer */
  98375. void *pv; /* aligned pointer alias */
  98376. } u;
  98377. FLAC__ASSERT(elements > 0);
  98378. FLAC__ASSERT(0 != unaligned_pointer);
  98379. FLAC__ASSERT(0 != aligned_pointer);
  98380. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98381. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98382. if(0 == pu) {
  98383. return false;
  98384. }
  98385. else {
  98386. if(*unaligned_pointer != 0)
  98387. free(*unaligned_pointer);
  98388. *unaligned_pointer = pu;
  98389. *aligned_pointer = u.pa;
  98390. return true;
  98391. }
  98392. }
  98393. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98394. {
  98395. FLAC__uint64 *pu; /* unaligned pointer */
  98396. union { /* union needed to comply with C99 pointer aliasing rules */
  98397. FLAC__uint64 *pa; /* aligned pointer */
  98398. void *pv; /* aligned pointer alias */
  98399. } u;
  98400. FLAC__ASSERT(elements > 0);
  98401. FLAC__ASSERT(0 != unaligned_pointer);
  98402. FLAC__ASSERT(0 != aligned_pointer);
  98403. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98404. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98405. if(0 == pu) {
  98406. return false;
  98407. }
  98408. else {
  98409. if(*unaligned_pointer != 0)
  98410. free(*unaligned_pointer);
  98411. *unaligned_pointer = pu;
  98412. *aligned_pointer = u.pa;
  98413. return true;
  98414. }
  98415. }
  98416. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98417. {
  98418. unsigned *pu; /* unaligned pointer */
  98419. union { /* union needed to comply with C99 pointer aliasing rules */
  98420. unsigned *pa; /* aligned pointer */
  98421. void *pv; /* aligned pointer alias */
  98422. } u;
  98423. FLAC__ASSERT(elements > 0);
  98424. FLAC__ASSERT(0 != unaligned_pointer);
  98425. FLAC__ASSERT(0 != aligned_pointer);
  98426. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98427. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98428. if(0 == pu) {
  98429. return false;
  98430. }
  98431. else {
  98432. if(*unaligned_pointer != 0)
  98433. free(*unaligned_pointer);
  98434. *unaligned_pointer = pu;
  98435. *aligned_pointer = u.pa;
  98436. return true;
  98437. }
  98438. }
  98439. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98440. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98441. {
  98442. FLAC__real *pu; /* unaligned pointer */
  98443. union { /* union needed to comply with C99 pointer aliasing rules */
  98444. FLAC__real *pa; /* aligned pointer */
  98445. void *pv; /* aligned pointer alias */
  98446. } u;
  98447. FLAC__ASSERT(elements > 0);
  98448. FLAC__ASSERT(0 != unaligned_pointer);
  98449. FLAC__ASSERT(0 != aligned_pointer);
  98450. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98451. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98452. if(0 == pu) {
  98453. return false;
  98454. }
  98455. else {
  98456. if(*unaligned_pointer != 0)
  98457. free(*unaligned_pointer);
  98458. *unaligned_pointer = pu;
  98459. *aligned_pointer = u.pa;
  98460. return true;
  98461. }
  98462. }
  98463. #endif
  98464. #endif
  98465. /*** End of inlined file: memory.c ***/
  98466. /*** Start of inlined file: stream_decoder.c ***/
  98467. /*** Start of inlined file: juce_FlacHeader.h ***/
  98468. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98469. // tasks..
  98470. #define VERSION "1.2.1"
  98471. #define FLAC__NO_DLL 1
  98472. #if JUCE_MSVC
  98473. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98474. #endif
  98475. #if JUCE_MAC
  98476. #define FLAC__SYS_DARWIN 1
  98477. #endif
  98478. /*** End of inlined file: juce_FlacHeader.h ***/
  98479. #if JUCE_USE_FLAC
  98480. #if HAVE_CONFIG_H
  98481. # include <config.h>
  98482. #endif
  98483. #if defined _MSC_VER || defined __MINGW32__
  98484. #include <io.h> /* for _setmode() */
  98485. #include <fcntl.h> /* for _O_BINARY */
  98486. #endif
  98487. #if defined __CYGWIN__ || defined __EMX__
  98488. #include <io.h> /* for setmode(), O_BINARY */
  98489. #include <fcntl.h> /* for _O_BINARY */
  98490. #endif
  98491. #include <stdio.h>
  98492. #include <stdlib.h> /* for malloc() */
  98493. #include <string.h> /* for memset/memcpy() */
  98494. #include <sys/stat.h> /* for stat() */
  98495. #include <sys/types.h> /* for off_t */
  98496. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98497. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98498. #define fseeko fseek
  98499. #define ftello ftell
  98500. #endif
  98501. #endif
  98502. /*** Start of inlined file: stream_decoder.h ***/
  98503. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98504. #define FLAC__PROTECTED__STREAM_DECODER_H
  98505. #if FLAC__HAS_OGG
  98506. #include "include/private/ogg_decoder_aspect.h"
  98507. #endif
  98508. typedef struct FLAC__StreamDecoderProtected {
  98509. FLAC__StreamDecoderState state;
  98510. unsigned channels;
  98511. FLAC__ChannelAssignment channel_assignment;
  98512. unsigned bits_per_sample;
  98513. unsigned sample_rate; /* in Hz */
  98514. unsigned blocksize; /* in samples (per channel) */
  98515. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98516. #if FLAC__HAS_OGG
  98517. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98518. #endif
  98519. } FLAC__StreamDecoderProtected;
  98520. /*
  98521. * return the number of input bytes consumed
  98522. */
  98523. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98524. #endif
  98525. /*** End of inlined file: stream_decoder.h ***/
  98526. #ifdef max
  98527. #undef max
  98528. #endif
  98529. #define max(a,b) ((a)>(b)?(a):(b))
  98530. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98531. #ifdef _MSC_VER
  98532. #define FLAC__U64L(x) x
  98533. #else
  98534. #define FLAC__U64L(x) x##LLU
  98535. #endif
  98536. /* technically this should be in an "export.c" but this is convenient enough */
  98537. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98538. #if FLAC__HAS_OGG
  98539. 1
  98540. #else
  98541. 0
  98542. #endif
  98543. ;
  98544. /***********************************************************************
  98545. *
  98546. * Private static data
  98547. *
  98548. ***********************************************************************/
  98549. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98550. /***********************************************************************
  98551. *
  98552. * Private class method prototypes
  98553. *
  98554. ***********************************************************************/
  98555. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98556. static FILE *get_binary_stdin_(void);
  98557. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98558. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98559. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98560. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98561. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98562. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98563. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98564. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98565. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98566. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98567. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98568. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98569. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98570. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98571. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98572. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98573. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98574. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98575. 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);
  98576. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98577. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98578. #if FLAC__HAS_OGG
  98579. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98580. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98581. #endif
  98582. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98583. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98584. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98585. #if FLAC__HAS_OGG
  98586. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98587. #endif
  98588. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98589. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98590. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98591. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98592. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98593. /***********************************************************************
  98594. *
  98595. * Private class data
  98596. *
  98597. ***********************************************************************/
  98598. typedef struct FLAC__StreamDecoderPrivate {
  98599. #if FLAC__HAS_OGG
  98600. FLAC__bool is_ogg;
  98601. #endif
  98602. FLAC__StreamDecoderReadCallback read_callback;
  98603. FLAC__StreamDecoderSeekCallback seek_callback;
  98604. FLAC__StreamDecoderTellCallback tell_callback;
  98605. FLAC__StreamDecoderLengthCallback length_callback;
  98606. FLAC__StreamDecoderEofCallback eof_callback;
  98607. FLAC__StreamDecoderWriteCallback write_callback;
  98608. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98609. FLAC__StreamDecoderErrorCallback error_callback;
  98610. /* generic 32-bit datapath: */
  98611. 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[]);
  98612. /* generic 64-bit datapath: */
  98613. 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[]);
  98614. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98615. 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[]);
  98616. /* 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: */
  98617. 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[]);
  98618. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98619. void *client_data;
  98620. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98621. FLAC__BitReader *input;
  98622. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98623. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98624. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98625. unsigned output_capacity, output_channels;
  98626. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98627. FLAC__uint64 samples_decoded;
  98628. FLAC__bool has_stream_info, has_seek_table;
  98629. FLAC__StreamMetadata stream_info;
  98630. FLAC__StreamMetadata seek_table;
  98631. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98632. FLAC__byte *metadata_filter_ids;
  98633. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98634. FLAC__Frame frame;
  98635. FLAC__bool cached; /* true if there is a byte in lookahead */
  98636. FLAC__CPUInfo cpuinfo;
  98637. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98638. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98639. /* unaligned (original) pointers to allocated data */
  98640. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98641. 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 */
  98642. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98643. FLAC__bool is_seeking;
  98644. FLAC__MD5Context md5context;
  98645. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98646. /* (the rest of these are only used for seeking) */
  98647. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98648. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98649. FLAC__uint64 target_sample;
  98650. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98651. #if FLAC__HAS_OGG
  98652. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98653. #endif
  98654. } FLAC__StreamDecoderPrivate;
  98655. /***********************************************************************
  98656. *
  98657. * Public static class data
  98658. *
  98659. ***********************************************************************/
  98660. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98661. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98662. "FLAC__STREAM_DECODER_READ_METADATA",
  98663. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98664. "FLAC__STREAM_DECODER_READ_FRAME",
  98665. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98666. "FLAC__STREAM_DECODER_OGG_ERROR",
  98667. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98668. "FLAC__STREAM_DECODER_ABORTED",
  98669. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98670. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98671. };
  98672. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98673. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98674. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98675. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98676. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98677. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98678. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98679. };
  98680. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98681. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98682. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98683. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98684. };
  98685. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98686. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98687. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98688. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98689. };
  98690. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98691. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98692. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98693. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98694. };
  98695. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98696. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98697. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98698. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98699. };
  98700. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98701. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98702. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98703. };
  98704. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98705. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98706. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98707. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98708. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98709. };
  98710. /***********************************************************************
  98711. *
  98712. * Class constructor/destructor
  98713. *
  98714. ***********************************************************************/
  98715. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98716. {
  98717. FLAC__StreamDecoder *decoder;
  98718. unsigned i;
  98719. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98720. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98721. if(decoder == 0) {
  98722. return 0;
  98723. }
  98724. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98725. if(decoder->protected_ == 0) {
  98726. free(decoder);
  98727. return 0;
  98728. }
  98729. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98730. if(decoder->private_ == 0) {
  98731. free(decoder->protected_);
  98732. free(decoder);
  98733. return 0;
  98734. }
  98735. decoder->private_->input = FLAC__bitreader_new();
  98736. if(decoder->private_->input == 0) {
  98737. free(decoder->private_);
  98738. free(decoder->protected_);
  98739. free(decoder);
  98740. return 0;
  98741. }
  98742. decoder->private_->metadata_filter_ids_capacity = 16;
  98743. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98744. FLAC__bitreader_delete(decoder->private_->input);
  98745. free(decoder->private_);
  98746. free(decoder->protected_);
  98747. free(decoder);
  98748. return 0;
  98749. }
  98750. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98751. decoder->private_->output[i] = 0;
  98752. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98753. }
  98754. decoder->private_->output_capacity = 0;
  98755. decoder->private_->output_channels = 0;
  98756. decoder->private_->has_seek_table = false;
  98757. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98758. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98759. decoder->private_->file = 0;
  98760. set_defaults_dec(decoder);
  98761. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98762. return decoder;
  98763. }
  98764. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98765. {
  98766. unsigned i;
  98767. FLAC__ASSERT(0 != decoder);
  98768. FLAC__ASSERT(0 != decoder->protected_);
  98769. FLAC__ASSERT(0 != decoder->private_);
  98770. FLAC__ASSERT(0 != decoder->private_->input);
  98771. (void)FLAC__stream_decoder_finish(decoder);
  98772. if(0 != decoder->private_->metadata_filter_ids)
  98773. free(decoder->private_->metadata_filter_ids);
  98774. FLAC__bitreader_delete(decoder->private_->input);
  98775. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98776. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98777. free(decoder->private_);
  98778. free(decoder->protected_);
  98779. free(decoder);
  98780. }
  98781. /***********************************************************************
  98782. *
  98783. * Public class methods
  98784. *
  98785. ***********************************************************************/
  98786. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98787. FLAC__StreamDecoder *decoder,
  98788. FLAC__StreamDecoderReadCallback read_callback,
  98789. FLAC__StreamDecoderSeekCallback seek_callback,
  98790. FLAC__StreamDecoderTellCallback tell_callback,
  98791. FLAC__StreamDecoderLengthCallback length_callback,
  98792. FLAC__StreamDecoderEofCallback eof_callback,
  98793. FLAC__StreamDecoderWriteCallback write_callback,
  98794. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98795. FLAC__StreamDecoderErrorCallback error_callback,
  98796. void *client_data,
  98797. FLAC__bool is_ogg
  98798. )
  98799. {
  98800. FLAC__ASSERT(0 != decoder);
  98801. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98802. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  98803. #if !FLAC__HAS_OGG
  98804. if(is_ogg)
  98805. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98806. #endif
  98807. if(
  98808. 0 == read_callback ||
  98809. 0 == write_callback ||
  98810. 0 == error_callback ||
  98811. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  98812. )
  98813. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  98814. #if FLAC__HAS_OGG
  98815. decoder->private_->is_ogg = is_ogg;
  98816. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  98817. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  98818. #endif
  98819. /*
  98820. * get the CPU info and set the function pointers
  98821. */
  98822. FLAC__cpu_info(&decoder->private_->cpuinfo);
  98823. /* first default to the non-asm routines */
  98824. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  98825. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  98826. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  98827. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  98828. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  98829. /* now override with asm where appropriate */
  98830. #ifndef FLAC__NO_ASM
  98831. if(decoder->private_->cpuinfo.use_asm) {
  98832. #ifdef FLAC__CPU_IA32
  98833. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98834. #ifdef FLAC__HAS_NASM
  98835. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  98836. if(decoder->private_->cpuinfo.data.ia32.bswap)
  98837. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  98838. #endif
  98839. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  98840. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98841. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98842. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98843. }
  98844. else {
  98845. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98846. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  98847. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  98848. }
  98849. #endif
  98850. #elif defined FLAC__CPU_PPC
  98851. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  98852. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  98853. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  98854. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  98855. }
  98856. #endif
  98857. }
  98858. #endif
  98859. /* from here on, errors are fatal */
  98860. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  98861. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98862. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98863. }
  98864. decoder->private_->read_callback = read_callback;
  98865. decoder->private_->seek_callback = seek_callback;
  98866. decoder->private_->tell_callback = tell_callback;
  98867. decoder->private_->length_callback = length_callback;
  98868. decoder->private_->eof_callback = eof_callback;
  98869. decoder->private_->write_callback = write_callback;
  98870. decoder->private_->metadata_callback = metadata_callback;
  98871. decoder->private_->error_callback = error_callback;
  98872. decoder->private_->client_data = client_data;
  98873. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98874. decoder->private_->samples_decoded = 0;
  98875. decoder->private_->has_stream_info = false;
  98876. decoder->private_->cached = false;
  98877. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98878. decoder->private_->is_seeking = false;
  98879. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  98880. if(!FLAC__stream_decoder_reset(decoder)) {
  98881. /* above call sets the state for us */
  98882. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98883. }
  98884. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  98885. }
  98886. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  98887. FLAC__StreamDecoder *decoder,
  98888. FLAC__StreamDecoderReadCallback read_callback,
  98889. FLAC__StreamDecoderSeekCallback seek_callback,
  98890. FLAC__StreamDecoderTellCallback tell_callback,
  98891. FLAC__StreamDecoderLengthCallback length_callback,
  98892. FLAC__StreamDecoderEofCallback eof_callback,
  98893. FLAC__StreamDecoderWriteCallback write_callback,
  98894. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98895. FLAC__StreamDecoderErrorCallback error_callback,
  98896. void *client_data
  98897. )
  98898. {
  98899. return init_stream_internal_dec(
  98900. decoder,
  98901. read_callback,
  98902. seek_callback,
  98903. tell_callback,
  98904. length_callback,
  98905. eof_callback,
  98906. write_callback,
  98907. metadata_callback,
  98908. error_callback,
  98909. client_data,
  98910. /*is_ogg=*/false
  98911. );
  98912. }
  98913. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  98914. FLAC__StreamDecoder *decoder,
  98915. FLAC__StreamDecoderReadCallback read_callback,
  98916. FLAC__StreamDecoderSeekCallback seek_callback,
  98917. FLAC__StreamDecoderTellCallback tell_callback,
  98918. FLAC__StreamDecoderLengthCallback length_callback,
  98919. FLAC__StreamDecoderEofCallback eof_callback,
  98920. FLAC__StreamDecoderWriteCallback write_callback,
  98921. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98922. FLAC__StreamDecoderErrorCallback error_callback,
  98923. void *client_data
  98924. )
  98925. {
  98926. return init_stream_internal_dec(
  98927. decoder,
  98928. read_callback,
  98929. seek_callback,
  98930. tell_callback,
  98931. length_callback,
  98932. eof_callback,
  98933. write_callback,
  98934. metadata_callback,
  98935. error_callback,
  98936. client_data,
  98937. /*is_ogg=*/true
  98938. );
  98939. }
  98940. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  98941. FLAC__StreamDecoder *decoder,
  98942. FILE *file,
  98943. FLAC__StreamDecoderWriteCallback write_callback,
  98944. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98945. FLAC__StreamDecoderErrorCallback error_callback,
  98946. void *client_data,
  98947. FLAC__bool is_ogg
  98948. )
  98949. {
  98950. FLAC__ASSERT(0 != decoder);
  98951. FLAC__ASSERT(0 != file);
  98952. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98953. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98954. if(0 == write_callback || 0 == error_callback)
  98955. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98956. /*
  98957. * To make sure that our file does not go unclosed after an error, we
  98958. * must assign the FILE pointer before any further error can occur in
  98959. * this routine.
  98960. */
  98961. if(file == stdin)
  98962. file = get_binary_stdin_(); /* just to be safe */
  98963. decoder->private_->file = file;
  98964. return init_stream_internal_dec(
  98965. decoder,
  98966. file_read_callback_dec,
  98967. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  98968. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  98969. decoder->private_->file == stdin? 0: file_length_callback_,
  98970. file_eof_callback_,
  98971. write_callback,
  98972. metadata_callback,
  98973. error_callback,
  98974. client_data,
  98975. is_ogg
  98976. );
  98977. }
  98978. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  98979. FLAC__StreamDecoder *decoder,
  98980. FILE *file,
  98981. FLAC__StreamDecoderWriteCallback write_callback,
  98982. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98983. FLAC__StreamDecoderErrorCallback error_callback,
  98984. void *client_data
  98985. )
  98986. {
  98987. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98988. }
  98989. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  98990. FLAC__StreamDecoder *decoder,
  98991. FILE *file,
  98992. FLAC__StreamDecoderWriteCallback write_callback,
  98993. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98994. FLAC__StreamDecoderErrorCallback error_callback,
  98995. void *client_data
  98996. )
  98997. {
  98998. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98999. }
  99000. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99001. FLAC__StreamDecoder *decoder,
  99002. const char *filename,
  99003. FLAC__StreamDecoderWriteCallback write_callback,
  99004. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99005. FLAC__StreamDecoderErrorCallback error_callback,
  99006. void *client_data,
  99007. FLAC__bool is_ogg
  99008. )
  99009. {
  99010. FILE *file;
  99011. FLAC__ASSERT(0 != decoder);
  99012. /*
  99013. * To make sure that our file does not go unclosed after an error, we
  99014. * have to do the same entrance checks here that are later performed
  99015. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99016. */
  99017. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99018. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99019. if(0 == write_callback || 0 == error_callback)
  99020. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99021. file = filename? fopen(filename, "rb") : stdin;
  99022. if(0 == file)
  99023. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99024. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99025. }
  99026. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99027. FLAC__StreamDecoder *decoder,
  99028. const char *filename,
  99029. FLAC__StreamDecoderWriteCallback write_callback,
  99030. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99031. FLAC__StreamDecoderErrorCallback error_callback,
  99032. void *client_data
  99033. )
  99034. {
  99035. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99036. }
  99037. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99038. FLAC__StreamDecoder *decoder,
  99039. const char *filename,
  99040. FLAC__StreamDecoderWriteCallback write_callback,
  99041. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99042. FLAC__StreamDecoderErrorCallback error_callback,
  99043. void *client_data
  99044. )
  99045. {
  99046. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99047. }
  99048. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99049. {
  99050. FLAC__bool md5_failed = false;
  99051. unsigned i;
  99052. FLAC__ASSERT(0 != decoder);
  99053. FLAC__ASSERT(0 != decoder->private_);
  99054. FLAC__ASSERT(0 != decoder->protected_);
  99055. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99056. return true;
  99057. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99058. * always call FLAC__MD5Final()
  99059. */
  99060. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99061. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99062. free(decoder->private_->seek_table.data.seek_table.points);
  99063. decoder->private_->seek_table.data.seek_table.points = 0;
  99064. decoder->private_->has_seek_table = false;
  99065. }
  99066. FLAC__bitreader_free(decoder->private_->input);
  99067. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99068. /* WATCHOUT:
  99069. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99070. * output arrays have a buffer of up to 3 zeroes in front
  99071. * (at negative indices) for alignment purposes; we use 4
  99072. * to keep the data well-aligned.
  99073. */
  99074. if(0 != decoder->private_->output[i]) {
  99075. free(decoder->private_->output[i]-4);
  99076. decoder->private_->output[i] = 0;
  99077. }
  99078. if(0 != decoder->private_->residual_unaligned[i]) {
  99079. free(decoder->private_->residual_unaligned[i]);
  99080. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99081. }
  99082. }
  99083. decoder->private_->output_capacity = 0;
  99084. decoder->private_->output_channels = 0;
  99085. #if FLAC__HAS_OGG
  99086. if(decoder->private_->is_ogg)
  99087. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99088. #endif
  99089. if(0 != decoder->private_->file) {
  99090. if(decoder->private_->file != stdin)
  99091. fclose(decoder->private_->file);
  99092. decoder->private_->file = 0;
  99093. }
  99094. if(decoder->private_->do_md5_checking) {
  99095. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99096. md5_failed = true;
  99097. }
  99098. decoder->private_->is_seeking = false;
  99099. set_defaults_dec(decoder);
  99100. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99101. return !md5_failed;
  99102. }
  99103. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99104. {
  99105. FLAC__ASSERT(0 != decoder);
  99106. FLAC__ASSERT(0 != decoder->private_);
  99107. FLAC__ASSERT(0 != decoder->protected_);
  99108. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99109. return false;
  99110. #if FLAC__HAS_OGG
  99111. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99112. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99113. return true;
  99114. #else
  99115. (void)value;
  99116. return false;
  99117. #endif
  99118. }
  99119. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99120. {
  99121. FLAC__ASSERT(0 != decoder);
  99122. FLAC__ASSERT(0 != decoder->protected_);
  99123. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99124. return false;
  99125. decoder->protected_->md5_checking = value;
  99126. return true;
  99127. }
  99128. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99129. {
  99130. FLAC__ASSERT(0 != decoder);
  99131. FLAC__ASSERT(0 != decoder->private_);
  99132. FLAC__ASSERT(0 != decoder->protected_);
  99133. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99134. /* double protection */
  99135. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99136. return false;
  99137. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99138. return false;
  99139. decoder->private_->metadata_filter[type] = true;
  99140. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99141. decoder->private_->metadata_filter_ids_count = 0;
  99142. return true;
  99143. }
  99144. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99145. {
  99146. FLAC__ASSERT(0 != decoder);
  99147. FLAC__ASSERT(0 != decoder->private_);
  99148. FLAC__ASSERT(0 != decoder->protected_);
  99149. FLAC__ASSERT(0 != id);
  99150. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99151. return false;
  99152. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99153. return true;
  99154. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99155. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99156. 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))) {
  99157. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99158. return false;
  99159. }
  99160. decoder->private_->metadata_filter_ids_capacity *= 2;
  99161. }
  99162. 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));
  99163. decoder->private_->metadata_filter_ids_count++;
  99164. return true;
  99165. }
  99166. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99167. {
  99168. unsigned i;
  99169. FLAC__ASSERT(0 != decoder);
  99170. FLAC__ASSERT(0 != decoder->private_);
  99171. FLAC__ASSERT(0 != decoder->protected_);
  99172. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99173. return false;
  99174. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99175. decoder->private_->metadata_filter[i] = true;
  99176. decoder->private_->metadata_filter_ids_count = 0;
  99177. return true;
  99178. }
  99179. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99180. {
  99181. FLAC__ASSERT(0 != decoder);
  99182. FLAC__ASSERT(0 != decoder->private_);
  99183. FLAC__ASSERT(0 != decoder->protected_);
  99184. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99185. /* double protection */
  99186. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99187. return false;
  99188. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99189. return false;
  99190. decoder->private_->metadata_filter[type] = false;
  99191. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99192. decoder->private_->metadata_filter_ids_count = 0;
  99193. return true;
  99194. }
  99195. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99196. {
  99197. FLAC__ASSERT(0 != decoder);
  99198. FLAC__ASSERT(0 != decoder->private_);
  99199. FLAC__ASSERT(0 != decoder->protected_);
  99200. FLAC__ASSERT(0 != id);
  99201. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99202. return false;
  99203. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99204. return true;
  99205. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99206. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99207. 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))) {
  99208. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99209. return false;
  99210. }
  99211. decoder->private_->metadata_filter_ids_capacity *= 2;
  99212. }
  99213. 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));
  99214. decoder->private_->metadata_filter_ids_count++;
  99215. return true;
  99216. }
  99217. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99218. {
  99219. FLAC__ASSERT(0 != decoder);
  99220. FLAC__ASSERT(0 != decoder->private_);
  99221. FLAC__ASSERT(0 != decoder->protected_);
  99222. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99223. return false;
  99224. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99225. decoder->private_->metadata_filter_ids_count = 0;
  99226. return true;
  99227. }
  99228. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99229. {
  99230. FLAC__ASSERT(0 != decoder);
  99231. FLAC__ASSERT(0 != decoder->protected_);
  99232. return decoder->protected_->state;
  99233. }
  99234. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99235. {
  99236. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99237. }
  99238. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99239. {
  99240. FLAC__ASSERT(0 != decoder);
  99241. FLAC__ASSERT(0 != decoder->protected_);
  99242. return decoder->protected_->md5_checking;
  99243. }
  99244. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99245. {
  99246. FLAC__ASSERT(0 != decoder);
  99247. FLAC__ASSERT(0 != decoder->protected_);
  99248. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99249. }
  99250. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99251. {
  99252. FLAC__ASSERT(0 != decoder);
  99253. FLAC__ASSERT(0 != decoder->protected_);
  99254. return decoder->protected_->channels;
  99255. }
  99256. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99257. {
  99258. FLAC__ASSERT(0 != decoder);
  99259. FLAC__ASSERT(0 != decoder->protected_);
  99260. return decoder->protected_->channel_assignment;
  99261. }
  99262. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99263. {
  99264. FLAC__ASSERT(0 != decoder);
  99265. FLAC__ASSERT(0 != decoder->protected_);
  99266. return decoder->protected_->bits_per_sample;
  99267. }
  99268. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99269. {
  99270. FLAC__ASSERT(0 != decoder);
  99271. FLAC__ASSERT(0 != decoder->protected_);
  99272. return decoder->protected_->sample_rate;
  99273. }
  99274. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99275. {
  99276. FLAC__ASSERT(0 != decoder);
  99277. FLAC__ASSERT(0 != decoder->protected_);
  99278. return decoder->protected_->blocksize;
  99279. }
  99280. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99281. {
  99282. FLAC__ASSERT(0 != decoder);
  99283. FLAC__ASSERT(0 != decoder->private_);
  99284. FLAC__ASSERT(0 != position);
  99285. #if FLAC__HAS_OGG
  99286. if(decoder->private_->is_ogg)
  99287. return false;
  99288. #endif
  99289. if(0 == decoder->private_->tell_callback)
  99290. return false;
  99291. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99292. return false;
  99293. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99294. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99295. return false;
  99296. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99297. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99298. return true;
  99299. }
  99300. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99301. {
  99302. FLAC__ASSERT(0 != decoder);
  99303. FLAC__ASSERT(0 != decoder->private_);
  99304. FLAC__ASSERT(0 != decoder->protected_);
  99305. decoder->private_->samples_decoded = 0;
  99306. decoder->private_->do_md5_checking = false;
  99307. #if FLAC__HAS_OGG
  99308. if(decoder->private_->is_ogg)
  99309. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99310. #endif
  99311. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99312. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99313. return false;
  99314. }
  99315. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99316. return true;
  99317. }
  99318. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99319. {
  99320. FLAC__ASSERT(0 != decoder);
  99321. FLAC__ASSERT(0 != decoder->private_);
  99322. FLAC__ASSERT(0 != decoder->protected_);
  99323. if(!FLAC__stream_decoder_flush(decoder)) {
  99324. /* above call sets the state for us */
  99325. return false;
  99326. }
  99327. #if FLAC__HAS_OGG
  99328. /*@@@ could go in !internal_reset_hack block below */
  99329. if(decoder->private_->is_ogg)
  99330. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99331. #endif
  99332. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99333. * (internal_reset_hack) don't try to rewind since we are already at
  99334. * the beginning of the stream and don't want to fail if the input is
  99335. * not seekable.
  99336. */
  99337. if(!decoder->private_->internal_reset_hack) {
  99338. if(decoder->private_->file == stdin)
  99339. return false; /* can't rewind stdin, reset fails */
  99340. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99341. return false; /* seekable and seek fails, reset fails */
  99342. }
  99343. else
  99344. decoder->private_->internal_reset_hack = false;
  99345. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99346. decoder->private_->has_stream_info = false;
  99347. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99348. free(decoder->private_->seek_table.data.seek_table.points);
  99349. decoder->private_->seek_table.data.seek_table.points = 0;
  99350. decoder->private_->has_seek_table = false;
  99351. }
  99352. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99353. /*
  99354. * This goes in reset() and not flush() because according to the spec, a
  99355. * fixed-blocksize stream must stay that way through the whole stream.
  99356. */
  99357. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99358. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99359. * is because md5 checking may be turned on to start and then turned off if
  99360. * a seek occurs. So we init the context here and finalize it in
  99361. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99362. * properly.
  99363. */
  99364. FLAC__MD5Init(&decoder->private_->md5context);
  99365. decoder->private_->first_frame_offset = 0;
  99366. decoder->private_->unparseable_frame_count = 0;
  99367. return true;
  99368. }
  99369. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99370. {
  99371. FLAC__bool got_a_frame;
  99372. FLAC__ASSERT(0 != decoder);
  99373. FLAC__ASSERT(0 != decoder->protected_);
  99374. while(1) {
  99375. switch(decoder->protected_->state) {
  99376. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99377. if(!find_metadata_(decoder))
  99378. return false; /* above function sets the status for us */
  99379. break;
  99380. case FLAC__STREAM_DECODER_READ_METADATA:
  99381. if(!read_metadata_(decoder))
  99382. return false; /* above function sets the status for us */
  99383. else
  99384. return true;
  99385. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99386. if(!frame_sync_(decoder))
  99387. return true; /* above function sets the status for us */
  99388. break;
  99389. case FLAC__STREAM_DECODER_READ_FRAME:
  99390. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99391. return false; /* above function sets the status for us */
  99392. if(got_a_frame)
  99393. return true; /* above function sets the status for us */
  99394. break;
  99395. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99396. case FLAC__STREAM_DECODER_ABORTED:
  99397. return true;
  99398. default:
  99399. FLAC__ASSERT(0);
  99400. return false;
  99401. }
  99402. }
  99403. }
  99404. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99405. {
  99406. FLAC__ASSERT(0 != decoder);
  99407. FLAC__ASSERT(0 != decoder->protected_);
  99408. while(1) {
  99409. switch(decoder->protected_->state) {
  99410. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99411. if(!find_metadata_(decoder))
  99412. return false; /* above function sets the status for us */
  99413. break;
  99414. case FLAC__STREAM_DECODER_READ_METADATA:
  99415. if(!read_metadata_(decoder))
  99416. return false; /* above function sets the status for us */
  99417. break;
  99418. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99419. case FLAC__STREAM_DECODER_READ_FRAME:
  99420. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99421. case FLAC__STREAM_DECODER_ABORTED:
  99422. return true;
  99423. default:
  99424. FLAC__ASSERT(0);
  99425. return false;
  99426. }
  99427. }
  99428. }
  99429. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99430. {
  99431. FLAC__bool dummy;
  99432. FLAC__ASSERT(0 != decoder);
  99433. FLAC__ASSERT(0 != decoder->protected_);
  99434. while(1) {
  99435. switch(decoder->protected_->state) {
  99436. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99437. if(!find_metadata_(decoder))
  99438. return false; /* above function sets the status for us */
  99439. break;
  99440. case FLAC__STREAM_DECODER_READ_METADATA:
  99441. if(!read_metadata_(decoder))
  99442. return false; /* above function sets the status for us */
  99443. break;
  99444. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99445. if(!frame_sync_(decoder))
  99446. return true; /* above function sets the status for us */
  99447. break;
  99448. case FLAC__STREAM_DECODER_READ_FRAME:
  99449. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99450. return false; /* above function sets the status for us */
  99451. break;
  99452. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99453. case FLAC__STREAM_DECODER_ABORTED:
  99454. return true;
  99455. default:
  99456. FLAC__ASSERT(0);
  99457. return false;
  99458. }
  99459. }
  99460. }
  99461. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99462. {
  99463. FLAC__bool got_a_frame;
  99464. FLAC__ASSERT(0 != decoder);
  99465. FLAC__ASSERT(0 != decoder->protected_);
  99466. while(1) {
  99467. switch(decoder->protected_->state) {
  99468. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99469. case FLAC__STREAM_DECODER_READ_METADATA:
  99470. return false; /* above function sets the status for us */
  99471. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99472. if(!frame_sync_(decoder))
  99473. return true; /* above function sets the status for us */
  99474. break;
  99475. case FLAC__STREAM_DECODER_READ_FRAME:
  99476. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99477. return false; /* above function sets the status for us */
  99478. if(got_a_frame)
  99479. return true; /* above function sets the status for us */
  99480. break;
  99481. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99482. case FLAC__STREAM_DECODER_ABORTED:
  99483. return true;
  99484. default:
  99485. FLAC__ASSERT(0);
  99486. return false;
  99487. }
  99488. }
  99489. }
  99490. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99491. {
  99492. FLAC__uint64 length;
  99493. FLAC__ASSERT(0 != decoder);
  99494. if(
  99495. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99496. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99497. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99498. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99499. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99500. )
  99501. return false;
  99502. if(0 == decoder->private_->seek_callback)
  99503. return false;
  99504. FLAC__ASSERT(decoder->private_->seek_callback);
  99505. FLAC__ASSERT(decoder->private_->tell_callback);
  99506. FLAC__ASSERT(decoder->private_->length_callback);
  99507. FLAC__ASSERT(decoder->private_->eof_callback);
  99508. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99509. return false;
  99510. decoder->private_->is_seeking = true;
  99511. /* turn off md5 checking if a seek is attempted */
  99512. decoder->private_->do_md5_checking = false;
  99513. /* 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) */
  99514. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99515. decoder->private_->is_seeking = false;
  99516. return false;
  99517. }
  99518. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99519. if(
  99520. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99521. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99522. ) {
  99523. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99524. /* above call sets the state for us */
  99525. decoder->private_->is_seeking = false;
  99526. return false;
  99527. }
  99528. /* check this again in case we didn't know total_samples the first time */
  99529. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99530. decoder->private_->is_seeking = false;
  99531. return false;
  99532. }
  99533. }
  99534. {
  99535. const FLAC__bool ok =
  99536. #if FLAC__HAS_OGG
  99537. decoder->private_->is_ogg?
  99538. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99539. #endif
  99540. seek_to_absolute_sample_(decoder, length, sample)
  99541. ;
  99542. decoder->private_->is_seeking = false;
  99543. return ok;
  99544. }
  99545. }
  99546. /***********************************************************************
  99547. *
  99548. * Protected class methods
  99549. *
  99550. ***********************************************************************/
  99551. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99552. {
  99553. FLAC__ASSERT(0 != decoder);
  99554. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99555. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99556. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99557. }
  99558. /***********************************************************************
  99559. *
  99560. * Private class methods
  99561. *
  99562. ***********************************************************************/
  99563. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99564. {
  99565. #if FLAC__HAS_OGG
  99566. decoder->private_->is_ogg = false;
  99567. #endif
  99568. decoder->private_->read_callback = 0;
  99569. decoder->private_->seek_callback = 0;
  99570. decoder->private_->tell_callback = 0;
  99571. decoder->private_->length_callback = 0;
  99572. decoder->private_->eof_callback = 0;
  99573. decoder->private_->write_callback = 0;
  99574. decoder->private_->metadata_callback = 0;
  99575. decoder->private_->error_callback = 0;
  99576. decoder->private_->client_data = 0;
  99577. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99578. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99579. decoder->private_->metadata_filter_ids_count = 0;
  99580. decoder->protected_->md5_checking = false;
  99581. #if FLAC__HAS_OGG
  99582. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99583. #endif
  99584. }
  99585. /*
  99586. * This will forcibly set stdin to binary mode (for OSes that require it)
  99587. */
  99588. FILE *get_binary_stdin_(void)
  99589. {
  99590. /* if something breaks here it is probably due to the presence or
  99591. * absence of an underscore before the identifiers 'setmode',
  99592. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99593. */
  99594. #if defined _MSC_VER || defined __MINGW32__
  99595. _setmode(_fileno(stdin), _O_BINARY);
  99596. #elif defined __CYGWIN__
  99597. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99598. setmode(_fileno(stdin), _O_BINARY);
  99599. #elif defined __EMX__
  99600. setmode(fileno(stdin), O_BINARY);
  99601. #endif
  99602. return stdin;
  99603. }
  99604. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99605. {
  99606. unsigned i;
  99607. FLAC__int32 *tmp;
  99608. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99609. return true;
  99610. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99611. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99612. if(0 != decoder->private_->output[i]) {
  99613. free(decoder->private_->output[i]-4);
  99614. decoder->private_->output[i] = 0;
  99615. }
  99616. if(0 != decoder->private_->residual_unaligned[i]) {
  99617. free(decoder->private_->residual_unaligned[i]);
  99618. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99619. }
  99620. }
  99621. for(i = 0; i < channels; i++) {
  99622. /* WATCHOUT:
  99623. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99624. * output arrays have a buffer of up to 3 zeroes in front
  99625. * (at negative indices) for alignment purposes; we use 4
  99626. * to keep the data well-aligned.
  99627. */
  99628. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99629. if(tmp == 0) {
  99630. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99631. return false;
  99632. }
  99633. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99634. decoder->private_->output[i] = tmp + 4;
  99635. /* WATCHOUT:
  99636. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99637. */
  99638. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99639. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99640. return false;
  99641. }
  99642. }
  99643. decoder->private_->output_capacity = size;
  99644. decoder->private_->output_channels = channels;
  99645. return true;
  99646. }
  99647. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99648. {
  99649. size_t i;
  99650. FLAC__ASSERT(0 != decoder);
  99651. FLAC__ASSERT(0 != decoder->private_);
  99652. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99653. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99654. return true;
  99655. return false;
  99656. }
  99657. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99658. {
  99659. FLAC__uint32 x;
  99660. unsigned i, id_;
  99661. FLAC__bool first = true;
  99662. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99663. for(i = id_ = 0; i < 4; ) {
  99664. if(decoder->private_->cached) {
  99665. x = (FLAC__uint32)decoder->private_->lookahead;
  99666. decoder->private_->cached = false;
  99667. }
  99668. else {
  99669. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99670. return false; /* read_callback_ sets the state for us */
  99671. }
  99672. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99673. first = true;
  99674. i++;
  99675. id_ = 0;
  99676. continue;
  99677. }
  99678. if(x == ID3V2_TAG_[id_]) {
  99679. id_++;
  99680. i = 0;
  99681. if(id_ == 3) {
  99682. if(!skip_id3v2_tag_(decoder))
  99683. return false; /* skip_id3v2_tag_ sets the state for us */
  99684. }
  99685. continue;
  99686. }
  99687. id_ = 0;
  99688. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99689. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99690. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99691. return false; /* read_callback_ sets the state for us */
  99692. /* 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 */
  99693. /* else we have to check if the second byte is the end of a sync code */
  99694. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99695. decoder->private_->lookahead = (FLAC__byte)x;
  99696. decoder->private_->cached = true;
  99697. }
  99698. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99699. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99700. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99701. return true;
  99702. }
  99703. }
  99704. i = 0;
  99705. if(first) {
  99706. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99707. first = false;
  99708. }
  99709. }
  99710. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99711. return true;
  99712. }
  99713. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99714. {
  99715. FLAC__bool is_last;
  99716. FLAC__uint32 i, x, type, length;
  99717. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99718. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99719. return false; /* read_callback_ sets the state for us */
  99720. is_last = x? true : false;
  99721. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99722. return false; /* read_callback_ sets the state for us */
  99723. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99724. return false; /* read_callback_ sets the state for us */
  99725. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99726. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99727. return false;
  99728. decoder->private_->has_stream_info = true;
  99729. 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))
  99730. decoder->private_->do_md5_checking = false;
  99731. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99732. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99733. }
  99734. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99735. if(!read_metadata_seektable_(decoder, is_last, length))
  99736. return false;
  99737. decoder->private_->has_seek_table = true;
  99738. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99739. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99740. }
  99741. else {
  99742. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99743. unsigned real_length = length;
  99744. FLAC__StreamMetadata block;
  99745. block.is_last = is_last;
  99746. block.type = (FLAC__MetadataType)type;
  99747. block.length = length;
  99748. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99749. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99750. return false; /* read_callback_ sets the state for us */
  99751. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99752. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99753. return false;
  99754. }
  99755. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99756. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99757. skip_it = !skip_it;
  99758. }
  99759. if(skip_it) {
  99760. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99761. return false; /* read_callback_ sets the state for us */
  99762. }
  99763. else {
  99764. switch(type) {
  99765. case FLAC__METADATA_TYPE_PADDING:
  99766. /* skip the padding bytes */
  99767. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99768. return false; /* read_callback_ sets the state for us */
  99769. break;
  99770. case FLAC__METADATA_TYPE_APPLICATION:
  99771. /* remember, we read the ID already */
  99772. if(real_length > 0) {
  99773. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99774. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99775. return false;
  99776. }
  99777. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99778. return false; /* read_callback_ sets the state for us */
  99779. }
  99780. else
  99781. block.data.application.data = 0;
  99782. break;
  99783. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99784. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99785. return false;
  99786. break;
  99787. case FLAC__METADATA_TYPE_CUESHEET:
  99788. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99789. return false;
  99790. break;
  99791. case FLAC__METADATA_TYPE_PICTURE:
  99792. if(!read_metadata_picture_(decoder, &block.data.picture))
  99793. return false;
  99794. break;
  99795. case FLAC__METADATA_TYPE_STREAMINFO:
  99796. case FLAC__METADATA_TYPE_SEEKTABLE:
  99797. FLAC__ASSERT(0);
  99798. break;
  99799. default:
  99800. if(real_length > 0) {
  99801. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  99802. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99803. return false;
  99804. }
  99805. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  99806. return false; /* read_callback_ sets the state for us */
  99807. }
  99808. else
  99809. block.data.unknown.data = 0;
  99810. break;
  99811. }
  99812. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  99813. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  99814. /* now we have to free any malloc()ed data in the block */
  99815. switch(type) {
  99816. case FLAC__METADATA_TYPE_PADDING:
  99817. break;
  99818. case FLAC__METADATA_TYPE_APPLICATION:
  99819. if(0 != block.data.application.data)
  99820. free(block.data.application.data);
  99821. break;
  99822. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99823. if(0 != block.data.vorbis_comment.vendor_string.entry)
  99824. free(block.data.vorbis_comment.vendor_string.entry);
  99825. if(block.data.vorbis_comment.num_comments > 0)
  99826. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  99827. if(0 != block.data.vorbis_comment.comments[i].entry)
  99828. free(block.data.vorbis_comment.comments[i].entry);
  99829. if(0 != block.data.vorbis_comment.comments)
  99830. free(block.data.vorbis_comment.comments);
  99831. break;
  99832. case FLAC__METADATA_TYPE_CUESHEET:
  99833. if(block.data.cue_sheet.num_tracks > 0)
  99834. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  99835. if(0 != block.data.cue_sheet.tracks[i].indices)
  99836. free(block.data.cue_sheet.tracks[i].indices);
  99837. if(0 != block.data.cue_sheet.tracks)
  99838. free(block.data.cue_sheet.tracks);
  99839. break;
  99840. case FLAC__METADATA_TYPE_PICTURE:
  99841. if(0 != block.data.picture.mime_type)
  99842. free(block.data.picture.mime_type);
  99843. if(0 != block.data.picture.description)
  99844. free(block.data.picture.description);
  99845. if(0 != block.data.picture.data)
  99846. free(block.data.picture.data);
  99847. break;
  99848. case FLAC__METADATA_TYPE_STREAMINFO:
  99849. case FLAC__METADATA_TYPE_SEEKTABLE:
  99850. FLAC__ASSERT(0);
  99851. default:
  99852. if(0 != block.data.unknown.data)
  99853. free(block.data.unknown.data);
  99854. break;
  99855. }
  99856. }
  99857. }
  99858. if(is_last) {
  99859. /* if this fails, it's OK, it's just a hint for the seek routine */
  99860. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  99861. decoder->private_->first_frame_offset = 0;
  99862. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99863. }
  99864. return true;
  99865. }
  99866. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99867. {
  99868. FLAC__uint32 x;
  99869. unsigned bits, used_bits = 0;
  99870. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99871. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  99872. decoder->private_->stream_info.is_last = is_last;
  99873. decoder->private_->stream_info.length = length;
  99874. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  99875. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  99876. return false; /* read_callback_ sets the state for us */
  99877. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  99878. used_bits += bits;
  99879. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  99880. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99881. return false; /* read_callback_ sets the state for us */
  99882. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  99883. used_bits += bits;
  99884. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  99885. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99886. return false; /* read_callback_ sets the state for us */
  99887. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  99888. used_bits += bits;
  99889. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  99890. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99891. return false; /* read_callback_ sets the state for us */
  99892. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  99893. used_bits += bits;
  99894. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  99895. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99896. return false; /* read_callback_ sets the state for us */
  99897. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  99898. used_bits += bits;
  99899. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  99900. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99901. return false; /* read_callback_ sets the state for us */
  99902. decoder->private_->stream_info.data.stream_info.channels = x+1;
  99903. used_bits += bits;
  99904. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  99905. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99906. return false; /* read_callback_ sets the state for us */
  99907. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  99908. used_bits += bits;
  99909. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  99910. 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))
  99911. return false; /* read_callback_ sets the state for us */
  99912. used_bits += bits;
  99913. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  99914. return false; /* read_callback_ sets the state for us */
  99915. used_bits += 16*8;
  99916. /* skip the rest of the block */
  99917. FLAC__ASSERT(used_bits % 8 == 0);
  99918. length -= (used_bits / 8);
  99919. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99920. return false; /* read_callback_ sets the state for us */
  99921. return true;
  99922. }
  99923. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99924. {
  99925. FLAC__uint32 i, x;
  99926. FLAC__uint64 xx;
  99927. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99928. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  99929. decoder->private_->seek_table.is_last = is_last;
  99930. decoder->private_->seek_table.length = length;
  99931. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  99932. /* use realloc since we may pass through here several times (e.g. after seeking) */
  99933. 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)))) {
  99934. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99935. return false;
  99936. }
  99937. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  99938. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99939. return false; /* read_callback_ sets the state for us */
  99940. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  99941. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99942. return false; /* read_callback_ sets the state for us */
  99943. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  99944. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99945. return false; /* read_callback_ sets the state for us */
  99946. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  99947. }
  99948. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  99949. /* if there is a partial point left, skip over it */
  99950. if(length > 0) {
  99951. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  99952. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99953. return false; /* read_callback_ sets the state for us */
  99954. }
  99955. return true;
  99956. }
  99957. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  99958. {
  99959. FLAC__uint32 i;
  99960. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99961. /* read vendor string */
  99962. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99963. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  99964. return false; /* read_callback_ sets the state for us */
  99965. if(obj->vendor_string.length > 0) {
  99966. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  99967. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99968. return false;
  99969. }
  99970. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  99971. return false; /* read_callback_ sets the state for us */
  99972. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  99973. }
  99974. else
  99975. obj->vendor_string.entry = 0;
  99976. /* read num comments */
  99977. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  99978. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  99979. return false; /* read_callback_ sets the state for us */
  99980. /* read comments */
  99981. if(obj->num_comments > 0) {
  99982. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  99983. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99984. return false;
  99985. }
  99986. for(i = 0; i < obj->num_comments; i++) {
  99987. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99988. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  99989. return false; /* read_callback_ sets the state for us */
  99990. if(obj->comments[i].length > 0) {
  99991. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  99992. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99993. return false;
  99994. }
  99995. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  99996. return false; /* read_callback_ sets the state for us */
  99997. obj->comments[i].entry[obj->comments[i].length] = '\0';
  99998. }
  99999. else
  100000. obj->comments[i].entry = 0;
  100001. }
  100002. }
  100003. else {
  100004. obj->comments = 0;
  100005. }
  100006. return true;
  100007. }
  100008. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100009. {
  100010. FLAC__uint32 i, j, x;
  100011. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100012. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100013. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100014. 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))
  100015. return false; /* read_callback_ sets the state for us */
  100016. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100017. return false; /* read_callback_ sets the state for us */
  100018. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100019. return false; /* read_callback_ sets the state for us */
  100020. obj->is_cd = x? true : false;
  100021. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100022. return false; /* read_callback_ sets the state for us */
  100023. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100024. return false; /* read_callback_ sets the state for us */
  100025. obj->num_tracks = x;
  100026. if(obj->num_tracks > 0) {
  100027. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100028. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100029. return false;
  100030. }
  100031. for(i = 0; i < obj->num_tracks; i++) {
  100032. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100033. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100034. return false; /* read_callback_ sets the state for us */
  100035. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100036. return false; /* read_callback_ sets the state for us */
  100037. track->number = (FLAC__byte)x;
  100038. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100039. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100040. return false; /* read_callback_ sets the state for us */
  100041. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100042. return false; /* read_callback_ sets the state for us */
  100043. track->type = x;
  100044. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100045. return false; /* read_callback_ sets the state for us */
  100046. track->pre_emphasis = x;
  100047. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100048. return false; /* read_callback_ sets the state for us */
  100049. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100050. return false; /* read_callback_ sets the state for us */
  100051. track->num_indices = (FLAC__byte)x;
  100052. if(track->num_indices > 0) {
  100053. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100054. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100055. return false;
  100056. }
  100057. for(j = 0; j < track->num_indices; j++) {
  100058. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100059. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100060. return false; /* read_callback_ sets the state for us */
  100061. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100062. return false; /* read_callback_ sets the state for us */
  100063. index->number = (FLAC__byte)x;
  100064. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100065. return false; /* read_callback_ sets the state for us */
  100066. }
  100067. }
  100068. }
  100069. }
  100070. return true;
  100071. }
  100072. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100073. {
  100074. FLAC__uint32 x;
  100075. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100076. /* read type */
  100077. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100078. return false; /* read_callback_ sets the state for us */
  100079. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100080. /* read MIME type */
  100081. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100082. return false; /* read_callback_ sets the state for us */
  100083. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100084. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100085. return false;
  100086. }
  100087. if(x > 0) {
  100088. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100089. return false; /* read_callback_ sets the state for us */
  100090. }
  100091. obj->mime_type[x] = '\0';
  100092. /* read description */
  100093. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100094. return false; /* read_callback_ sets the state for us */
  100095. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100096. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100097. return false;
  100098. }
  100099. if(x > 0) {
  100100. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100101. return false; /* read_callback_ sets the state for us */
  100102. }
  100103. obj->description[x] = '\0';
  100104. /* read width */
  100105. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100106. return false; /* read_callback_ sets the state for us */
  100107. /* read height */
  100108. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100109. return false; /* read_callback_ sets the state for us */
  100110. /* read depth */
  100111. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100112. return false; /* read_callback_ sets the state for us */
  100113. /* read colors */
  100114. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100115. return false; /* read_callback_ sets the state for us */
  100116. /* read data */
  100117. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100118. return false; /* read_callback_ sets the state for us */
  100119. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100120. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100121. return false;
  100122. }
  100123. if(obj->data_length > 0) {
  100124. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100125. return false; /* read_callback_ sets the state for us */
  100126. }
  100127. return true;
  100128. }
  100129. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100130. {
  100131. FLAC__uint32 x;
  100132. unsigned i, skip;
  100133. /* skip the version and flags bytes */
  100134. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100135. return false; /* read_callback_ sets the state for us */
  100136. /* get the size (in bytes) to skip */
  100137. skip = 0;
  100138. for(i = 0; i < 4; i++) {
  100139. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100140. return false; /* read_callback_ sets the state for us */
  100141. skip <<= 7;
  100142. skip |= (x & 0x7f);
  100143. }
  100144. /* skip the rest of the tag */
  100145. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100146. return false; /* read_callback_ sets the state for us */
  100147. return true;
  100148. }
  100149. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100150. {
  100151. FLAC__uint32 x;
  100152. FLAC__bool first = true;
  100153. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100154. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100155. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100156. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100157. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100158. return true;
  100159. }
  100160. }
  100161. /* make sure we're byte aligned */
  100162. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100163. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100164. return false; /* read_callback_ sets the state for us */
  100165. }
  100166. while(1) {
  100167. if(decoder->private_->cached) {
  100168. x = (FLAC__uint32)decoder->private_->lookahead;
  100169. decoder->private_->cached = false;
  100170. }
  100171. else {
  100172. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100173. return false; /* read_callback_ sets the state for us */
  100174. }
  100175. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100176. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100177. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100178. return false; /* read_callback_ sets the state for us */
  100179. /* 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 */
  100180. /* else we have to check if the second byte is the end of a sync code */
  100181. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100182. decoder->private_->lookahead = (FLAC__byte)x;
  100183. decoder->private_->cached = true;
  100184. }
  100185. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100186. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100187. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100188. return true;
  100189. }
  100190. }
  100191. if(first) {
  100192. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100193. first = false;
  100194. }
  100195. }
  100196. return true;
  100197. }
  100198. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100199. {
  100200. unsigned channel;
  100201. unsigned i;
  100202. FLAC__int32 mid, side;
  100203. unsigned frame_crc; /* the one we calculate from the input stream */
  100204. FLAC__uint32 x;
  100205. *got_a_frame = false;
  100206. /* init the CRC */
  100207. frame_crc = 0;
  100208. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100209. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100210. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100211. if(!read_frame_header_(decoder))
  100212. return false;
  100213. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100214. return true;
  100215. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100216. return false;
  100217. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100218. /*
  100219. * first figure the correct bits-per-sample of the subframe
  100220. */
  100221. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100222. switch(decoder->private_->frame.header.channel_assignment) {
  100223. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100224. /* no adjustment needed */
  100225. break;
  100226. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100227. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100228. if(channel == 1)
  100229. bps++;
  100230. break;
  100231. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100232. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100233. if(channel == 0)
  100234. bps++;
  100235. break;
  100236. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100237. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100238. if(channel == 1)
  100239. bps++;
  100240. break;
  100241. default:
  100242. FLAC__ASSERT(0);
  100243. }
  100244. /*
  100245. * now read it
  100246. */
  100247. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100248. return false;
  100249. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100250. return true;
  100251. }
  100252. if(!read_zero_padding_(decoder))
  100253. return false;
  100254. 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) */
  100255. return true;
  100256. /*
  100257. * Read the frame CRC-16 from the footer and check
  100258. */
  100259. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100260. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100261. return false; /* read_callback_ sets the state for us */
  100262. if(frame_crc == x) {
  100263. if(do_full_decode) {
  100264. /* Undo any special channel coding */
  100265. switch(decoder->private_->frame.header.channel_assignment) {
  100266. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100267. /* do nothing */
  100268. break;
  100269. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100270. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100271. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100272. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100273. break;
  100274. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100275. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100276. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100277. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100278. break;
  100279. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100280. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100281. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100282. #if 1
  100283. mid = decoder->private_->output[0][i];
  100284. side = decoder->private_->output[1][i];
  100285. mid <<= 1;
  100286. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100287. decoder->private_->output[0][i] = (mid + side) >> 1;
  100288. decoder->private_->output[1][i] = (mid - side) >> 1;
  100289. #else
  100290. /* OPT: without 'side' temp variable */
  100291. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100292. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100293. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100294. #endif
  100295. }
  100296. break;
  100297. default:
  100298. FLAC__ASSERT(0);
  100299. break;
  100300. }
  100301. }
  100302. }
  100303. else {
  100304. /* Bad frame, emit error and zero the output signal */
  100305. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100306. if(do_full_decode) {
  100307. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100308. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100309. }
  100310. }
  100311. }
  100312. *got_a_frame = true;
  100313. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100314. if(decoder->private_->next_fixed_block_size)
  100315. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100316. /* put the latest values into the public section of the decoder instance */
  100317. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100318. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100319. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100320. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100321. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100322. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100323. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100324. /* write it */
  100325. if(do_full_decode) {
  100326. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100327. return false;
  100328. }
  100329. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100330. return true;
  100331. }
  100332. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100333. {
  100334. FLAC__uint32 x;
  100335. FLAC__uint64 xx;
  100336. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100337. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100338. unsigned raw_header_len;
  100339. FLAC__bool is_unparseable = false;
  100340. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100341. /* init the raw header with the saved bits from synchronization */
  100342. raw_header[0] = decoder->private_->header_warmup[0];
  100343. raw_header[1] = decoder->private_->header_warmup[1];
  100344. raw_header_len = 2;
  100345. /* check to make sure that reserved bit is 0 */
  100346. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100347. is_unparseable = true;
  100348. /*
  100349. * Note that along the way as we read the header, we look for a sync
  100350. * code inside. If we find one it would indicate that our original
  100351. * sync was bad since there cannot be a sync code in a valid header.
  100352. *
  100353. * Three kinds of things can go wrong when reading the frame header:
  100354. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100355. * If we don't find a sync code, it can end up looking like we read
  100356. * a valid but unparseable header, until getting to the frame header
  100357. * CRC. Even then we could get a false positive on the CRC.
  100358. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100359. * future encoder).
  100360. * 3) We may be on a damaged frame which appears valid but unparseable.
  100361. *
  100362. * For all these reasons, we try and read a complete frame header as
  100363. * long as it seems valid, even if unparseable, up until the frame
  100364. * header CRC.
  100365. */
  100366. /*
  100367. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100368. */
  100369. for(i = 0; i < 2; i++) {
  100370. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100371. return false; /* read_callback_ sets the state for us */
  100372. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100373. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100374. decoder->private_->lookahead = (FLAC__byte)x;
  100375. decoder->private_->cached = true;
  100376. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100377. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100378. return true;
  100379. }
  100380. raw_header[raw_header_len++] = (FLAC__byte)x;
  100381. }
  100382. switch(x = raw_header[2] >> 4) {
  100383. case 0:
  100384. is_unparseable = true;
  100385. break;
  100386. case 1:
  100387. decoder->private_->frame.header.blocksize = 192;
  100388. break;
  100389. case 2:
  100390. case 3:
  100391. case 4:
  100392. case 5:
  100393. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100394. break;
  100395. case 6:
  100396. case 7:
  100397. blocksize_hint = x;
  100398. break;
  100399. case 8:
  100400. case 9:
  100401. case 10:
  100402. case 11:
  100403. case 12:
  100404. case 13:
  100405. case 14:
  100406. case 15:
  100407. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100408. break;
  100409. default:
  100410. FLAC__ASSERT(0);
  100411. break;
  100412. }
  100413. switch(x = raw_header[2] & 0x0f) {
  100414. case 0:
  100415. if(decoder->private_->has_stream_info)
  100416. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100417. else
  100418. is_unparseable = true;
  100419. break;
  100420. case 1:
  100421. decoder->private_->frame.header.sample_rate = 88200;
  100422. break;
  100423. case 2:
  100424. decoder->private_->frame.header.sample_rate = 176400;
  100425. break;
  100426. case 3:
  100427. decoder->private_->frame.header.sample_rate = 192000;
  100428. break;
  100429. case 4:
  100430. decoder->private_->frame.header.sample_rate = 8000;
  100431. break;
  100432. case 5:
  100433. decoder->private_->frame.header.sample_rate = 16000;
  100434. break;
  100435. case 6:
  100436. decoder->private_->frame.header.sample_rate = 22050;
  100437. break;
  100438. case 7:
  100439. decoder->private_->frame.header.sample_rate = 24000;
  100440. break;
  100441. case 8:
  100442. decoder->private_->frame.header.sample_rate = 32000;
  100443. break;
  100444. case 9:
  100445. decoder->private_->frame.header.sample_rate = 44100;
  100446. break;
  100447. case 10:
  100448. decoder->private_->frame.header.sample_rate = 48000;
  100449. break;
  100450. case 11:
  100451. decoder->private_->frame.header.sample_rate = 96000;
  100452. break;
  100453. case 12:
  100454. case 13:
  100455. case 14:
  100456. sample_rate_hint = x;
  100457. break;
  100458. case 15:
  100459. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100460. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100461. return true;
  100462. default:
  100463. FLAC__ASSERT(0);
  100464. }
  100465. x = (unsigned)(raw_header[3] >> 4);
  100466. if(x & 8) {
  100467. decoder->private_->frame.header.channels = 2;
  100468. switch(x & 7) {
  100469. case 0:
  100470. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100471. break;
  100472. case 1:
  100473. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100474. break;
  100475. case 2:
  100476. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100477. break;
  100478. default:
  100479. is_unparseable = true;
  100480. break;
  100481. }
  100482. }
  100483. else {
  100484. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100485. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100486. }
  100487. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100488. case 0:
  100489. if(decoder->private_->has_stream_info)
  100490. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100491. else
  100492. is_unparseable = true;
  100493. break;
  100494. case 1:
  100495. decoder->private_->frame.header.bits_per_sample = 8;
  100496. break;
  100497. case 2:
  100498. decoder->private_->frame.header.bits_per_sample = 12;
  100499. break;
  100500. case 4:
  100501. decoder->private_->frame.header.bits_per_sample = 16;
  100502. break;
  100503. case 5:
  100504. decoder->private_->frame.header.bits_per_sample = 20;
  100505. break;
  100506. case 6:
  100507. decoder->private_->frame.header.bits_per_sample = 24;
  100508. break;
  100509. case 3:
  100510. case 7:
  100511. is_unparseable = true;
  100512. break;
  100513. default:
  100514. FLAC__ASSERT(0);
  100515. break;
  100516. }
  100517. /* check to make sure that reserved bit is 0 */
  100518. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100519. is_unparseable = true;
  100520. /* read the frame's starting sample number (or frame number as the case may be) */
  100521. if(
  100522. raw_header[1] & 0x01 ||
  100523. /*@@@ 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 */
  100524. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100525. ) { /* variable blocksize */
  100526. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100527. return false; /* read_callback_ sets the state for us */
  100528. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100529. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100530. decoder->private_->cached = true;
  100531. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100532. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100533. return true;
  100534. }
  100535. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100536. decoder->private_->frame.header.number.sample_number = xx;
  100537. }
  100538. else { /* fixed blocksize */
  100539. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100540. return false; /* read_callback_ sets the state for us */
  100541. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100542. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100543. decoder->private_->cached = true;
  100544. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100545. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100546. return true;
  100547. }
  100548. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100549. decoder->private_->frame.header.number.frame_number = x;
  100550. }
  100551. if(blocksize_hint) {
  100552. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100553. return false; /* read_callback_ sets the state for us */
  100554. raw_header[raw_header_len++] = (FLAC__byte)x;
  100555. if(blocksize_hint == 7) {
  100556. FLAC__uint32 _x;
  100557. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100558. return false; /* read_callback_ sets the state for us */
  100559. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100560. x = (x << 8) | _x;
  100561. }
  100562. decoder->private_->frame.header.blocksize = x+1;
  100563. }
  100564. if(sample_rate_hint) {
  100565. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100566. return false; /* read_callback_ sets the state for us */
  100567. raw_header[raw_header_len++] = (FLAC__byte)x;
  100568. if(sample_rate_hint != 12) {
  100569. FLAC__uint32 _x;
  100570. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100571. return false; /* read_callback_ sets the state for us */
  100572. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100573. x = (x << 8) | _x;
  100574. }
  100575. if(sample_rate_hint == 12)
  100576. decoder->private_->frame.header.sample_rate = x*1000;
  100577. else if(sample_rate_hint == 13)
  100578. decoder->private_->frame.header.sample_rate = x;
  100579. else
  100580. decoder->private_->frame.header.sample_rate = x*10;
  100581. }
  100582. /* read the CRC-8 byte */
  100583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100584. return false; /* read_callback_ sets the state for us */
  100585. crc8 = (FLAC__byte)x;
  100586. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100587. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100588. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100589. return true;
  100590. }
  100591. /* calculate the sample number from the frame number if needed */
  100592. decoder->private_->next_fixed_block_size = 0;
  100593. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100594. x = decoder->private_->frame.header.number.frame_number;
  100595. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100596. if(decoder->private_->fixed_block_size)
  100597. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100598. else if(decoder->private_->has_stream_info) {
  100599. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100600. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100601. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100602. }
  100603. else
  100604. is_unparseable = true;
  100605. }
  100606. else if(x == 0) {
  100607. decoder->private_->frame.header.number.sample_number = 0;
  100608. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100609. }
  100610. else {
  100611. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100612. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100613. }
  100614. }
  100615. if(is_unparseable) {
  100616. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100617. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100618. return true;
  100619. }
  100620. return true;
  100621. }
  100622. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100623. {
  100624. FLAC__uint32 x;
  100625. FLAC__bool wasted_bits;
  100626. unsigned i;
  100627. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100628. return false; /* read_callback_ sets the state for us */
  100629. wasted_bits = (x & 1);
  100630. x &= 0xfe;
  100631. if(wasted_bits) {
  100632. unsigned u;
  100633. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100634. return false; /* read_callback_ sets the state for us */
  100635. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100636. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100637. }
  100638. else
  100639. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100640. /*
  100641. * Lots of magic numbers here
  100642. */
  100643. if(x & 0x80) {
  100644. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100645. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100646. return true;
  100647. }
  100648. else if(x == 0) {
  100649. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100650. return false;
  100651. }
  100652. else if(x == 2) {
  100653. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100654. return false;
  100655. }
  100656. else if(x < 16) {
  100657. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100658. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100659. return true;
  100660. }
  100661. else if(x <= 24) {
  100662. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100663. return false;
  100664. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100665. return true;
  100666. }
  100667. else if(x < 64) {
  100668. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100669. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100670. return true;
  100671. }
  100672. else {
  100673. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100674. return false;
  100675. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100676. return true;
  100677. }
  100678. if(wasted_bits && do_full_decode) {
  100679. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100680. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100681. decoder->private_->output[channel][i] <<= x;
  100682. }
  100683. return true;
  100684. }
  100685. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100686. {
  100687. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100688. FLAC__int32 x;
  100689. unsigned i;
  100690. FLAC__int32 *output = decoder->private_->output[channel];
  100691. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100692. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100693. return false; /* read_callback_ sets the state for us */
  100694. subframe->value = x;
  100695. /* decode the subframe */
  100696. if(do_full_decode) {
  100697. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100698. output[i] = x;
  100699. }
  100700. return true;
  100701. }
  100702. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100703. {
  100704. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100705. FLAC__int32 i32;
  100706. FLAC__uint32 u32;
  100707. unsigned u;
  100708. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100709. subframe->residual = decoder->private_->residual[channel];
  100710. subframe->order = order;
  100711. /* read warm-up samples */
  100712. for(u = 0; u < order; u++) {
  100713. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100714. return false; /* read_callback_ sets the state for us */
  100715. subframe->warmup[u] = i32;
  100716. }
  100717. /* read entropy coding method info */
  100718. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100719. return false; /* read_callback_ sets the state for us */
  100720. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100721. switch(subframe->entropy_coding_method.type) {
  100722. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100723. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100724. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100725. return false; /* read_callback_ sets the state for us */
  100726. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100727. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100728. break;
  100729. default:
  100730. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100731. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100732. return true;
  100733. }
  100734. /* read residual */
  100735. switch(subframe->entropy_coding_method.type) {
  100736. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100737. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100738. 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))
  100739. return false;
  100740. break;
  100741. default:
  100742. FLAC__ASSERT(0);
  100743. }
  100744. /* decode the subframe */
  100745. if(do_full_decode) {
  100746. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100747. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100748. }
  100749. return true;
  100750. }
  100751. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100752. {
  100753. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100754. FLAC__int32 i32;
  100755. FLAC__uint32 u32;
  100756. unsigned u;
  100757. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100758. subframe->residual = decoder->private_->residual[channel];
  100759. subframe->order = order;
  100760. /* read warm-up samples */
  100761. for(u = 0; u < order; u++) {
  100762. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100763. return false; /* read_callback_ sets the state for us */
  100764. subframe->warmup[u] = i32;
  100765. }
  100766. /* read qlp coeff precision */
  100767. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100768. return false; /* read_callback_ sets the state for us */
  100769. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100770. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100771. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100772. return true;
  100773. }
  100774. subframe->qlp_coeff_precision = u32+1;
  100775. /* read qlp shift */
  100776. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100777. return false; /* read_callback_ sets the state for us */
  100778. subframe->quantization_level = i32;
  100779. /* read quantized lp coefficiencts */
  100780. for(u = 0; u < order; u++) {
  100781. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100782. return false; /* read_callback_ sets the state for us */
  100783. subframe->qlp_coeff[u] = i32;
  100784. }
  100785. /* read entropy coding method info */
  100786. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100787. return false; /* read_callback_ sets the state for us */
  100788. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100789. switch(subframe->entropy_coding_method.type) {
  100790. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100791. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100792. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100793. return false; /* read_callback_ sets the state for us */
  100794. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100795. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100796. break;
  100797. default:
  100798. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100799. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100800. return true;
  100801. }
  100802. /* read residual */
  100803. switch(subframe->entropy_coding_method.type) {
  100804. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100805. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100806. 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))
  100807. return false;
  100808. break;
  100809. default:
  100810. FLAC__ASSERT(0);
  100811. }
  100812. /* decode the subframe */
  100813. if(do_full_decode) {
  100814. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100815. /*@@@@@@ technically not pessimistic enough, should be more like
  100816. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  100817. */
  100818. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100819. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  100820. if(order <= 8)
  100821. 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);
  100822. else
  100823. 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);
  100824. }
  100825. else
  100826. 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);
  100827. else
  100828. 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);
  100829. }
  100830. return true;
  100831. }
  100832. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100833. {
  100834. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  100835. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  100836. unsigned i;
  100837. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100838. subframe->data = residual;
  100839. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100840. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100841. return false; /* read_callback_ sets the state for us */
  100842. residual[i] = x;
  100843. }
  100844. /* decode the subframe */
  100845. if(do_full_decode)
  100846. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100847. return true;
  100848. }
  100849. 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)
  100850. {
  100851. FLAC__uint32 rice_parameter;
  100852. int i;
  100853. unsigned partition, sample, u;
  100854. const unsigned partitions = 1u << partition_order;
  100855. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  100856. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100857. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100858. /* sanity checks */
  100859. if(partition_order == 0) {
  100860. if(decoder->private_->frame.header.blocksize < predictor_order) {
  100861. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100862. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100863. return true;
  100864. }
  100865. }
  100866. else {
  100867. if(partition_samples < predictor_order) {
  100868. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100869. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100870. return true;
  100871. }
  100872. }
  100873. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  100874. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100875. return false;
  100876. }
  100877. sample = 0;
  100878. for(partition = 0; partition < partitions; partition++) {
  100879. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  100880. return false; /* read_callback_ sets the state for us */
  100881. partitioned_rice_contents->parameters[partition] = rice_parameter;
  100882. if(rice_parameter < pesc) {
  100883. partitioned_rice_contents->raw_bits[partition] = 0;
  100884. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  100885. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  100886. return false; /* read_callback_ sets the state for us */
  100887. sample += u;
  100888. }
  100889. else {
  100890. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100891. return false; /* read_callback_ sets the state for us */
  100892. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  100893. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  100894. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  100895. return false; /* read_callback_ sets the state for us */
  100896. residual[sample] = i;
  100897. }
  100898. }
  100899. }
  100900. return true;
  100901. }
  100902. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  100903. {
  100904. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100905. FLAC__uint32 zero = 0;
  100906. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100907. return false; /* read_callback_ sets the state for us */
  100908. if(zero != 0) {
  100909. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100910. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100911. }
  100912. }
  100913. return true;
  100914. }
  100915. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  100916. {
  100917. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  100918. if(
  100919. #if FLAC__HAS_OGG
  100920. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100921. !decoder->private_->is_ogg &&
  100922. #endif
  100923. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100924. ) {
  100925. *bytes = 0;
  100926. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100927. return false;
  100928. }
  100929. else if(*bytes > 0) {
  100930. /* While seeking, it is possible for our seek to land in the
  100931. * middle of audio data that looks exactly like a frame header
  100932. * from a future version of an encoder. When that happens, our
  100933. * error callback will get an
  100934. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  100935. * unparseable_frame_count. But there is a remote possibility
  100936. * that it is properly synced at such a "future-codec frame",
  100937. * so to make sure, we wait to see many "unparseable" errors in
  100938. * a row before bailing out.
  100939. */
  100940. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  100941. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100942. return false;
  100943. }
  100944. else {
  100945. const FLAC__StreamDecoderReadStatus status =
  100946. #if FLAC__HAS_OGG
  100947. decoder->private_->is_ogg?
  100948. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  100949. #endif
  100950. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  100951. ;
  100952. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  100953. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100954. return false;
  100955. }
  100956. else if(*bytes == 0) {
  100957. if(
  100958. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  100959. (
  100960. #if FLAC__HAS_OGG
  100961. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100962. !decoder->private_->is_ogg &&
  100963. #endif
  100964. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100965. )
  100966. ) {
  100967. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100968. return false;
  100969. }
  100970. else
  100971. return true;
  100972. }
  100973. else
  100974. return true;
  100975. }
  100976. }
  100977. else {
  100978. /* abort to avoid a deadlock */
  100979. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100980. return false;
  100981. }
  100982. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  100983. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  100984. * and at the same time hit the end of the stream (for example, seeking
  100985. * to a point that is after the beginning of the last Ogg page). There
  100986. * is no way to report an Ogg sync loss through the callbacks (see note
  100987. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  100988. * So to keep the decoder from stopping at this point we gate the call
  100989. * to the eof_callback and let the Ogg decoder aspect set the
  100990. * end-of-stream state when it is needed.
  100991. */
  100992. }
  100993. #if FLAC__HAS_OGG
  100994. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  100995. {
  100996. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  100997. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  100998. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100999. /* we don't really have a way to handle lost sync via read
  101000. * callback so we'll let it pass and let the underlying
  101001. * FLAC decoder catch the error
  101002. */
  101003. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101004. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101005. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101006. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101007. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101008. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101009. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101010. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101011. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101012. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101013. default:
  101014. FLAC__ASSERT(0);
  101015. /* double protection */
  101016. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101017. }
  101018. }
  101019. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101020. {
  101021. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101022. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101023. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101024. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101025. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101026. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101027. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101028. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101029. default:
  101030. /* double protection: */
  101031. FLAC__ASSERT(0);
  101032. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101033. }
  101034. }
  101035. #endif
  101036. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101037. {
  101038. if(decoder->private_->is_seeking) {
  101039. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101040. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101041. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101042. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101043. #if FLAC__HAS_OGG
  101044. decoder->private_->got_a_frame = true;
  101045. #endif
  101046. decoder->private_->last_frame = *frame; /* save the frame */
  101047. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101048. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101049. /* kick out of seek mode */
  101050. decoder->private_->is_seeking = false;
  101051. /* shift out the samples before target_sample */
  101052. if(delta > 0) {
  101053. unsigned channel;
  101054. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101055. for(channel = 0; channel < frame->header.channels; channel++)
  101056. newbuffer[channel] = buffer[channel] + delta;
  101057. decoder->private_->last_frame.header.blocksize -= delta;
  101058. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101059. /* write the relevant samples */
  101060. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101061. }
  101062. else {
  101063. /* write the relevant samples */
  101064. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101065. }
  101066. }
  101067. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101068. }
  101069. /*
  101070. * If we never got STREAMINFO, turn off MD5 checking to save
  101071. * cycles since we don't have a sum to compare to anyway
  101072. */
  101073. if(!decoder->private_->has_stream_info)
  101074. decoder->private_->do_md5_checking = false;
  101075. if(decoder->private_->do_md5_checking) {
  101076. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101077. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101078. }
  101079. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101080. }
  101081. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101082. {
  101083. if(!decoder->private_->is_seeking)
  101084. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101085. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101086. decoder->private_->unparseable_frame_count++;
  101087. }
  101088. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101089. {
  101090. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101091. FLAC__int64 pos = -1;
  101092. int i;
  101093. unsigned approx_bytes_per_frame;
  101094. FLAC__bool first_seek = true;
  101095. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101096. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101097. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101098. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101099. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101100. /* take these from the current frame in case they've changed mid-stream */
  101101. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101102. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101103. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101104. /* use values from stream info if we didn't decode a frame */
  101105. if(channels == 0)
  101106. channels = decoder->private_->stream_info.data.stream_info.channels;
  101107. if(bps == 0)
  101108. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101109. /* we are just guessing here */
  101110. if(max_framesize > 0)
  101111. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101112. /*
  101113. * Check if it's a known fixed-blocksize stream. Note that though
  101114. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101115. * never get a STREAMINFO block when decoding so the value of
  101116. * min_blocksize might be zero.
  101117. */
  101118. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101119. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101120. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101121. }
  101122. else
  101123. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101124. /*
  101125. * First, we set an upper and lower bound on where in the
  101126. * stream we will search. For now we assume the worst case
  101127. * scenario, which is our best guess at the beginning of
  101128. * the first frame and end of the stream.
  101129. */
  101130. lower_bound = first_frame_offset;
  101131. lower_bound_sample = 0;
  101132. upper_bound = stream_length;
  101133. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101134. /*
  101135. * Now we refine the bounds if we have a seektable with
  101136. * suitable points. Note that according to the spec they
  101137. * must be ordered by ascending sample number.
  101138. *
  101139. * Note: to protect against invalid seek tables we will ignore points
  101140. * that have frame_samples==0 or sample_number>=total_samples
  101141. */
  101142. if(seek_table) {
  101143. FLAC__uint64 new_lower_bound = lower_bound;
  101144. FLAC__uint64 new_upper_bound = upper_bound;
  101145. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101146. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101147. /* find the closest seek point <= target_sample, if it exists */
  101148. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101149. if(
  101150. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101151. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101152. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101153. seek_table->points[i].sample_number <= target_sample
  101154. )
  101155. break;
  101156. }
  101157. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101158. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101159. new_lower_bound_sample = seek_table->points[i].sample_number;
  101160. }
  101161. /* find the closest seek point > target_sample, if it exists */
  101162. for(i = 0; i < (int)seek_table->num_points; i++) {
  101163. if(
  101164. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101165. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101166. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101167. seek_table->points[i].sample_number > target_sample
  101168. )
  101169. break;
  101170. }
  101171. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101172. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101173. new_upper_bound_sample = seek_table->points[i].sample_number;
  101174. }
  101175. /* final protection against unsorted seek tables; keep original values if bogus */
  101176. if(new_upper_bound >= new_lower_bound) {
  101177. lower_bound = new_lower_bound;
  101178. upper_bound = new_upper_bound;
  101179. lower_bound_sample = new_lower_bound_sample;
  101180. upper_bound_sample = new_upper_bound_sample;
  101181. }
  101182. }
  101183. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101184. /* there are 2 insidious ways that the following equality occurs, which
  101185. * we need to fix:
  101186. * 1) total_samples is 0 (unknown) and target_sample is 0
  101187. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101188. * exactly equal to the last seek point in the seek table; this
  101189. * means there is no seek point above it, and upper_bound_samples
  101190. * remains equal to the estimate (of target_samples) we made above
  101191. * in either case it does not hurt to move upper_bound_sample up by 1
  101192. */
  101193. if(upper_bound_sample == lower_bound_sample)
  101194. upper_bound_sample++;
  101195. decoder->private_->target_sample = target_sample;
  101196. while(1) {
  101197. /* check if the bounds are still ok */
  101198. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101199. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101200. return false;
  101201. }
  101202. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101203. #if defined _MSC_VER || defined __MINGW32__
  101204. /* with VC++ you have to spoon feed it the casting */
  101205. 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;
  101206. #else
  101207. 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;
  101208. #endif
  101209. #else
  101210. /* a little less accurate: */
  101211. if(upper_bound - lower_bound < 0xffffffff)
  101212. 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;
  101213. else /* @@@ WATCHOUT, ~2TB limit */
  101214. 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;
  101215. #endif
  101216. if(pos >= (FLAC__int64)upper_bound)
  101217. pos = (FLAC__int64)upper_bound - 1;
  101218. if(pos < (FLAC__int64)lower_bound)
  101219. pos = (FLAC__int64)lower_bound;
  101220. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101221. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101222. return false;
  101223. }
  101224. if(!FLAC__stream_decoder_flush(decoder)) {
  101225. /* above call sets the state for us */
  101226. return false;
  101227. }
  101228. /* Now we need to get a frame. First we need to reset our
  101229. * unparseable_frame_count; if we get too many unparseable
  101230. * frames in a row, the read callback will return
  101231. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101232. * FLAC__stream_decoder_process_single() to return false.
  101233. */
  101234. decoder->private_->unparseable_frame_count = 0;
  101235. if(!FLAC__stream_decoder_process_single(decoder)) {
  101236. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101237. return false;
  101238. }
  101239. /* our write callback will change the state when it gets to the target frame */
  101240. /* 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 */
  101241. #if 0
  101242. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101243. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101244. break;
  101245. #endif
  101246. if(!decoder->private_->is_seeking)
  101247. break;
  101248. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101249. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101250. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101251. if (pos == (FLAC__int64)lower_bound) {
  101252. /* can't move back any more than the first frame, something is fatally wrong */
  101253. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101254. return false;
  101255. }
  101256. /* our last move backwards wasn't big enough, try again */
  101257. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101258. continue;
  101259. }
  101260. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101261. first_seek = false;
  101262. /* make sure we are not seeking in corrupted stream */
  101263. if (this_frame_sample < lower_bound_sample) {
  101264. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101265. return false;
  101266. }
  101267. /* we need to narrow the search */
  101268. if(target_sample < this_frame_sample) {
  101269. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101270. /*@@@@@@ what will decode position be if at end of stream? */
  101271. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101272. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101273. return false;
  101274. }
  101275. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101276. }
  101277. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101278. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101279. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101280. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101281. return false;
  101282. }
  101283. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101284. }
  101285. }
  101286. return true;
  101287. }
  101288. #if FLAC__HAS_OGG
  101289. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101290. {
  101291. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101292. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101293. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101294. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101295. FLAC__bool did_a_seek;
  101296. unsigned iteration = 0;
  101297. /* In the first iterations, we will calculate the target byte position
  101298. * by the distance from the target sample to left_sample and
  101299. * right_sample (let's call it "proportional search"). After that, we
  101300. * will switch to binary search.
  101301. */
  101302. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101303. /* We will switch to a linear search once our current sample is less
  101304. * than this number of samples ahead of the target sample
  101305. */
  101306. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101307. /* If the total number of samples is unknown, use a large value, and
  101308. * force binary search immediately.
  101309. */
  101310. if(right_sample == 0) {
  101311. right_sample = (FLAC__uint64)(-1);
  101312. BINARY_SEARCH_AFTER_ITERATION = 0;
  101313. }
  101314. decoder->private_->target_sample = target_sample;
  101315. for( ; ; iteration++) {
  101316. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101317. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101318. pos = (right_pos + left_pos) / 2;
  101319. }
  101320. else {
  101321. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101322. #if defined _MSC_VER || defined __MINGW32__
  101323. /* with MSVC you have to spoon feed it the casting */
  101324. 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));
  101325. #else
  101326. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101327. #endif
  101328. #else
  101329. /* a little less accurate: */
  101330. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101331. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101332. else /* @@@ WATCHOUT, ~2TB limit */
  101333. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101334. #endif
  101335. /* @@@ TODO: might want to limit pos to some distance
  101336. * before EOF, to make sure we land before the last frame,
  101337. * thereby getting a this_frame_sample and so having a better
  101338. * estimate.
  101339. */
  101340. }
  101341. /* physical seek */
  101342. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101343. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101344. return false;
  101345. }
  101346. if(!FLAC__stream_decoder_flush(decoder)) {
  101347. /* above call sets the state for us */
  101348. return false;
  101349. }
  101350. did_a_seek = true;
  101351. }
  101352. else
  101353. did_a_seek = false;
  101354. decoder->private_->got_a_frame = false;
  101355. if(!FLAC__stream_decoder_process_single(decoder)) {
  101356. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101357. return false;
  101358. }
  101359. if(!decoder->private_->got_a_frame) {
  101360. if(did_a_seek) {
  101361. /* this can happen if we seek to a point after the last frame; we drop
  101362. * to binary search right away in this case to avoid any wasted
  101363. * iterations of proportional search.
  101364. */
  101365. right_pos = pos;
  101366. BINARY_SEARCH_AFTER_ITERATION = 0;
  101367. }
  101368. else {
  101369. /* this can probably only happen if total_samples is unknown and the
  101370. * target_sample is past the end of the stream
  101371. */
  101372. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101373. return false;
  101374. }
  101375. }
  101376. /* our write callback will change the state when it gets to the target frame */
  101377. else if(!decoder->private_->is_seeking) {
  101378. break;
  101379. }
  101380. else {
  101381. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101382. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101383. if (did_a_seek) {
  101384. if (this_frame_sample <= target_sample) {
  101385. /* The 'equal' case should not happen, since
  101386. * FLAC__stream_decoder_process_single()
  101387. * should recognize that it has hit the
  101388. * target sample and we would exit through
  101389. * the 'break' above.
  101390. */
  101391. FLAC__ASSERT(this_frame_sample != target_sample);
  101392. left_sample = this_frame_sample;
  101393. /* sanity check to avoid infinite loop */
  101394. if (left_pos == pos) {
  101395. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101396. return false;
  101397. }
  101398. left_pos = pos;
  101399. }
  101400. else if(this_frame_sample > target_sample) {
  101401. right_sample = this_frame_sample;
  101402. /* sanity check to avoid infinite loop */
  101403. if (right_pos == pos) {
  101404. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101405. return false;
  101406. }
  101407. right_pos = pos;
  101408. }
  101409. }
  101410. }
  101411. }
  101412. return true;
  101413. }
  101414. #endif
  101415. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101416. {
  101417. (void)client_data;
  101418. if(*bytes > 0) {
  101419. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101420. if(ferror(decoder->private_->file))
  101421. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101422. else if(*bytes == 0)
  101423. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101424. else
  101425. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101426. }
  101427. else
  101428. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101429. }
  101430. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101431. {
  101432. (void)client_data;
  101433. if(decoder->private_->file == stdin)
  101434. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101435. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101436. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101437. else
  101438. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101439. }
  101440. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101441. {
  101442. off_t pos;
  101443. (void)client_data;
  101444. if(decoder->private_->file == stdin)
  101445. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101446. else if((pos = ftello(decoder->private_->file)) < 0)
  101447. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101448. else {
  101449. *absolute_byte_offset = (FLAC__uint64)pos;
  101450. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101451. }
  101452. }
  101453. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101454. {
  101455. struct stat filestats;
  101456. (void)client_data;
  101457. if(decoder->private_->file == stdin)
  101458. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101459. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101460. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101461. else {
  101462. *stream_length = (FLAC__uint64)filestats.st_size;
  101463. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101464. }
  101465. }
  101466. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101467. {
  101468. (void)client_data;
  101469. return feof(decoder->private_->file)? true : false;
  101470. }
  101471. #endif
  101472. /*** End of inlined file: stream_decoder.c ***/
  101473. /*** Start of inlined file: stream_encoder.c ***/
  101474. /*** Start of inlined file: juce_FlacHeader.h ***/
  101475. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101476. // tasks..
  101477. #define VERSION "1.2.1"
  101478. #define FLAC__NO_DLL 1
  101479. #if JUCE_MSVC
  101480. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101481. #endif
  101482. #if JUCE_MAC
  101483. #define FLAC__SYS_DARWIN 1
  101484. #endif
  101485. /*** End of inlined file: juce_FlacHeader.h ***/
  101486. #if JUCE_USE_FLAC
  101487. #if HAVE_CONFIG_H
  101488. # include <config.h>
  101489. #endif
  101490. #if defined _MSC_VER || defined __MINGW32__
  101491. #include <io.h> /* for _setmode() */
  101492. #include <fcntl.h> /* for _O_BINARY */
  101493. #endif
  101494. #if defined __CYGWIN__ || defined __EMX__
  101495. #include <io.h> /* for setmode(), O_BINARY */
  101496. #include <fcntl.h> /* for _O_BINARY */
  101497. #endif
  101498. #include <limits.h>
  101499. #include <stdio.h>
  101500. #include <stdlib.h> /* for malloc() */
  101501. #include <string.h> /* for memcpy() */
  101502. #include <sys/types.h> /* for off_t */
  101503. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101504. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101505. #define fseeko fseek
  101506. #define ftello ftell
  101507. #endif
  101508. #endif
  101509. /*** Start of inlined file: stream_encoder.h ***/
  101510. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101511. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101512. #if FLAC__HAS_OGG
  101513. #include "private/ogg_encoder_aspect.h"
  101514. #endif
  101515. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101516. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101517. typedef enum {
  101518. FLAC__APODIZATION_BARTLETT,
  101519. FLAC__APODIZATION_BARTLETT_HANN,
  101520. FLAC__APODIZATION_BLACKMAN,
  101521. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101522. FLAC__APODIZATION_CONNES,
  101523. FLAC__APODIZATION_FLATTOP,
  101524. FLAC__APODIZATION_GAUSS,
  101525. FLAC__APODIZATION_HAMMING,
  101526. FLAC__APODIZATION_HANN,
  101527. FLAC__APODIZATION_KAISER_BESSEL,
  101528. FLAC__APODIZATION_NUTTALL,
  101529. FLAC__APODIZATION_RECTANGLE,
  101530. FLAC__APODIZATION_TRIANGLE,
  101531. FLAC__APODIZATION_TUKEY,
  101532. FLAC__APODIZATION_WELCH
  101533. } FLAC__ApodizationFunction;
  101534. typedef struct {
  101535. FLAC__ApodizationFunction type;
  101536. union {
  101537. struct {
  101538. FLAC__real stddev;
  101539. } gauss;
  101540. struct {
  101541. FLAC__real p;
  101542. } tukey;
  101543. } parameters;
  101544. } FLAC__ApodizationSpecification;
  101545. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101546. typedef struct FLAC__StreamEncoderProtected {
  101547. FLAC__StreamEncoderState state;
  101548. FLAC__bool verify;
  101549. FLAC__bool streamable_subset;
  101550. FLAC__bool do_md5;
  101551. FLAC__bool do_mid_side_stereo;
  101552. FLAC__bool loose_mid_side_stereo;
  101553. unsigned channels;
  101554. unsigned bits_per_sample;
  101555. unsigned sample_rate;
  101556. unsigned blocksize;
  101557. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101558. unsigned num_apodizations;
  101559. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101560. #endif
  101561. unsigned max_lpc_order;
  101562. unsigned qlp_coeff_precision;
  101563. FLAC__bool do_qlp_coeff_prec_search;
  101564. FLAC__bool do_exhaustive_model_search;
  101565. FLAC__bool do_escape_coding;
  101566. unsigned min_residual_partition_order;
  101567. unsigned max_residual_partition_order;
  101568. unsigned rice_parameter_search_dist;
  101569. FLAC__uint64 total_samples_estimate;
  101570. FLAC__StreamMetadata **metadata;
  101571. unsigned num_metadata_blocks;
  101572. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101573. #if FLAC__HAS_OGG
  101574. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101575. #endif
  101576. } FLAC__StreamEncoderProtected;
  101577. #endif
  101578. /*** End of inlined file: stream_encoder.h ***/
  101579. #if FLAC__HAS_OGG
  101580. #include "include/private/ogg_helper.h"
  101581. #include "include/private/ogg_mapping.h"
  101582. #endif
  101583. /*** Start of inlined file: stream_encoder_framing.h ***/
  101584. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101585. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101586. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101587. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101588. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101589. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101590. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101591. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101592. #endif
  101593. /*** End of inlined file: stream_encoder_framing.h ***/
  101594. /*** Start of inlined file: window.h ***/
  101595. #ifndef FLAC__PRIVATE__WINDOW_H
  101596. #define FLAC__PRIVATE__WINDOW_H
  101597. #ifdef HAVE_CONFIG_H
  101598. #include <config.h>
  101599. #endif
  101600. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101601. /*
  101602. * FLAC__window_*()
  101603. * --------------------------------------------------------------------
  101604. * Calculates window coefficients according to different apodization
  101605. * functions.
  101606. *
  101607. * OUT window[0,L-1]
  101608. * IN L (number of points in window)
  101609. */
  101610. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101611. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101612. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101613. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101614. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101615. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101616. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101617. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101618. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101619. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101620. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101621. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101622. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101623. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101624. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101625. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101626. #endif
  101627. /*** End of inlined file: window.h ***/
  101628. #ifndef FLaC__INLINE
  101629. #define FLaC__INLINE
  101630. #endif
  101631. #ifdef min
  101632. #undef min
  101633. #endif
  101634. #define min(x,y) ((x)<(y)?(x):(y))
  101635. #ifdef max
  101636. #undef max
  101637. #endif
  101638. #define max(x,y) ((x)>(y)?(x):(y))
  101639. /* Exact Rice codeword length calculation is off by default. The simple
  101640. * (and fast) estimation (of how many bits a residual value will be
  101641. * encoded with) in this encoder is very good, almost always yielding
  101642. * compression within 0.1% of exact calculation.
  101643. */
  101644. #undef EXACT_RICE_BITS_CALCULATION
  101645. /* Rice parameter searching is off by default. The simple (and fast)
  101646. * parameter estimation in this encoder is very good, almost always
  101647. * yielding compression within 0.1% of the optimal parameters.
  101648. */
  101649. #undef ENABLE_RICE_PARAMETER_SEARCH
  101650. typedef struct {
  101651. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101652. unsigned size; /* of each data[] in samples */
  101653. unsigned tail;
  101654. } verify_input_fifo;
  101655. typedef struct {
  101656. const FLAC__byte *data;
  101657. unsigned capacity;
  101658. unsigned bytes;
  101659. } verify_output;
  101660. typedef enum {
  101661. ENCODER_IN_MAGIC = 0,
  101662. ENCODER_IN_METADATA = 1,
  101663. ENCODER_IN_AUDIO = 2
  101664. } EncoderStateHint;
  101665. static struct CompressionLevels {
  101666. FLAC__bool do_mid_side_stereo;
  101667. FLAC__bool loose_mid_side_stereo;
  101668. unsigned max_lpc_order;
  101669. unsigned qlp_coeff_precision;
  101670. FLAC__bool do_qlp_coeff_prec_search;
  101671. FLAC__bool do_escape_coding;
  101672. FLAC__bool do_exhaustive_model_search;
  101673. unsigned min_residual_partition_order;
  101674. unsigned max_residual_partition_order;
  101675. unsigned rice_parameter_search_dist;
  101676. } compression_levels_[] = {
  101677. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101678. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101679. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101680. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101681. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101682. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101683. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101684. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101685. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101686. };
  101687. /***********************************************************************
  101688. *
  101689. * Private class method prototypes
  101690. *
  101691. ***********************************************************************/
  101692. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101693. static void free_(FLAC__StreamEncoder *encoder);
  101694. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101695. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101696. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101697. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101698. #if FLAC__HAS_OGG
  101699. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101700. #endif
  101701. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101702. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101703. static FLAC__bool process_subframe_(
  101704. FLAC__StreamEncoder *encoder,
  101705. unsigned min_partition_order,
  101706. unsigned max_partition_order,
  101707. const FLAC__FrameHeader *frame_header,
  101708. unsigned subframe_bps,
  101709. const FLAC__int32 integer_signal[],
  101710. FLAC__Subframe *subframe[2],
  101711. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101712. FLAC__int32 *residual[2],
  101713. unsigned *best_subframe,
  101714. unsigned *best_bits
  101715. );
  101716. static FLAC__bool add_subframe_(
  101717. FLAC__StreamEncoder *encoder,
  101718. unsigned blocksize,
  101719. unsigned subframe_bps,
  101720. const FLAC__Subframe *subframe,
  101721. FLAC__BitWriter *frame
  101722. );
  101723. static unsigned evaluate_constant_subframe_(
  101724. FLAC__StreamEncoder *encoder,
  101725. const FLAC__int32 signal,
  101726. unsigned blocksize,
  101727. unsigned subframe_bps,
  101728. FLAC__Subframe *subframe
  101729. );
  101730. static unsigned evaluate_fixed_subframe_(
  101731. FLAC__StreamEncoder *encoder,
  101732. const FLAC__int32 signal[],
  101733. FLAC__int32 residual[],
  101734. FLAC__uint64 abs_residual_partition_sums[],
  101735. unsigned raw_bits_per_partition[],
  101736. unsigned blocksize,
  101737. unsigned subframe_bps,
  101738. unsigned order,
  101739. unsigned rice_parameter,
  101740. unsigned rice_parameter_limit,
  101741. unsigned min_partition_order,
  101742. unsigned max_partition_order,
  101743. FLAC__bool do_escape_coding,
  101744. unsigned rice_parameter_search_dist,
  101745. FLAC__Subframe *subframe,
  101746. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101747. );
  101748. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101749. static unsigned evaluate_lpc_subframe_(
  101750. FLAC__StreamEncoder *encoder,
  101751. const FLAC__int32 signal[],
  101752. FLAC__int32 residual[],
  101753. FLAC__uint64 abs_residual_partition_sums[],
  101754. unsigned raw_bits_per_partition[],
  101755. const FLAC__real lp_coeff[],
  101756. unsigned blocksize,
  101757. unsigned subframe_bps,
  101758. unsigned order,
  101759. unsigned qlp_coeff_precision,
  101760. unsigned rice_parameter,
  101761. unsigned rice_parameter_limit,
  101762. unsigned min_partition_order,
  101763. unsigned max_partition_order,
  101764. FLAC__bool do_escape_coding,
  101765. unsigned rice_parameter_search_dist,
  101766. FLAC__Subframe *subframe,
  101767. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101768. );
  101769. #endif
  101770. static unsigned evaluate_verbatim_subframe_(
  101771. FLAC__StreamEncoder *encoder,
  101772. const FLAC__int32 signal[],
  101773. unsigned blocksize,
  101774. unsigned subframe_bps,
  101775. FLAC__Subframe *subframe
  101776. );
  101777. static unsigned find_best_partition_order_(
  101778. struct FLAC__StreamEncoderPrivate *private_,
  101779. const FLAC__int32 residual[],
  101780. FLAC__uint64 abs_residual_partition_sums[],
  101781. unsigned raw_bits_per_partition[],
  101782. unsigned residual_samples,
  101783. unsigned predictor_order,
  101784. unsigned rice_parameter,
  101785. unsigned rice_parameter_limit,
  101786. unsigned min_partition_order,
  101787. unsigned max_partition_order,
  101788. unsigned bps,
  101789. FLAC__bool do_escape_coding,
  101790. unsigned rice_parameter_search_dist,
  101791. FLAC__EntropyCodingMethod *best_ecm
  101792. );
  101793. static void precompute_partition_info_sums_(
  101794. const FLAC__int32 residual[],
  101795. FLAC__uint64 abs_residual_partition_sums[],
  101796. unsigned residual_samples,
  101797. unsigned predictor_order,
  101798. unsigned min_partition_order,
  101799. unsigned max_partition_order,
  101800. unsigned bps
  101801. );
  101802. static void precompute_partition_info_escapes_(
  101803. const FLAC__int32 residual[],
  101804. unsigned raw_bits_per_partition[],
  101805. unsigned residual_samples,
  101806. unsigned predictor_order,
  101807. unsigned min_partition_order,
  101808. unsigned max_partition_order
  101809. );
  101810. static FLAC__bool set_partitioned_rice_(
  101811. #ifdef EXACT_RICE_BITS_CALCULATION
  101812. const FLAC__int32 residual[],
  101813. #endif
  101814. const FLAC__uint64 abs_residual_partition_sums[],
  101815. const unsigned raw_bits_per_partition[],
  101816. const unsigned residual_samples,
  101817. const unsigned predictor_order,
  101818. const unsigned suggested_rice_parameter,
  101819. const unsigned rice_parameter_limit,
  101820. const unsigned rice_parameter_search_dist,
  101821. const unsigned partition_order,
  101822. const FLAC__bool search_for_escapes,
  101823. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101824. unsigned *bits
  101825. );
  101826. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  101827. /* verify-related routines: */
  101828. static void append_to_verify_fifo_(
  101829. verify_input_fifo *fifo,
  101830. const FLAC__int32 * const input[],
  101831. unsigned input_offset,
  101832. unsigned channels,
  101833. unsigned wide_samples
  101834. );
  101835. static void append_to_verify_fifo_interleaved_(
  101836. verify_input_fifo *fifo,
  101837. const FLAC__int32 input[],
  101838. unsigned input_offset,
  101839. unsigned channels,
  101840. unsigned wide_samples
  101841. );
  101842. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101843. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  101844. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  101845. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  101846. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101847. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  101848. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  101849. 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);
  101850. static FILE *get_binary_stdout_(void);
  101851. /***********************************************************************
  101852. *
  101853. * Private class data
  101854. *
  101855. ***********************************************************************/
  101856. typedef struct FLAC__StreamEncoderPrivate {
  101857. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  101858. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  101859. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  101860. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101861. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  101862. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  101863. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  101864. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  101865. #endif
  101866. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  101867. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  101868. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  101869. FLAC__int32 *residual_workspace_mid_side[2][2];
  101870. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  101871. FLAC__Subframe subframe_workspace_mid_side[2][2];
  101872. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101873. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  101874. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  101875. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  101876. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101877. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  101878. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  101879. unsigned best_subframe_mid_side[2];
  101880. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  101881. unsigned best_subframe_bits_mid_side[2];
  101882. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  101883. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  101884. FLAC__BitWriter *frame; /* the current frame being worked on */
  101885. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  101886. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  101887. FLAC__ChannelAssignment last_channel_assignment;
  101888. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  101889. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  101890. unsigned current_sample_number;
  101891. unsigned current_frame_number;
  101892. FLAC__MD5Context md5context;
  101893. FLAC__CPUInfo cpuinfo;
  101894. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101895. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101896. #else
  101897. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101898. #endif
  101899. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101900. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  101901. 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[]);
  101902. 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[]);
  101903. 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[]);
  101904. #endif
  101905. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  101906. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  101907. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  101908. FLAC__bool disable_constant_subframes;
  101909. FLAC__bool disable_fixed_subframes;
  101910. FLAC__bool disable_verbatim_subframes;
  101911. #if FLAC__HAS_OGG
  101912. FLAC__bool is_ogg;
  101913. #endif
  101914. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  101915. FLAC__StreamEncoderSeekCallback seek_callback;
  101916. FLAC__StreamEncoderTellCallback tell_callback;
  101917. FLAC__StreamEncoderWriteCallback write_callback;
  101918. FLAC__StreamEncoderMetadataCallback metadata_callback;
  101919. FLAC__StreamEncoderProgressCallback progress_callback;
  101920. void *client_data;
  101921. unsigned first_seekpoint_to_check;
  101922. FILE *file; /* only used when encoding to a file */
  101923. FLAC__uint64 bytes_written;
  101924. FLAC__uint64 samples_written;
  101925. unsigned frames_written;
  101926. unsigned total_frames_estimate;
  101927. /* unaligned (original) pointers to allocated data */
  101928. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  101929. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  101930. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101931. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  101932. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  101933. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  101934. FLAC__real *windowed_signal_unaligned;
  101935. #endif
  101936. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  101937. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  101938. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  101939. unsigned *raw_bits_per_partition_unaligned;
  101940. /*
  101941. * These fields have been moved here from private function local
  101942. * declarations merely to save stack space during encoding.
  101943. */
  101944. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101945. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  101946. #endif
  101947. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  101948. /*
  101949. * The data for the verify section
  101950. */
  101951. struct {
  101952. FLAC__StreamDecoder *decoder;
  101953. EncoderStateHint state_hint;
  101954. FLAC__bool needs_magic_hack;
  101955. verify_input_fifo input_fifo;
  101956. verify_output output;
  101957. struct {
  101958. FLAC__uint64 absolute_sample;
  101959. unsigned frame_number;
  101960. unsigned channel;
  101961. unsigned sample;
  101962. FLAC__int32 expected;
  101963. FLAC__int32 got;
  101964. } error_stats;
  101965. } verify;
  101966. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  101967. } FLAC__StreamEncoderPrivate;
  101968. /***********************************************************************
  101969. *
  101970. * Public static class data
  101971. *
  101972. ***********************************************************************/
  101973. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  101974. "FLAC__STREAM_ENCODER_OK",
  101975. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  101976. "FLAC__STREAM_ENCODER_OGG_ERROR",
  101977. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  101978. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  101979. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  101980. "FLAC__STREAM_ENCODER_IO_ERROR",
  101981. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  101982. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  101983. };
  101984. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  101985. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  101986. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  101987. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  101988. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  101989. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  101990. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  101991. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  101992. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  101993. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  101994. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  101995. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  101996. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  101997. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  101998. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  101999. };
  102000. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102001. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102002. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102003. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102004. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102005. };
  102006. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102007. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102008. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102009. };
  102010. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102011. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102012. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102013. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102014. };
  102015. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102016. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102017. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102018. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102019. };
  102020. /* Number of samples that will be overread to watch for end of stream. By
  102021. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102022. * always try to read blocksize+1 samples before encoding a block, so that
  102023. * even if the stream has a total sample count that is an integral multiple
  102024. * of the blocksize, we will still notice when we are encoding the last
  102025. * block. This is needed, for example, to correctly set the end-of-stream
  102026. * marker in Ogg FLAC.
  102027. *
  102028. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102029. * not really any reason to change it.
  102030. */
  102031. static const unsigned OVERREAD_ = 1;
  102032. /***********************************************************************
  102033. *
  102034. * Class constructor/destructor
  102035. *
  102036. */
  102037. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102038. {
  102039. FLAC__StreamEncoder *encoder;
  102040. unsigned i;
  102041. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102042. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102043. if(encoder == 0) {
  102044. return 0;
  102045. }
  102046. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102047. if(encoder->protected_ == 0) {
  102048. free(encoder);
  102049. return 0;
  102050. }
  102051. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102052. if(encoder->private_ == 0) {
  102053. free(encoder->protected_);
  102054. free(encoder);
  102055. return 0;
  102056. }
  102057. encoder->private_->frame = FLAC__bitwriter_new();
  102058. if(encoder->private_->frame == 0) {
  102059. free(encoder->private_);
  102060. free(encoder->protected_);
  102061. free(encoder);
  102062. return 0;
  102063. }
  102064. encoder->private_->file = 0;
  102065. set_defaults_enc(encoder);
  102066. encoder->private_->is_being_deleted = false;
  102067. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102068. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102069. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102070. }
  102071. for(i = 0; i < 2; i++) {
  102072. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102073. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102074. }
  102075. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102076. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102077. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102078. }
  102079. for(i = 0; i < 2; i++) {
  102080. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102081. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102082. }
  102083. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102084. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102085. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102086. }
  102087. for(i = 0; i < 2; i++) {
  102088. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102089. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102090. }
  102091. for(i = 0; i < 2; i++)
  102092. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102093. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102094. return encoder;
  102095. }
  102096. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102097. {
  102098. unsigned i;
  102099. FLAC__ASSERT(0 != encoder);
  102100. FLAC__ASSERT(0 != encoder->protected_);
  102101. FLAC__ASSERT(0 != encoder->private_);
  102102. FLAC__ASSERT(0 != encoder->private_->frame);
  102103. encoder->private_->is_being_deleted = true;
  102104. (void)FLAC__stream_encoder_finish(encoder);
  102105. if(0 != encoder->private_->verify.decoder)
  102106. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102107. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102108. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102109. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102110. }
  102111. for(i = 0; i < 2; i++) {
  102112. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102113. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102114. }
  102115. for(i = 0; i < 2; i++)
  102116. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102117. FLAC__bitwriter_delete(encoder->private_->frame);
  102118. free(encoder->private_);
  102119. free(encoder->protected_);
  102120. free(encoder);
  102121. }
  102122. /***********************************************************************
  102123. *
  102124. * Public class methods
  102125. *
  102126. ***********************************************************************/
  102127. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102128. FLAC__StreamEncoder *encoder,
  102129. FLAC__StreamEncoderReadCallback read_callback,
  102130. FLAC__StreamEncoderWriteCallback write_callback,
  102131. FLAC__StreamEncoderSeekCallback seek_callback,
  102132. FLAC__StreamEncoderTellCallback tell_callback,
  102133. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102134. void *client_data,
  102135. FLAC__bool is_ogg
  102136. )
  102137. {
  102138. unsigned i;
  102139. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102140. FLAC__ASSERT(0 != encoder);
  102141. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102142. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102143. #if !FLAC__HAS_OGG
  102144. if(is_ogg)
  102145. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102146. #endif
  102147. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102148. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102149. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102150. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102151. if(encoder->protected_->channels != 2) {
  102152. encoder->protected_->do_mid_side_stereo = false;
  102153. encoder->protected_->loose_mid_side_stereo = false;
  102154. }
  102155. else if(!encoder->protected_->do_mid_side_stereo)
  102156. encoder->protected_->loose_mid_side_stereo = false;
  102157. if(encoder->protected_->bits_per_sample >= 32)
  102158. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102159. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102160. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102161. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102162. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102163. if(encoder->protected_->blocksize == 0) {
  102164. if(encoder->protected_->max_lpc_order == 0)
  102165. encoder->protected_->blocksize = 1152;
  102166. else
  102167. encoder->protected_->blocksize = 4096;
  102168. }
  102169. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102170. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102171. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102172. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102173. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102174. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102175. if(encoder->protected_->qlp_coeff_precision == 0) {
  102176. if(encoder->protected_->bits_per_sample < 16) {
  102177. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102178. /* @@@ until then we'll make a guess */
  102179. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102180. }
  102181. else if(encoder->protected_->bits_per_sample == 16) {
  102182. if(encoder->protected_->blocksize <= 192)
  102183. encoder->protected_->qlp_coeff_precision = 7;
  102184. else if(encoder->protected_->blocksize <= 384)
  102185. encoder->protected_->qlp_coeff_precision = 8;
  102186. else if(encoder->protected_->blocksize <= 576)
  102187. encoder->protected_->qlp_coeff_precision = 9;
  102188. else if(encoder->protected_->blocksize <= 1152)
  102189. encoder->protected_->qlp_coeff_precision = 10;
  102190. else if(encoder->protected_->blocksize <= 2304)
  102191. encoder->protected_->qlp_coeff_precision = 11;
  102192. else if(encoder->protected_->blocksize <= 4608)
  102193. encoder->protected_->qlp_coeff_precision = 12;
  102194. else
  102195. encoder->protected_->qlp_coeff_precision = 13;
  102196. }
  102197. else {
  102198. if(encoder->protected_->blocksize <= 384)
  102199. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102200. else if(encoder->protected_->blocksize <= 1152)
  102201. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102202. else
  102203. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102204. }
  102205. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102206. }
  102207. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102208. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102209. if(encoder->protected_->streamable_subset) {
  102210. if(
  102211. encoder->protected_->blocksize != 192 &&
  102212. encoder->protected_->blocksize != 576 &&
  102213. encoder->protected_->blocksize != 1152 &&
  102214. encoder->protected_->blocksize != 2304 &&
  102215. encoder->protected_->blocksize != 4608 &&
  102216. encoder->protected_->blocksize != 256 &&
  102217. encoder->protected_->blocksize != 512 &&
  102218. encoder->protected_->blocksize != 1024 &&
  102219. encoder->protected_->blocksize != 2048 &&
  102220. encoder->protected_->blocksize != 4096 &&
  102221. encoder->protected_->blocksize != 8192 &&
  102222. encoder->protected_->blocksize != 16384
  102223. )
  102224. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102225. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102226. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102227. if(
  102228. encoder->protected_->bits_per_sample != 8 &&
  102229. encoder->protected_->bits_per_sample != 12 &&
  102230. encoder->protected_->bits_per_sample != 16 &&
  102231. encoder->protected_->bits_per_sample != 20 &&
  102232. encoder->protected_->bits_per_sample != 24
  102233. )
  102234. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102235. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102236. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102237. if(
  102238. encoder->protected_->sample_rate <= 48000 &&
  102239. (
  102240. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102241. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102242. )
  102243. ) {
  102244. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102245. }
  102246. }
  102247. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102248. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102249. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102250. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102251. #if FLAC__HAS_OGG
  102252. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102253. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102254. unsigned i;
  102255. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102256. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102257. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102258. for( ; i > 0; i--)
  102259. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102260. encoder->protected_->metadata[0] = vc;
  102261. break;
  102262. }
  102263. }
  102264. }
  102265. #endif
  102266. /* keep track of any SEEKTABLE block */
  102267. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102268. unsigned i;
  102269. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102270. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102271. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102272. break; /* take only the first one */
  102273. }
  102274. }
  102275. }
  102276. /* validate metadata */
  102277. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102278. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102279. metadata_has_seektable = false;
  102280. metadata_has_vorbis_comment = false;
  102281. metadata_picture_has_type1 = false;
  102282. metadata_picture_has_type2 = false;
  102283. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102284. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102285. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102286. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102287. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102288. if(metadata_has_seektable) /* only one is allowed */
  102289. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102290. metadata_has_seektable = true;
  102291. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102292. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102293. }
  102294. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102295. if(metadata_has_vorbis_comment) /* only one is allowed */
  102296. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102297. metadata_has_vorbis_comment = true;
  102298. }
  102299. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102300. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102301. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102302. }
  102303. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102304. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102305. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102306. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102307. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102308. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102309. metadata_picture_has_type1 = true;
  102310. /* standard icon must be 32x32 pixel PNG */
  102311. if(
  102312. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102313. (
  102314. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102315. m->data.picture.width != 32 ||
  102316. m->data.picture.height != 32
  102317. )
  102318. )
  102319. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102320. }
  102321. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102322. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102323. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102324. metadata_picture_has_type2 = true;
  102325. }
  102326. }
  102327. }
  102328. encoder->private_->input_capacity = 0;
  102329. for(i = 0; i < encoder->protected_->channels; i++) {
  102330. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102331. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102332. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102333. #endif
  102334. }
  102335. for(i = 0; i < 2; i++) {
  102336. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102337. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102338. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102339. #endif
  102340. }
  102341. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102342. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102343. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102344. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102345. #endif
  102346. for(i = 0; i < encoder->protected_->channels; i++) {
  102347. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102348. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102349. encoder->private_->best_subframe[i] = 0;
  102350. }
  102351. for(i = 0; i < 2; i++) {
  102352. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102353. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102354. encoder->private_->best_subframe_mid_side[i] = 0;
  102355. }
  102356. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102357. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102358. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102359. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102360. #else
  102361. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102362. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102363. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102364. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102365. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102366. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102367. 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);
  102368. #endif
  102369. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102370. encoder->private_->loose_mid_side_stereo_frames = 1;
  102371. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102372. encoder->private_->current_sample_number = 0;
  102373. encoder->private_->current_frame_number = 0;
  102374. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102375. 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? */
  102376. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102377. /*
  102378. * get the CPU info and set the function pointers
  102379. */
  102380. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102381. /* first default to the non-asm routines */
  102382. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102383. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102384. #endif
  102385. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102386. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102387. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102388. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102389. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102390. #endif
  102391. /* now override with asm where appropriate */
  102392. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102393. # ifndef FLAC__NO_ASM
  102394. if(encoder->private_->cpuinfo.use_asm) {
  102395. # ifdef FLAC__CPU_IA32
  102396. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102397. # ifdef FLAC__HAS_NASM
  102398. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102399. if(encoder->protected_->max_lpc_order < 4)
  102400. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102401. else if(encoder->protected_->max_lpc_order < 8)
  102402. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102403. else if(encoder->protected_->max_lpc_order < 12)
  102404. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102405. else
  102406. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102407. }
  102408. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102409. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102410. else
  102411. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102412. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102413. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102414. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102415. }
  102416. else {
  102417. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102418. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102419. }
  102420. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102421. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102422. # endif /* FLAC__HAS_NASM */
  102423. # endif /* FLAC__CPU_IA32 */
  102424. }
  102425. # endif /* !FLAC__NO_ASM */
  102426. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102427. /* finally override based on wide-ness if necessary */
  102428. if(encoder->private_->use_wide_by_block) {
  102429. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102430. }
  102431. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102432. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102433. #if FLAC__HAS_OGG
  102434. encoder->private_->is_ogg = is_ogg;
  102435. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102436. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102437. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102438. }
  102439. #endif
  102440. encoder->private_->read_callback = read_callback;
  102441. encoder->private_->write_callback = write_callback;
  102442. encoder->private_->seek_callback = seek_callback;
  102443. encoder->private_->tell_callback = tell_callback;
  102444. encoder->private_->metadata_callback = metadata_callback;
  102445. encoder->private_->client_data = client_data;
  102446. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102447. /* the above function sets the state for us in case of an error */
  102448. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102449. }
  102450. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102451. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102452. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102453. }
  102454. /*
  102455. * Set up the verify stuff if necessary
  102456. */
  102457. if(encoder->protected_->verify) {
  102458. /*
  102459. * First, set up the fifo which will hold the
  102460. * original signal to compare against
  102461. */
  102462. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102463. for(i = 0; i < encoder->protected_->channels; i++) {
  102464. 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))) {
  102465. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102466. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102467. }
  102468. }
  102469. encoder->private_->verify.input_fifo.tail = 0;
  102470. /*
  102471. * Now set up a stream decoder for verification
  102472. */
  102473. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102474. if(0 == encoder->private_->verify.decoder) {
  102475. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102476. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102477. }
  102478. 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) {
  102479. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102480. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102481. }
  102482. }
  102483. encoder->private_->verify.error_stats.absolute_sample = 0;
  102484. encoder->private_->verify.error_stats.frame_number = 0;
  102485. encoder->private_->verify.error_stats.channel = 0;
  102486. encoder->private_->verify.error_stats.sample = 0;
  102487. encoder->private_->verify.error_stats.expected = 0;
  102488. encoder->private_->verify.error_stats.got = 0;
  102489. /*
  102490. * These must be done before we write any metadata, because that
  102491. * calls the write_callback, which uses these values.
  102492. */
  102493. encoder->private_->first_seekpoint_to_check = 0;
  102494. encoder->private_->samples_written = 0;
  102495. encoder->protected_->streaminfo_offset = 0;
  102496. encoder->protected_->seektable_offset = 0;
  102497. encoder->protected_->audio_offset = 0;
  102498. /*
  102499. * write the stream header
  102500. */
  102501. if(encoder->protected_->verify)
  102502. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102503. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102504. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102505. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102506. }
  102507. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102508. /* the above function sets the state for us in case of an error */
  102509. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102510. }
  102511. /*
  102512. * write the STREAMINFO metadata block
  102513. */
  102514. if(encoder->protected_->verify)
  102515. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102516. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102517. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102518. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102519. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102520. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102521. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102522. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102523. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102524. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102525. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102526. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102527. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102528. if(encoder->protected_->do_md5)
  102529. FLAC__MD5Init(&encoder->private_->md5context);
  102530. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102531. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102532. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102533. }
  102534. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102535. /* the above function sets the state for us in case of an error */
  102536. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102537. }
  102538. /*
  102539. * Now that the STREAMINFO block is written, we can init this to an
  102540. * absurdly-high value...
  102541. */
  102542. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102543. /* ... and clear this to 0 */
  102544. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102545. /*
  102546. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102547. * if not, we will write an empty one (FLAC__add_metadata_block()
  102548. * automatically supplies the vendor string).
  102549. *
  102550. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102551. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102552. * true it will have already insured that the metadata list is properly
  102553. * ordered.)
  102554. */
  102555. if(!metadata_has_vorbis_comment) {
  102556. FLAC__StreamMetadata vorbis_comment;
  102557. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102558. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102559. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102560. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102561. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102562. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102563. vorbis_comment.data.vorbis_comment.comments = 0;
  102564. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102565. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102566. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102567. }
  102568. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102569. /* the above function sets the state for us in case of an error */
  102570. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102571. }
  102572. }
  102573. /*
  102574. * write the user's metadata blocks
  102575. */
  102576. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102577. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102578. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102579. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102580. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102581. }
  102582. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102583. /* the above function sets the state for us in case of an error */
  102584. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102585. }
  102586. }
  102587. /* now that all the metadata is written, we save the stream offset */
  102588. 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 */
  102589. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102590. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102591. }
  102592. if(encoder->protected_->verify)
  102593. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102594. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102595. }
  102596. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102597. FLAC__StreamEncoder *encoder,
  102598. FLAC__StreamEncoderWriteCallback write_callback,
  102599. FLAC__StreamEncoderSeekCallback seek_callback,
  102600. FLAC__StreamEncoderTellCallback tell_callback,
  102601. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102602. void *client_data
  102603. )
  102604. {
  102605. return init_stream_internal_enc(
  102606. encoder,
  102607. /*read_callback=*/0,
  102608. write_callback,
  102609. seek_callback,
  102610. tell_callback,
  102611. metadata_callback,
  102612. client_data,
  102613. /*is_ogg=*/false
  102614. );
  102615. }
  102616. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102617. FLAC__StreamEncoder *encoder,
  102618. FLAC__StreamEncoderReadCallback read_callback,
  102619. FLAC__StreamEncoderWriteCallback write_callback,
  102620. FLAC__StreamEncoderSeekCallback seek_callback,
  102621. FLAC__StreamEncoderTellCallback tell_callback,
  102622. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102623. void *client_data
  102624. )
  102625. {
  102626. return init_stream_internal_enc(
  102627. encoder,
  102628. read_callback,
  102629. write_callback,
  102630. seek_callback,
  102631. tell_callback,
  102632. metadata_callback,
  102633. client_data,
  102634. /*is_ogg=*/true
  102635. );
  102636. }
  102637. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102638. FLAC__StreamEncoder *encoder,
  102639. FILE *file,
  102640. FLAC__StreamEncoderProgressCallback progress_callback,
  102641. void *client_data,
  102642. FLAC__bool is_ogg
  102643. )
  102644. {
  102645. FLAC__StreamEncoderInitStatus init_status;
  102646. FLAC__ASSERT(0 != encoder);
  102647. FLAC__ASSERT(0 != file);
  102648. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102649. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102650. /* double protection */
  102651. if(file == 0) {
  102652. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102653. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102654. }
  102655. /*
  102656. * To make sure that our file does not go unclosed after an error, we
  102657. * must assign the FILE pointer before any further error can occur in
  102658. * this routine.
  102659. */
  102660. if(file == stdout)
  102661. file = get_binary_stdout_(); /* just to be safe */
  102662. encoder->private_->file = file;
  102663. encoder->private_->progress_callback = progress_callback;
  102664. encoder->private_->bytes_written = 0;
  102665. encoder->private_->samples_written = 0;
  102666. encoder->private_->frames_written = 0;
  102667. init_status = init_stream_internal_enc(
  102668. encoder,
  102669. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102670. file_write_callback_,
  102671. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102672. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102673. /*metadata_callback=*/0,
  102674. client_data,
  102675. is_ogg
  102676. );
  102677. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102678. /* the above function sets the state for us in case of an error */
  102679. return init_status;
  102680. }
  102681. {
  102682. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102683. FLAC__ASSERT(blocksize != 0);
  102684. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102685. }
  102686. return init_status;
  102687. }
  102688. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102689. FLAC__StreamEncoder *encoder,
  102690. FILE *file,
  102691. FLAC__StreamEncoderProgressCallback progress_callback,
  102692. void *client_data
  102693. )
  102694. {
  102695. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102696. }
  102697. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102698. FLAC__StreamEncoder *encoder,
  102699. FILE *file,
  102700. FLAC__StreamEncoderProgressCallback progress_callback,
  102701. void *client_data
  102702. )
  102703. {
  102704. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102705. }
  102706. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102707. FLAC__StreamEncoder *encoder,
  102708. const char *filename,
  102709. FLAC__StreamEncoderProgressCallback progress_callback,
  102710. void *client_data,
  102711. FLAC__bool is_ogg
  102712. )
  102713. {
  102714. FILE *file;
  102715. FLAC__ASSERT(0 != encoder);
  102716. /*
  102717. * To make sure that our file does not go unclosed after an error, we
  102718. * have to do the same entrance checks here that are later performed
  102719. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102720. */
  102721. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102722. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102723. file = filename? fopen(filename, "w+b") : stdout;
  102724. if(file == 0) {
  102725. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102726. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102727. }
  102728. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102729. }
  102730. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102731. FLAC__StreamEncoder *encoder,
  102732. const char *filename,
  102733. FLAC__StreamEncoderProgressCallback progress_callback,
  102734. void *client_data
  102735. )
  102736. {
  102737. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102738. }
  102739. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102740. FLAC__StreamEncoder *encoder,
  102741. const char *filename,
  102742. FLAC__StreamEncoderProgressCallback progress_callback,
  102743. void *client_data
  102744. )
  102745. {
  102746. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102747. }
  102748. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102749. {
  102750. FLAC__bool error = false;
  102751. FLAC__ASSERT(0 != encoder);
  102752. FLAC__ASSERT(0 != encoder->private_);
  102753. FLAC__ASSERT(0 != encoder->protected_);
  102754. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102755. return true;
  102756. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102757. if(encoder->private_->current_sample_number != 0) {
  102758. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102759. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102760. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102761. error = true;
  102762. }
  102763. }
  102764. if(encoder->protected_->do_md5)
  102765. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102766. if(!encoder->private_->is_being_deleted) {
  102767. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102768. if(encoder->private_->seek_callback) {
  102769. #if FLAC__HAS_OGG
  102770. if(encoder->private_->is_ogg)
  102771. update_ogg_metadata_(encoder);
  102772. else
  102773. #endif
  102774. update_metadata_(encoder);
  102775. /* check if an error occurred while updating metadata */
  102776. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102777. error = true;
  102778. }
  102779. if(encoder->private_->metadata_callback)
  102780. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102781. }
  102782. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102783. if(!error)
  102784. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102785. error = true;
  102786. }
  102787. }
  102788. if(0 != encoder->private_->file) {
  102789. if(encoder->private_->file != stdout)
  102790. fclose(encoder->private_->file);
  102791. encoder->private_->file = 0;
  102792. }
  102793. #if FLAC__HAS_OGG
  102794. if(encoder->private_->is_ogg)
  102795. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  102796. #endif
  102797. free_(encoder);
  102798. set_defaults_enc(encoder);
  102799. if(!error)
  102800. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102801. return !error;
  102802. }
  102803. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  102804. {
  102805. FLAC__ASSERT(0 != encoder);
  102806. FLAC__ASSERT(0 != encoder->private_);
  102807. FLAC__ASSERT(0 != encoder->protected_);
  102808. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102809. return false;
  102810. #if FLAC__HAS_OGG
  102811. /* can't check encoder->private_->is_ogg since that's not set until init time */
  102812. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  102813. return true;
  102814. #else
  102815. (void)value;
  102816. return false;
  102817. #endif
  102818. }
  102819. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102820. {
  102821. FLAC__ASSERT(0 != encoder);
  102822. FLAC__ASSERT(0 != encoder->private_);
  102823. FLAC__ASSERT(0 != encoder->protected_);
  102824. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102825. return false;
  102826. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102827. encoder->protected_->verify = value;
  102828. #endif
  102829. return true;
  102830. }
  102831. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102832. {
  102833. FLAC__ASSERT(0 != encoder);
  102834. FLAC__ASSERT(0 != encoder->private_);
  102835. FLAC__ASSERT(0 != encoder->protected_);
  102836. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102837. return false;
  102838. encoder->protected_->streamable_subset = value;
  102839. return true;
  102840. }
  102841. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102842. {
  102843. FLAC__ASSERT(0 != encoder);
  102844. FLAC__ASSERT(0 != encoder->private_);
  102845. FLAC__ASSERT(0 != encoder->protected_);
  102846. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102847. return false;
  102848. encoder->protected_->do_md5 = value;
  102849. return true;
  102850. }
  102851. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  102852. {
  102853. FLAC__ASSERT(0 != encoder);
  102854. FLAC__ASSERT(0 != encoder->private_);
  102855. FLAC__ASSERT(0 != encoder->protected_);
  102856. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102857. return false;
  102858. encoder->protected_->channels = value;
  102859. return true;
  102860. }
  102861. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  102862. {
  102863. FLAC__ASSERT(0 != encoder);
  102864. FLAC__ASSERT(0 != encoder->private_);
  102865. FLAC__ASSERT(0 != encoder->protected_);
  102866. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102867. return false;
  102868. encoder->protected_->bits_per_sample = value;
  102869. return true;
  102870. }
  102871. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  102872. {
  102873. FLAC__ASSERT(0 != encoder);
  102874. FLAC__ASSERT(0 != encoder->private_);
  102875. FLAC__ASSERT(0 != encoder->protected_);
  102876. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102877. return false;
  102878. encoder->protected_->sample_rate = value;
  102879. return true;
  102880. }
  102881. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  102882. {
  102883. FLAC__bool ok = true;
  102884. FLAC__ASSERT(0 != encoder);
  102885. FLAC__ASSERT(0 != encoder->private_);
  102886. FLAC__ASSERT(0 != encoder->protected_);
  102887. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102888. return false;
  102889. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  102890. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  102891. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  102892. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  102893. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102894. #if 0
  102895. /* was: */
  102896. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  102897. /* but it's too hard to specify the string in a locale-specific way */
  102898. #else
  102899. encoder->protected_->num_apodizations = 1;
  102900. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102901. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102902. #endif
  102903. #endif
  102904. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  102905. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  102906. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  102907. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  102908. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  102909. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  102910. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  102911. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  102912. return ok;
  102913. }
  102914. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  102915. {
  102916. FLAC__ASSERT(0 != encoder);
  102917. FLAC__ASSERT(0 != encoder->private_);
  102918. FLAC__ASSERT(0 != encoder->protected_);
  102919. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102920. return false;
  102921. encoder->protected_->blocksize = value;
  102922. return true;
  102923. }
  102924. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102925. {
  102926. FLAC__ASSERT(0 != encoder);
  102927. FLAC__ASSERT(0 != encoder->private_);
  102928. FLAC__ASSERT(0 != encoder->protected_);
  102929. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102930. return false;
  102931. encoder->protected_->do_mid_side_stereo = value;
  102932. return true;
  102933. }
  102934. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102935. {
  102936. FLAC__ASSERT(0 != encoder);
  102937. FLAC__ASSERT(0 != encoder->private_);
  102938. FLAC__ASSERT(0 != encoder->protected_);
  102939. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102940. return false;
  102941. encoder->protected_->loose_mid_side_stereo = value;
  102942. return true;
  102943. }
  102944. /*@@@@add to tests*/
  102945. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  102946. {
  102947. FLAC__ASSERT(0 != encoder);
  102948. FLAC__ASSERT(0 != encoder->private_);
  102949. FLAC__ASSERT(0 != encoder->protected_);
  102950. FLAC__ASSERT(0 != specification);
  102951. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102952. return false;
  102953. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  102954. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  102955. #else
  102956. encoder->protected_->num_apodizations = 0;
  102957. while(1) {
  102958. const char *s = strchr(specification, ';');
  102959. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  102960. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  102961. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  102962. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  102963. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  102964. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  102965. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  102966. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  102967. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  102968. else if(n==6 && 0 == strncmp("connes" , specification, n))
  102969. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  102970. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  102971. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  102972. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  102973. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  102974. if (stddev > 0.0 && stddev <= 0.5) {
  102975. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  102976. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  102977. }
  102978. }
  102979. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  102980. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  102981. else if(n==4 && 0 == strncmp("hann" , specification, n))
  102982. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  102983. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  102984. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  102985. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  102986. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  102987. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  102988. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  102989. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  102990. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  102991. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  102992. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  102993. if (p >= 0.0 && p <= 1.0) {
  102994. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  102995. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  102996. }
  102997. }
  102998. else if(n==5 && 0 == strncmp("welch" , specification, n))
  102999. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103000. if (encoder->protected_->num_apodizations == 32)
  103001. break;
  103002. if (s)
  103003. specification = s+1;
  103004. else
  103005. break;
  103006. }
  103007. if(encoder->protected_->num_apodizations == 0) {
  103008. encoder->protected_->num_apodizations = 1;
  103009. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103010. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103011. }
  103012. #endif
  103013. return true;
  103014. }
  103015. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103016. {
  103017. FLAC__ASSERT(0 != encoder);
  103018. FLAC__ASSERT(0 != encoder->private_);
  103019. FLAC__ASSERT(0 != encoder->protected_);
  103020. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103021. return false;
  103022. encoder->protected_->max_lpc_order = value;
  103023. return true;
  103024. }
  103025. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103026. {
  103027. FLAC__ASSERT(0 != encoder);
  103028. FLAC__ASSERT(0 != encoder->private_);
  103029. FLAC__ASSERT(0 != encoder->protected_);
  103030. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103031. return false;
  103032. encoder->protected_->qlp_coeff_precision = value;
  103033. return true;
  103034. }
  103035. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103036. {
  103037. FLAC__ASSERT(0 != encoder);
  103038. FLAC__ASSERT(0 != encoder->private_);
  103039. FLAC__ASSERT(0 != encoder->protected_);
  103040. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103041. return false;
  103042. encoder->protected_->do_qlp_coeff_prec_search = value;
  103043. return true;
  103044. }
  103045. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103046. {
  103047. FLAC__ASSERT(0 != encoder);
  103048. FLAC__ASSERT(0 != encoder->private_);
  103049. FLAC__ASSERT(0 != encoder->protected_);
  103050. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103051. return false;
  103052. #if 0
  103053. /*@@@ deprecated: */
  103054. encoder->protected_->do_escape_coding = value;
  103055. #else
  103056. (void)value;
  103057. #endif
  103058. return true;
  103059. }
  103060. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103061. {
  103062. FLAC__ASSERT(0 != encoder);
  103063. FLAC__ASSERT(0 != encoder->private_);
  103064. FLAC__ASSERT(0 != encoder->protected_);
  103065. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103066. return false;
  103067. encoder->protected_->do_exhaustive_model_search = value;
  103068. return true;
  103069. }
  103070. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103071. {
  103072. FLAC__ASSERT(0 != encoder);
  103073. FLAC__ASSERT(0 != encoder->private_);
  103074. FLAC__ASSERT(0 != encoder->protected_);
  103075. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103076. return false;
  103077. encoder->protected_->min_residual_partition_order = value;
  103078. return true;
  103079. }
  103080. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103081. {
  103082. FLAC__ASSERT(0 != encoder);
  103083. FLAC__ASSERT(0 != encoder->private_);
  103084. FLAC__ASSERT(0 != encoder->protected_);
  103085. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103086. return false;
  103087. encoder->protected_->max_residual_partition_order = value;
  103088. return true;
  103089. }
  103090. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103091. {
  103092. FLAC__ASSERT(0 != encoder);
  103093. FLAC__ASSERT(0 != encoder->private_);
  103094. FLAC__ASSERT(0 != encoder->protected_);
  103095. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103096. return false;
  103097. #if 0
  103098. /*@@@ deprecated: */
  103099. encoder->protected_->rice_parameter_search_dist = value;
  103100. #else
  103101. (void)value;
  103102. #endif
  103103. return true;
  103104. }
  103105. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103106. {
  103107. FLAC__ASSERT(0 != encoder);
  103108. FLAC__ASSERT(0 != encoder->private_);
  103109. FLAC__ASSERT(0 != encoder->protected_);
  103110. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103111. return false;
  103112. encoder->protected_->total_samples_estimate = value;
  103113. return true;
  103114. }
  103115. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103116. {
  103117. FLAC__ASSERT(0 != encoder);
  103118. FLAC__ASSERT(0 != encoder->private_);
  103119. FLAC__ASSERT(0 != encoder->protected_);
  103120. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103121. return false;
  103122. if(0 == metadata)
  103123. num_blocks = 0;
  103124. if(0 == num_blocks)
  103125. metadata = 0;
  103126. /* realloc() does not do exactly what we want so... */
  103127. if(encoder->protected_->metadata) {
  103128. free(encoder->protected_->metadata);
  103129. encoder->protected_->metadata = 0;
  103130. encoder->protected_->num_metadata_blocks = 0;
  103131. }
  103132. if(num_blocks) {
  103133. FLAC__StreamMetadata **m;
  103134. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103135. return false;
  103136. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103137. encoder->protected_->metadata = m;
  103138. encoder->protected_->num_metadata_blocks = num_blocks;
  103139. }
  103140. #if FLAC__HAS_OGG
  103141. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103142. return false;
  103143. #endif
  103144. return true;
  103145. }
  103146. /*
  103147. * These three functions are not static, but not publically exposed in
  103148. * include/FLAC/ either. They are used by the test suite.
  103149. */
  103150. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103151. {
  103152. FLAC__ASSERT(0 != encoder);
  103153. FLAC__ASSERT(0 != encoder->private_);
  103154. FLAC__ASSERT(0 != encoder->protected_);
  103155. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103156. return false;
  103157. encoder->private_->disable_constant_subframes = value;
  103158. return true;
  103159. }
  103160. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103161. {
  103162. FLAC__ASSERT(0 != encoder);
  103163. FLAC__ASSERT(0 != encoder->private_);
  103164. FLAC__ASSERT(0 != encoder->protected_);
  103165. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103166. return false;
  103167. encoder->private_->disable_fixed_subframes = value;
  103168. return true;
  103169. }
  103170. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103171. {
  103172. FLAC__ASSERT(0 != encoder);
  103173. FLAC__ASSERT(0 != encoder->private_);
  103174. FLAC__ASSERT(0 != encoder->protected_);
  103175. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103176. return false;
  103177. encoder->private_->disable_verbatim_subframes = value;
  103178. return true;
  103179. }
  103180. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103181. {
  103182. FLAC__ASSERT(0 != encoder);
  103183. FLAC__ASSERT(0 != encoder->private_);
  103184. FLAC__ASSERT(0 != encoder->protected_);
  103185. return encoder->protected_->state;
  103186. }
  103187. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103188. {
  103189. FLAC__ASSERT(0 != encoder);
  103190. FLAC__ASSERT(0 != encoder->private_);
  103191. FLAC__ASSERT(0 != encoder->protected_);
  103192. if(encoder->protected_->verify)
  103193. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103194. else
  103195. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103196. }
  103197. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103198. {
  103199. FLAC__ASSERT(0 != encoder);
  103200. FLAC__ASSERT(0 != encoder->private_);
  103201. FLAC__ASSERT(0 != encoder->protected_);
  103202. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103203. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103204. else
  103205. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103206. }
  103207. 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)
  103208. {
  103209. FLAC__ASSERT(0 != encoder);
  103210. FLAC__ASSERT(0 != encoder->private_);
  103211. FLAC__ASSERT(0 != encoder->protected_);
  103212. if(0 != absolute_sample)
  103213. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103214. if(0 != frame_number)
  103215. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103216. if(0 != channel)
  103217. *channel = encoder->private_->verify.error_stats.channel;
  103218. if(0 != sample)
  103219. *sample = encoder->private_->verify.error_stats.sample;
  103220. if(0 != expected)
  103221. *expected = encoder->private_->verify.error_stats.expected;
  103222. if(0 != got)
  103223. *got = encoder->private_->verify.error_stats.got;
  103224. }
  103225. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103226. {
  103227. FLAC__ASSERT(0 != encoder);
  103228. FLAC__ASSERT(0 != encoder->private_);
  103229. FLAC__ASSERT(0 != encoder->protected_);
  103230. return encoder->protected_->verify;
  103231. }
  103232. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103233. {
  103234. FLAC__ASSERT(0 != encoder);
  103235. FLAC__ASSERT(0 != encoder->private_);
  103236. FLAC__ASSERT(0 != encoder->protected_);
  103237. return encoder->protected_->streamable_subset;
  103238. }
  103239. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103240. {
  103241. FLAC__ASSERT(0 != encoder);
  103242. FLAC__ASSERT(0 != encoder->private_);
  103243. FLAC__ASSERT(0 != encoder->protected_);
  103244. return encoder->protected_->do_md5;
  103245. }
  103246. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103247. {
  103248. FLAC__ASSERT(0 != encoder);
  103249. FLAC__ASSERT(0 != encoder->private_);
  103250. FLAC__ASSERT(0 != encoder->protected_);
  103251. return encoder->protected_->channels;
  103252. }
  103253. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103254. {
  103255. FLAC__ASSERT(0 != encoder);
  103256. FLAC__ASSERT(0 != encoder->private_);
  103257. FLAC__ASSERT(0 != encoder->protected_);
  103258. return encoder->protected_->bits_per_sample;
  103259. }
  103260. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103261. {
  103262. FLAC__ASSERT(0 != encoder);
  103263. FLAC__ASSERT(0 != encoder->private_);
  103264. FLAC__ASSERT(0 != encoder->protected_);
  103265. return encoder->protected_->sample_rate;
  103266. }
  103267. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103268. {
  103269. FLAC__ASSERT(0 != encoder);
  103270. FLAC__ASSERT(0 != encoder->private_);
  103271. FLAC__ASSERT(0 != encoder->protected_);
  103272. return encoder->protected_->blocksize;
  103273. }
  103274. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103275. {
  103276. FLAC__ASSERT(0 != encoder);
  103277. FLAC__ASSERT(0 != encoder->private_);
  103278. FLAC__ASSERT(0 != encoder->protected_);
  103279. return encoder->protected_->do_mid_side_stereo;
  103280. }
  103281. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103282. {
  103283. FLAC__ASSERT(0 != encoder);
  103284. FLAC__ASSERT(0 != encoder->private_);
  103285. FLAC__ASSERT(0 != encoder->protected_);
  103286. return encoder->protected_->loose_mid_side_stereo;
  103287. }
  103288. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103289. {
  103290. FLAC__ASSERT(0 != encoder);
  103291. FLAC__ASSERT(0 != encoder->private_);
  103292. FLAC__ASSERT(0 != encoder->protected_);
  103293. return encoder->protected_->max_lpc_order;
  103294. }
  103295. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103296. {
  103297. FLAC__ASSERT(0 != encoder);
  103298. FLAC__ASSERT(0 != encoder->private_);
  103299. FLAC__ASSERT(0 != encoder->protected_);
  103300. return encoder->protected_->qlp_coeff_precision;
  103301. }
  103302. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103303. {
  103304. FLAC__ASSERT(0 != encoder);
  103305. FLAC__ASSERT(0 != encoder->private_);
  103306. FLAC__ASSERT(0 != encoder->protected_);
  103307. return encoder->protected_->do_qlp_coeff_prec_search;
  103308. }
  103309. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103310. {
  103311. FLAC__ASSERT(0 != encoder);
  103312. FLAC__ASSERT(0 != encoder->private_);
  103313. FLAC__ASSERT(0 != encoder->protected_);
  103314. return encoder->protected_->do_escape_coding;
  103315. }
  103316. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103317. {
  103318. FLAC__ASSERT(0 != encoder);
  103319. FLAC__ASSERT(0 != encoder->private_);
  103320. FLAC__ASSERT(0 != encoder->protected_);
  103321. return encoder->protected_->do_exhaustive_model_search;
  103322. }
  103323. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103324. {
  103325. FLAC__ASSERT(0 != encoder);
  103326. FLAC__ASSERT(0 != encoder->private_);
  103327. FLAC__ASSERT(0 != encoder->protected_);
  103328. return encoder->protected_->min_residual_partition_order;
  103329. }
  103330. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103331. {
  103332. FLAC__ASSERT(0 != encoder);
  103333. FLAC__ASSERT(0 != encoder->private_);
  103334. FLAC__ASSERT(0 != encoder->protected_);
  103335. return encoder->protected_->max_residual_partition_order;
  103336. }
  103337. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103338. {
  103339. FLAC__ASSERT(0 != encoder);
  103340. FLAC__ASSERT(0 != encoder->private_);
  103341. FLAC__ASSERT(0 != encoder->protected_);
  103342. return encoder->protected_->rice_parameter_search_dist;
  103343. }
  103344. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103345. {
  103346. FLAC__ASSERT(0 != encoder);
  103347. FLAC__ASSERT(0 != encoder->private_);
  103348. FLAC__ASSERT(0 != encoder->protected_);
  103349. return encoder->protected_->total_samples_estimate;
  103350. }
  103351. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103352. {
  103353. unsigned i, j = 0, channel;
  103354. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103355. FLAC__ASSERT(0 != encoder);
  103356. FLAC__ASSERT(0 != encoder->private_);
  103357. FLAC__ASSERT(0 != encoder->protected_);
  103358. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103359. do {
  103360. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103361. if(encoder->protected_->verify)
  103362. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103363. for(channel = 0; channel < channels; channel++)
  103364. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103365. if(encoder->protected_->do_mid_side_stereo) {
  103366. FLAC__ASSERT(channels == 2);
  103367. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103368. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103369. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103370. 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' ! */
  103371. }
  103372. }
  103373. else
  103374. j += n;
  103375. encoder->private_->current_sample_number += n;
  103376. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103377. if(encoder->private_->current_sample_number > blocksize) {
  103378. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103379. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103380. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103381. return false;
  103382. /* move unprocessed overread samples to beginnings of arrays */
  103383. for(channel = 0; channel < channels; channel++)
  103384. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103385. if(encoder->protected_->do_mid_side_stereo) {
  103386. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103387. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103388. }
  103389. encoder->private_->current_sample_number = 1;
  103390. }
  103391. } while(j < samples);
  103392. return true;
  103393. }
  103394. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103395. {
  103396. unsigned i, j, k, channel;
  103397. FLAC__int32 x, mid, side;
  103398. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103399. FLAC__ASSERT(0 != encoder);
  103400. FLAC__ASSERT(0 != encoder->private_);
  103401. FLAC__ASSERT(0 != encoder->protected_);
  103402. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103403. j = k = 0;
  103404. /*
  103405. * we have several flavors of the same basic loop, optimized for
  103406. * different conditions:
  103407. */
  103408. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103409. /*
  103410. * stereo coding: unroll channel loop
  103411. */
  103412. do {
  103413. if(encoder->protected_->verify)
  103414. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103415. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103416. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103417. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103418. x = buffer[k++];
  103419. encoder->private_->integer_signal[1][i] = x;
  103420. mid += x;
  103421. side -= x;
  103422. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103423. encoder->private_->integer_signal_mid_side[1][i] = side;
  103424. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103425. }
  103426. encoder->private_->current_sample_number = i;
  103427. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103428. if(i > blocksize) {
  103429. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103430. return false;
  103431. /* move unprocessed overread samples to beginnings of arrays */
  103432. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103433. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103434. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103435. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103436. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103437. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103438. encoder->private_->current_sample_number = 1;
  103439. }
  103440. } while(j < samples);
  103441. }
  103442. else {
  103443. /*
  103444. * independent channel coding: buffer each channel in inner loop
  103445. */
  103446. do {
  103447. if(encoder->protected_->verify)
  103448. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103449. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103450. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103451. for(channel = 0; channel < channels; channel++)
  103452. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103453. }
  103454. encoder->private_->current_sample_number = i;
  103455. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103456. if(i > blocksize) {
  103457. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103458. return false;
  103459. /* move unprocessed overread samples to beginnings of arrays */
  103460. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103461. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103462. for(channel = 0; channel < channels; channel++)
  103463. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103464. encoder->private_->current_sample_number = 1;
  103465. }
  103466. } while(j < samples);
  103467. }
  103468. return true;
  103469. }
  103470. /***********************************************************************
  103471. *
  103472. * Private class methods
  103473. *
  103474. ***********************************************************************/
  103475. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103476. {
  103477. FLAC__ASSERT(0 != encoder);
  103478. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103479. encoder->protected_->verify = true;
  103480. #else
  103481. encoder->protected_->verify = false;
  103482. #endif
  103483. encoder->protected_->streamable_subset = true;
  103484. encoder->protected_->do_md5 = true;
  103485. encoder->protected_->do_mid_side_stereo = false;
  103486. encoder->protected_->loose_mid_side_stereo = false;
  103487. encoder->protected_->channels = 2;
  103488. encoder->protected_->bits_per_sample = 16;
  103489. encoder->protected_->sample_rate = 44100;
  103490. encoder->protected_->blocksize = 0;
  103491. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103492. encoder->protected_->num_apodizations = 1;
  103493. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103494. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103495. #endif
  103496. encoder->protected_->max_lpc_order = 0;
  103497. encoder->protected_->qlp_coeff_precision = 0;
  103498. encoder->protected_->do_qlp_coeff_prec_search = false;
  103499. encoder->protected_->do_exhaustive_model_search = false;
  103500. encoder->protected_->do_escape_coding = false;
  103501. encoder->protected_->min_residual_partition_order = 0;
  103502. encoder->protected_->max_residual_partition_order = 0;
  103503. encoder->protected_->rice_parameter_search_dist = 0;
  103504. encoder->protected_->total_samples_estimate = 0;
  103505. encoder->protected_->metadata = 0;
  103506. encoder->protected_->num_metadata_blocks = 0;
  103507. encoder->private_->seek_table = 0;
  103508. encoder->private_->disable_constant_subframes = false;
  103509. encoder->private_->disable_fixed_subframes = false;
  103510. encoder->private_->disable_verbatim_subframes = false;
  103511. #if FLAC__HAS_OGG
  103512. encoder->private_->is_ogg = false;
  103513. #endif
  103514. encoder->private_->read_callback = 0;
  103515. encoder->private_->write_callback = 0;
  103516. encoder->private_->seek_callback = 0;
  103517. encoder->private_->tell_callback = 0;
  103518. encoder->private_->metadata_callback = 0;
  103519. encoder->private_->progress_callback = 0;
  103520. encoder->private_->client_data = 0;
  103521. #if FLAC__HAS_OGG
  103522. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103523. #endif
  103524. }
  103525. void free_(FLAC__StreamEncoder *encoder)
  103526. {
  103527. unsigned i, channel;
  103528. FLAC__ASSERT(0 != encoder);
  103529. if(encoder->protected_->metadata) {
  103530. free(encoder->protected_->metadata);
  103531. encoder->protected_->metadata = 0;
  103532. encoder->protected_->num_metadata_blocks = 0;
  103533. }
  103534. for(i = 0; i < encoder->protected_->channels; i++) {
  103535. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103536. free(encoder->private_->integer_signal_unaligned[i]);
  103537. encoder->private_->integer_signal_unaligned[i] = 0;
  103538. }
  103539. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103540. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103541. free(encoder->private_->real_signal_unaligned[i]);
  103542. encoder->private_->real_signal_unaligned[i] = 0;
  103543. }
  103544. #endif
  103545. }
  103546. for(i = 0; i < 2; i++) {
  103547. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103548. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103549. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103550. }
  103551. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103552. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103553. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103554. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103555. }
  103556. #endif
  103557. }
  103558. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103559. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103560. if(0 != encoder->private_->window_unaligned[i]) {
  103561. free(encoder->private_->window_unaligned[i]);
  103562. encoder->private_->window_unaligned[i] = 0;
  103563. }
  103564. }
  103565. if(0 != encoder->private_->windowed_signal_unaligned) {
  103566. free(encoder->private_->windowed_signal_unaligned);
  103567. encoder->private_->windowed_signal_unaligned = 0;
  103568. }
  103569. #endif
  103570. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103571. for(i = 0; i < 2; i++) {
  103572. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103573. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103574. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103575. }
  103576. }
  103577. }
  103578. for(channel = 0; channel < 2; channel++) {
  103579. for(i = 0; i < 2; i++) {
  103580. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103581. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103582. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103583. }
  103584. }
  103585. }
  103586. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103587. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103588. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103589. }
  103590. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103591. free(encoder->private_->raw_bits_per_partition_unaligned);
  103592. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103593. }
  103594. if(encoder->protected_->verify) {
  103595. for(i = 0; i < encoder->protected_->channels; i++) {
  103596. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103597. free(encoder->private_->verify.input_fifo.data[i]);
  103598. encoder->private_->verify.input_fifo.data[i] = 0;
  103599. }
  103600. }
  103601. }
  103602. FLAC__bitwriter_free(encoder->private_->frame);
  103603. }
  103604. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103605. {
  103606. FLAC__bool ok;
  103607. unsigned i, channel;
  103608. FLAC__ASSERT(new_blocksize > 0);
  103609. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103610. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103611. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103612. if(new_blocksize <= encoder->private_->input_capacity)
  103613. return true;
  103614. ok = true;
  103615. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103616. * requires that the input arrays (in our case the integer signals)
  103617. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103618. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103619. */
  103620. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103621. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103622. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103623. encoder->private_->integer_signal[i] += 4;
  103624. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103625. #if 0 /* @@@ currently unused */
  103626. if(encoder->protected_->max_lpc_order > 0)
  103627. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103628. #endif
  103629. #endif
  103630. }
  103631. for(i = 0; ok && i < 2; i++) {
  103632. 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]);
  103633. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103634. encoder->private_->integer_signal_mid_side[i] += 4;
  103635. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103636. #if 0 /* @@@ currently unused */
  103637. if(encoder->protected_->max_lpc_order > 0)
  103638. 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]);
  103639. #endif
  103640. #endif
  103641. }
  103642. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103643. if(ok && encoder->protected_->max_lpc_order > 0) {
  103644. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103645. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103646. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103647. }
  103648. #endif
  103649. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103650. for(i = 0; ok && i < 2; i++) {
  103651. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103652. }
  103653. }
  103654. for(channel = 0; ok && channel < 2; channel++) {
  103655. for(i = 0; ok && i < 2; i++) {
  103656. 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]);
  103657. }
  103658. }
  103659. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103660. /*@@@ 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) */
  103661. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103662. if(encoder->protected_->do_escape_coding)
  103663. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103664. /* now adjust the windows if the blocksize has changed */
  103665. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103666. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103667. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103668. switch(encoder->protected_->apodizations[i].type) {
  103669. case FLAC__APODIZATION_BARTLETT:
  103670. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103671. break;
  103672. case FLAC__APODIZATION_BARTLETT_HANN:
  103673. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103674. break;
  103675. case FLAC__APODIZATION_BLACKMAN:
  103676. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103677. break;
  103678. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103679. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103680. break;
  103681. case FLAC__APODIZATION_CONNES:
  103682. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103683. break;
  103684. case FLAC__APODIZATION_FLATTOP:
  103685. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103686. break;
  103687. case FLAC__APODIZATION_GAUSS:
  103688. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103689. break;
  103690. case FLAC__APODIZATION_HAMMING:
  103691. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103692. break;
  103693. case FLAC__APODIZATION_HANN:
  103694. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103695. break;
  103696. case FLAC__APODIZATION_KAISER_BESSEL:
  103697. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103698. break;
  103699. case FLAC__APODIZATION_NUTTALL:
  103700. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103701. break;
  103702. case FLAC__APODIZATION_RECTANGLE:
  103703. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103704. break;
  103705. case FLAC__APODIZATION_TRIANGLE:
  103706. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103707. break;
  103708. case FLAC__APODIZATION_TUKEY:
  103709. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103710. break;
  103711. case FLAC__APODIZATION_WELCH:
  103712. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103713. break;
  103714. default:
  103715. FLAC__ASSERT(0);
  103716. /* double protection */
  103717. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103718. break;
  103719. }
  103720. }
  103721. }
  103722. #endif
  103723. if(ok)
  103724. encoder->private_->input_capacity = new_blocksize;
  103725. else
  103726. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103727. return ok;
  103728. }
  103729. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103730. {
  103731. const FLAC__byte *buffer;
  103732. size_t bytes;
  103733. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103734. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103735. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103736. return false;
  103737. }
  103738. if(encoder->protected_->verify) {
  103739. encoder->private_->verify.output.data = buffer;
  103740. encoder->private_->verify.output.bytes = bytes;
  103741. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103742. encoder->private_->verify.needs_magic_hack = true;
  103743. }
  103744. else {
  103745. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103746. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103747. FLAC__bitwriter_clear(encoder->private_->frame);
  103748. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103749. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103750. return false;
  103751. }
  103752. }
  103753. }
  103754. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103755. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103756. FLAC__bitwriter_clear(encoder->private_->frame);
  103757. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103758. return false;
  103759. }
  103760. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103761. FLAC__bitwriter_clear(encoder->private_->frame);
  103762. if(samples > 0) {
  103763. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103764. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103765. }
  103766. return true;
  103767. }
  103768. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103769. {
  103770. FLAC__StreamEncoderWriteStatus status;
  103771. FLAC__uint64 output_position = 0;
  103772. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103773. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103774. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103775. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103776. }
  103777. /*
  103778. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103779. */
  103780. if(samples == 0) {
  103781. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103782. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103783. encoder->protected_->streaminfo_offset = output_position;
  103784. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103785. encoder->protected_->seektable_offset = output_position;
  103786. }
  103787. /*
  103788. * Mark the current seek point if hit (if audio_offset == 0 that
  103789. * means we're still writing metadata and haven't hit the first
  103790. * frame yet)
  103791. */
  103792. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  103793. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103794. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  103795. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  103796. FLAC__uint64 test_sample;
  103797. unsigned i;
  103798. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  103799. test_sample = encoder->private_->seek_table->points[i].sample_number;
  103800. if(test_sample > frame_last_sample) {
  103801. break;
  103802. }
  103803. else if(test_sample >= frame_first_sample) {
  103804. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  103805. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  103806. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  103807. encoder->private_->first_seekpoint_to_check++;
  103808. /* DO NOT: "break;" and here's why:
  103809. * The seektable template may contain more than one target
  103810. * sample for any given frame; we will keep looping, generating
  103811. * duplicate seekpoints for them, and we'll clean it up later,
  103812. * just before writing the seektable back to the metadata.
  103813. */
  103814. }
  103815. else {
  103816. encoder->private_->first_seekpoint_to_check++;
  103817. }
  103818. }
  103819. }
  103820. #if FLAC__HAS_OGG
  103821. if(encoder->private_->is_ogg) {
  103822. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  103823. &encoder->protected_->ogg_encoder_aspect,
  103824. buffer,
  103825. bytes,
  103826. samples,
  103827. encoder->private_->current_frame_number,
  103828. is_last_block,
  103829. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  103830. encoder,
  103831. encoder->private_->client_data
  103832. );
  103833. }
  103834. else
  103835. #endif
  103836. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  103837. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103838. encoder->private_->bytes_written += bytes;
  103839. encoder->private_->samples_written += samples;
  103840. /* we keep a high watermark on the number of frames written because
  103841. * when the encoder goes back to write metadata, 'current_frame'
  103842. * will drop back to 0.
  103843. */
  103844. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  103845. }
  103846. else
  103847. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103848. return status;
  103849. }
  103850. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103851. void update_metadata_(const FLAC__StreamEncoder *encoder)
  103852. {
  103853. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103854. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103855. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103856. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103857. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103858. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  103859. FLAC__StreamEncoderSeekStatus seek_status;
  103860. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103861. /* All this is based on intimate knowledge of the stream header
  103862. * layout, but a change to the header format that would break this
  103863. * would also break all streams encoded in the previous format.
  103864. */
  103865. /*
  103866. * Write MD5 signature
  103867. */
  103868. {
  103869. const unsigned md5_offset =
  103870. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103871. (
  103872. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103873. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103874. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103875. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103876. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103877. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103878. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103879. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103880. ) / 8;
  103881. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103882. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103883. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103884. return;
  103885. }
  103886. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103887. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103888. return;
  103889. }
  103890. }
  103891. /*
  103892. * Write total samples
  103893. */
  103894. {
  103895. const unsigned total_samples_byte_offset =
  103896. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103897. (
  103898. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103899. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103900. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103901. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103902. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103903. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103904. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103905. - 4
  103906. ) / 8;
  103907. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  103908. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103909. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103910. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103911. b[4] = (FLAC__byte)(samples & 0xFF);
  103912. 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) {
  103913. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103914. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103915. return;
  103916. }
  103917. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103918. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103919. return;
  103920. }
  103921. }
  103922. /*
  103923. * Write min/max framesize
  103924. */
  103925. {
  103926. const unsigned min_framesize_offset =
  103927. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103928. (
  103929. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103930. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103931. ) / 8;
  103932. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103933. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103934. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103935. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103936. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103937. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103938. 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) {
  103939. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103940. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103941. return;
  103942. }
  103943. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103944. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103945. return;
  103946. }
  103947. }
  103948. /*
  103949. * Write seektable
  103950. */
  103951. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103952. unsigned i;
  103953. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103954. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103955. 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) {
  103956. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103957. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103958. return;
  103959. }
  103960. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  103961. FLAC__uint64 xx;
  103962. unsigned x;
  103963. xx = encoder->private_->seek_table->points[i].sample_number;
  103964. b[7] = (FLAC__byte)xx; xx >>= 8;
  103965. b[6] = (FLAC__byte)xx; xx >>= 8;
  103966. b[5] = (FLAC__byte)xx; xx >>= 8;
  103967. b[4] = (FLAC__byte)xx; xx >>= 8;
  103968. b[3] = (FLAC__byte)xx; xx >>= 8;
  103969. b[2] = (FLAC__byte)xx; xx >>= 8;
  103970. b[1] = (FLAC__byte)xx; xx >>= 8;
  103971. b[0] = (FLAC__byte)xx; xx >>= 8;
  103972. xx = encoder->private_->seek_table->points[i].stream_offset;
  103973. b[15] = (FLAC__byte)xx; xx >>= 8;
  103974. b[14] = (FLAC__byte)xx; xx >>= 8;
  103975. b[13] = (FLAC__byte)xx; xx >>= 8;
  103976. b[12] = (FLAC__byte)xx; xx >>= 8;
  103977. b[11] = (FLAC__byte)xx; xx >>= 8;
  103978. b[10] = (FLAC__byte)xx; xx >>= 8;
  103979. b[9] = (FLAC__byte)xx; xx >>= 8;
  103980. b[8] = (FLAC__byte)xx; xx >>= 8;
  103981. x = encoder->private_->seek_table->points[i].frame_samples;
  103982. b[17] = (FLAC__byte)x; x >>= 8;
  103983. b[16] = (FLAC__byte)x; x >>= 8;
  103984. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103985. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103986. return;
  103987. }
  103988. }
  103989. }
  103990. }
  103991. #if FLAC__HAS_OGG
  103992. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103993. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  103994. {
  103995. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  103996. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  103997. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  103998. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  103999. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104000. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104001. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104002. FLAC__STREAM_SYNC_LENGTH
  104003. ;
  104004. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104005. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104006. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104007. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104008. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104009. ogg_page page;
  104010. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104011. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104012. /* Pre-check that client supports seeking, since we don't want the
  104013. * ogg_helper code to ever have to deal with this condition.
  104014. */
  104015. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104016. return;
  104017. /* All this is based on intimate knowledge of the stream header
  104018. * layout, but a change to the header format that would break this
  104019. * would also break all streams encoded in the previous format.
  104020. */
  104021. /**
  104022. ** Write STREAMINFO stats
  104023. **/
  104024. simple_ogg_page__init(&page);
  104025. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104026. simple_ogg_page__clear(&page);
  104027. return; /* state already set */
  104028. }
  104029. /*
  104030. * Write MD5 signature
  104031. */
  104032. {
  104033. const unsigned md5_offset =
  104034. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104035. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104036. (
  104037. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104038. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104039. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104040. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104041. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104042. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104043. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104044. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104045. ) / 8;
  104046. if(md5_offset + 16 > (unsigned)page.body_len) {
  104047. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104048. simple_ogg_page__clear(&page);
  104049. return;
  104050. }
  104051. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104052. }
  104053. /*
  104054. * Write total samples
  104055. */
  104056. {
  104057. const unsigned total_samples_byte_offset =
  104058. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104059. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104060. (
  104061. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104062. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104063. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104064. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104065. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104066. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104067. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104068. - 4
  104069. ) / 8;
  104070. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104071. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104072. simple_ogg_page__clear(&page);
  104073. return;
  104074. }
  104075. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104076. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104077. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104078. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104079. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104080. b[4] = (FLAC__byte)(samples & 0xFF);
  104081. memcpy(page.body + total_samples_byte_offset, b, 5);
  104082. }
  104083. /*
  104084. * Write min/max framesize
  104085. */
  104086. {
  104087. const unsigned min_framesize_offset =
  104088. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104089. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104090. (
  104091. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104092. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104093. ) / 8;
  104094. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104095. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104096. simple_ogg_page__clear(&page);
  104097. return;
  104098. }
  104099. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104100. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104101. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104102. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104103. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104104. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104105. memcpy(page.body + min_framesize_offset, b, 6);
  104106. }
  104107. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104108. simple_ogg_page__clear(&page);
  104109. return; /* state already set */
  104110. }
  104111. simple_ogg_page__clear(&page);
  104112. /*
  104113. * Write seektable
  104114. */
  104115. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104116. unsigned i;
  104117. FLAC__byte *p;
  104118. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104119. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104120. simple_ogg_page__init(&page);
  104121. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104122. simple_ogg_page__clear(&page);
  104123. return; /* state already set */
  104124. }
  104125. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104126. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104127. simple_ogg_page__clear(&page);
  104128. return;
  104129. }
  104130. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104131. FLAC__uint64 xx;
  104132. unsigned x;
  104133. xx = encoder->private_->seek_table->points[i].sample_number;
  104134. b[7] = (FLAC__byte)xx; xx >>= 8;
  104135. b[6] = (FLAC__byte)xx; xx >>= 8;
  104136. b[5] = (FLAC__byte)xx; xx >>= 8;
  104137. b[4] = (FLAC__byte)xx; xx >>= 8;
  104138. b[3] = (FLAC__byte)xx; xx >>= 8;
  104139. b[2] = (FLAC__byte)xx; xx >>= 8;
  104140. b[1] = (FLAC__byte)xx; xx >>= 8;
  104141. b[0] = (FLAC__byte)xx; xx >>= 8;
  104142. xx = encoder->private_->seek_table->points[i].stream_offset;
  104143. b[15] = (FLAC__byte)xx; xx >>= 8;
  104144. b[14] = (FLAC__byte)xx; xx >>= 8;
  104145. b[13] = (FLAC__byte)xx; xx >>= 8;
  104146. b[12] = (FLAC__byte)xx; xx >>= 8;
  104147. b[11] = (FLAC__byte)xx; xx >>= 8;
  104148. b[10] = (FLAC__byte)xx; xx >>= 8;
  104149. b[9] = (FLAC__byte)xx; xx >>= 8;
  104150. b[8] = (FLAC__byte)xx; xx >>= 8;
  104151. x = encoder->private_->seek_table->points[i].frame_samples;
  104152. b[17] = (FLAC__byte)x; x >>= 8;
  104153. b[16] = (FLAC__byte)x; x >>= 8;
  104154. memcpy(p, b, 18);
  104155. }
  104156. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104157. simple_ogg_page__clear(&page);
  104158. return; /* state already set */
  104159. }
  104160. simple_ogg_page__clear(&page);
  104161. }
  104162. }
  104163. #endif
  104164. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104165. {
  104166. FLAC__uint16 crc;
  104167. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104168. /*
  104169. * Accumulate raw signal to the MD5 signature
  104170. */
  104171. 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)) {
  104172. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104173. return false;
  104174. }
  104175. /*
  104176. * Process the frame header and subframes into the frame bitbuffer
  104177. */
  104178. if(!process_subframes_(encoder, is_fractional_block)) {
  104179. /* the above function sets the state for us in case of an error */
  104180. return false;
  104181. }
  104182. /*
  104183. * Zero-pad the frame to a byte_boundary
  104184. */
  104185. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104186. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104187. return false;
  104188. }
  104189. /*
  104190. * CRC-16 the whole thing
  104191. */
  104192. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104193. if(
  104194. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104195. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104196. ) {
  104197. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104198. return false;
  104199. }
  104200. /*
  104201. * Write it
  104202. */
  104203. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104204. /* the above function sets the state for us in case of an error */
  104205. return false;
  104206. }
  104207. /*
  104208. * Get ready for the next frame
  104209. */
  104210. encoder->private_->current_sample_number = 0;
  104211. encoder->private_->current_frame_number++;
  104212. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104213. return true;
  104214. }
  104215. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104216. {
  104217. FLAC__FrameHeader frame_header;
  104218. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104219. FLAC__bool do_independent, do_mid_side;
  104220. /*
  104221. * Calculate the min,max Rice partition orders
  104222. */
  104223. if(is_fractional_block) {
  104224. max_partition_order = 0;
  104225. }
  104226. else {
  104227. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104228. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104229. }
  104230. min_partition_order = min(min_partition_order, max_partition_order);
  104231. /*
  104232. * Setup the frame
  104233. */
  104234. frame_header.blocksize = encoder->protected_->blocksize;
  104235. frame_header.sample_rate = encoder->protected_->sample_rate;
  104236. frame_header.channels = encoder->protected_->channels;
  104237. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104238. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104239. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104240. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104241. /*
  104242. * Figure out what channel assignments to try
  104243. */
  104244. if(encoder->protected_->do_mid_side_stereo) {
  104245. if(encoder->protected_->loose_mid_side_stereo) {
  104246. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104247. do_independent = true;
  104248. do_mid_side = true;
  104249. }
  104250. else {
  104251. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104252. do_mid_side = !do_independent;
  104253. }
  104254. }
  104255. else {
  104256. do_independent = true;
  104257. do_mid_side = true;
  104258. }
  104259. }
  104260. else {
  104261. do_independent = true;
  104262. do_mid_side = false;
  104263. }
  104264. FLAC__ASSERT(do_independent || do_mid_side);
  104265. /*
  104266. * Check for wasted bits; set effective bps for each subframe
  104267. */
  104268. if(do_independent) {
  104269. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104270. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104271. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104272. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104273. }
  104274. }
  104275. if(do_mid_side) {
  104276. FLAC__ASSERT(encoder->protected_->channels == 2);
  104277. for(channel = 0; channel < 2; channel++) {
  104278. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104279. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104280. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104281. }
  104282. }
  104283. /*
  104284. * First do a normal encoding pass of each independent channel
  104285. */
  104286. if(do_independent) {
  104287. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104288. if(!
  104289. process_subframe_(
  104290. encoder,
  104291. min_partition_order,
  104292. max_partition_order,
  104293. &frame_header,
  104294. encoder->private_->subframe_bps[channel],
  104295. encoder->private_->integer_signal[channel],
  104296. encoder->private_->subframe_workspace_ptr[channel],
  104297. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104298. encoder->private_->residual_workspace[channel],
  104299. encoder->private_->best_subframe+channel,
  104300. encoder->private_->best_subframe_bits+channel
  104301. )
  104302. )
  104303. return false;
  104304. }
  104305. }
  104306. /*
  104307. * Now do mid and side channels if requested
  104308. */
  104309. if(do_mid_side) {
  104310. FLAC__ASSERT(encoder->protected_->channels == 2);
  104311. for(channel = 0; channel < 2; channel++) {
  104312. if(!
  104313. process_subframe_(
  104314. encoder,
  104315. min_partition_order,
  104316. max_partition_order,
  104317. &frame_header,
  104318. encoder->private_->subframe_bps_mid_side[channel],
  104319. encoder->private_->integer_signal_mid_side[channel],
  104320. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104321. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104322. encoder->private_->residual_workspace_mid_side[channel],
  104323. encoder->private_->best_subframe_mid_side+channel,
  104324. encoder->private_->best_subframe_bits_mid_side+channel
  104325. )
  104326. )
  104327. return false;
  104328. }
  104329. }
  104330. /*
  104331. * Compose the frame bitbuffer
  104332. */
  104333. if(do_mid_side) {
  104334. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104335. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104336. FLAC__ChannelAssignment channel_assignment;
  104337. FLAC__ASSERT(encoder->protected_->channels == 2);
  104338. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104339. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104340. }
  104341. else {
  104342. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104343. unsigned min_bits;
  104344. int ca;
  104345. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104346. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104347. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104348. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104349. FLAC__ASSERT(do_independent && do_mid_side);
  104350. /* We have to figure out which channel assignent results in the smallest frame */
  104351. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104352. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104353. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104354. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104355. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104356. min_bits = bits[channel_assignment];
  104357. for(ca = 1; ca <= 3; ca++) {
  104358. if(bits[ca] < min_bits) {
  104359. min_bits = bits[ca];
  104360. channel_assignment = (FLAC__ChannelAssignment)ca;
  104361. }
  104362. }
  104363. }
  104364. frame_header.channel_assignment = channel_assignment;
  104365. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104366. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104367. return false;
  104368. }
  104369. switch(channel_assignment) {
  104370. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104371. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104372. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104373. break;
  104374. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104375. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104376. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104377. break;
  104378. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104379. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104380. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104381. break;
  104382. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104383. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104384. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104385. break;
  104386. default:
  104387. FLAC__ASSERT(0);
  104388. }
  104389. switch(channel_assignment) {
  104390. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104391. left_bps = encoder->private_->subframe_bps [0];
  104392. right_bps = encoder->private_->subframe_bps [1];
  104393. break;
  104394. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104395. left_bps = encoder->private_->subframe_bps [0];
  104396. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104397. break;
  104398. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104399. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104400. right_bps = encoder->private_->subframe_bps [1];
  104401. break;
  104402. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104403. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104404. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104405. break;
  104406. default:
  104407. FLAC__ASSERT(0);
  104408. }
  104409. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104410. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104411. return false;
  104412. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104413. return false;
  104414. }
  104415. else {
  104416. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104417. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104418. return false;
  104419. }
  104420. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104421. 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)) {
  104422. /* the above function sets the state for us in case of an error */
  104423. return false;
  104424. }
  104425. }
  104426. }
  104427. if(encoder->protected_->loose_mid_side_stereo) {
  104428. encoder->private_->loose_mid_side_stereo_frame_count++;
  104429. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104430. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104431. }
  104432. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104433. return true;
  104434. }
  104435. FLAC__bool process_subframe_(
  104436. FLAC__StreamEncoder *encoder,
  104437. unsigned min_partition_order,
  104438. unsigned max_partition_order,
  104439. const FLAC__FrameHeader *frame_header,
  104440. unsigned subframe_bps,
  104441. const FLAC__int32 integer_signal[],
  104442. FLAC__Subframe *subframe[2],
  104443. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104444. FLAC__int32 *residual[2],
  104445. unsigned *best_subframe,
  104446. unsigned *best_bits
  104447. )
  104448. {
  104449. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104450. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104451. #else
  104452. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104453. #endif
  104454. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104455. FLAC__double lpc_residual_bits_per_sample;
  104456. 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 */
  104457. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104458. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104459. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104460. #endif
  104461. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104462. unsigned rice_parameter;
  104463. unsigned _candidate_bits, _best_bits;
  104464. unsigned _best_subframe;
  104465. /* only use RICE2 partitions if stream bps > 16 */
  104466. 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;
  104467. FLAC__ASSERT(frame_header->blocksize > 0);
  104468. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104469. _best_subframe = 0;
  104470. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104471. _best_bits = UINT_MAX;
  104472. else
  104473. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104474. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104475. unsigned signal_is_constant = false;
  104476. 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);
  104477. /* check for constant subframe */
  104478. if(
  104479. !encoder->private_->disable_constant_subframes &&
  104480. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104481. fixed_residual_bits_per_sample[1] == 0.0
  104482. #else
  104483. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104484. #endif
  104485. ) {
  104486. /* the above means it's possible all samples are the same value; now double-check it: */
  104487. unsigned i;
  104488. signal_is_constant = true;
  104489. for(i = 1; i < frame_header->blocksize; i++) {
  104490. if(integer_signal[0] != integer_signal[i]) {
  104491. signal_is_constant = false;
  104492. break;
  104493. }
  104494. }
  104495. }
  104496. if(signal_is_constant) {
  104497. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104498. if(_candidate_bits < _best_bits) {
  104499. _best_subframe = !_best_subframe;
  104500. _best_bits = _candidate_bits;
  104501. }
  104502. }
  104503. else {
  104504. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104505. /* encode fixed */
  104506. if(encoder->protected_->do_exhaustive_model_search) {
  104507. min_fixed_order = 0;
  104508. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104509. }
  104510. else {
  104511. min_fixed_order = max_fixed_order = guess_fixed_order;
  104512. }
  104513. if(max_fixed_order >= frame_header->blocksize)
  104514. max_fixed_order = frame_header->blocksize - 1;
  104515. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104516. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104517. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104518. continue; /* don't even try */
  104519. 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 */
  104520. #else
  104521. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104522. continue; /* don't even try */
  104523. 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 */
  104524. #endif
  104525. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104526. if(rice_parameter >= rice_parameter_limit) {
  104527. #ifdef DEBUG_VERBOSE
  104528. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104529. #endif
  104530. rice_parameter = rice_parameter_limit - 1;
  104531. }
  104532. _candidate_bits =
  104533. evaluate_fixed_subframe_(
  104534. encoder,
  104535. integer_signal,
  104536. residual[!_best_subframe],
  104537. encoder->private_->abs_residual_partition_sums,
  104538. encoder->private_->raw_bits_per_partition,
  104539. frame_header->blocksize,
  104540. subframe_bps,
  104541. fixed_order,
  104542. rice_parameter,
  104543. rice_parameter_limit,
  104544. min_partition_order,
  104545. max_partition_order,
  104546. encoder->protected_->do_escape_coding,
  104547. encoder->protected_->rice_parameter_search_dist,
  104548. subframe[!_best_subframe],
  104549. partitioned_rice_contents[!_best_subframe]
  104550. );
  104551. if(_candidate_bits < _best_bits) {
  104552. _best_subframe = !_best_subframe;
  104553. _best_bits = _candidate_bits;
  104554. }
  104555. }
  104556. }
  104557. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104558. /* encode lpc */
  104559. if(encoder->protected_->max_lpc_order > 0) {
  104560. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104561. max_lpc_order = frame_header->blocksize-1;
  104562. else
  104563. max_lpc_order = encoder->protected_->max_lpc_order;
  104564. if(max_lpc_order > 0) {
  104565. unsigned a;
  104566. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104567. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104568. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104569. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104570. if(autoc[0] != 0.0) {
  104571. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104572. if(encoder->protected_->do_exhaustive_model_search) {
  104573. min_lpc_order = 1;
  104574. }
  104575. else {
  104576. const unsigned guess_lpc_order =
  104577. FLAC__lpc_compute_best_order(
  104578. lpc_error,
  104579. max_lpc_order,
  104580. frame_header->blocksize,
  104581. subframe_bps + (
  104582. encoder->protected_->do_qlp_coeff_prec_search?
  104583. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104584. encoder->protected_->qlp_coeff_precision
  104585. )
  104586. );
  104587. min_lpc_order = max_lpc_order = guess_lpc_order;
  104588. }
  104589. if(max_lpc_order >= frame_header->blocksize)
  104590. max_lpc_order = frame_header->blocksize - 1;
  104591. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104592. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104593. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104594. continue; /* don't even try */
  104595. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104596. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104597. if(rice_parameter >= rice_parameter_limit) {
  104598. #ifdef DEBUG_VERBOSE
  104599. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104600. #endif
  104601. rice_parameter = rice_parameter_limit - 1;
  104602. }
  104603. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104604. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104605. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104606. if(subframe_bps <= 17) {
  104607. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104608. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104609. }
  104610. else
  104611. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104612. }
  104613. else {
  104614. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104615. }
  104616. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104617. _candidate_bits =
  104618. evaluate_lpc_subframe_(
  104619. encoder,
  104620. integer_signal,
  104621. residual[!_best_subframe],
  104622. encoder->private_->abs_residual_partition_sums,
  104623. encoder->private_->raw_bits_per_partition,
  104624. encoder->private_->lp_coeff[lpc_order-1],
  104625. frame_header->blocksize,
  104626. subframe_bps,
  104627. lpc_order,
  104628. qlp_coeff_precision,
  104629. rice_parameter,
  104630. rice_parameter_limit,
  104631. min_partition_order,
  104632. max_partition_order,
  104633. encoder->protected_->do_escape_coding,
  104634. encoder->protected_->rice_parameter_search_dist,
  104635. subframe[!_best_subframe],
  104636. partitioned_rice_contents[!_best_subframe]
  104637. );
  104638. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104639. if(_candidate_bits < _best_bits) {
  104640. _best_subframe = !_best_subframe;
  104641. _best_bits = _candidate_bits;
  104642. }
  104643. }
  104644. }
  104645. }
  104646. }
  104647. }
  104648. }
  104649. }
  104650. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104651. }
  104652. }
  104653. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104654. if(_best_bits == UINT_MAX) {
  104655. FLAC__ASSERT(_best_subframe == 0);
  104656. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104657. }
  104658. *best_subframe = _best_subframe;
  104659. *best_bits = _best_bits;
  104660. return true;
  104661. }
  104662. FLAC__bool add_subframe_(
  104663. FLAC__StreamEncoder *encoder,
  104664. unsigned blocksize,
  104665. unsigned subframe_bps,
  104666. const FLAC__Subframe *subframe,
  104667. FLAC__BitWriter *frame
  104668. )
  104669. {
  104670. switch(subframe->type) {
  104671. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104672. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104673. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104674. return false;
  104675. }
  104676. break;
  104677. case FLAC__SUBFRAME_TYPE_FIXED:
  104678. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104679. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104680. return false;
  104681. }
  104682. break;
  104683. case FLAC__SUBFRAME_TYPE_LPC:
  104684. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104685. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104686. return false;
  104687. }
  104688. break;
  104689. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104690. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104691. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104692. return false;
  104693. }
  104694. break;
  104695. default:
  104696. FLAC__ASSERT(0);
  104697. }
  104698. return true;
  104699. }
  104700. #define SPOTCHECK_ESTIMATE 0
  104701. #if SPOTCHECK_ESTIMATE
  104702. static void spotcheck_subframe_estimate_(
  104703. FLAC__StreamEncoder *encoder,
  104704. unsigned blocksize,
  104705. unsigned subframe_bps,
  104706. const FLAC__Subframe *subframe,
  104707. unsigned estimate
  104708. )
  104709. {
  104710. FLAC__bool ret;
  104711. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104712. if(frame == 0) {
  104713. fprintf(stderr, "EST: can't allocate frame\n");
  104714. return;
  104715. }
  104716. if(!FLAC__bitwriter_init(frame)) {
  104717. fprintf(stderr, "EST: can't init frame\n");
  104718. return;
  104719. }
  104720. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104721. FLAC__ASSERT(ret);
  104722. {
  104723. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104724. if(estimate != actual)
  104725. 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);
  104726. }
  104727. FLAC__bitwriter_delete(frame);
  104728. }
  104729. #endif
  104730. unsigned evaluate_constant_subframe_(
  104731. FLAC__StreamEncoder *encoder,
  104732. const FLAC__int32 signal,
  104733. unsigned blocksize,
  104734. unsigned subframe_bps,
  104735. FLAC__Subframe *subframe
  104736. )
  104737. {
  104738. unsigned estimate;
  104739. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104740. subframe->data.constant.value = signal;
  104741. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104742. #if SPOTCHECK_ESTIMATE
  104743. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104744. #else
  104745. (void)encoder, (void)blocksize;
  104746. #endif
  104747. return estimate;
  104748. }
  104749. unsigned evaluate_fixed_subframe_(
  104750. FLAC__StreamEncoder *encoder,
  104751. const FLAC__int32 signal[],
  104752. FLAC__int32 residual[],
  104753. FLAC__uint64 abs_residual_partition_sums[],
  104754. unsigned raw_bits_per_partition[],
  104755. unsigned blocksize,
  104756. unsigned subframe_bps,
  104757. unsigned order,
  104758. unsigned rice_parameter,
  104759. unsigned rice_parameter_limit,
  104760. unsigned min_partition_order,
  104761. unsigned max_partition_order,
  104762. FLAC__bool do_escape_coding,
  104763. unsigned rice_parameter_search_dist,
  104764. FLAC__Subframe *subframe,
  104765. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104766. )
  104767. {
  104768. unsigned i, residual_bits, estimate;
  104769. const unsigned residual_samples = blocksize - order;
  104770. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104771. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104772. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104773. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104774. subframe->data.fixed.residual = residual;
  104775. residual_bits =
  104776. find_best_partition_order_(
  104777. encoder->private_,
  104778. residual,
  104779. abs_residual_partition_sums,
  104780. raw_bits_per_partition,
  104781. residual_samples,
  104782. order,
  104783. rice_parameter,
  104784. rice_parameter_limit,
  104785. min_partition_order,
  104786. max_partition_order,
  104787. subframe_bps,
  104788. do_escape_coding,
  104789. rice_parameter_search_dist,
  104790. &subframe->data.fixed.entropy_coding_method
  104791. );
  104792. subframe->data.fixed.order = order;
  104793. for(i = 0; i < order; i++)
  104794. subframe->data.fixed.warmup[i] = signal[i];
  104795. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  104796. #if SPOTCHECK_ESTIMATE
  104797. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104798. #endif
  104799. return estimate;
  104800. }
  104801. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104802. unsigned evaluate_lpc_subframe_(
  104803. FLAC__StreamEncoder *encoder,
  104804. const FLAC__int32 signal[],
  104805. FLAC__int32 residual[],
  104806. FLAC__uint64 abs_residual_partition_sums[],
  104807. unsigned raw_bits_per_partition[],
  104808. const FLAC__real lp_coeff[],
  104809. unsigned blocksize,
  104810. unsigned subframe_bps,
  104811. unsigned order,
  104812. unsigned qlp_coeff_precision,
  104813. unsigned rice_parameter,
  104814. unsigned rice_parameter_limit,
  104815. unsigned min_partition_order,
  104816. unsigned max_partition_order,
  104817. FLAC__bool do_escape_coding,
  104818. unsigned rice_parameter_search_dist,
  104819. FLAC__Subframe *subframe,
  104820. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104821. )
  104822. {
  104823. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  104824. unsigned i, residual_bits, estimate;
  104825. int quantization, ret;
  104826. const unsigned residual_samples = blocksize - order;
  104827. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  104828. if(subframe_bps <= 16) {
  104829. FLAC__ASSERT(order > 0);
  104830. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  104831. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  104832. }
  104833. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  104834. if(ret != 0)
  104835. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  104836. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  104837. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  104838. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104839. else
  104840. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104841. else
  104842. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104843. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  104844. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104845. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104846. subframe->data.lpc.residual = residual;
  104847. residual_bits =
  104848. find_best_partition_order_(
  104849. encoder->private_,
  104850. residual,
  104851. abs_residual_partition_sums,
  104852. raw_bits_per_partition,
  104853. residual_samples,
  104854. order,
  104855. rice_parameter,
  104856. rice_parameter_limit,
  104857. min_partition_order,
  104858. max_partition_order,
  104859. subframe_bps,
  104860. do_escape_coding,
  104861. rice_parameter_search_dist,
  104862. &subframe->data.lpc.entropy_coding_method
  104863. );
  104864. subframe->data.lpc.order = order;
  104865. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  104866. subframe->data.lpc.quantization_level = quantization;
  104867. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  104868. for(i = 0; i < order; i++)
  104869. subframe->data.lpc.warmup[i] = signal[i];
  104870. 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;
  104871. #if SPOTCHECK_ESTIMATE
  104872. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104873. #endif
  104874. return estimate;
  104875. }
  104876. #endif
  104877. unsigned evaluate_verbatim_subframe_(
  104878. FLAC__StreamEncoder *encoder,
  104879. const FLAC__int32 signal[],
  104880. unsigned blocksize,
  104881. unsigned subframe_bps,
  104882. FLAC__Subframe *subframe
  104883. )
  104884. {
  104885. unsigned estimate;
  104886. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  104887. subframe->data.verbatim.data = signal;
  104888. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  104889. #if SPOTCHECK_ESTIMATE
  104890. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104891. #else
  104892. (void)encoder;
  104893. #endif
  104894. return estimate;
  104895. }
  104896. unsigned find_best_partition_order_(
  104897. FLAC__StreamEncoderPrivate *private_,
  104898. const FLAC__int32 residual[],
  104899. FLAC__uint64 abs_residual_partition_sums[],
  104900. unsigned raw_bits_per_partition[],
  104901. unsigned residual_samples,
  104902. unsigned predictor_order,
  104903. unsigned rice_parameter,
  104904. unsigned rice_parameter_limit,
  104905. unsigned min_partition_order,
  104906. unsigned max_partition_order,
  104907. unsigned bps,
  104908. FLAC__bool do_escape_coding,
  104909. unsigned rice_parameter_search_dist,
  104910. FLAC__EntropyCodingMethod *best_ecm
  104911. )
  104912. {
  104913. unsigned residual_bits, best_residual_bits = 0;
  104914. unsigned best_parameters_index = 0;
  104915. unsigned best_partition_order = 0;
  104916. const unsigned blocksize = residual_samples + predictor_order;
  104917. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  104918. min_partition_order = min(min_partition_order, max_partition_order);
  104919. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  104920. if(do_escape_coding)
  104921. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  104922. {
  104923. int partition_order;
  104924. unsigned sum;
  104925. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  104926. if(!
  104927. set_partitioned_rice_(
  104928. #ifdef EXACT_RICE_BITS_CALCULATION
  104929. residual,
  104930. #endif
  104931. abs_residual_partition_sums+sum,
  104932. raw_bits_per_partition+sum,
  104933. residual_samples,
  104934. predictor_order,
  104935. rice_parameter,
  104936. rice_parameter_limit,
  104937. rice_parameter_search_dist,
  104938. (unsigned)partition_order,
  104939. do_escape_coding,
  104940. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  104941. &residual_bits
  104942. )
  104943. )
  104944. {
  104945. FLAC__ASSERT(best_residual_bits != 0);
  104946. break;
  104947. }
  104948. sum += 1u << partition_order;
  104949. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  104950. best_residual_bits = residual_bits;
  104951. best_parameters_index = !best_parameters_index;
  104952. best_partition_order = partition_order;
  104953. }
  104954. }
  104955. }
  104956. best_ecm->data.partitioned_rice.order = best_partition_order;
  104957. {
  104958. /*
  104959. * We are allowed to de-const the pointer based on our special
  104960. * knowledge; it is const to the outside world.
  104961. */
  104962. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  104963. unsigned partition;
  104964. /* save best parameters and raw_bits */
  104965. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  104966. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  104967. if(do_escape_coding)
  104968. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  104969. /*
  104970. * Now need to check if the type should be changed to
  104971. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  104972. * size of the rice parameters.
  104973. */
  104974. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  104975. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  104976. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  104977. break;
  104978. }
  104979. }
  104980. }
  104981. return best_residual_bits;
  104982. }
  104983. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104984. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  104985. const FLAC__int32 residual[],
  104986. FLAC__uint64 abs_residual_partition_sums[],
  104987. unsigned blocksize,
  104988. unsigned predictor_order,
  104989. unsigned min_partition_order,
  104990. unsigned max_partition_order
  104991. );
  104992. #endif
  104993. void precompute_partition_info_sums_(
  104994. const FLAC__int32 residual[],
  104995. FLAC__uint64 abs_residual_partition_sums[],
  104996. unsigned residual_samples,
  104997. unsigned predictor_order,
  104998. unsigned min_partition_order,
  104999. unsigned max_partition_order,
  105000. unsigned bps
  105001. )
  105002. {
  105003. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105004. unsigned partitions = 1u << max_partition_order;
  105005. FLAC__ASSERT(default_partition_samples > predictor_order);
  105006. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105007. /* slightly pessimistic but still catches all common cases */
  105008. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105009. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105010. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105011. return;
  105012. }
  105013. #endif
  105014. /* first do max_partition_order */
  105015. {
  105016. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105017. /* slightly pessimistic but still catches all common cases */
  105018. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105019. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105020. FLAC__uint32 abs_residual_partition_sum;
  105021. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105022. end += default_partition_samples;
  105023. abs_residual_partition_sum = 0;
  105024. for( ; residual_sample < end; residual_sample++)
  105025. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105026. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105027. }
  105028. }
  105029. else { /* have to pessimistically use 64 bits for accumulator */
  105030. FLAC__uint64 abs_residual_partition_sum;
  105031. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105032. end += default_partition_samples;
  105033. abs_residual_partition_sum = 0;
  105034. for( ; residual_sample < end; residual_sample++)
  105035. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105036. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105037. }
  105038. }
  105039. }
  105040. /* now merge partitions for lower orders */
  105041. {
  105042. unsigned from_partition = 0, to_partition = partitions;
  105043. int partition_order;
  105044. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105045. unsigned i;
  105046. partitions >>= 1;
  105047. for(i = 0; i < partitions; i++) {
  105048. abs_residual_partition_sums[to_partition++] =
  105049. abs_residual_partition_sums[from_partition ] +
  105050. abs_residual_partition_sums[from_partition+1];
  105051. from_partition += 2;
  105052. }
  105053. }
  105054. }
  105055. }
  105056. void precompute_partition_info_escapes_(
  105057. const FLAC__int32 residual[],
  105058. unsigned raw_bits_per_partition[],
  105059. unsigned residual_samples,
  105060. unsigned predictor_order,
  105061. unsigned min_partition_order,
  105062. unsigned max_partition_order
  105063. )
  105064. {
  105065. int partition_order;
  105066. unsigned from_partition, to_partition = 0;
  105067. const unsigned blocksize = residual_samples + predictor_order;
  105068. /* first do max_partition_order */
  105069. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105070. FLAC__int32 r;
  105071. FLAC__uint32 rmax;
  105072. unsigned partition, partition_sample, partition_samples, residual_sample;
  105073. const unsigned partitions = 1u << partition_order;
  105074. const unsigned default_partition_samples = blocksize >> partition_order;
  105075. FLAC__ASSERT(default_partition_samples > predictor_order);
  105076. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105077. partition_samples = default_partition_samples;
  105078. if(partition == 0)
  105079. partition_samples -= predictor_order;
  105080. rmax = 0;
  105081. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105082. r = residual[residual_sample++];
  105083. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105084. if(r < 0)
  105085. rmax |= ~r;
  105086. else
  105087. rmax |= r;
  105088. }
  105089. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105090. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105091. }
  105092. to_partition = partitions;
  105093. break; /*@@@ yuck, should remove the 'for' loop instead */
  105094. }
  105095. /* now merge partitions for lower orders */
  105096. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105097. unsigned m;
  105098. unsigned i;
  105099. const unsigned partitions = 1u << partition_order;
  105100. for(i = 0; i < partitions; i++) {
  105101. m = raw_bits_per_partition[from_partition];
  105102. from_partition++;
  105103. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105104. from_partition++;
  105105. to_partition++;
  105106. }
  105107. }
  105108. }
  105109. #ifdef EXACT_RICE_BITS_CALCULATION
  105110. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105111. const unsigned rice_parameter,
  105112. const unsigned partition_samples,
  105113. const FLAC__int32 *residual
  105114. )
  105115. {
  105116. unsigned i, partition_bits =
  105117. 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 */
  105118. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105119. ;
  105120. for(i = 0; i < partition_samples; i++)
  105121. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105122. return partition_bits;
  105123. }
  105124. #else
  105125. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105126. const unsigned rice_parameter,
  105127. const unsigned partition_samples,
  105128. const FLAC__uint64 abs_residual_partition_sum
  105129. )
  105130. {
  105131. return
  105132. 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 */
  105133. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105134. (
  105135. rice_parameter?
  105136. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105137. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105138. )
  105139. - (partition_samples >> 1)
  105140. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105141. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105142. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105143. * So the subtraction term tries to guess how many extra bits were contributed.
  105144. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105145. */
  105146. ;
  105147. }
  105148. #endif
  105149. FLAC__bool set_partitioned_rice_(
  105150. #ifdef EXACT_RICE_BITS_CALCULATION
  105151. const FLAC__int32 residual[],
  105152. #endif
  105153. const FLAC__uint64 abs_residual_partition_sums[],
  105154. const unsigned raw_bits_per_partition[],
  105155. const unsigned residual_samples,
  105156. const unsigned predictor_order,
  105157. const unsigned suggested_rice_parameter,
  105158. const unsigned rice_parameter_limit,
  105159. const unsigned rice_parameter_search_dist,
  105160. const unsigned partition_order,
  105161. const FLAC__bool search_for_escapes,
  105162. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105163. unsigned *bits
  105164. )
  105165. {
  105166. unsigned rice_parameter, partition_bits;
  105167. unsigned best_partition_bits, best_rice_parameter = 0;
  105168. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105169. unsigned *parameters, *raw_bits;
  105170. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105171. unsigned min_rice_parameter, max_rice_parameter;
  105172. #else
  105173. (void)rice_parameter_search_dist;
  105174. #endif
  105175. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105176. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105177. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105178. parameters = partitioned_rice_contents->parameters;
  105179. raw_bits = partitioned_rice_contents->raw_bits;
  105180. if(partition_order == 0) {
  105181. best_partition_bits = (unsigned)(-1);
  105182. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105183. if(rice_parameter_search_dist) {
  105184. if(suggested_rice_parameter < rice_parameter_search_dist)
  105185. min_rice_parameter = 0;
  105186. else
  105187. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105188. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105189. if(max_rice_parameter >= rice_parameter_limit) {
  105190. #ifdef DEBUG_VERBOSE
  105191. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105192. #endif
  105193. max_rice_parameter = rice_parameter_limit - 1;
  105194. }
  105195. }
  105196. else
  105197. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105198. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105199. #else
  105200. rice_parameter = suggested_rice_parameter;
  105201. #endif
  105202. #ifdef EXACT_RICE_BITS_CALCULATION
  105203. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105204. #else
  105205. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105206. #endif
  105207. if(partition_bits < best_partition_bits) {
  105208. best_rice_parameter = rice_parameter;
  105209. best_partition_bits = partition_bits;
  105210. }
  105211. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105212. }
  105213. #endif
  105214. if(search_for_escapes) {
  105215. 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;
  105216. if(partition_bits <= best_partition_bits) {
  105217. raw_bits[0] = raw_bits_per_partition[0];
  105218. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105219. best_partition_bits = partition_bits;
  105220. }
  105221. else
  105222. raw_bits[0] = 0;
  105223. }
  105224. parameters[0] = best_rice_parameter;
  105225. bits_ += best_partition_bits;
  105226. }
  105227. else {
  105228. unsigned partition, residual_sample;
  105229. unsigned partition_samples;
  105230. FLAC__uint64 mean, k;
  105231. const unsigned partitions = 1u << partition_order;
  105232. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105233. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105234. if(partition == 0) {
  105235. if(partition_samples <= predictor_order)
  105236. return false;
  105237. else
  105238. partition_samples -= predictor_order;
  105239. }
  105240. mean = abs_residual_partition_sums[partition];
  105241. /* we are basically calculating the size in bits of the
  105242. * average residual magnitude in the partition:
  105243. * rice_parameter = floor(log2(mean/partition_samples))
  105244. * 'mean' is not a good name for the variable, it is
  105245. * actually the sum of magnitudes of all residual values
  105246. * in the partition, so the actual mean is
  105247. * mean/partition_samples
  105248. */
  105249. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105250. ;
  105251. if(rice_parameter >= rice_parameter_limit) {
  105252. #ifdef DEBUG_VERBOSE
  105253. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105254. #endif
  105255. rice_parameter = rice_parameter_limit - 1;
  105256. }
  105257. best_partition_bits = (unsigned)(-1);
  105258. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105259. if(rice_parameter_search_dist) {
  105260. if(rice_parameter < rice_parameter_search_dist)
  105261. min_rice_parameter = 0;
  105262. else
  105263. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105264. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105265. if(max_rice_parameter >= rice_parameter_limit) {
  105266. #ifdef DEBUG_VERBOSE
  105267. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105268. #endif
  105269. max_rice_parameter = rice_parameter_limit - 1;
  105270. }
  105271. }
  105272. else
  105273. min_rice_parameter = max_rice_parameter = rice_parameter;
  105274. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105275. #endif
  105276. #ifdef EXACT_RICE_BITS_CALCULATION
  105277. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105278. #else
  105279. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105280. #endif
  105281. if(partition_bits < best_partition_bits) {
  105282. best_rice_parameter = rice_parameter;
  105283. best_partition_bits = partition_bits;
  105284. }
  105285. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105286. }
  105287. #endif
  105288. if(search_for_escapes) {
  105289. 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;
  105290. if(partition_bits <= best_partition_bits) {
  105291. raw_bits[partition] = raw_bits_per_partition[partition];
  105292. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105293. best_partition_bits = partition_bits;
  105294. }
  105295. else
  105296. raw_bits[partition] = 0;
  105297. }
  105298. parameters[partition] = best_rice_parameter;
  105299. bits_ += best_partition_bits;
  105300. residual_sample += partition_samples;
  105301. }
  105302. }
  105303. *bits = bits_;
  105304. return true;
  105305. }
  105306. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105307. {
  105308. unsigned i, shift;
  105309. FLAC__int32 x = 0;
  105310. for(i = 0; i < samples && !(x&1); i++)
  105311. x |= signal[i];
  105312. if(x == 0) {
  105313. shift = 0;
  105314. }
  105315. else {
  105316. for(shift = 0; !(x&1); shift++)
  105317. x >>= 1;
  105318. }
  105319. if(shift > 0) {
  105320. for(i = 0; i < samples; i++)
  105321. signal[i] >>= shift;
  105322. }
  105323. return shift;
  105324. }
  105325. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105326. {
  105327. unsigned channel;
  105328. for(channel = 0; channel < channels; channel++)
  105329. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105330. fifo->tail += wide_samples;
  105331. FLAC__ASSERT(fifo->tail <= fifo->size);
  105332. }
  105333. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105334. {
  105335. unsigned channel;
  105336. unsigned sample, wide_sample;
  105337. unsigned tail = fifo->tail;
  105338. sample = input_offset * channels;
  105339. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105340. for(channel = 0; channel < channels; channel++)
  105341. fifo->data[channel][tail] = input[sample++];
  105342. tail++;
  105343. }
  105344. fifo->tail = tail;
  105345. FLAC__ASSERT(fifo->tail <= fifo->size);
  105346. }
  105347. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105348. {
  105349. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105350. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105351. (void)decoder;
  105352. if(encoder->private_->verify.needs_magic_hack) {
  105353. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105354. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105355. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105356. encoder->private_->verify.needs_magic_hack = false;
  105357. }
  105358. else {
  105359. if(encoded_bytes == 0) {
  105360. /*
  105361. * If we get here, a FIFO underflow has occurred,
  105362. * which means there is a bug somewhere.
  105363. */
  105364. FLAC__ASSERT(0);
  105365. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105366. }
  105367. else if(encoded_bytes < *bytes)
  105368. *bytes = encoded_bytes;
  105369. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105370. encoder->private_->verify.output.data += *bytes;
  105371. encoder->private_->verify.output.bytes -= *bytes;
  105372. }
  105373. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105374. }
  105375. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105376. {
  105377. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105378. unsigned channel;
  105379. const unsigned channels = frame->header.channels;
  105380. const unsigned blocksize = frame->header.blocksize;
  105381. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105382. (void)decoder;
  105383. for(channel = 0; channel < channels; channel++) {
  105384. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105385. unsigned i, sample = 0;
  105386. FLAC__int32 expect = 0, got = 0;
  105387. for(i = 0; i < blocksize; i++) {
  105388. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105389. sample = i;
  105390. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105391. got = (FLAC__int32)buffer[channel][i];
  105392. break;
  105393. }
  105394. }
  105395. FLAC__ASSERT(i < blocksize);
  105396. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105397. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105398. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105399. encoder->private_->verify.error_stats.channel = channel;
  105400. encoder->private_->verify.error_stats.sample = sample;
  105401. encoder->private_->verify.error_stats.expected = expect;
  105402. encoder->private_->verify.error_stats.got = got;
  105403. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105404. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105405. }
  105406. }
  105407. /* dequeue the frame from the fifo */
  105408. encoder->private_->verify.input_fifo.tail -= blocksize;
  105409. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105410. for(channel = 0; channel < channels; channel++)
  105411. 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]));
  105412. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105413. }
  105414. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105415. {
  105416. (void)decoder, (void)metadata, (void)client_data;
  105417. }
  105418. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105419. {
  105420. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105421. (void)decoder, (void)status;
  105422. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105423. }
  105424. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105425. {
  105426. (void)client_data;
  105427. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105428. if (*bytes == 0) {
  105429. if (feof(encoder->private_->file))
  105430. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105431. else if (ferror(encoder->private_->file))
  105432. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105433. }
  105434. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105435. }
  105436. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105437. {
  105438. (void)client_data;
  105439. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105440. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105441. else
  105442. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105443. }
  105444. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105445. {
  105446. off_t offset;
  105447. (void)client_data;
  105448. offset = ftello(encoder->private_->file);
  105449. if(offset < 0) {
  105450. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105451. }
  105452. else {
  105453. *absolute_byte_offset = (FLAC__uint64)offset;
  105454. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105455. }
  105456. }
  105457. #ifdef FLAC__VALGRIND_TESTING
  105458. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105459. {
  105460. size_t ret = fwrite(ptr, size, nmemb, stream);
  105461. if(!ferror(stream))
  105462. fflush(stream);
  105463. return ret;
  105464. }
  105465. #else
  105466. #define local__fwrite fwrite
  105467. #endif
  105468. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105469. {
  105470. (void)client_data, (void)current_frame;
  105471. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105472. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105473. #if FLAC__HAS_OGG
  105474. /* We would like to be able to use 'samples > 0' in the
  105475. * clause here but currently because of the nature of our
  105476. * Ogg writing implementation, 'samples' is always 0 (see
  105477. * ogg_encoder_aspect.c). The downside is extra progress
  105478. * callbacks.
  105479. */
  105480. encoder->private_->is_ogg? true :
  105481. #endif
  105482. samples > 0
  105483. );
  105484. if(call_it) {
  105485. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105486. * because at this point in the callback chain, the stats
  105487. * have not been updated. Only after we return and control
  105488. * gets back to write_frame_() are the stats updated
  105489. */
  105490. 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);
  105491. }
  105492. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105493. }
  105494. else
  105495. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105496. }
  105497. /*
  105498. * This will forcibly set stdout to binary mode (for OSes that require it)
  105499. */
  105500. FILE *get_binary_stdout_(void)
  105501. {
  105502. /* if something breaks here it is probably due to the presence or
  105503. * absence of an underscore before the identifiers 'setmode',
  105504. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105505. */
  105506. #if defined _MSC_VER || defined __MINGW32__
  105507. _setmode(_fileno(stdout), _O_BINARY);
  105508. #elif defined __CYGWIN__
  105509. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105510. setmode(_fileno(stdout), _O_BINARY);
  105511. #elif defined __EMX__
  105512. setmode(fileno(stdout), O_BINARY);
  105513. #endif
  105514. return stdout;
  105515. }
  105516. #endif
  105517. /*** End of inlined file: stream_encoder.c ***/
  105518. /*** Start of inlined file: stream_encoder_framing.c ***/
  105519. /*** Start of inlined file: juce_FlacHeader.h ***/
  105520. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105521. // tasks..
  105522. #define VERSION "1.2.1"
  105523. #define FLAC__NO_DLL 1
  105524. #if JUCE_MSVC
  105525. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105526. #endif
  105527. #if JUCE_MAC
  105528. #define FLAC__SYS_DARWIN 1
  105529. #endif
  105530. /*** End of inlined file: juce_FlacHeader.h ***/
  105531. #if JUCE_USE_FLAC
  105532. #if HAVE_CONFIG_H
  105533. # include <config.h>
  105534. #endif
  105535. #include <stdio.h>
  105536. #include <string.h> /* for strlen() */
  105537. #ifdef max
  105538. #undef max
  105539. #endif
  105540. #define max(x,y) ((x)>(y)?(x):(y))
  105541. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105542. 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);
  105543. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105544. {
  105545. unsigned i, j;
  105546. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105547. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105548. return false;
  105549. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105550. return false;
  105551. /*
  105552. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105553. */
  105554. i = metadata->length;
  105555. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105556. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105557. i -= metadata->data.vorbis_comment.vendor_string.length;
  105558. i += vendor_string_length;
  105559. }
  105560. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105561. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105562. return false;
  105563. switch(metadata->type) {
  105564. case FLAC__METADATA_TYPE_STREAMINFO:
  105565. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105566. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105567. return false;
  105568. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105569. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105570. return false;
  105571. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105572. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105573. return false;
  105574. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105575. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105576. return false;
  105577. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105578. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105579. return false;
  105580. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105581. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105582. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105583. return false;
  105584. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105585. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105586. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105587. return false;
  105588. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105589. return false;
  105590. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105591. return false;
  105592. break;
  105593. case FLAC__METADATA_TYPE_PADDING:
  105594. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105595. return false;
  105596. break;
  105597. case FLAC__METADATA_TYPE_APPLICATION:
  105598. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105599. return false;
  105600. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105601. return false;
  105602. break;
  105603. case FLAC__METADATA_TYPE_SEEKTABLE:
  105604. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105605. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105606. return false;
  105607. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105608. return false;
  105609. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105610. return false;
  105611. }
  105612. break;
  105613. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105614. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105615. return false;
  105616. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105617. return false;
  105618. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105619. return false;
  105620. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105621. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105622. return false;
  105623. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105624. return false;
  105625. }
  105626. break;
  105627. case FLAC__METADATA_TYPE_CUESHEET:
  105628. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105629. 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))
  105630. return false;
  105631. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105632. return false;
  105633. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105634. return false;
  105635. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105636. return false;
  105637. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105638. return false;
  105639. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105640. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105641. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105642. return false;
  105643. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105644. return false;
  105645. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105646. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105647. return false;
  105648. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105649. return false;
  105650. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105651. return false;
  105652. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105653. return false;
  105654. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105655. return false;
  105656. for(j = 0; j < track->num_indices; j++) {
  105657. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105658. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105659. return false;
  105660. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105661. return false;
  105662. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105663. return false;
  105664. }
  105665. }
  105666. break;
  105667. case FLAC__METADATA_TYPE_PICTURE:
  105668. {
  105669. size_t len;
  105670. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105671. return false;
  105672. len = strlen(metadata->data.picture.mime_type);
  105673. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105674. return false;
  105675. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105676. return false;
  105677. len = strlen((const char *)metadata->data.picture.description);
  105678. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105679. return false;
  105680. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105681. return false;
  105682. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105683. return false;
  105684. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105685. return false;
  105686. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105687. return false;
  105688. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105689. return false;
  105690. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105691. return false;
  105692. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105693. return false;
  105694. }
  105695. break;
  105696. default:
  105697. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105698. return false;
  105699. break;
  105700. }
  105701. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105702. return true;
  105703. }
  105704. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105705. {
  105706. unsigned u, blocksize_hint, sample_rate_hint;
  105707. FLAC__byte crc;
  105708. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105709. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105710. return false;
  105711. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105712. return false;
  105713. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105714. return false;
  105715. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105716. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105717. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105718. blocksize_hint = 0;
  105719. switch(header->blocksize) {
  105720. case 192: u = 1; break;
  105721. case 576: u = 2; break;
  105722. case 1152: u = 3; break;
  105723. case 2304: u = 4; break;
  105724. case 4608: u = 5; break;
  105725. case 256: u = 8; break;
  105726. case 512: u = 9; break;
  105727. case 1024: u = 10; break;
  105728. case 2048: u = 11; break;
  105729. case 4096: u = 12; break;
  105730. case 8192: u = 13; break;
  105731. case 16384: u = 14; break;
  105732. case 32768: u = 15; break;
  105733. default:
  105734. if(header->blocksize <= 0x100)
  105735. blocksize_hint = u = 6;
  105736. else
  105737. blocksize_hint = u = 7;
  105738. break;
  105739. }
  105740. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105741. return false;
  105742. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105743. sample_rate_hint = 0;
  105744. switch(header->sample_rate) {
  105745. case 88200: u = 1; break;
  105746. case 176400: u = 2; break;
  105747. case 192000: u = 3; break;
  105748. case 8000: u = 4; break;
  105749. case 16000: u = 5; break;
  105750. case 22050: u = 6; break;
  105751. case 24000: u = 7; break;
  105752. case 32000: u = 8; break;
  105753. case 44100: u = 9; break;
  105754. case 48000: u = 10; break;
  105755. case 96000: u = 11; break;
  105756. default:
  105757. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105758. sample_rate_hint = u = 12;
  105759. else if(header->sample_rate % 10 == 0)
  105760. sample_rate_hint = u = 14;
  105761. else if(header->sample_rate <= 0xffff)
  105762. sample_rate_hint = u = 13;
  105763. else
  105764. u = 0;
  105765. break;
  105766. }
  105767. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105768. return false;
  105769. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105770. switch(header->channel_assignment) {
  105771. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105772. u = header->channels - 1;
  105773. break;
  105774. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105775. FLAC__ASSERT(header->channels == 2);
  105776. u = 8;
  105777. break;
  105778. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105779. FLAC__ASSERT(header->channels == 2);
  105780. u = 9;
  105781. break;
  105782. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105783. FLAC__ASSERT(header->channels == 2);
  105784. u = 10;
  105785. break;
  105786. default:
  105787. FLAC__ASSERT(0);
  105788. }
  105789. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105790. return false;
  105791. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105792. switch(header->bits_per_sample) {
  105793. case 8 : u = 1; break;
  105794. case 12: u = 2; break;
  105795. case 16: u = 4; break;
  105796. case 20: u = 5; break;
  105797. case 24: u = 6; break;
  105798. default: u = 0; break;
  105799. }
  105800. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  105801. return false;
  105802. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  105803. return false;
  105804. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  105805. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  105806. return false;
  105807. }
  105808. else {
  105809. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  105810. return false;
  105811. }
  105812. if(blocksize_hint)
  105813. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  105814. return false;
  105815. switch(sample_rate_hint) {
  105816. case 12:
  105817. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  105818. return false;
  105819. break;
  105820. case 13:
  105821. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  105822. return false;
  105823. break;
  105824. case 14:
  105825. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  105826. return false;
  105827. break;
  105828. }
  105829. /* write the CRC */
  105830. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  105831. return false;
  105832. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  105833. return false;
  105834. return true;
  105835. }
  105836. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105837. {
  105838. FLAC__bool ok;
  105839. ok =
  105840. 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) &&
  105841. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  105842. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  105843. ;
  105844. return ok;
  105845. }
  105846. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105847. {
  105848. unsigned i;
  105849. 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))
  105850. return false;
  105851. if(wasted_bits)
  105852. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105853. return false;
  105854. for(i = 0; i < subframe->order; i++)
  105855. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105856. return false;
  105857. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105858. return false;
  105859. switch(subframe->entropy_coding_method.type) {
  105860. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105861. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105862. if(!add_residual_partitioned_rice_(
  105863. bw,
  105864. subframe->residual,
  105865. residual_samples,
  105866. subframe->order,
  105867. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105868. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105869. subframe->entropy_coding_method.data.partitioned_rice.order,
  105870. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105871. ))
  105872. return false;
  105873. break;
  105874. default:
  105875. FLAC__ASSERT(0);
  105876. }
  105877. return true;
  105878. }
  105879. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105880. {
  105881. unsigned i;
  105882. 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))
  105883. return false;
  105884. if(wasted_bits)
  105885. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105886. return false;
  105887. for(i = 0; i < subframe->order; i++)
  105888. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105889. return false;
  105890. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  105891. return false;
  105892. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  105893. return false;
  105894. for(i = 0; i < subframe->order; i++)
  105895. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  105896. return false;
  105897. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105898. return false;
  105899. switch(subframe->entropy_coding_method.type) {
  105900. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105901. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105902. if(!add_residual_partitioned_rice_(
  105903. bw,
  105904. subframe->residual,
  105905. residual_samples,
  105906. subframe->order,
  105907. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105908. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105909. subframe->entropy_coding_method.data.partitioned_rice.order,
  105910. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105911. ))
  105912. return false;
  105913. break;
  105914. default:
  105915. FLAC__ASSERT(0);
  105916. }
  105917. return true;
  105918. }
  105919. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105920. {
  105921. unsigned i;
  105922. const FLAC__int32 *signal = subframe->data;
  105923. 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))
  105924. return false;
  105925. if(wasted_bits)
  105926. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105927. return false;
  105928. for(i = 0; i < samples; i++)
  105929. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  105930. return false;
  105931. return true;
  105932. }
  105933. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  105934. {
  105935. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  105936. return false;
  105937. switch(method->type) {
  105938. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105939. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105940. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  105941. return false;
  105942. break;
  105943. default:
  105944. FLAC__ASSERT(0);
  105945. }
  105946. return true;
  105947. }
  105948. 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)
  105949. {
  105950. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  105951. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  105952. if(partition_order == 0) {
  105953. unsigned i;
  105954. if(raw_bits[0] == 0) {
  105955. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  105956. return false;
  105957. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  105958. return false;
  105959. }
  105960. else {
  105961. FLAC__ASSERT(rice_parameters[0] == 0);
  105962. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105963. return false;
  105964. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105965. return false;
  105966. for(i = 0; i < residual_samples; i++) {
  105967. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  105968. return false;
  105969. }
  105970. }
  105971. return true;
  105972. }
  105973. else {
  105974. unsigned i, j, k = 0, k_last = 0;
  105975. unsigned partition_samples;
  105976. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  105977. for(i = 0; i < (1u<<partition_order); i++) {
  105978. partition_samples = default_partition_samples;
  105979. if(i == 0)
  105980. partition_samples -= predictor_order;
  105981. k += partition_samples;
  105982. if(raw_bits[i] == 0) {
  105983. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  105984. return false;
  105985. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  105986. return false;
  105987. }
  105988. else {
  105989. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105990. return false;
  105991. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105992. return false;
  105993. for(j = k_last; j < k; j++) {
  105994. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  105995. return false;
  105996. }
  105997. }
  105998. k_last = k;
  105999. }
  106000. return true;
  106001. }
  106002. }
  106003. #endif
  106004. /*** End of inlined file: stream_encoder_framing.c ***/
  106005. /*** Start of inlined file: window_flac.c ***/
  106006. /*** Start of inlined file: juce_FlacHeader.h ***/
  106007. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106008. // tasks..
  106009. #define VERSION "1.2.1"
  106010. #define FLAC__NO_DLL 1
  106011. #if JUCE_MSVC
  106012. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106013. #endif
  106014. #if JUCE_MAC
  106015. #define FLAC__SYS_DARWIN 1
  106016. #endif
  106017. /*** End of inlined file: juce_FlacHeader.h ***/
  106018. #if JUCE_USE_FLAC
  106019. #if HAVE_CONFIG_H
  106020. # include <config.h>
  106021. #endif
  106022. #include <math.h>
  106023. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106024. #ifndef M_PI
  106025. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106026. #define M_PI 3.14159265358979323846
  106027. #endif
  106028. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106029. {
  106030. const FLAC__int32 N = L - 1;
  106031. FLAC__int32 n;
  106032. if (L & 1) {
  106033. for (n = 0; n <= N/2; n++)
  106034. window[n] = 2.0f * n / (float)N;
  106035. for (; n <= N; n++)
  106036. window[n] = 2.0f - 2.0f * n / (float)N;
  106037. }
  106038. else {
  106039. for (n = 0; n <= L/2-1; n++)
  106040. window[n] = 2.0f * n / (float)N;
  106041. for (; n <= N; n++)
  106042. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106043. }
  106044. }
  106045. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106046. {
  106047. const FLAC__int32 N = L - 1;
  106048. FLAC__int32 n;
  106049. for (n = 0; n < L; n++)
  106050. 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)));
  106051. }
  106052. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106053. {
  106054. const FLAC__int32 N = L - 1;
  106055. FLAC__int32 n;
  106056. for (n = 0; n < L; n++)
  106057. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106058. }
  106059. /* 4-term -92dB side-lobe */
  106060. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106061. {
  106062. const FLAC__int32 N = L - 1;
  106063. FLAC__int32 n;
  106064. for (n = 0; n <= N; n++)
  106065. 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));
  106066. }
  106067. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106068. {
  106069. const FLAC__int32 N = L - 1;
  106070. const double N2 = (double)N / 2.;
  106071. FLAC__int32 n;
  106072. for (n = 0; n <= N; n++) {
  106073. double k = ((double)n - N2) / N2;
  106074. k = 1.0f - k * k;
  106075. window[n] = (FLAC__real)(k * k);
  106076. }
  106077. }
  106078. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106079. {
  106080. const FLAC__int32 N = L - 1;
  106081. FLAC__int32 n;
  106082. for (n = 0; n < L; n++)
  106083. 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));
  106084. }
  106085. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106086. {
  106087. const FLAC__int32 N = L - 1;
  106088. const double N2 = (double)N / 2.;
  106089. FLAC__int32 n;
  106090. for (n = 0; n <= N; n++) {
  106091. const double k = ((double)n - N2) / (stddev * N2);
  106092. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106093. }
  106094. }
  106095. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106096. {
  106097. const FLAC__int32 N = L - 1;
  106098. FLAC__int32 n;
  106099. for (n = 0; n < L; n++)
  106100. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106101. }
  106102. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106103. {
  106104. const FLAC__int32 N = L - 1;
  106105. FLAC__int32 n;
  106106. for (n = 0; n < L; n++)
  106107. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106108. }
  106109. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106110. {
  106111. const FLAC__int32 N = L - 1;
  106112. FLAC__int32 n;
  106113. for (n = 0; n < L; n++)
  106114. window[n] = (FLAC__real)(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));
  106115. }
  106116. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106117. {
  106118. const FLAC__int32 N = L - 1;
  106119. FLAC__int32 n;
  106120. for (n = 0; n < L; n++)
  106121. 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));
  106122. }
  106123. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106124. {
  106125. FLAC__int32 n;
  106126. for (n = 0; n < L; n++)
  106127. window[n] = 1.0f;
  106128. }
  106129. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106130. {
  106131. FLAC__int32 n;
  106132. if (L & 1) {
  106133. for (n = 1; n <= L+1/2; n++)
  106134. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106135. for (; n <= L; n++)
  106136. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106137. }
  106138. else {
  106139. for (n = 1; n <= L/2; n++)
  106140. window[n-1] = 2.0f * n / (float)L;
  106141. for (; n <= L; n++)
  106142. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106143. }
  106144. }
  106145. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106146. {
  106147. if (p <= 0.0)
  106148. FLAC__window_rectangle(window, L);
  106149. else if (p >= 1.0)
  106150. FLAC__window_hann(window, L);
  106151. else {
  106152. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106153. FLAC__int32 n;
  106154. /* start with rectangle... */
  106155. FLAC__window_rectangle(window, L);
  106156. /* ...replace ends with hann */
  106157. if (Np > 0) {
  106158. for (n = 0; n <= Np; n++) {
  106159. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106160. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106161. }
  106162. }
  106163. }
  106164. }
  106165. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106166. {
  106167. const FLAC__int32 N = L - 1;
  106168. const double N2 = (double)N / 2.;
  106169. FLAC__int32 n;
  106170. for (n = 0; n <= N; n++) {
  106171. const double k = ((double)n - N2) / N2;
  106172. window[n] = (FLAC__real)(1.0f - k * k);
  106173. }
  106174. }
  106175. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106176. #endif
  106177. /*** End of inlined file: window_flac.c ***/
  106178. #else
  106179. #include <FLAC/all.h>
  106180. #endif
  106181. }
  106182. #undef max
  106183. #undef min
  106184. BEGIN_JUCE_NAMESPACE
  106185. static const char* const flacFormatName = "FLAC file";
  106186. static const char* const flacExtensions[] = { ".flac", 0 };
  106187. class FlacReader : public AudioFormatReader
  106188. {
  106189. public:
  106190. FlacReader (InputStream* const in)
  106191. : AudioFormatReader (in, TRANS (flacFormatName)),
  106192. reservoir (2, 0),
  106193. reservoirStart (0),
  106194. samplesInReservoir (0),
  106195. scanningForLength (false)
  106196. {
  106197. using namespace FlacNamespace;
  106198. lengthInSamples = 0;
  106199. decoder = FLAC__stream_decoder_new();
  106200. ok = FLAC__stream_decoder_init_stream (decoder,
  106201. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106202. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106203. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106204. if (ok)
  106205. {
  106206. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106207. if (lengthInSamples == 0 && sampleRate > 0)
  106208. {
  106209. // the length hasn't been stored in the metadata, so we'll need to
  106210. // work it out the length the hard way, by scanning the whole file..
  106211. scanningForLength = true;
  106212. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106213. scanningForLength = false;
  106214. const int64 tempLength = lengthInSamples;
  106215. FLAC__stream_decoder_reset (decoder);
  106216. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106217. lengthInSamples = tempLength;
  106218. }
  106219. }
  106220. }
  106221. ~FlacReader()
  106222. {
  106223. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106224. }
  106225. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106226. {
  106227. sampleRate = info.sample_rate;
  106228. bitsPerSample = info.bits_per_sample;
  106229. lengthInSamples = (unsigned int) info.total_samples;
  106230. numChannels = info.channels;
  106231. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106232. }
  106233. // returns the number of samples read
  106234. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106235. int64 startSampleInFile, int numSamples)
  106236. {
  106237. using namespace FlacNamespace;
  106238. if (! ok)
  106239. return false;
  106240. while (numSamples > 0)
  106241. {
  106242. if (startSampleInFile >= reservoirStart
  106243. && startSampleInFile < reservoirStart + samplesInReservoir)
  106244. {
  106245. const int num = (int) jmin ((int64) numSamples,
  106246. reservoirStart + samplesInReservoir - startSampleInFile);
  106247. jassert (num > 0);
  106248. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106249. if (destSamples[i] != 0)
  106250. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106251. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106252. sizeof (int) * num);
  106253. startOffsetInDestBuffer += num;
  106254. startSampleInFile += num;
  106255. numSamples -= num;
  106256. }
  106257. else
  106258. {
  106259. if (startSampleInFile >= (int) lengthInSamples)
  106260. {
  106261. samplesInReservoir = 0;
  106262. }
  106263. else if (startSampleInFile < reservoirStart
  106264. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106265. {
  106266. // had some problems with flac crashing if the read pos is aligned more
  106267. // accurately than this. Probably fixed in newer versions of the library, though.
  106268. reservoirStart = (int) (startSampleInFile & ~511);
  106269. samplesInReservoir = 0;
  106270. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106271. }
  106272. else
  106273. {
  106274. reservoirStart += samplesInReservoir;
  106275. samplesInReservoir = 0;
  106276. FLAC__stream_decoder_process_single (decoder);
  106277. }
  106278. if (samplesInReservoir == 0)
  106279. break;
  106280. }
  106281. }
  106282. if (numSamples > 0)
  106283. {
  106284. for (int i = numDestChannels; --i >= 0;)
  106285. if (destSamples[i] != 0)
  106286. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106287. sizeof (int) * numSamples);
  106288. }
  106289. return true;
  106290. }
  106291. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106292. {
  106293. if (scanningForLength)
  106294. {
  106295. lengthInSamples += numSamples;
  106296. }
  106297. else
  106298. {
  106299. if (numSamples > reservoir.getNumSamples())
  106300. reservoir.setSize (numChannels, numSamples, false, false, true);
  106301. const int bitsToShift = 32 - bitsPerSample;
  106302. for (int i = 0; i < (int) numChannels; ++i)
  106303. {
  106304. const FlacNamespace::FLAC__int32* src = buffer[i];
  106305. int n = i;
  106306. while (src == 0 && n > 0)
  106307. src = buffer [--n];
  106308. if (src != 0)
  106309. {
  106310. int* dest = (int*) reservoir.getSampleData(i);
  106311. for (int j = 0; j < numSamples; ++j)
  106312. dest[j] = src[j] << bitsToShift;
  106313. }
  106314. }
  106315. samplesInReservoir = numSamples;
  106316. }
  106317. }
  106318. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106319. {
  106320. using namespace FlacNamespace;
  106321. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106322. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106323. }
  106324. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106325. {
  106326. using namespace FlacNamespace;
  106327. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106328. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106329. }
  106330. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106331. {
  106332. using namespace FlacNamespace;
  106333. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106334. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106335. }
  106336. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106337. {
  106338. using namespace FlacNamespace;
  106339. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106340. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106341. }
  106342. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106343. {
  106344. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106345. }
  106346. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106347. const FlacNamespace::FLAC__Frame* frame,
  106348. const FlacNamespace::FLAC__int32* const buffer[],
  106349. void* client_data)
  106350. {
  106351. using namespace FlacNamespace;
  106352. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106353. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106354. }
  106355. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106356. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106357. void* client_data)
  106358. {
  106359. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106360. }
  106361. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106362. {
  106363. }
  106364. juce_UseDebuggingNewOperator
  106365. private:
  106366. FlacNamespace::FLAC__StreamDecoder* decoder;
  106367. AudioSampleBuffer reservoir;
  106368. int reservoirStart, samplesInReservoir;
  106369. bool ok, scanningForLength;
  106370. FlacReader (const FlacReader&);
  106371. FlacReader& operator= (const FlacReader&);
  106372. };
  106373. class FlacWriter : public AudioFormatWriter
  106374. {
  106375. public:
  106376. FlacWriter (OutputStream* const out,
  106377. const double sampleRate_,
  106378. const int numChannels_,
  106379. const int bitsPerSample_)
  106380. : AudioFormatWriter (out, TRANS (flacFormatName),
  106381. sampleRate_,
  106382. numChannels_,
  106383. bitsPerSample_)
  106384. {
  106385. using namespace FlacNamespace;
  106386. encoder = FLAC__stream_encoder_new();
  106387. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106388. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106389. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106390. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106391. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106392. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106393. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106394. ok = FLAC__stream_encoder_init_stream (encoder,
  106395. encodeWriteCallback, encodeSeekCallback,
  106396. encodeTellCallback, encodeMetadataCallback,
  106397. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106398. }
  106399. ~FlacWriter()
  106400. {
  106401. if (ok)
  106402. {
  106403. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106404. output->flush();
  106405. }
  106406. else
  106407. {
  106408. output = 0; // to stop the base class deleting this, as it needs to be returned
  106409. // to the caller of createWriter()
  106410. }
  106411. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106412. }
  106413. bool write (const int** samplesToWrite, int numSamples)
  106414. {
  106415. using namespace FlacNamespace;
  106416. if (! ok)
  106417. return false;
  106418. int* buf[3];
  106419. const int bitsToShift = 32 - bitsPerSample;
  106420. if (bitsToShift > 0)
  106421. {
  106422. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106423. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  106424. buf[0] = (int*) temp.getData();
  106425. buf[1] = buf[0] + numSamples;
  106426. buf[2] = 0;
  106427. for (int i = numChannelsToWrite; --i >= 0;)
  106428. {
  106429. if (samplesToWrite[i] != 0)
  106430. {
  106431. for (int j = 0; j < numSamples; ++j)
  106432. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106433. }
  106434. }
  106435. samplesToWrite = (const int**) buf;
  106436. }
  106437. return FLAC__stream_encoder_process (encoder,
  106438. (const FLAC__int32**) samplesToWrite,
  106439. numSamples) != 0;
  106440. }
  106441. bool writeData (const void* const data, const int size) const
  106442. {
  106443. return output->write (data, size);
  106444. }
  106445. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106446. {
  106447. using namespace FlacNamespace;
  106448. b += bytes;
  106449. for (int i = 0; i < bytes; ++i)
  106450. {
  106451. *(--b) = (FLAC__byte) (val & 0xff);
  106452. val >>= 8;
  106453. }
  106454. }
  106455. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106456. {
  106457. using namespace FlacNamespace;
  106458. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106459. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106460. const unsigned int channelsMinus1 = info.channels - 1;
  106461. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106462. packUint32 (info.min_blocksize, buffer, 2);
  106463. packUint32 (info.max_blocksize, buffer + 2, 2);
  106464. packUint32 (info.min_framesize, buffer + 4, 3);
  106465. packUint32 (info.max_framesize, buffer + 7, 3);
  106466. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106467. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106468. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106469. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106470. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106471. memcpy (buffer + 18, info.md5sum, 16);
  106472. const bool seekOk = output->setPosition (4);
  106473. (void) seekOk;
  106474. // if this fails, you've given it an output stream that can't seek! It needs
  106475. // to be able to seek back to write the header
  106476. jassert (seekOk);
  106477. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106478. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106479. }
  106480. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106481. const FlacNamespace::FLAC__byte buffer[],
  106482. size_t bytes,
  106483. unsigned int /*samples*/,
  106484. unsigned int /*current_frame*/,
  106485. void* client_data)
  106486. {
  106487. using namespace FlacNamespace;
  106488. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106489. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106490. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106491. }
  106492. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106493. {
  106494. using namespace FlacNamespace;
  106495. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106496. }
  106497. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106498. {
  106499. using namespace FlacNamespace;
  106500. if (client_data == 0)
  106501. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106502. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106503. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106504. }
  106505. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106506. {
  106507. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106508. }
  106509. juce_UseDebuggingNewOperator
  106510. bool ok;
  106511. private:
  106512. FlacNamespace::FLAC__StreamEncoder* encoder;
  106513. MemoryBlock temp;
  106514. FlacWriter (const FlacWriter&);
  106515. FlacWriter& operator= (const FlacWriter&);
  106516. };
  106517. FlacAudioFormat::FlacAudioFormat()
  106518. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106519. {
  106520. }
  106521. FlacAudioFormat::~FlacAudioFormat()
  106522. {
  106523. }
  106524. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106525. {
  106526. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106527. return Array <int> (rates);
  106528. }
  106529. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106530. {
  106531. const int depths[] = { 16, 24, 0 };
  106532. return Array <int> (depths);
  106533. }
  106534. bool FlacAudioFormat::canDoStereo()
  106535. {
  106536. return true;
  106537. }
  106538. bool FlacAudioFormat::canDoMono()
  106539. {
  106540. return true;
  106541. }
  106542. bool FlacAudioFormat::isCompressed()
  106543. {
  106544. return true;
  106545. }
  106546. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106547. const bool deleteStreamIfOpeningFails)
  106548. {
  106549. ScopedPointer<FlacReader> r (new FlacReader (in));
  106550. if (r->sampleRate != 0)
  106551. return r.release();
  106552. if (! deleteStreamIfOpeningFails)
  106553. r->input = 0;
  106554. return 0;
  106555. }
  106556. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106557. double sampleRate,
  106558. unsigned int numberOfChannels,
  106559. int bitsPerSample,
  106560. const StringPairArray& /*metadataValues*/,
  106561. int /*qualityOptionIndex*/)
  106562. {
  106563. if (getPossibleBitDepths().contains (bitsPerSample))
  106564. {
  106565. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  106566. if (w->ok)
  106567. return w.release();
  106568. }
  106569. return 0;
  106570. }
  106571. END_JUCE_NAMESPACE
  106572. #endif
  106573. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106574. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106575. #if JUCE_USE_OGGVORBIS
  106576. #if JUCE_MAC
  106577. #define __MACOSX__ 1
  106578. #endif
  106579. namespace OggVorbisNamespace
  106580. {
  106581. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106582. /*** Start of inlined file: vorbisenc.h ***/
  106583. #ifndef _OV_ENC_H_
  106584. #define _OV_ENC_H_
  106585. #ifdef __cplusplus
  106586. extern "C"
  106587. {
  106588. #endif /* __cplusplus */
  106589. /*** Start of inlined file: codec.h ***/
  106590. #ifndef _vorbis_codec_h_
  106591. #define _vorbis_codec_h_
  106592. #ifdef __cplusplus
  106593. extern "C"
  106594. {
  106595. #endif /* __cplusplus */
  106596. /*** Start of inlined file: ogg.h ***/
  106597. #ifndef _OGG_H
  106598. #define _OGG_H
  106599. #ifdef __cplusplus
  106600. extern "C" {
  106601. #endif
  106602. /*** Start of inlined file: os_types.h ***/
  106603. #ifndef _OS_TYPES_H
  106604. #define _OS_TYPES_H
  106605. /* make it easy on the folks that want to compile the libs with a
  106606. different malloc than stdlib */
  106607. #define _ogg_malloc malloc
  106608. #define _ogg_calloc calloc
  106609. #define _ogg_realloc realloc
  106610. #define _ogg_free free
  106611. #if defined(_WIN32)
  106612. # if defined(__CYGWIN__)
  106613. # include <_G_config.h>
  106614. typedef _G_int64_t ogg_int64_t;
  106615. typedef _G_int32_t ogg_int32_t;
  106616. typedef _G_uint32_t ogg_uint32_t;
  106617. typedef _G_int16_t ogg_int16_t;
  106618. typedef _G_uint16_t ogg_uint16_t;
  106619. # elif defined(__MINGW32__)
  106620. typedef short ogg_int16_t;
  106621. typedef unsigned short ogg_uint16_t;
  106622. typedef int ogg_int32_t;
  106623. typedef unsigned int ogg_uint32_t;
  106624. typedef long long ogg_int64_t;
  106625. typedef unsigned long long ogg_uint64_t;
  106626. # elif defined(__MWERKS__)
  106627. typedef long long ogg_int64_t;
  106628. typedef int ogg_int32_t;
  106629. typedef unsigned int ogg_uint32_t;
  106630. typedef short ogg_int16_t;
  106631. typedef unsigned short ogg_uint16_t;
  106632. # else
  106633. /* MSVC/Borland */
  106634. typedef __int64 ogg_int64_t;
  106635. typedef __int32 ogg_int32_t;
  106636. typedef unsigned __int32 ogg_uint32_t;
  106637. typedef __int16 ogg_int16_t;
  106638. typedef unsigned __int16 ogg_uint16_t;
  106639. # endif
  106640. #elif defined(__MACOS__)
  106641. # include <sys/types.h>
  106642. typedef SInt16 ogg_int16_t;
  106643. typedef UInt16 ogg_uint16_t;
  106644. typedef SInt32 ogg_int32_t;
  106645. typedef UInt32 ogg_uint32_t;
  106646. typedef SInt64 ogg_int64_t;
  106647. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106648. # include <sys/types.h>
  106649. typedef int16_t ogg_int16_t;
  106650. typedef u_int16_t ogg_uint16_t;
  106651. typedef int32_t ogg_int32_t;
  106652. typedef u_int32_t ogg_uint32_t;
  106653. typedef int64_t ogg_int64_t;
  106654. #elif defined(__BEOS__)
  106655. /* Be */
  106656. # include <inttypes.h>
  106657. typedef int16_t ogg_int16_t;
  106658. typedef u_int16_t ogg_uint16_t;
  106659. typedef int32_t ogg_int32_t;
  106660. typedef u_int32_t ogg_uint32_t;
  106661. typedef int64_t ogg_int64_t;
  106662. #elif defined (__EMX__)
  106663. /* OS/2 GCC */
  106664. typedef short ogg_int16_t;
  106665. typedef unsigned short ogg_uint16_t;
  106666. typedef int ogg_int32_t;
  106667. typedef unsigned int ogg_uint32_t;
  106668. typedef long long ogg_int64_t;
  106669. #elif defined (DJGPP)
  106670. /* DJGPP */
  106671. typedef short ogg_int16_t;
  106672. typedef int ogg_int32_t;
  106673. typedef unsigned int ogg_uint32_t;
  106674. typedef long long ogg_int64_t;
  106675. #elif defined(R5900)
  106676. /* PS2 EE */
  106677. typedef long ogg_int64_t;
  106678. typedef int ogg_int32_t;
  106679. typedef unsigned ogg_uint32_t;
  106680. typedef short ogg_int16_t;
  106681. #elif defined(__SYMBIAN32__)
  106682. /* Symbian GCC */
  106683. typedef signed short ogg_int16_t;
  106684. typedef unsigned short ogg_uint16_t;
  106685. typedef signed int ogg_int32_t;
  106686. typedef unsigned int ogg_uint32_t;
  106687. typedef long long int ogg_int64_t;
  106688. #else
  106689. # include <sys/types.h>
  106690. /*** Start of inlined file: config_types.h ***/
  106691. #ifndef __CONFIG_TYPES_H__
  106692. #define __CONFIG_TYPES_H__
  106693. typedef int16_t ogg_int16_t;
  106694. typedef unsigned short ogg_uint16_t;
  106695. typedef int32_t ogg_int32_t;
  106696. typedef unsigned int ogg_uint32_t;
  106697. typedef int64_t ogg_int64_t;
  106698. #endif
  106699. /*** End of inlined file: config_types.h ***/
  106700. #endif
  106701. #endif /* _OS_TYPES_H */
  106702. /*** End of inlined file: os_types.h ***/
  106703. typedef struct {
  106704. long endbyte;
  106705. int endbit;
  106706. unsigned char *buffer;
  106707. unsigned char *ptr;
  106708. long storage;
  106709. } oggpack_buffer;
  106710. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106711. typedef struct {
  106712. unsigned char *header;
  106713. long header_len;
  106714. unsigned char *body;
  106715. long body_len;
  106716. } ogg_page;
  106717. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106718. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106719. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106720. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106721. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106722. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106723. }
  106724. /* ogg_stream_state contains the current encode/decode state of a logical
  106725. Ogg bitstream **********************************************************/
  106726. typedef struct {
  106727. unsigned char *body_data; /* bytes from packet bodies */
  106728. long body_storage; /* storage elements allocated */
  106729. long body_fill; /* elements stored; fill mark */
  106730. long body_returned; /* elements of fill returned */
  106731. int *lacing_vals; /* The values that will go to the segment table */
  106732. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106733. this way, but it is simple coupled to the
  106734. lacing fifo */
  106735. long lacing_storage;
  106736. long lacing_fill;
  106737. long lacing_packet;
  106738. long lacing_returned;
  106739. unsigned char header[282]; /* working space for header encode */
  106740. int header_fill;
  106741. int e_o_s; /* set when we have buffered the last packet in the
  106742. logical bitstream */
  106743. int b_o_s; /* set after we've written the initial page
  106744. of a logical bitstream */
  106745. long serialno;
  106746. long pageno;
  106747. ogg_int64_t packetno; /* sequence number for decode; the framing
  106748. knows where there's a hole in the data,
  106749. but we need coupling so that the codec
  106750. (which is in a seperate abstraction
  106751. layer) also knows about the gap */
  106752. ogg_int64_t granulepos;
  106753. } ogg_stream_state;
  106754. /* ogg_packet is used to encapsulate the data and metadata belonging
  106755. to a single raw Ogg/Vorbis packet *************************************/
  106756. typedef struct {
  106757. unsigned char *packet;
  106758. long bytes;
  106759. long b_o_s;
  106760. long e_o_s;
  106761. ogg_int64_t granulepos;
  106762. ogg_int64_t packetno; /* sequence number for decode; the framing
  106763. knows where there's a hole in the data,
  106764. but we need coupling so that the codec
  106765. (which is in a seperate abstraction
  106766. layer) also knows about the gap */
  106767. } ogg_packet;
  106768. typedef struct {
  106769. unsigned char *data;
  106770. int storage;
  106771. int fill;
  106772. int returned;
  106773. int unsynced;
  106774. int headerbytes;
  106775. int bodybytes;
  106776. } ogg_sync_state;
  106777. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106778. extern void oggpack_writeinit(oggpack_buffer *b);
  106779. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106780. extern void oggpack_writealign(oggpack_buffer *b);
  106781. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106782. extern void oggpack_reset(oggpack_buffer *b);
  106783. extern void oggpack_writeclear(oggpack_buffer *b);
  106784. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106785. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106786. extern long oggpack_look(oggpack_buffer *b,int bits);
  106787. extern long oggpack_look1(oggpack_buffer *b);
  106788. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106789. extern void oggpack_adv1(oggpack_buffer *b);
  106790. extern long oggpack_read(oggpack_buffer *b,int bits);
  106791. extern long oggpack_read1(oggpack_buffer *b);
  106792. extern long oggpack_bytes(oggpack_buffer *b);
  106793. extern long oggpack_bits(oggpack_buffer *b);
  106794. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106795. extern void oggpackB_writeinit(oggpack_buffer *b);
  106796. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106797. extern void oggpackB_writealign(oggpack_buffer *b);
  106798. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106799. extern void oggpackB_reset(oggpack_buffer *b);
  106800. extern void oggpackB_writeclear(oggpack_buffer *b);
  106801. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106802. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106803. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106804. extern long oggpackB_look1(oggpack_buffer *b);
  106805. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106806. extern void oggpackB_adv1(oggpack_buffer *b);
  106807. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106808. extern long oggpackB_read1(oggpack_buffer *b);
  106809. extern long oggpackB_bytes(oggpack_buffer *b);
  106810. extern long oggpackB_bits(oggpack_buffer *b);
  106811. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106812. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106813. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  106814. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  106815. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  106816. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  106817. extern int ogg_sync_init(ogg_sync_state *oy);
  106818. extern int ogg_sync_clear(ogg_sync_state *oy);
  106819. extern int ogg_sync_reset(ogg_sync_state *oy);
  106820. extern int ogg_sync_destroy(ogg_sync_state *oy);
  106821. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  106822. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  106823. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  106824. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  106825. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  106826. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  106827. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  106828. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  106829. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  106830. extern int ogg_stream_clear(ogg_stream_state *os);
  106831. extern int ogg_stream_reset(ogg_stream_state *os);
  106832. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  106833. extern int ogg_stream_destroy(ogg_stream_state *os);
  106834. extern int ogg_stream_eos(ogg_stream_state *os);
  106835. extern void ogg_page_checksum_set(ogg_page *og);
  106836. extern int ogg_page_version(ogg_page *og);
  106837. extern int ogg_page_continued(ogg_page *og);
  106838. extern int ogg_page_bos(ogg_page *og);
  106839. extern int ogg_page_eos(ogg_page *og);
  106840. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  106841. extern int ogg_page_serialno(ogg_page *og);
  106842. extern long ogg_page_pageno(ogg_page *og);
  106843. extern int ogg_page_packets(ogg_page *og);
  106844. extern void ogg_packet_clear(ogg_packet *op);
  106845. #ifdef __cplusplus
  106846. }
  106847. #endif
  106848. #endif /* _OGG_H */
  106849. /*** End of inlined file: ogg.h ***/
  106850. typedef struct vorbis_info{
  106851. int version;
  106852. int channels;
  106853. long rate;
  106854. /* The below bitrate declarations are *hints*.
  106855. Combinations of the three values carry the following implications:
  106856. all three set to the same value:
  106857. implies a fixed rate bitstream
  106858. only nominal set:
  106859. implies a VBR stream that averages the nominal bitrate. No hard
  106860. upper/lower limit
  106861. upper and or lower set:
  106862. implies a VBR bitstream that obeys the bitrate limits. nominal
  106863. may also be set to give a nominal rate.
  106864. none set:
  106865. the coder does not care to speculate.
  106866. */
  106867. long bitrate_upper;
  106868. long bitrate_nominal;
  106869. long bitrate_lower;
  106870. long bitrate_window;
  106871. void *codec_setup;
  106872. } vorbis_info;
  106873. /* vorbis_dsp_state buffers the current vorbis audio
  106874. analysis/synthesis state. The DSP state belongs to a specific
  106875. logical bitstream ****************************************************/
  106876. typedef struct vorbis_dsp_state{
  106877. int analysisp;
  106878. vorbis_info *vi;
  106879. float **pcm;
  106880. float **pcmret;
  106881. int pcm_storage;
  106882. int pcm_current;
  106883. int pcm_returned;
  106884. int preextrapolate;
  106885. int eofflag;
  106886. long lW;
  106887. long W;
  106888. long nW;
  106889. long centerW;
  106890. ogg_int64_t granulepos;
  106891. ogg_int64_t sequence;
  106892. ogg_int64_t glue_bits;
  106893. ogg_int64_t time_bits;
  106894. ogg_int64_t floor_bits;
  106895. ogg_int64_t res_bits;
  106896. void *backend_state;
  106897. } vorbis_dsp_state;
  106898. typedef struct vorbis_block{
  106899. /* necessary stream state for linking to the framing abstraction */
  106900. float **pcm; /* this is a pointer into local storage */
  106901. oggpack_buffer opb;
  106902. long lW;
  106903. long W;
  106904. long nW;
  106905. int pcmend;
  106906. int mode;
  106907. int eofflag;
  106908. ogg_int64_t granulepos;
  106909. ogg_int64_t sequence;
  106910. vorbis_dsp_state *vd; /* For read-only access of configuration */
  106911. /* local storage to avoid remallocing; it's up to the mapping to
  106912. structure it */
  106913. void *localstore;
  106914. long localtop;
  106915. long localalloc;
  106916. long totaluse;
  106917. struct alloc_chain *reap;
  106918. /* bitmetrics for the frame */
  106919. long glue_bits;
  106920. long time_bits;
  106921. long floor_bits;
  106922. long res_bits;
  106923. void *internal;
  106924. } vorbis_block;
  106925. /* vorbis_block is a single block of data to be processed as part of
  106926. the analysis/synthesis stream; it belongs to a specific logical
  106927. bitstream, but is independant from other vorbis_blocks belonging to
  106928. that logical bitstream. *************************************************/
  106929. struct alloc_chain{
  106930. void *ptr;
  106931. struct alloc_chain *next;
  106932. };
  106933. /* vorbis_info contains all the setup information specific to the
  106934. specific compression/decompression mode in progress (eg,
  106935. psychoacoustic settings, channel setup, options, codebook
  106936. etc). vorbis_info and substructures are in backends.h.
  106937. *********************************************************************/
  106938. /* the comments are not part of vorbis_info so that vorbis_info can be
  106939. static storage */
  106940. typedef struct vorbis_comment{
  106941. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  106942. whatever vendor is set to in encode */
  106943. char **user_comments;
  106944. int *comment_lengths;
  106945. int comments;
  106946. char *vendor;
  106947. } vorbis_comment;
  106948. /* libvorbis encodes in two abstraction layers; first we perform DSP
  106949. and produce a packet (see docs/analysis.txt). The packet is then
  106950. coded into a framed OggSquish bitstream by the second layer (see
  106951. docs/framing.txt). Decode is the reverse process; we sync/frame
  106952. the bitstream and extract individual packets, then decode the
  106953. packet back into PCM audio.
  106954. The extra framing/packetizing is used in streaming formats, such as
  106955. files. Over the net (such as with UDP), the framing and
  106956. packetization aren't necessary as they're provided by the transport
  106957. and the streaming layer is not used */
  106958. /* Vorbis PRIMITIVES: general ***************************************/
  106959. extern void vorbis_info_init(vorbis_info *vi);
  106960. extern void vorbis_info_clear(vorbis_info *vi);
  106961. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  106962. extern void vorbis_comment_init(vorbis_comment *vc);
  106963. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  106964. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  106965. const char *tag, char *contents);
  106966. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  106967. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  106968. extern void vorbis_comment_clear(vorbis_comment *vc);
  106969. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  106970. extern int vorbis_block_clear(vorbis_block *vb);
  106971. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  106972. extern double vorbis_granule_time(vorbis_dsp_state *v,
  106973. ogg_int64_t granulepos);
  106974. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  106975. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106976. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  106977. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  106978. vorbis_comment *vc,
  106979. ogg_packet *op,
  106980. ogg_packet *op_comm,
  106981. ogg_packet *op_code);
  106982. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  106983. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  106984. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  106985. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  106986. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106987. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  106988. ogg_packet *op);
  106989. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  106990. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  106991. ogg_packet *op);
  106992. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106993. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  106994. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  106995. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  106996. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  106997. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  106998. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  106999. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107000. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107001. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107002. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107003. /* Vorbis ERRORS and return codes ***********************************/
  107004. #define OV_FALSE -1
  107005. #define OV_EOF -2
  107006. #define OV_HOLE -3
  107007. #define OV_EREAD -128
  107008. #define OV_EFAULT -129
  107009. #define OV_EIMPL -130
  107010. #define OV_EINVAL -131
  107011. #define OV_ENOTVORBIS -132
  107012. #define OV_EBADHEADER -133
  107013. #define OV_EVERSION -134
  107014. #define OV_ENOTAUDIO -135
  107015. #define OV_EBADPACKET -136
  107016. #define OV_EBADLINK -137
  107017. #define OV_ENOSEEK -138
  107018. #ifdef __cplusplus
  107019. }
  107020. #endif /* __cplusplus */
  107021. #endif
  107022. /*** End of inlined file: codec.h ***/
  107023. extern int vorbis_encode_init(vorbis_info *vi,
  107024. long channels,
  107025. long rate,
  107026. long max_bitrate,
  107027. long nominal_bitrate,
  107028. long min_bitrate);
  107029. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107030. long channels,
  107031. long rate,
  107032. long max_bitrate,
  107033. long nominal_bitrate,
  107034. long min_bitrate);
  107035. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107036. long channels,
  107037. long rate,
  107038. float quality /* quality level from 0. (lo) to 1. (hi) */
  107039. );
  107040. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107041. long channels,
  107042. long rate,
  107043. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107044. );
  107045. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107046. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107047. /* deprecated rate management supported only for compatability */
  107048. #define OV_ECTL_RATEMANAGE_GET 0x10
  107049. #define OV_ECTL_RATEMANAGE_SET 0x11
  107050. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107051. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107052. struct ovectl_ratemanage_arg {
  107053. int management_active;
  107054. long bitrate_hard_min;
  107055. long bitrate_hard_max;
  107056. double bitrate_hard_window;
  107057. long bitrate_av_lo;
  107058. long bitrate_av_hi;
  107059. double bitrate_av_window;
  107060. double bitrate_av_window_center;
  107061. };
  107062. /* new rate setup */
  107063. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107064. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107065. struct ovectl_ratemanage2_arg {
  107066. int management_active;
  107067. long bitrate_limit_min_kbps;
  107068. long bitrate_limit_max_kbps;
  107069. long bitrate_limit_reservoir_bits;
  107070. double bitrate_limit_reservoir_bias;
  107071. long bitrate_average_kbps;
  107072. double bitrate_average_damping;
  107073. };
  107074. #define OV_ECTL_LOWPASS_GET 0x20
  107075. #define OV_ECTL_LOWPASS_SET 0x21
  107076. #define OV_ECTL_IBLOCK_GET 0x30
  107077. #define OV_ECTL_IBLOCK_SET 0x31
  107078. #ifdef __cplusplus
  107079. }
  107080. #endif /* __cplusplus */
  107081. #endif
  107082. /*** End of inlined file: vorbisenc.h ***/
  107083. /*** Start of inlined file: vorbisfile.h ***/
  107084. #ifndef _OV_FILE_H_
  107085. #define _OV_FILE_H_
  107086. #ifdef __cplusplus
  107087. extern "C"
  107088. {
  107089. #endif /* __cplusplus */
  107090. #include <stdio.h>
  107091. /* The function prototypes for the callbacks are basically the same as for
  107092. * the stdio functions fread, fseek, fclose, ftell.
  107093. * The one difference is that the FILE * arguments have been replaced with
  107094. * a void * - this is to be used as a pointer to whatever internal data these
  107095. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107096. *
  107097. * If you use other functions, check the docs for these functions and return
  107098. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107099. * unseekable
  107100. */
  107101. typedef struct {
  107102. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107103. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107104. int (*close_func) (void *datasource);
  107105. long (*tell_func) (void *datasource);
  107106. } ov_callbacks;
  107107. #define NOTOPEN 0
  107108. #define PARTOPEN 1
  107109. #define OPENED 2
  107110. #define STREAMSET 3
  107111. #define INITSET 4
  107112. typedef struct OggVorbis_File {
  107113. void *datasource; /* Pointer to a FILE *, etc. */
  107114. int seekable;
  107115. ogg_int64_t offset;
  107116. ogg_int64_t end;
  107117. ogg_sync_state oy;
  107118. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107119. stream appears */
  107120. int links;
  107121. ogg_int64_t *offsets;
  107122. ogg_int64_t *dataoffsets;
  107123. long *serialnos;
  107124. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107125. compatability; x2 size, stores both
  107126. beginning and end values */
  107127. vorbis_info *vi;
  107128. vorbis_comment *vc;
  107129. /* Decoding working state local storage */
  107130. ogg_int64_t pcm_offset;
  107131. int ready_state;
  107132. long current_serialno;
  107133. int current_link;
  107134. double bittrack;
  107135. double samptrack;
  107136. ogg_stream_state os; /* take physical pages, weld into a logical
  107137. stream of packets */
  107138. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107139. vorbis_block vb; /* local working space for packet->PCM decode */
  107140. ov_callbacks callbacks;
  107141. } OggVorbis_File;
  107142. extern int ov_clear(OggVorbis_File *vf);
  107143. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107144. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107145. char *initial, long ibytes, ov_callbacks callbacks);
  107146. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107147. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107148. char *initial, long ibytes, ov_callbacks callbacks);
  107149. extern int ov_test_open(OggVorbis_File *vf);
  107150. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107151. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107152. extern long ov_streams(OggVorbis_File *vf);
  107153. extern long ov_seekable(OggVorbis_File *vf);
  107154. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107155. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107156. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107157. extern double ov_time_total(OggVorbis_File *vf,int i);
  107158. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107159. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107160. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107161. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107162. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107163. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107164. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107165. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107166. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107167. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107168. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107169. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107170. extern double ov_time_tell(OggVorbis_File *vf);
  107171. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107172. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107173. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107174. int *bitstream);
  107175. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107176. int bigendianp,int word,int sgned,int *bitstream);
  107177. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107178. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107179. extern int ov_halfrate_p(OggVorbis_File *vf);
  107180. #ifdef __cplusplus
  107181. }
  107182. #endif /* __cplusplus */
  107183. #endif
  107184. /*** End of inlined file: vorbisfile.h ***/
  107185. /*** Start of inlined file: bitwise.c ***/
  107186. /* We're 'LSb' endian; if we write a word but read individual bits,
  107187. then we'll read the lsb first */
  107188. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107189. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107190. // tasks..
  107191. #if JUCE_MSVC
  107192. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107193. #endif
  107194. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107195. #if JUCE_USE_OGGVORBIS
  107196. #include <string.h>
  107197. #include <stdlib.h>
  107198. #define BUFFER_INCREMENT 256
  107199. static const unsigned long mask[]=
  107200. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107201. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107202. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107203. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107204. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107205. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107206. 0x3fffffff,0x7fffffff,0xffffffff };
  107207. static const unsigned int mask8B[]=
  107208. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107209. void oggpack_writeinit(oggpack_buffer *b){
  107210. memset(b,0,sizeof(*b));
  107211. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107212. b->buffer[0]='\0';
  107213. b->storage=BUFFER_INCREMENT;
  107214. }
  107215. void oggpackB_writeinit(oggpack_buffer *b){
  107216. oggpack_writeinit(b);
  107217. }
  107218. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107219. long bytes=bits>>3;
  107220. bits-=bytes*8;
  107221. b->ptr=b->buffer+bytes;
  107222. b->endbit=bits;
  107223. b->endbyte=bytes;
  107224. *b->ptr&=mask[bits];
  107225. }
  107226. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107227. long bytes=bits>>3;
  107228. bits-=bytes*8;
  107229. b->ptr=b->buffer+bytes;
  107230. b->endbit=bits;
  107231. b->endbyte=bytes;
  107232. *b->ptr&=mask8B[bits];
  107233. }
  107234. /* Takes only up to 32 bits. */
  107235. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107236. if(b->endbyte+4>=b->storage){
  107237. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107238. b->storage+=BUFFER_INCREMENT;
  107239. b->ptr=b->buffer+b->endbyte;
  107240. }
  107241. value&=mask[bits];
  107242. bits+=b->endbit;
  107243. b->ptr[0]|=value<<b->endbit;
  107244. if(bits>=8){
  107245. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107246. if(bits>=16){
  107247. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107248. if(bits>=24){
  107249. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107250. if(bits>=32){
  107251. if(b->endbit)
  107252. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107253. else
  107254. b->ptr[4]=0;
  107255. }
  107256. }
  107257. }
  107258. }
  107259. b->endbyte+=bits/8;
  107260. b->ptr+=bits/8;
  107261. b->endbit=bits&7;
  107262. }
  107263. /* Takes only up to 32 bits. */
  107264. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107265. if(b->endbyte+4>=b->storage){
  107266. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107267. b->storage+=BUFFER_INCREMENT;
  107268. b->ptr=b->buffer+b->endbyte;
  107269. }
  107270. value=(value&mask[bits])<<(32-bits);
  107271. bits+=b->endbit;
  107272. b->ptr[0]|=value>>(24+b->endbit);
  107273. if(bits>=8){
  107274. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107275. if(bits>=16){
  107276. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107277. if(bits>=24){
  107278. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107279. if(bits>=32){
  107280. if(b->endbit)
  107281. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107282. else
  107283. b->ptr[4]=0;
  107284. }
  107285. }
  107286. }
  107287. }
  107288. b->endbyte+=bits/8;
  107289. b->ptr+=bits/8;
  107290. b->endbit=bits&7;
  107291. }
  107292. void oggpack_writealign(oggpack_buffer *b){
  107293. int bits=8-b->endbit;
  107294. if(bits<8)
  107295. oggpack_write(b,0,bits);
  107296. }
  107297. void oggpackB_writealign(oggpack_buffer *b){
  107298. int bits=8-b->endbit;
  107299. if(bits<8)
  107300. oggpackB_write(b,0,bits);
  107301. }
  107302. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107303. void *source,
  107304. long bits,
  107305. void (*w)(oggpack_buffer *,
  107306. unsigned long,
  107307. int),
  107308. int msb){
  107309. unsigned char *ptr=(unsigned char *)source;
  107310. long bytes=bits/8;
  107311. bits-=bytes*8;
  107312. if(b->endbit){
  107313. int i;
  107314. /* unaligned copy. Do it the hard way. */
  107315. for(i=0;i<bytes;i++)
  107316. w(b,(unsigned long)(ptr[i]),8);
  107317. }else{
  107318. /* aligned block copy */
  107319. if(b->endbyte+bytes+1>=b->storage){
  107320. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107321. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107322. b->ptr=b->buffer+b->endbyte;
  107323. }
  107324. memmove(b->ptr,source,bytes);
  107325. b->ptr+=bytes;
  107326. b->endbyte+=bytes;
  107327. *b->ptr=0;
  107328. }
  107329. if(bits){
  107330. if(msb)
  107331. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107332. else
  107333. w(b,(unsigned long)(ptr[bytes]),bits);
  107334. }
  107335. }
  107336. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107337. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107338. }
  107339. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107340. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107341. }
  107342. void oggpack_reset(oggpack_buffer *b){
  107343. b->ptr=b->buffer;
  107344. b->buffer[0]=0;
  107345. b->endbit=b->endbyte=0;
  107346. }
  107347. void oggpackB_reset(oggpack_buffer *b){
  107348. oggpack_reset(b);
  107349. }
  107350. void oggpack_writeclear(oggpack_buffer *b){
  107351. _ogg_free(b->buffer);
  107352. memset(b,0,sizeof(*b));
  107353. }
  107354. void oggpackB_writeclear(oggpack_buffer *b){
  107355. oggpack_writeclear(b);
  107356. }
  107357. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107358. memset(b,0,sizeof(*b));
  107359. b->buffer=b->ptr=buf;
  107360. b->storage=bytes;
  107361. }
  107362. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107363. oggpack_readinit(b,buf,bytes);
  107364. }
  107365. /* Read in bits without advancing the bitptr; bits <= 32 */
  107366. long oggpack_look(oggpack_buffer *b,int bits){
  107367. unsigned long ret;
  107368. unsigned long m=mask[bits];
  107369. bits+=b->endbit;
  107370. if(b->endbyte+4>=b->storage){
  107371. /* not the main path */
  107372. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107373. }
  107374. ret=b->ptr[0]>>b->endbit;
  107375. if(bits>8){
  107376. ret|=b->ptr[1]<<(8-b->endbit);
  107377. if(bits>16){
  107378. ret|=b->ptr[2]<<(16-b->endbit);
  107379. if(bits>24){
  107380. ret|=b->ptr[3]<<(24-b->endbit);
  107381. if(bits>32 && b->endbit)
  107382. ret|=b->ptr[4]<<(32-b->endbit);
  107383. }
  107384. }
  107385. }
  107386. return(m&ret);
  107387. }
  107388. /* Read in bits without advancing the bitptr; bits <= 32 */
  107389. long oggpackB_look(oggpack_buffer *b,int bits){
  107390. unsigned long ret;
  107391. int m=32-bits;
  107392. bits+=b->endbit;
  107393. if(b->endbyte+4>=b->storage){
  107394. /* not the main path */
  107395. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107396. }
  107397. ret=b->ptr[0]<<(24+b->endbit);
  107398. if(bits>8){
  107399. ret|=b->ptr[1]<<(16+b->endbit);
  107400. if(bits>16){
  107401. ret|=b->ptr[2]<<(8+b->endbit);
  107402. if(bits>24){
  107403. ret|=b->ptr[3]<<(b->endbit);
  107404. if(bits>32 && b->endbit)
  107405. ret|=b->ptr[4]>>(8-b->endbit);
  107406. }
  107407. }
  107408. }
  107409. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107410. }
  107411. long oggpack_look1(oggpack_buffer *b){
  107412. if(b->endbyte>=b->storage)return(-1);
  107413. return((b->ptr[0]>>b->endbit)&1);
  107414. }
  107415. long oggpackB_look1(oggpack_buffer *b){
  107416. if(b->endbyte>=b->storage)return(-1);
  107417. return((b->ptr[0]>>(7-b->endbit))&1);
  107418. }
  107419. void oggpack_adv(oggpack_buffer *b,int bits){
  107420. bits+=b->endbit;
  107421. b->ptr+=bits/8;
  107422. b->endbyte+=bits/8;
  107423. b->endbit=bits&7;
  107424. }
  107425. void oggpackB_adv(oggpack_buffer *b,int bits){
  107426. oggpack_adv(b,bits);
  107427. }
  107428. void oggpack_adv1(oggpack_buffer *b){
  107429. if(++(b->endbit)>7){
  107430. b->endbit=0;
  107431. b->ptr++;
  107432. b->endbyte++;
  107433. }
  107434. }
  107435. void oggpackB_adv1(oggpack_buffer *b){
  107436. oggpack_adv1(b);
  107437. }
  107438. /* bits <= 32 */
  107439. long oggpack_read(oggpack_buffer *b,int bits){
  107440. long ret;
  107441. unsigned long m=mask[bits];
  107442. bits+=b->endbit;
  107443. if(b->endbyte+4>=b->storage){
  107444. /* not the main path */
  107445. ret=-1L;
  107446. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107447. }
  107448. ret=b->ptr[0]>>b->endbit;
  107449. if(bits>8){
  107450. ret|=b->ptr[1]<<(8-b->endbit);
  107451. if(bits>16){
  107452. ret|=b->ptr[2]<<(16-b->endbit);
  107453. if(bits>24){
  107454. ret|=b->ptr[3]<<(24-b->endbit);
  107455. if(bits>32 && b->endbit){
  107456. ret|=b->ptr[4]<<(32-b->endbit);
  107457. }
  107458. }
  107459. }
  107460. }
  107461. ret&=m;
  107462. overflow:
  107463. b->ptr+=bits/8;
  107464. b->endbyte+=bits/8;
  107465. b->endbit=bits&7;
  107466. return(ret);
  107467. }
  107468. /* bits <= 32 */
  107469. long oggpackB_read(oggpack_buffer *b,int bits){
  107470. long ret;
  107471. long m=32-bits;
  107472. bits+=b->endbit;
  107473. if(b->endbyte+4>=b->storage){
  107474. /* not the main path */
  107475. ret=-1L;
  107476. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107477. }
  107478. ret=b->ptr[0]<<(24+b->endbit);
  107479. if(bits>8){
  107480. ret|=b->ptr[1]<<(16+b->endbit);
  107481. if(bits>16){
  107482. ret|=b->ptr[2]<<(8+b->endbit);
  107483. if(bits>24){
  107484. ret|=b->ptr[3]<<(b->endbit);
  107485. if(bits>32 && b->endbit)
  107486. ret|=b->ptr[4]>>(8-b->endbit);
  107487. }
  107488. }
  107489. }
  107490. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107491. overflow:
  107492. b->ptr+=bits/8;
  107493. b->endbyte+=bits/8;
  107494. b->endbit=bits&7;
  107495. return(ret);
  107496. }
  107497. long oggpack_read1(oggpack_buffer *b){
  107498. long ret;
  107499. if(b->endbyte>=b->storage){
  107500. /* not the main path */
  107501. ret=-1L;
  107502. goto overflow;
  107503. }
  107504. ret=(b->ptr[0]>>b->endbit)&1;
  107505. overflow:
  107506. b->endbit++;
  107507. if(b->endbit>7){
  107508. b->endbit=0;
  107509. b->ptr++;
  107510. b->endbyte++;
  107511. }
  107512. return(ret);
  107513. }
  107514. long oggpackB_read1(oggpack_buffer *b){
  107515. long ret;
  107516. if(b->endbyte>=b->storage){
  107517. /* not the main path */
  107518. ret=-1L;
  107519. goto overflow;
  107520. }
  107521. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107522. overflow:
  107523. b->endbit++;
  107524. if(b->endbit>7){
  107525. b->endbit=0;
  107526. b->ptr++;
  107527. b->endbyte++;
  107528. }
  107529. return(ret);
  107530. }
  107531. long oggpack_bytes(oggpack_buffer *b){
  107532. return(b->endbyte+(b->endbit+7)/8);
  107533. }
  107534. long oggpack_bits(oggpack_buffer *b){
  107535. return(b->endbyte*8+b->endbit);
  107536. }
  107537. long oggpackB_bytes(oggpack_buffer *b){
  107538. return oggpack_bytes(b);
  107539. }
  107540. long oggpackB_bits(oggpack_buffer *b){
  107541. return oggpack_bits(b);
  107542. }
  107543. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107544. return(b->buffer);
  107545. }
  107546. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107547. return oggpack_get_buffer(b);
  107548. }
  107549. /* Self test of the bitwise routines; everything else is based on
  107550. them, so they damned well better be solid. */
  107551. #ifdef _V_SELFTEST
  107552. #include <stdio.h>
  107553. static int ilog(unsigned int v){
  107554. int ret=0;
  107555. while(v){
  107556. ret++;
  107557. v>>=1;
  107558. }
  107559. return(ret);
  107560. }
  107561. oggpack_buffer o;
  107562. oggpack_buffer r;
  107563. void report(char *in){
  107564. fprintf(stderr,"%s",in);
  107565. exit(1);
  107566. }
  107567. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107568. long bytes,i;
  107569. unsigned char *buffer;
  107570. oggpack_reset(&o);
  107571. for(i=0;i<vals;i++)
  107572. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107573. buffer=oggpack_get_buffer(&o);
  107574. bytes=oggpack_bytes(&o);
  107575. if(bytes!=compsize)report("wrong number of bytes!\n");
  107576. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107577. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107578. report("wrote incorrect value!\n");
  107579. }
  107580. oggpack_readinit(&r,buffer,bytes);
  107581. for(i=0;i<vals;i++){
  107582. int tbit=bits?bits:ilog(b[i]);
  107583. if(oggpack_look(&r,tbit)==-1)
  107584. report("out of data!\n");
  107585. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107586. report("looked at incorrect value!\n");
  107587. if(tbit==1)
  107588. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107589. report("looked at single bit incorrect value!\n");
  107590. if(tbit==1){
  107591. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107592. report("read incorrect single bit value!\n");
  107593. }else{
  107594. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107595. report("read incorrect value!\n");
  107596. }
  107597. }
  107598. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107599. }
  107600. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107601. long bytes,i;
  107602. unsigned char *buffer;
  107603. oggpackB_reset(&o);
  107604. for(i=0;i<vals;i++)
  107605. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107606. buffer=oggpackB_get_buffer(&o);
  107607. bytes=oggpackB_bytes(&o);
  107608. if(bytes!=compsize)report("wrong number of bytes!\n");
  107609. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107610. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107611. report("wrote incorrect value!\n");
  107612. }
  107613. oggpackB_readinit(&r,buffer,bytes);
  107614. for(i=0;i<vals;i++){
  107615. int tbit=bits?bits:ilog(b[i]);
  107616. if(oggpackB_look(&r,tbit)==-1)
  107617. report("out of data!\n");
  107618. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107619. report("looked at incorrect value!\n");
  107620. if(tbit==1)
  107621. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107622. report("looked at single bit incorrect value!\n");
  107623. if(tbit==1){
  107624. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107625. report("read incorrect single bit value!\n");
  107626. }else{
  107627. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107628. report("read incorrect value!\n");
  107629. }
  107630. }
  107631. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107632. }
  107633. int main(void){
  107634. unsigned char *buffer;
  107635. long bytes,i;
  107636. static unsigned long testbuffer1[]=
  107637. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107638. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107639. int test1size=43;
  107640. static unsigned long testbuffer2[]=
  107641. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107642. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107643. 85525151,0,12321,1,349528352};
  107644. int test2size=21;
  107645. static unsigned long testbuffer3[]=
  107646. {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,
  107647. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107648. int test3size=56;
  107649. static unsigned long large[]=
  107650. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107651. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107652. 85525151,0,12321,1,2146528352};
  107653. int onesize=33;
  107654. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107655. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107656. 223,4};
  107657. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107658. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107659. 245,251,128};
  107660. int twosize=6;
  107661. static int two[6]={61,255,255,251,231,29};
  107662. static int twoB[6]={247,63,255,253,249,120};
  107663. int threesize=54;
  107664. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107665. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107666. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107667. 100,52,4,14,18,86,77,1};
  107668. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107669. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107670. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107671. 200,20,254,4,58,106,176,144,0};
  107672. int foursize=38;
  107673. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107674. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107675. 28,2,133,0,1};
  107676. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107677. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107678. 129,10,4,32};
  107679. int fivesize=45;
  107680. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107681. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107682. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107683. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107684. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107685. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107686. int sixsize=7;
  107687. static int six[7]={17,177,170,242,169,19,148};
  107688. static int sixB[7]={136,141,85,79,149,200,41};
  107689. /* Test read/write together */
  107690. /* Later we test against pregenerated bitstreams */
  107691. oggpack_writeinit(&o);
  107692. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107693. cliptest(testbuffer1,test1size,0,one,onesize);
  107694. fprintf(stderr,"ok.");
  107695. fprintf(stderr,"\nNull bit call (LSb): ");
  107696. cliptest(testbuffer3,test3size,0,two,twosize);
  107697. fprintf(stderr,"ok.");
  107698. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107699. cliptest(testbuffer2,test2size,0,three,threesize);
  107700. fprintf(stderr,"ok.");
  107701. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107702. oggpack_reset(&o);
  107703. for(i=0;i<test2size;i++)
  107704. oggpack_write(&o,large[i],32);
  107705. buffer=oggpack_get_buffer(&o);
  107706. bytes=oggpack_bytes(&o);
  107707. oggpack_readinit(&r,buffer,bytes);
  107708. for(i=0;i<test2size;i++){
  107709. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107710. if(oggpack_look(&r,32)!=large[i]){
  107711. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107712. oggpack_look(&r,32),large[i]);
  107713. report("read incorrect value!\n");
  107714. }
  107715. oggpack_adv(&r,32);
  107716. }
  107717. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107718. fprintf(stderr,"ok.");
  107719. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107720. cliptest(testbuffer1,test1size,7,four,foursize);
  107721. fprintf(stderr,"ok.");
  107722. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107723. cliptest(testbuffer2,test2size,17,five,fivesize);
  107724. fprintf(stderr,"ok.");
  107725. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107726. cliptest(testbuffer3,test3size,1,six,sixsize);
  107727. fprintf(stderr,"ok.");
  107728. fprintf(stderr,"\nTesting read past end (LSb): ");
  107729. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107730. for(i=0;i<64;i++){
  107731. if(oggpack_read(&r,1)!=0){
  107732. fprintf(stderr,"failed; got -1 prematurely.\n");
  107733. exit(1);
  107734. }
  107735. }
  107736. if(oggpack_look(&r,1)!=-1 ||
  107737. oggpack_read(&r,1)!=-1){
  107738. fprintf(stderr,"failed; read past end without -1.\n");
  107739. exit(1);
  107740. }
  107741. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107742. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107743. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107744. exit(1);
  107745. }
  107746. if(oggpack_look(&r,18)!=0 ||
  107747. oggpack_look(&r,18)!=0){
  107748. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107749. exit(1);
  107750. }
  107751. if(oggpack_look(&r,19)!=-1 ||
  107752. oggpack_look(&r,19)!=-1){
  107753. fprintf(stderr,"failed; read past end without -1.\n");
  107754. exit(1);
  107755. }
  107756. if(oggpack_look(&r,32)!=-1 ||
  107757. oggpack_look(&r,32)!=-1){
  107758. fprintf(stderr,"failed; read past end without -1.\n");
  107759. exit(1);
  107760. }
  107761. oggpack_writeclear(&o);
  107762. fprintf(stderr,"ok.\n");
  107763. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107764. /* Test read/write together */
  107765. /* Later we test against pregenerated bitstreams */
  107766. oggpackB_writeinit(&o);
  107767. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107768. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107769. fprintf(stderr,"ok.");
  107770. fprintf(stderr,"\nNull bit call (MSb): ");
  107771. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107772. fprintf(stderr,"ok.");
  107773. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107774. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107775. fprintf(stderr,"ok.");
  107776. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107777. oggpackB_reset(&o);
  107778. for(i=0;i<test2size;i++)
  107779. oggpackB_write(&o,large[i],32);
  107780. buffer=oggpackB_get_buffer(&o);
  107781. bytes=oggpackB_bytes(&o);
  107782. oggpackB_readinit(&r,buffer,bytes);
  107783. for(i=0;i<test2size;i++){
  107784. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107785. if(oggpackB_look(&r,32)!=large[i]){
  107786. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107787. oggpackB_look(&r,32),large[i]);
  107788. report("read incorrect value!\n");
  107789. }
  107790. oggpackB_adv(&r,32);
  107791. }
  107792. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107793. fprintf(stderr,"ok.");
  107794. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107795. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107796. fprintf(stderr,"ok.");
  107797. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107798. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107799. fprintf(stderr,"ok.");
  107800. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107801. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107802. fprintf(stderr,"ok.");
  107803. fprintf(stderr,"\nTesting read past end (MSb): ");
  107804. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107805. for(i=0;i<64;i++){
  107806. if(oggpackB_read(&r,1)!=0){
  107807. fprintf(stderr,"failed; got -1 prematurely.\n");
  107808. exit(1);
  107809. }
  107810. }
  107811. if(oggpackB_look(&r,1)!=-1 ||
  107812. oggpackB_read(&r,1)!=-1){
  107813. fprintf(stderr,"failed; read past end without -1.\n");
  107814. exit(1);
  107815. }
  107816. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107817. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  107818. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107819. exit(1);
  107820. }
  107821. if(oggpackB_look(&r,18)!=0 ||
  107822. oggpackB_look(&r,18)!=0){
  107823. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107824. exit(1);
  107825. }
  107826. if(oggpackB_look(&r,19)!=-1 ||
  107827. oggpackB_look(&r,19)!=-1){
  107828. fprintf(stderr,"failed; read past end without -1.\n");
  107829. exit(1);
  107830. }
  107831. if(oggpackB_look(&r,32)!=-1 ||
  107832. oggpackB_look(&r,32)!=-1){
  107833. fprintf(stderr,"failed; read past end without -1.\n");
  107834. exit(1);
  107835. }
  107836. oggpackB_writeclear(&o);
  107837. fprintf(stderr,"ok.\n\n");
  107838. return(0);
  107839. }
  107840. #endif /* _V_SELFTEST */
  107841. #undef BUFFER_INCREMENT
  107842. #endif
  107843. /*** End of inlined file: bitwise.c ***/
  107844. /*** Start of inlined file: framing.c ***/
  107845. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107846. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107847. // tasks..
  107848. #if JUCE_MSVC
  107849. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107850. #endif
  107851. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107852. #if JUCE_USE_OGGVORBIS
  107853. #include <stdlib.h>
  107854. #include <string.h>
  107855. /* A complete description of Ogg framing exists in docs/framing.html */
  107856. int ogg_page_version(ogg_page *og){
  107857. return((int)(og->header[4]));
  107858. }
  107859. int ogg_page_continued(ogg_page *og){
  107860. return((int)(og->header[5]&0x01));
  107861. }
  107862. int ogg_page_bos(ogg_page *og){
  107863. return((int)(og->header[5]&0x02));
  107864. }
  107865. int ogg_page_eos(ogg_page *og){
  107866. return((int)(og->header[5]&0x04));
  107867. }
  107868. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  107869. unsigned char *page=og->header;
  107870. ogg_int64_t granulepos=page[13]&(0xff);
  107871. granulepos= (granulepos<<8)|(page[12]&0xff);
  107872. granulepos= (granulepos<<8)|(page[11]&0xff);
  107873. granulepos= (granulepos<<8)|(page[10]&0xff);
  107874. granulepos= (granulepos<<8)|(page[9]&0xff);
  107875. granulepos= (granulepos<<8)|(page[8]&0xff);
  107876. granulepos= (granulepos<<8)|(page[7]&0xff);
  107877. granulepos= (granulepos<<8)|(page[6]&0xff);
  107878. return(granulepos);
  107879. }
  107880. int ogg_page_serialno(ogg_page *og){
  107881. return(og->header[14] |
  107882. (og->header[15]<<8) |
  107883. (og->header[16]<<16) |
  107884. (og->header[17]<<24));
  107885. }
  107886. long ogg_page_pageno(ogg_page *og){
  107887. return(og->header[18] |
  107888. (og->header[19]<<8) |
  107889. (og->header[20]<<16) |
  107890. (og->header[21]<<24));
  107891. }
  107892. /* returns the number of packets that are completed on this page (if
  107893. the leading packet is begun on a previous page, but ends on this
  107894. page, it's counted */
  107895. /* NOTE:
  107896. If a page consists of a packet begun on a previous page, and a new
  107897. packet begun (but not completed) on this page, the return will be:
  107898. ogg_page_packets(page) ==1,
  107899. ogg_page_continued(page) !=0
  107900. If a page happens to be a single packet that was begun on a
  107901. previous page, and spans to the next page (in the case of a three or
  107902. more page packet), the return will be:
  107903. ogg_page_packets(page) ==0,
  107904. ogg_page_continued(page) !=0
  107905. */
  107906. int ogg_page_packets(ogg_page *og){
  107907. int i,n=og->header[26],count=0;
  107908. for(i=0;i<n;i++)
  107909. if(og->header[27+i]<255)count++;
  107910. return(count);
  107911. }
  107912. #if 0
  107913. /* helper to initialize lookup for direct-table CRC (illustrative; we
  107914. use the static init below) */
  107915. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  107916. int i;
  107917. unsigned long r;
  107918. r = index << 24;
  107919. for (i=0; i<8; i++)
  107920. if (r & 0x80000000UL)
  107921. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  107922. polynomial, although we use an
  107923. unreflected alg and an init/final
  107924. of 0, not 0xffffffff */
  107925. else
  107926. r<<=1;
  107927. return (r & 0xffffffffUL);
  107928. }
  107929. #endif
  107930. static const ogg_uint32_t crc_lookup[256]={
  107931. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  107932. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  107933. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  107934. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  107935. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  107936. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  107937. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  107938. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  107939. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  107940. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  107941. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  107942. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  107943. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  107944. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  107945. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  107946. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  107947. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  107948. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  107949. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  107950. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  107951. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  107952. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  107953. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  107954. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  107955. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  107956. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  107957. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  107958. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  107959. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  107960. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  107961. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  107962. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  107963. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  107964. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  107965. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  107966. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  107967. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  107968. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  107969. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  107970. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  107971. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  107972. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  107973. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  107974. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  107975. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  107976. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  107977. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  107978. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  107979. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  107980. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  107981. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  107982. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  107983. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  107984. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  107985. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  107986. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  107987. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  107988. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  107989. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  107990. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  107991. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  107992. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  107993. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  107994. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  107995. /* init the encode/decode logical stream state */
  107996. int ogg_stream_init(ogg_stream_state *os,int serialno){
  107997. if(os){
  107998. memset(os,0,sizeof(*os));
  107999. os->body_storage=16*1024;
  108000. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108001. os->lacing_storage=1024;
  108002. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108003. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108004. os->serialno=serialno;
  108005. return(0);
  108006. }
  108007. return(-1);
  108008. }
  108009. /* _clear does not free os, only the non-flat storage within */
  108010. int ogg_stream_clear(ogg_stream_state *os){
  108011. if(os){
  108012. if(os->body_data)_ogg_free(os->body_data);
  108013. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108014. if(os->granule_vals)_ogg_free(os->granule_vals);
  108015. memset(os,0,sizeof(*os));
  108016. }
  108017. return(0);
  108018. }
  108019. int ogg_stream_destroy(ogg_stream_state *os){
  108020. if(os){
  108021. ogg_stream_clear(os);
  108022. _ogg_free(os);
  108023. }
  108024. return(0);
  108025. }
  108026. /* Helpers for ogg_stream_encode; this keeps the structure and
  108027. what's happening fairly clear */
  108028. static void _os_body_expand(ogg_stream_state *os,int needed){
  108029. if(os->body_storage<=os->body_fill+needed){
  108030. os->body_storage+=(needed+1024);
  108031. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108032. }
  108033. }
  108034. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108035. if(os->lacing_storage<=os->lacing_fill+needed){
  108036. os->lacing_storage+=(needed+32);
  108037. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108038. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108039. }
  108040. }
  108041. /* checksum the page */
  108042. /* Direct table CRC; note that this will be faster in the future if we
  108043. perform the checksum silmultaneously with other copies */
  108044. void ogg_page_checksum_set(ogg_page *og){
  108045. if(og){
  108046. ogg_uint32_t crc_reg=0;
  108047. int i;
  108048. /* safety; needed for API behavior, but not framing code */
  108049. og->header[22]=0;
  108050. og->header[23]=0;
  108051. og->header[24]=0;
  108052. og->header[25]=0;
  108053. for(i=0;i<og->header_len;i++)
  108054. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108055. for(i=0;i<og->body_len;i++)
  108056. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108057. og->header[22]=(unsigned char)(crc_reg&0xff);
  108058. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108059. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108060. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108061. }
  108062. }
  108063. /* submit data to the internal buffer of the framing engine */
  108064. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108065. int lacing_vals=op->bytes/255+1,i;
  108066. if(os->body_returned){
  108067. /* advance packet data according to the body_returned pointer. We
  108068. had to keep it around to return a pointer into the buffer last
  108069. call */
  108070. os->body_fill-=os->body_returned;
  108071. if(os->body_fill)
  108072. memmove(os->body_data,os->body_data+os->body_returned,
  108073. os->body_fill);
  108074. os->body_returned=0;
  108075. }
  108076. /* make sure we have the buffer storage */
  108077. _os_body_expand(os,op->bytes);
  108078. _os_lacing_expand(os,lacing_vals);
  108079. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108080. the liability of overly clean abstraction for the time being. It
  108081. will actually be fairly easy to eliminate the extra copy in the
  108082. future */
  108083. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108084. os->body_fill+=op->bytes;
  108085. /* Store lacing vals for this packet */
  108086. for(i=0;i<lacing_vals-1;i++){
  108087. os->lacing_vals[os->lacing_fill+i]=255;
  108088. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108089. }
  108090. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108091. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108092. /* flag the first segment as the beginning of the packet */
  108093. os->lacing_vals[os->lacing_fill]|= 0x100;
  108094. os->lacing_fill+=lacing_vals;
  108095. /* for the sake of completeness */
  108096. os->packetno++;
  108097. if(op->e_o_s)os->e_o_s=1;
  108098. return(0);
  108099. }
  108100. /* This will flush remaining packets into a page (returning nonzero),
  108101. even if there is not enough data to trigger a flush normally
  108102. (undersized page). If there are no packets or partial packets to
  108103. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108104. try to flush a normal sized page like ogg_stream_pageout; a call to
  108105. ogg_stream_flush does not guarantee that all packets have flushed.
  108106. Only a return value of 0 from ogg_stream_flush indicates all packet
  108107. data is flushed into pages.
  108108. since ogg_stream_flush will flush the last page in a stream even if
  108109. it's undersized, you almost certainly want to use ogg_stream_pageout
  108110. (and *not* ogg_stream_flush) unless you specifically need to flush
  108111. an page regardless of size in the middle of a stream. */
  108112. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108113. int i;
  108114. int vals=0;
  108115. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108116. int bytes=0;
  108117. long acc=0;
  108118. ogg_int64_t granule_pos=-1;
  108119. if(maxvals==0)return(0);
  108120. /* construct a page */
  108121. /* decide how many segments to include */
  108122. /* If this is the initial header case, the first page must only include
  108123. the initial header packet */
  108124. if(os->b_o_s==0){ /* 'initial header page' case */
  108125. granule_pos=0;
  108126. for(vals=0;vals<maxvals;vals++){
  108127. if((os->lacing_vals[vals]&0x0ff)<255){
  108128. vals++;
  108129. break;
  108130. }
  108131. }
  108132. }else{
  108133. for(vals=0;vals<maxvals;vals++){
  108134. if(acc>4096)break;
  108135. acc+=os->lacing_vals[vals]&0x0ff;
  108136. if((os->lacing_vals[vals]&0xff)<255)
  108137. granule_pos=os->granule_vals[vals];
  108138. }
  108139. }
  108140. /* construct the header in temp storage */
  108141. memcpy(os->header,"OggS",4);
  108142. /* stream structure version */
  108143. os->header[4]=0x00;
  108144. /* continued packet flag? */
  108145. os->header[5]=0x00;
  108146. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108147. /* first page flag? */
  108148. if(os->b_o_s==0)os->header[5]|=0x02;
  108149. /* last page flag? */
  108150. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108151. os->b_o_s=1;
  108152. /* 64 bits of PCM position */
  108153. for(i=6;i<14;i++){
  108154. os->header[i]=(unsigned char)(granule_pos&0xff);
  108155. granule_pos>>=8;
  108156. }
  108157. /* 32 bits of stream serial number */
  108158. {
  108159. long serialno=os->serialno;
  108160. for(i=14;i<18;i++){
  108161. os->header[i]=(unsigned char)(serialno&0xff);
  108162. serialno>>=8;
  108163. }
  108164. }
  108165. /* 32 bits of page counter (we have both counter and page header
  108166. because this val can roll over) */
  108167. if(os->pageno==-1)os->pageno=0; /* because someone called
  108168. stream_reset; this would be a
  108169. strange thing to do in an
  108170. encode stream, but it has
  108171. plausible uses */
  108172. {
  108173. long pageno=os->pageno++;
  108174. for(i=18;i<22;i++){
  108175. os->header[i]=(unsigned char)(pageno&0xff);
  108176. pageno>>=8;
  108177. }
  108178. }
  108179. /* zero for computation; filled in later */
  108180. os->header[22]=0;
  108181. os->header[23]=0;
  108182. os->header[24]=0;
  108183. os->header[25]=0;
  108184. /* segment table */
  108185. os->header[26]=(unsigned char)(vals&0xff);
  108186. for(i=0;i<vals;i++)
  108187. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108188. /* set pointers in the ogg_page struct */
  108189. og->header=os->header;
  108190. og->header_len=os->header_fill=vals+27;
  108191. og->body=os->body_data+os->body_returned;
  108192. og->body_len=bytes;
  108193. /* advance the lacing data and set the body_returned pointer */
  108194. os->lacing_fill-=vals;
  108195. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108196. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108197. os->body_returned+=bytes;
  108198. /* calculate the checksum */
  108199. ogg_page_checksum_set(og);
  108200. /* done */
  108201. return(1);
  108202. }
  108203. /* This constructs pages from buffered packet segments. The pointers
  108204. returned are to static buffers; do not free. The returned buffers are
  108205. good only until the next call (using the same ogg_stream_state) */
  108206. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108207. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108208. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108209. os->lacing_fill>=255 || /* 'segment table full' case */
  108210. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108211. return(ogg_stream_flush(os,og));
  108212. }
  108213. /* not enough data to construct a page and not end of stream */
  108214. return(0);
  108215. }
  108216. int ogg_stream_eos(ogg_stream_state *os){
  108217. return os->e_o_s;
  108218. }
  108219. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108220. /* This has two layers to place more of the multi-serialno and paging
  108221. control in the application's hands. First, we expose a data buffer
  108222. using ogg_sync_buffer(). The app either copies into the
  108223. buffer, or passes it directly to read(), etc. We then call
  108224. ogg_sync_wrote() to tell how many bytes we just added.
  108225. Pages are returned (pointers into the buffer in ogg_sync_state)
  108226. by ogg_sync_pageout(). The page is then submitted to
  108227. ogg_stream_pagein() along with the appropriate
  108228. ogg_stream_state* (ie, matching serialno). We then get raw
  108229. packets out calling ogg_stream_packetout() with a
  108230. ogg_stream_state. */
  108231. /* initialize the struct to a known state */
  108232. int ogg_sync_init(ogg_sync_state *oy){
  108233. if(oy){
  108234. memset(oy,0,sizeof(*oy));
  108235. }
  108236. return(0);
  108237. }
  108238. /* clear non-flat storage within */
  108239. int ogg_sync_clear(ogg_sync_state *oy){
  108240. if(oy){
  108241. if(oy->data)_ogg_free(oy->data);
  108242. ogg_sync_init(oy);
  108243. }
  108244. return(0);
  108245. }
  108246. int ogg_sync_destroy(ogg_sync_state *oy){
  108247. if(oy){
  108248. ogg_sync_clear(oy);
  108249. _ogg_free(oy);
  108250. }
  108251. return(0);
  108252. }
  108253. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108254. /* first, clear out any space that has been previously returned */
  108255. if(oy->returned){
  108256. oy->fill-=oy->returned;
  108257. if(oy->fill>0)
  108258. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108259. oy->returned=0;
  108260. }
  108261. if(size>oy->storage-oy->fill){
  108262. /* We need to extend the internal buffer */
  108263. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108264. if(oy->data)
  108265. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108266. else
  108267. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108268. oy->storage=newsize;
  108269. }
  108270. /* expose a segment at least as large as requested at the fill mark */
  108271. return((char *)oy->data+oy->fill);
  108272. }
  108273. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108274. if(oy->fill+bytes>oy->storage)return(-1);
  108275. oy->fill+=bytes;
  108276. return(0);
  108277. }
  108278. /* sync the stream. This is meant to be useful for finding page
  108279. boundaries.
  108280. return values for this:
  108281. -n) skipped n bytes
  108282. 0) page not ready; more data (no bytes skipped)
  108283. n) page synced at current location; page length n bytes
  108284. */
  108285. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108286. unsigned char *page=oy->data+oy->returned;
  108287. unsigned char *next;
  108288. long bytes=oy->fill-oy->returned;
  108289. if(oy->headerbytes==0){
  108290. int headerbytes,i;
  108291. if(bytes<27)return(0); /* not enough for a header */
  108292. /* verify capture pattern */
  108293. if(memcmp(page,"OggS",4))goto sync_fail;
  108294. headerbytes=page[26]+27;
  108295. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108296. /* count up body length in the segment table */
  108297. for(i=0;i<page[26];i++)
  108298. oy->bodybytes+=page[27+i];
  108299. oy->headerbytes=headerbytes;
  108300. }
  108301. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108302. /* The whole test page is buffered. Verify the checksum */
  108303. {
  108304. /* Grab the checksum bytes, set the header field to zero */
  108305. char chksum[4];
  108306. ogg_page log;
  108307. memcpy(chksum,page+22,4);
  108308. memset(page+22,0,4);
  108309. /* set up a temp page struct and recompute the checksum */
  108310. log.header=page;
  108311. log.header_len=oy->headerbytes;
  108312. log.body=page+oy->headerbytes;
  108313. log.body_len=oy->bodybytes;
  108314. ogg_page_checksum_set(&log);
  108315. /* Compare */
  108316. if(memcmp(chksum,page+22,4)){
  108317. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108318. at all) */
  108319. /* replace the computed checksum with the one actually read in */
  108320. memcpy(page+22,chksum,4);
  108321. /* Bad checksum. Lose sync */
  108322. goto sync_fail;
  108323. }
  108324. }
  108325. /* yes, have a whole page all ready to go */
  108326. {
  108327. unsigned char *page=oy->data+oy->returned;
  108328. long bytes;
  108329. if(og){
  108330. og->header=page;
  108331. og->header_len=oy->headerbytes;
  108332. og->body=page+oy->headerbytes;
  108333. og->body_len=oy->bodybytes;
  108334. }
  108335. oy->unsynced=0;
  108336. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108337. oy->headerbytes=0;
  108338. oy->bodybytes=0;
  108339. return(bytes);
  108340. }
  108341. sync_fail:
  108342. oy->headerbytes=0;
  108343. oy->bodybytes=0;
  108344. /* search for possible capture */
  108345. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108346. if(!next)
  108347. next=oy->data+oy->fill;
  108348. oy->returned=next-oy->data;
  108349. return(-(next-page));
  108350. }
  108351. /* sync the stream and get a page. Keep trying until we find a page.
  108352. Supress 'sync errors' after reporting the first.
  108353. return values:
  108354. -1) recapture (hole in data)
  108355. 0) need more data
  108356. 1) page returned
  108357. Returns pointers into buffered data; invalidated by next call to
  108358. _stream, _clear, _init, or _buffer */
  108359. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108360. /* all we need to do is verify a page at the head of the stream
  108361. buffer. If it doesn't verify, we look for the next potential
  108362. frame */
  108363. for(;;){
  108364. long ret=ogg_sync_pageseek(oy,og);
  108365. if(ret>0){
  108366. /* have a page */
  108367. return(1);
  108368. }
  108369. if(ret==0){
  108370. /* need more data */
  108371. return(0);
  108372. }
  108373. /* head did not start a synced page... skipped some bytes */
  108374. if(!oy->unsynced){
  108375. oy->unsynced=1;
  108376. return(-1);
  108377. }
  108378. /* loop. keep looking */
  108379. }
  108380. }
  108381. /* add the incoming page to the stream state; we decompose the page
  108382. into packet segments here as well. */
  108383. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108384. unsigned char *header=og->header;
  108385. unsigned char *body=og->body;
  108386. long bodysize=og->body_len;
  108387. int segptr=0;
  108388. int version=ogg_page_version(og);
  108389. int continued=ogg_page_continued(og);
  108390. int bos=ogg_page_bos(og);
  108391. int eos=ogg_page_eos(og);
  108392. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108393. int serialno=ogg_page_serialno(og);
  108394. long pageno=ogg_page_pageno(og);
  108395. int segments=header[26];
  108396. /* clean up 'returned data' */
  108397. {
  108398. long lr=os->lacing_returned;
  108399. long br=os->body_returned;
  108400. /* body data */
  108401. if(br){
  108402. os->body_fill-=br;
  108403. if(os->body_fill)
  108404. memmove(os->body_data,os->body_data+br,os->body_fill);
  108405. os->body_returned=0;
  108406. }
  108407. if(lr){
  108408. /* segment table */
  108409. if(os->lacing_fill-lr){
  108410. memmove(os->lacing_vals,os->lacing_vals+lr,
  108411. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108412. memmove(os->granule_vals,os->granule_vals+lr,
  108413. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108414. }
  108415. os->lacing_fill-=lr;
  108416. os->lacing_packet-=lr;
  108417. os->lacing_returned=0;
  108418. }
  108419. }
  108420. /* check the serial number */
  108421. if(serialno!=os->serialno)return(-1);
  108422. if(version>0)return(-1);
  108423. _os_lacing_expand(os,segments+1);
  108424. /* are we in sequence? */
  108425. if(pageno!=os->pageno){
  108426. int i;
  108427. /* unroll previous partial packet (if any) */
  108428. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108429. os->body_fill-=os->lacing_vals[i]&0xff;
  108430. os->lacing_fill=os->lacing_packet;
  108431. /* make a note of dropped data in segment table */
  108432. if(os->pageno!=-1){
  108433. os->lacing_vals[os->lacing_fill++]=0x400;
  108434. os->lacing_packet++;
  108435. }
  108436. }
  108437. /* are we a 'continued packet' page? If so, we may need to skip
  108438. some segments */
  108439. if(continued){
  108440. if(os->lacing_fill<1 ||
  108441. os->lacing_vals[os->lacing_fill-1]==0x400){
  108442. bos=0;
  108443. for(;segptr<segments;segptr++){
  108444. int val=header[27+segptr];
  108445. body+=val;
  108446. bodysize-=val;
  108447. if(val<255){
  108448. segptr++;
  108449. break;
  108450. }
  108451. }
  108452. }
  108453. }
  108454. if(bodysize){
  108455. _os_body_expand(os,bodysize);
  108456. memcpy(os->body_data+os->body_fill,body,bodysize);
  108457. os->body_fill+=bodysize;
  108458. }
  108459. {
  108460. int saved=-1;
  108461. while(segptr<segments){
  108462. int val=header[27+segptr];
  108463. os->lacing_vals[os->lacing_fill]=val;
  108464. os->granule_vals[os->lacing_fill]=-1;
  108465. if(bos){
  108466. os->lacing_vals[os->lacing_fill]|=0x100;
  108467. bos=0;
  108468. }
  108469. if(val<255)saved=os->lacing_fill;
  108470. os->lacing_fill++;
  108471. segptr++;
  108472. if(val<255)os->lacing_packet=os->lacing_fill;
  108473. }
  108474. /* set the granulepos on the last granuleval of the last full packet */
  108475. if(saved!=-1){
  108476. os->granule_vals[saved]=granulepos;
  108477. }
  108478. }
  108479. if(eos){
  108480. os->e_o_s=1;
  108481. if(os->lacing_fill>0)
  108482. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108483. }
  108484. os->pageno=pageno+1;
  108485. return(0);
  108486. }
  108487. /* clear things to an initial state. Good to call, eg, before seeking */
  108488. int ogg_sync_reset(ogg_sync_state *oy){
  108489. oy->fill=0;
  108490. oy->returned=0;
  108491. oy->unsynced=0;
  108492. oy->headerbytes=0;
  108493. oy->bodybytes=0;
  108494. return(0);
  108495. }
  108496. int ogg_stream_reset(ogg_stream_state *os){
  108497. os->body_fill=0;
  108498. os->body_returned=0;
  108499. os->lacing_fill=0;
  108500. os->lacing_packet=0;
  108501. os->lacing_returned=0;
  108502. os->header_fill=0;
  108503. os->e_o_s=0;
  108504. os->b_o_s=0;
  108505. os->pageno=-1;
  108506. os->packetno=0;
  108507. os->granulepos=0;
  108508. return(0);
  108509. }
  108510. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108511. ogg_stream_reset(os);
  108512. os->serialno=serialno;
  108513. return(0);
  108514. }
  108515. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108516. /* The last part of decode. We have the stream broken into packet
  108517. segments. Now we need to group them into packets (or return the
  108518. out of sync markers) */
  108519. int ptr=os->lacing_returned;
  108520. if(os->lacing_packet<=ptr)return(0);
  108521. if(os->lacing_vals[ptr]&0x400){
  108522. /* we need to tell the codec there's a gap; it might need to
  108523. handle previous packet dependencies. */
  108524. os->lacing_returned++;
  108525. os->packetno++;
  108526. return(-1);
  108527. }
  108528. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108529. to ask if there's a whole packet
  108530. waiting */
  108531. /* Gather the whole packet. We'll have no holes or a partial packet */
  108532. {
  108533. int size=os->lacing_vals[ptr]&0xff;
  108534. int bytes=size;
  108535. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108536. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108537. while(size==255){
  108538. int val=os->lacing_vals[++ptr];
  108539. size=val&0xff;
  108540. if(val&0x200)eos=0x200;
  108541. bytes+=size;
  108542. }
  108543. if(op){
  108544. op->e_o_s=eos;
  108545. op->b_o_s=bos;
  108546. op->packet=os->body_data+os->body_returned;
  108547. op->packetno=os->packetno;
  108548. op->granulepos=os->granule_vals[ptr];
  108549. op->bytes=bytes;
  108550. }
  108551. if(adv){
  108552. os->body_returned+=bytes;
  108553. os->lacing_returned=ptr+1;
  108554. os->packetno++;
  108555. }
  108556. }
  108557. return(1);
  108558. }
  108559. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108560. return _packetout(os,op,1);
  108561. }
  108562. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108563. return _packetout(os,op,0);
  108564. }
  108565. void ogg_packet_clear(ogg_packet *op) {
  108566. _ogg_free(op->packet);
  108567. memset(op, 0, sizeof(*op));
  108568. }
  108569. #ifdef _V_SELFTEST
  108570. #include <stdio.h>
  108571. ogg_stream_state os_en, os_de;
  108572. ogg_sync_state oy;
  108573. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108574. long j;
  108575. static int sequence=0;
  108576. static int lastno=0;
  108577. if(op->bytes!=len){
  108578. fprintf(stderr,"incorrect packet length!\n");
  108579. exit(1);
  108580. }
  108581. if(op->granulepos!=pos){
  108582. fprintf(stderr,"incorrect packet position!\n");
  108583. exit(1);
  108584. }
  108585. /* packet number just follows sequence/gap; adjust the input number
  108586. for that */
  108587. if(no==0){
  108588. sequence=0;
  108589. }else{
  108590. sequence++;
  108591. if(no>lastno+1)
  108592. sequence++;
  108593. }
  108594. lastno=no;
  108595. if(op->packetno!=sequence){
  108596. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108597. (long)(op->packetno),sequence);
  108598. exit(1);
  108599. }
  108600. /* Test data */
  108601. for(j=0;j<op->bytes;j++)
  108602. if(op->packet[j]!=((j+no)&0xff)){
  108603. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108604. j,op->packet[j],(j+no)&0xff);
  108605. exit(1);
  108606. }
  108607. }
  108608. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108609. long j;
  108610. /* Test data */
  108611. for(j=0;j<og->body_len;j++)
  108612. if(og->body[j]!=data[j]){
  108613. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108614. j,data[j],og->body[j]);
  108615. exit(1);
  108616. }
  108617. /* Test header */
  108618. for(j=0;j<og->header_len;j++){
  108619. if(og->header[j]!=header[j]){
  108620. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108621. for(j=0;j<header[26]+27;j++)
  108622. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108623. fprintf(stderr,"\n");
  108624. exit(1);
  108625. }
  108626. }
  108627. if(og->header_len!=header[26]+27){
  108628. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108629. og->header_len,header[26]+27);
  108630. exit(1);
  108631. }
  108632. }
  108633. void print_header(ogg_page *og){
  108634. int j;
  108635. fprintf(stderr,"\nHEADER:\n");
  108636. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108637. og->header[0],og->header[1],og->header[2],og->header[3],
  108638. (int)og->header[4],(int)og->header[5]);
  108639. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108640. (og->header[9]<<24)|(og->header[8]<<16)|
  108641. (og->header[7]<<8)|og->header[6],
  108642. (og->header[17]<<24)|(og->header[16]<<16)|
  108643. (og->header[15]<<8)|og->header[14],
  108644. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108645. (og->header[19]<<8)|og->header[18]);
  108646. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108647. (int)og->header[22],(int)og->header[23],
  108648. (int)og->header[24],(int)og->header[25],
  108649. (int)og->header[26]);
  108650. for(j=27;j<og->header_len;j++)
  108651. fprintf(stderr,"%d ",(int)og->header[j]);
  108652. fprintf(stderr,")\n\n");
  108653. }
  108654. void copy_page(ogg_page *og){
  108655. unsigned char *temp=_ogg_malloc(og->header_len);
  108656. memcpy(temp,og->header,og->header_len);
  108657. og->header=temp;
  108658. temp=_ogg_malloc(og->body_len);
  108659. memcpy(temp,og->body,og->body_len);
  108660. og->body=temp;
  108661. }
  108662. void free_page(ogg_page *og){
  108663. _ogg_free (og->header);
  108664. _ogg_free (og->body);
  108665. }
  108666. void error(void){
  108667. fprintf(stderr,"error!\n");
  108668. exit(1);
  108669. }
  108670. /* 17 only */
  108671. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108672. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108673. 0x01,0x02,0x03,0x04,0,0,0,0,
  108674. 0x15,0xed,0xec,0x91,
  108675. 1,
  108676. 17};
  108677. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108678. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108679. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108680. 0x01,0x02,0x03,0x04,0,0,0,0,
  108681. 0x59,0x10,0x6c,0x2c,
  108682. 1,
  108683. 17};
  108684. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108685. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108686. 0x01,0x02,0x03,0x04,1,0,0,0,
  108687. 0x89,0x33,0x85,0xce,
  108688. 13,
  108689. 254,255,0,255,1,255,245,255,255,0,
  108690. 255,255,90};
  108691. /* nil packets; beginning,middle,end */
  108692. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108693. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108694. 0x01,0x02,0x03,0x04,0,0,0,0,
  108695. 0xff,0x7b,0x23,0x17,
  108696. 1,
  108697. 0};
  108698. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108699. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108700. 0x01,0x02,0x03,0x04,1,0,0,0,
  108701. 0x5c,0x3f,0x66,0xcb,
  108702. 17,
  108703. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108704. 255,255,90,0};
  108705. /* large initial packet */
  108706. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108707. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108708. 0x01,0x02,0x03,0x04,0,0,0,0,
  108709. 0x01,0x27,0x31,0xaa,
  108710. 18,
  108711. 255,255,255,255,255,255,255,255,
  108712. 255,255,255,255,255,255,255,255,255,10};
  108713. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108714. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108715. 0x01,0x02,0x03,0x04,1,0,0,0,
  108716. 0x7f,0x4e,0x8a,0xd2,
  108717. 4,
  108718. 255,4,255,0};
  108719. /* continuing packet test */
  108720. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108721. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108722. 0x01,0x02,0x03,0x04,0,0,0,0,
  108723. 0xff,0x7b,0x23,0x17,
  108724. 1,
  108725. 0};
  108726. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108727. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108728. 0x01,0x02,0x03,0x04,1,0,0,0,
  108729. 0x54,0x05,0x51,0xc8,
  108730. 17,
  108731. 255,255,255,255,255,255,255,255,
  108732. 255,255,255,255,255,255,255,255,255};
  108733. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108734. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108735. 0x01,0x02,0x03,0x04,2,0,0,0,
  108736. 0xc8,0xc3,0xcb,0xed,
  108737. 5,
  108738. 10,255,4,255,0};
  108739. /* page with the 255 segment limit */
  108740. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108741. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108742. 0x01,0x02,0x03,0x04,0,0,0,0,
  108743. 0xff,0x7b,0x23,0x17,
  108744. 1,
  108745. 0};
  108746. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108747. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108748. 0x01,0x02,0x03,0x04,1,0,0,0,
  108749. 0xed,0x2a,0x2e,0xa7,
  108750. 255,
  108751. 10,10,10,10,10,10,10,10,
  108752. 10,10,10,10,10,10,10,10,
  108753. 10,10,10,10,10,10,10,10,
  108754. 10,10,10,10,10,10,10,10,
  108755. 10,10,10,10,10,10,10,10,
  108756. 10,10,10,10,10,10,10,10,
  108757. 10,10,10,10,10,10,10,10,
  108758. 10,10,10,10,10,10,10,10,
  108759. 10,10,10,10,10,10,10,10,
  108760. 10,10,10,10,10,10,10,10,
  108761. 10,10,10,10,10,10,10,10,
  108762. 10,10,10,10,10,10,10,10,
  108763. 10,10,10,10,10,10,10,10,
  108764. 10,10,10,10,10,10,10,10,
  108765. 10,10,10,10,10,10,10,10,
  108766. 10,10,10,10,10,10,10,10,
  108767. 10,10,10,10,10,10,10,10,
  108768. 10,10,10,10,10,10,10,10,
  108769. 10,10,10,10,10,10,10,10,
  108770. 10,10,10,10,10,10,10,10,
  108771. 10,10,10,10,10,10,10,10,
  108772. 10,10,10,10,10,10,10,10,
  108773. 10,10,10,10,10,10,10,10,
  108774. 10,10,10,10,10,10,10,10,
  108775. 10,10,10,10,10,10,10,10,
  108776. 10,10,10,10,10,10,10,10,
  108777. 10,10,10,10,10,10,10,10,
  108778. 10,10,10,10,10,10,10,10,
  108779. 10,10,10,10,10,10,10,10,
  108780. 10,10,10,10,10,10,10,10,
  108781. 10,10,10,10,10,10,10,10,
  108782. 10,10,10,10,10,10,10};
  108783. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108784. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108785. 0x01,0x02,0x03,0x04,2,0,0,0,
  108786. 0x6c,0x3b,0x82,0x3d,
  108787. 1,
  108788. 50};
  108789. /* packet that overspans over an entire page */
  108790. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108791. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108792. 0x01,0x02,0x03,0x04,0,0,0,0,
  108793. 0xff,0x7b,0x23,0x17,
  108794. 1,
  108795. 0};
  108796. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108797. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108798. 0x01,0x02,0x03,0x04,1,0,0,0,
  108799. 0x3c,0xd9,0x4d,0x3f,
  108800. 17,
  108801. 100,255,255,255,255,255,255,255,255,
  108802. 255,255,255,255,255,255,255,255};
  108803. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108804. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108805. 0x01,0x02,0x03,0x04,2,0,0,0,
  108806. 0x01,0xd2,0xe5,0xe5,
  108807. 17,
  108808. 255,255,255,255,255,255,255,255,
  108809. 255,255,255,255,255,255,255,255,255};
  108810. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108811. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108812. 0x01,0x02,0x03,0x04,3,0,0,0,
  108813. 0xef,0xdd,0x88,0xde,
  108814. 7,
  108815. 255,255,75,255,4,255,0};
  108816. /* packet that overspans over an entire page */
  108817. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108818. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108819. 0x01,0x02,0x03,0x04,0,0,0,0,
  108820. 0xff,0x7b,0x23,0x17,
  108821. 1,
  108822. 0};
  108823. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108824. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108825. 0x01,0x02,0x03,0x04,1,0,0,0,
  108826. 0x3c,0xd9,0x4d,0x3f,
  108827. 17,
  108828. 100,255,255,255,255,255,255,255,255,
  108829. 255,255,255,255,255,255,255,255};
  108830. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108831. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108832. 0x01,0x02,0x03,0x04,2,0,0,0,
  108833. 0xd4,0xe0,0x60,0xe5,
  108834. 1,0};
  108835. void test_pack(const int *pl, const int **headers, int byteskip,
  108836. int pageskip, int packetskip){
  108837. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  108838. long inptr=0;
  108839. long outptr=0;
  108840. long deptr=0;
  108841. long depacket=0;
  108842. long granule_pos=7,pageno=0;
  108843. int i,j,packets,pageout=pageskip;
  108844. int eosflag=0;
  108845. int bosflag=0;
  108846. int byteskipcount=0;
  108847. ogg_stream_reset(&os_en);
  108848. ogg_stream_reset(&os_de);
  108849. ogg_sync_reset(&oy);
  108850. for(packets=0;packets<packetskip;packets++)
  108851. depacket+=pl[packets];
  108852. for(packets=0;;packets++)if(pl[packets]==-1)break;
  108853. for(i=0;i<packets;i++){
  108854. /* construct a test packet */
  108855. ogg_packet op;
  108856. int len=pl[i];
  108857. op.packet=data+inptr;
  108858. op.bytes=len;
  108859. op.e_o_s=(pl[i+1]<0?1:0);
  108860. op.granulepos=granule_pos;
  108861. granule_pos+=1024;
  108862. for(j=0;j<len;j++)data[inptr++]=i+j;
  108863. /* submit the test packet */
  108864. ogg_stream_packetin(&os_en,&op);
  108865. /* retrieve any finished pages */
  108866. {
  108867. ogg_page og;
  108868. while(ogg_stream_pageout(&os_en,&og)){
  108869. /* We have a page. Check it carefully */
  108870. fprintf(stderr,"%ld, ",pageno);
  108871. if(headers[pageno]==NULL){
  108872. fprintf(stderr,"coded too many pages!\n");
  108873. exit(1);
  108874. }
  108875. check_page(data+outptr,headers[pageno],&og);
  108876. outptr+=og.body_len;
  108877. pageno++;
  108878. if(pageskip){
  108879. bosflag=1;
  108880. pageskip--;
  108881. deptr+=og.body_len;
  108882. }
  108883. /* have a complete page; submit it to sync/decode */
  108884. {
  108885. ogg_page og_de;
  108886. ogg_packet op_de,op_de2;
  108887. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  108888. char *next=buf;
  108889. byteskipcount+=og.header_len;
  108890. if(byteskipcount>byteskip){
  108891. memcpy(next,og.header,byteskipcount-byteskip);
  108892. next+=byteskipcount-byteskip;
  108893. byteskipcount=byteskip;
  108894. }
  108895. byteskipcount+=og.body_len;
  108896. if(byteskipcount>byteskip){
  108897. memcpy(next,og.body,byteskipcount-byteskip);
  108898. next+=byteskipcount-byteskip;
  108899. byteskipcount=byteskip;
  108900. }
  108901. ogg_sync_wrote(&oy,next-buf);
  108902. while(1){
  108903. int ret=ogg_sync_pageout(&oy,&og_de);
  108904. if(ret==0)break;
  108905. if(ret<0)continue;
  108906. /* got a page. Happy happy. Verify that it's good. */
  108907. fprintf(stderr,"(%ld), ",pageout);
  108908. check_page(data+deptr,headers[pageout],&og_de);
  108909. deptr+=og_de.body_len;
  108910. pageout++;
  108911. /* submit it to deconstitution */
  108912. ogg_stream_pagein(&os_de,&og_de);
  108913. /* packets out? */
  108914. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  108915. ogg_stream_packetpeek(&os_de,NULL);
  108916. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  108917. /* verify peek and out match */
  108918. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  108919. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  108920. depacket);
  108921. exit(1);
  108922. }
  108923. /* verify the packet! */
  108924. /* check data */
  108925. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  108926. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  108927. depacket);
  108928. exit(1);
  108929. }
  108930. /* check bos flag */
  108931. if(bosflag==0 && op_de.b_o_s==0){
  108932. fprintf(stderr,"b_o_s flag not set on packet!\n");
  108933. exit(1);
  108934. }
  108935. if(bosflag && op_de.b_o_s){
  108936. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  108937. exit(1);
  108938. }
  108939. bosflag=1;
  108940. depacket+=op_de.bytes;
  108941. /* check eos flag */
  108942. if(eosflag){
  108943. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  108944. exit(1);
  108945. }
  108946. if(op_de.e_o_s)eosflag=1;
  108947. /* check granulepos flag */
  108948. if(op_de.granulepos!=-1){
  108949. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  108950. }
  108951. }
  108952. }
  108953. }
  108954. }
  108955. }
  108956. }
  108957. _ogg_free(data);
  108958. if(headers[pageno]!=NULL){
  108959. fprintf(stderr,"did not write last page!\n");
  108960. exit(1);
  108961. }
  108962. if(headers[pageout]!=NULL){
  108963. fprintf(stderr,"did not decode last page!\n");
  108964. exit(1);
  108965. }
  108966. if(inptr!=outptr){
  108967. fprintf(stderr,"encoded page data incomplete!\n");
  108968. exit(1);
  108969. }
  108970. if(inptr!=deptr){
  108971. fprintf(stderr,"decoded page data incomplete!\n");
  108972. exit(1);
  108973. }
  108974. if(inptr!=depacket){
  108975. fprintf(stderr,"decoded packet data incomplete!\n");
  108976. exit(1);
  108977. }
  108978. if(!eosflag){
  108979. fprintf(stderr,"Never got a packet with EOS set!\n");
  108980. exit(1);
  108981. }
  108982. fprintf(stderr,"ok.\n");
  108983. }
  108984. int main(void){
  108985. ogg_stream_init(&os_en,0x04030201);
  108986. ogg_stream_init(&os_de,0x04030201);
  108987. ogg_sync_init(&oy);
  108988. /* Exercise each code path in the framing code. Also verify that
  108989. the checksums are working. */
  108990. {
  108991. /* 17 only */
  108992. const int packets[]={17, -1};
  108993. const int *headret[]={head1_0,NULL};
  108994. fprintf(stderr,"testing single page encoding... ");
  108995. test_pack(packets,headret,0,0,0);
  108996. }
  108997. {
  108998. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108999. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109000. const int *headret[]={head1_1,head2_1,NULL};
  109001. fprintf(stderr,"testing basic page encoding... ");
  109002. test_pack(packets,headret,0,0,0);
  109003. }
  109004. {
  109005. /* nil packets; beginning,middle,end */
  109006. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109007. const int *headret[]={head1_2,head2_2,NULL};
  109008. fprintf(stderr,"testing basic nil packets... ");
  109009. test_pack(packets,headret,0,0,0);
  109010. }
  109011. {
  109012. /* large initial packet */
  109013. const int packets[]={4345,259,255,-1};
  109014. const int *headret[]={head1_3,head2_3,NULL};
  109015. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109016. test_pack(packets,headret,0,0,0);
  109017. }
  109018. {
  109019. /* continuing packet test */
  109020. const int packets[]={0,4345,259,255,-1};
  109021. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109022. fprintf(stderr,"testing single packet page span... ");
  109023. test_pack(packets,headret,0,0,0);
  109024. }
  109025. /* page with the 255 segment limit */
  109026. {
  109027. const int packets[]={0,10,10,10,10,10,10,10,10,
  109028. 10,10,10,10,10,10,10,10,
  109029. 10,10,10,10,10,10,10,10,
  109030. 10,10,10,10,10,10,10,10,
  109031. 10,10,10,10,10,10,10,10,
  109032. 10,10,10,10,10,10,10,10,
  109033. 10,10,10,10,10,10,10,10,
  109034. 10,10,10,10,10,10,10,10,
  109035. 10,10,10,10,10,10,10,10,
  109036. 10,10,10,10,10,10,10,10,
  109037. 10,10,10,10,10,10,10,10,
  109038. 10,10,10,10,10,10,10,10,
  109039. 10,10,10,10,10,10,10,10,
  109040. 10,10,10,10,10,10,10,10,
  109041. 10,10,10,10,10,10,10,10,
  109042. 10,10,10,10,10,10,10,10,
  109043. 10,10,10,10,10,10,10,10,
  109044. 10,10,10,10,10,10,10,10,
  109045. 10,10,10,10,10,10,10,10,
  109046. 10,10,10,10,10,10,10,10,
  109047. 10,10,10,10,10,10,10,10,
  109048. 10,10,10,10,10,10,10,10,
  109049. 10,10,10,10,10,10,10,10,
  109050. 10,10,10,10,10,10,10,10,
  109051. 10,10,10,10,10,10,10,10,
  109052. 10,10,10,10,10,10,10,10,
  109053. 10,10,10,10,10,10,10,10,
  109054. 10,10,10,10,10,10,10,10,
  109055. 10,10,10,10,10,10,10,10,
  109056. 10,10,10,10,10,10,10,10,
  109057. 10,10,10,10,10,10,10,10,
  109058. 10,10,10,10,10,10,10,50,-1};
  109059. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109060. fprintf(stderr,"testing max packet segments... ");
  109061. test_pack(packets,headret,0,0,0);
  109062. }
  109063. {
  109064. /* packet that overspans over an entire page */
  109065. const int packets[]={0,100,9000,259,255,-1};
  109066. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109067. fprintf(stderr,"testing very large packets... ");
  109068. test_pack(packets,headret,0,0,0);
  109069. }
  109070. {
  109071. /* test for the libogg 1.1.1 resync in large continuation bug
  109072. found by Josh Coalson) */
  109073. const int packets[]={0,100,9000,259,255,-1};
  109074. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109075. fprintf(stderr,"testing continuation resync in very large packets... ");
  109076. test_pack(packets,headret,100,2,3);
  109077. }
  109078. {
  109079. /* term only page. why not? */
  109080. const int packets[]={0,100,4080,-1};
  109081. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109082. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109083. test_pack(packets,headret,0,0,0);
  109084. }
  109085. {
  109086. /* build a bunch of pages for testing */
  109087. unsigned char *data=_ogg_malloc(1024*1024);
  109088. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109089. int inptr=0,i,j;
  109090. ogg_page og[5];
  109091. ogg_stream_reset(&os_en);
  109092. for(i=0;pl[i]!=-1;i++){
  109093. ogg_packet op;
  109094. int len=pl[i];
  109095. op.packet=data+inptr;
  109096. op.bytes=len;
  109097. op.e_o_s=(pl[i+1]<0?1:0);
  109098. op.granulepos=(i+1)*1000;
  109099. for(j=0;j<len;j++)data[inptr++]=i+j;
  109100. ogg_stream_packetin(&os_en,&op);
  109101. }
  109102. _ogg_free(data);
  109103. /* retrieve finished pages */
  109104. for(i=0;i<5;i++){
  109105. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109106. fprintf(stderr,"Too few pages output building sync tests!\n");
  109107. exit(1);
  109108. }
  109109. copy_page(&og[i]);
  109110. }
  109111. /* Test lost pages on pagein/packetout: no rollback */
  109112. {
  109113. ogg_page temp;
  109114. ogg_packet test;
  109115. fprintf(stderr,"Testing loss of pages... ");
  109116. ogg_sync_reset(&oy);
  109117. ogg_stream_reset(&os_de);
  109118. for(i=0;i<5;i++){
  109119. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109120. og[i].header_len);
  109121. ogg_sync_wrote(&oy,og[i].header_len);
  109122. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109123. ogg_sync_wrote(&oy,og[i].body_len);
  109124. }
  109125. ogg_sync_pageout(&oy,&temp);
  109126. ogg_stream_pagein(&os_de,&temp);
  109127. ogg_sync_pageout(&oy,&temp);
  109128. ogg_stream_pagein(&os_de,&temp);
  109129. ogg_sync_pageout(&oy,&temp);
  109130. /* skip */
  109131. ogg_sync_pageout(&oy,&temp);
  109132. ogg_stream_pagein(&os_de,&temp);
  109133. /* do we get the expected results/packets? */
  109134. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109135. checkpacket(&test,0,0,0);
  109136. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109137. checkpacket(&test,100,1,-1);
  109138. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109139. checkpacket(&test,4079,2,3000);
  109140. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109141. fprintf(stderr,"Error: loss of page did not return error\n");
  109142. exit(1);
  109143. }
  109144. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109145. checkpacket(&test,76,5,-1);
  109146. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109147. checkpacket(&test,34,6,-1);
  109148. fprintf(stderr,"ok.\n");
  109149. }
  109150. /* Test lost pages on pagein/packetout: rollback with continuation */
  109151. {
  109152. ogg_page temp;
  109153. ogg_packet test;
  109154. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109155. ogg_sync_reset(&oy);
  109156. ogg_stream_reset(&os_de);
  109157. for(i=0;i<5;i++){
  109158. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109159. og[i].header_len);
  109160. ogg_sync_wrote(&oy,og[i].header_len);
  109161. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109162. ogg_sync_wrote(&oy,og[i].body_len);
  109163. }
  109164. ogg_sync_pageout(&oy,&temp);
  109165. ogg_stream_pagein(&os_de,&temp);
  109166. ogg_sync_pageout(&oy,&temp);
  109167. ogg_stream_pagein(&os_de,&temp);
  109168. ogg_sync_pageout(&oy,&temp);
  109169. ogg_stream_pagein(&os_de,&temp);
  109170. ogg_sync_pageout(&oy,&temp);
  109171. /* skip */
  109172. ogg_sync_pageout(&oy,&temp);
  109173. ogg_stream_pagein(&os_de,&temp);
  109174. /* do we get the expected results/packets? */
  109175. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109176. checkpacket(&test,0,0,0);
  109177. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109178. checkpacket(&test,100,1,-1);
  109179. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109180. checkpacket(&test,4079,2,3000);
  109181. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109182. checkpacket(&test,2956,3,4000);
  109183. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109184. fprintf(stderr,"Error: loss of page did not return error\n");
  109185. exit(1);
  109186. }
  109187. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109188. checkpacket(&test,300,13,14000);
  109189. fprintf(stderr,"ok.\n");
  109190. }
  109191. /* the rest only test sync */
  109192. {
  109193. ogg_page og_de;
  109194. /* Test fractional page inputs: incomplete capture */
  109195. fprintf(stderr,"Testing sync on partial inputs... ");
  109196. ogg_sync_reset(&oy);
  109197. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109198. 3);
  109199. ogg_sync_wrote(&oy,3);
  109200. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109201. /* Test fractional page inputs: incomplete fixed header */
  109202. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109203. 20);
  109204. ogg_sync_wrote(&oy,20);
  109205. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109206. /* Test fractional page inputs: incomplete header */
  109207. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109208. 5);
  109209. ogg_sync_wrote(&oy,5);
  109210. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109211. /* Test fractional page inputs: incomplete body */
  109212. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109213. og[1].header_len-28);
  109214. ogg_sync_wrote(&oy,og[1].header_len-28);
  109215. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109216. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109217. ogg_sync_wrote(&oy,1000);
  109218. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109219. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109220. og[1].body_len-1000);
  109221. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109222. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109223. fprintf(stderr,"ok.\n");
  109224. }
  109225. /* Test fractional page inputs: page + incomplete capture */
  109226. {
  109227. ogg_page og_de;
  109228. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109229. ogg_sync_reset(&oy);
  109230. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109231. og[1].header_len);
  109232. ogg_sync_wrote(&oy,og[1].header_len);
  109233. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109234. og[1].body_len);
  109235. ogg_sync_wrote(&oy,og[1].body_len);
  109236. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109237. 20);
  109238. ogg_sync_wrote(&oy,20);
  109239. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109240. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109241. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109242. og[1].header_len-20);
  109243. ogg_sync_wrote(&oy,og[1].header_len-20);
  109244. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109245. og[1].body_len);
  109246. ogg_sync_wrote(&oy,og[1].body_len);
  109247. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109248. fprintf(stderr,"ok.\n");
  109249. }
  109250. /* Test recapture: garbage + page */
  109251. {
  109252. ogg_page og_de;
  109253. fprintf(stderr,"Testing search for capture... ");
  109254. ogg_sync_reset(&oy);
  109255. /* 'garbage' */
  109256. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109257. og[1].body_len);
  109258. ogg_sync_wrote(&oy,og[1].body_len);
  109259. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109260. og[1].header_len);
  109261. ogg_sync_wrote(&oy,og[1].header_len);
  109262. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109263. og[1].body_len);
  109264. ogg_sync_wrote(&oy,og[1].body_len);
  109265. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109266. 20);
  109267. ogg_sync_wrote(&oy,20);
  109268. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109269. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109270. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109271. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109272. og[2].header_len-20);
  109273. ogg_sync_wrote(&oy,og[2].header_len-20);
  109274. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109275. og[2].body_len);
  109276. ogg_sync_wrote(&oy,og[2].body_len);
  109277. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109278. fprintf(stderr,"ok.\n");
  109279. }
  109280. /* Test recapture: page + garbage + page */
  109281. {
  109282. ogg_page og_de;
  109283. fprintf(stderr,"Testing recapture... ");
  109284. ogg_sync_reset(&oy);
  109285. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109286. og[1].header_len);
  109287. ogg_sync_wrote(&oy,og[1].header_len);
  109288. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109289. og[1].body_len);
  109290. ogg_sync_wrote(&oy,og[1].body_len);
  109291. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109292. og[2].header_len);
  109293. ogg_sync_wrote(&oy,og[2].header_len);
  109294. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109295. og[2].header_len);
  109296. ogg_sync_wrote(&oy,og[2].header_len);
  109297. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109298. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109299. og[2].body_len-5);
  109300. ogg_sync_wrote(&oy,og[2].body_len-5);
  109301. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109302. og[3].header_len);
  109303. ogg_sync_wrote(&oy,og[3].header_len);
  109304. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109305. og[3].body_len);
  109306. ogg_sync_wrote(&oy,og[3].body_len);
  109307. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109308. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109309. fprintf(stderr,"ok.\n");
  109310. }
  109311. /* Free page data that was previously copied */
  109312. {
  109313. for(i=0;i<5;i++){
  109314. free_page(&og[i]);
  109315. }
  109316. }
  109317. }
  109318. return(0);
  109319. }
  109320. #endif
  109321. #endif
  109322. /*** End of inlined file: framing.c ***/
  109323. /*** Start of inlined file: analysis.c ***/
  109324. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109325. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109326. // tasks..
  109327. #if JUCE_MSVC
  109328. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109329. #endif
  109330. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109331. #if JUCE_USE_OGGVORBIS
  109332. #include <stdio.h>
  109333. #include <string.h>
  109334. #include <math.h>
  109335. /*** Start of inlined file: codec_internal.h ***/
  109336. #ifndef _V_CODECI_H_
  109337. #define _V_CODECI_H_
  109338. /*** Start of inlined file: envelope.h ***/
  109339. #ifndef _V_ENVELOPE_
  109340. #define _V_ENVELOPE_
  109341. /*** Start of inlined file: mdct.h ***/
  109342. #ifndef _OGG_mdct_H_
  109343. #define _OGG_mdct_H_
  109344. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109345. #ifdef MDCT_INTEGERIZED
  109346. #define DATA_TYPE int
  109347. #define REG_TYPE register int
  109348. #define TRIGBITS 14
  109349. #define cPI3_8 6270
  109350. #define cPI2_8 11585
  109351. #define cPI1_8 15137
  109352. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109353. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109354. #define HALVE(x) ((x)>>1)
  109355. #else
  109356. #define DATA_TYPE float
  109357. #define REG_TYPE float
  109358. #define cPI3_8 .38268343236508977175F
  109359. #define cPI2_8 .70710678118654752441F
  109360. #define cPI1_8 .92387953251128675613F
  109361. #define FLOAT_CONV(x) (x)
  109362. #define MULT_NORM(x) (x)
  109363. #define HALVE(x) ((x)*.5f)
  109364. #endif
  109365. typedef struct {
  109366. int n;
  109367. int log2n;
  109368. DATA_TYPE *trig;
  109369. int *bitrev;
  109370. DATA_TYPE scale;
  109371. } mdct_lookup;
  109372. extern void mdct_init(mdct_lookup *lookup,int n);
  109373. extern void mdct_clear(mdct_lookup *l);
  109374. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109375. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109376. #endif
  109377. /*** End of inlined file: mdct.h ***/
  109378. #define VE_PRE 16
  109379. #define VE_WIN 4
  109380. #define VE_POST 2
  109381. #define VE_AMP (VE_PRE+VE_POST-1)
  109382. #define VE_BANDS 7
  109383. #define VE_NEARDC 15
  109384. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109385. #define VE_MAXSTRETCH 12 /* one-third full block */
  109386. typedef struct {
  109387. float ampbuf[VE_AMP];
  109388. int ampptr;
  109389. float nearDC[VE_NEARDC];
  109390. float nearDC_acc;
  109391. float nearDC_partialacc;
  109392. int nearptr;
  109393. } envelope_filter_state;
  109394. typedef struct {
  109395. int begin;
  109396. int end;
  109397. float *window;
  109398. float total;
  109399. } envelope_band;
  109400. typedef struct {
  109401. int ch;
  109402. int winlength;
  109403. int searchstep;
  109404. float minenergy;
  109405. mdct_lookup mdct;
  109406. float *mdct_win;
  109407. envelope_band band[VE_BANDS];
  109408. envelope_filter_state *filter;
  109409. int stretch;
  109410. int *mark;
  109411. long storage;
  109412. long current;
  109413. long curmark;
  109414. long cursor;
  109415. } envelope_lookup;
  109416. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109417. extern void _ve_envelope_clear(envelope_lookup *e);
  109418. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109419. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109420. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109421. #endif
  109422. /*** End of inlined file: envelope.h ***/
  109423. /*** Start of inlined file: codebook.h ***/
  109424. #ifndef _V_CODEBOOK_H_
  109425. #define _V_CODEBOOK_H_
  109426. /* This structure encapsulates huffman and VQ style encoding books; it
  109427. doesn't do anything specific to either.
  109428. valuelist/quantlist are nonNULL (and q_* significant) only if
  109429. there's entry->value mapping to be done.
  109430. If encode-side mapping must be done (and thus the entry needs to be
  109431. hunted), the auxiliary encode pointer will point to a decision
  109432. tree. This is true of both VQ and huffman, but is mostly useful
  109433. with VQ.
  109434. */
  109435. typedef struct static_codebook{
  109436. long dim; /* codebook dimensions (elements per vector) */
  109437. long entries; /* codebook entries */
  109438. long *lengthlist; /* codeword lengths in bits */
  109439. /* mapping ***************************************************************/
  109440. int maptype; /* 0=none
  109441. 1=implicitly populated values from map column
  109442. 2=listed arbitrary values */
  109443. /* The below does a linear, single monotonic sequence mapping. */
  109444. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109445. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109446. int q_quant; /* bits: 0 < quant <= 16 */
  109447. int q_sequencep; /* bitflag */
  109448. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109449. map == 2: list of dim*entries quantized entry vals
  109450. */
  109451. /* encode helpers ********************************************************/
  109452. struct encode_aux_nearestmatch *nearest_tree;
  109453. struct encode_aux_threshmatch *thresh_tree;
  109454. struct encode_aux_pigeonhole *pigeon_tree;
  109455. int allocedp;
  109456. } static_codebook;
  109457. /* this structures an arbitrary trained book to quickly find the
  109458. nearest cell match */
  109459. typedef struct encode_aux_nearestmatch{
  109460. /* pre-calculated partitioning tree */
  109461. long *ptr0;
  109462. long *ptr1;
  109463. long *p; /* decision points (each is an entry) */
  109464. long *q; /* decision points (each is an entry) */
  109465. long aux; /* number of tree entries */
  109466. long alloc;
  109467. } encode_aux_nearestmatch;
  109468. /* assumes a maptype of 1; encode side only, so that's OK */
  109469. typedef struct encode_aux_threshmatch{
  109470. float *quantthresh;
  109471. long *quantmap;
  109472. int quantvals;
  109473. int threshvals;
  109474. } encode_aux_threshmatch;
  109475. typedef struct encode_aux_pigeonhole{
  109476. float min;
  109477. float del;
  109478. int mapentries;
  109479. int quantvals;
  109480. long *pigeonmap;
  109481. long fittotal;
  109482. long *fitlist;
  109483. long *fitmap;
  109484. long *fitlength;
  109485. } encode_aux_pigeonhole;
  109486. typedef struct codebook{
  109487. long dim; /* codebook dimensions (elements per vector) */
  109488. long entries; /* codebook entries */
  109489. long used_entries; /* populated codebook entries */
  109490. const static_codebook *c;
  109491. /* for encode, the below are entry-ordered, fully populated */
  109492. /* for decode, the below are ordered by bitreversed codeword and only
  109493. used entries are populated */
  109494. float *valuelist; /* list of dim*entries actual entry values */
  109495. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109496. int *dec_index; /* only used if sparseness collapsed */
  109497. char *dec_codelengths;
  109498. ogg_uint32_t *dec_firsttable;
  109499. int dec_firsttablen;
  109500. int dec_maxlength;
  109501. } codebook;
  109502. extern void vorbis_staticbook_clear(static_codebook *b);
  109503. extern void vorbis_staticbook_destroy(static_codebook *b);
  109504. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109505. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109506. extern void vorbis_book_clear(codebook *b);
  109507. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109508. extern float *_book_logdist(const static_codebook *b,float *vals);
  109509. extern float _float32_unpack(long val);
  109510. extern long _float32_pack(float val);
  109511. extern int _best(codebook *book, float *a, int step);
  109512. extern int _ilog(unsigned int v);
  109513. extern long _book_maptype1_quantvals(const static_codebook *b);
  109514. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109515. extern long vorbis_book_codeword(codebook *book,int entry);
  109516. extern long vorbis_book_codelen(codebook *book,int entry);
  109517. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109518. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109519. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109520. extern int vorbis_book_errorv(codebook *book, float *a);
  109521. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109522. oggpack_buffer *b);
  109523. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109524. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109525. oggpack_buffer *b,int n);
  109526. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109527. oggpack_buffer *b,int n);
  109528. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109529. oggpack_buffer *b,int n);
  109530. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109531. long off,int ch,
  109532. oggpack_buffer *b,int n);
  109533. #endif
  109534. /*** End of inlined file: codebook.h ***/
  109535. #define BLOCKTYPE_IMPULSE 0
  109536. #define BLOCKTYPE_PADDING 1
  109537. #define BLOCKTYPE_TRANSITION 0
  109538. #define BLOCKTYPE_LONG 1
  109539. #define PACKETBLOBS 15
  109540. typedef struct vorbis_block_internal{
  109541. float **pcmdelay; /* this is a pointer into local storage */
  109542. float ampmax;
  109543. int blocktype;
  109544. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109545. blob [PACKETBLOBS/2] points to
  109546. the oggpack_buffer in the
  109547. main vorbis_block */
  109548. } vorbis_block_internal;
  109549. typedef void vorbis_look_floor;
  109550. typedef void vorbis_look_residue;
  109551. typedef void vorbis_look_transform;
  109552. /* mode ************************************************************/
  109553. typedef struct {
  109554. int blockflag;
  109555. int windowtype;
  109556. int transformtype;
  109557. int mapping;
  109558. } vorbis_info_mode;
  109559. typedef void vorbis_info_floor;
  109560. typedef void vorbis_info_residue;
  109561. typedef void vorbis_info_mapping;
  109562. /*** Start of inlined file: psy.h ***/
  109563. #ifndef _V_PSY_H_
  109564. #define _V_PSY_H_
  109565. /*** Start of inlined file: smallft.h ***/
  109566. #ifndef _V_SMFT_H_
  109567. #define _V_SMFT_H_
  109568. typedef struct {
  109569. int n;
  109570. float *trigcache;
  109571. int *splitcache;
  109572. } drft_lookup;
  109573. extern void drft_forward(drft_lookup *l,float *data);
  109574. extern void drft_backward(drft_lookup *l,float *data);
  109575. extern void drft_init(drft_lookup *l,int n);
  109576. extern void drft_clear(drft_lookup *l);
  109577. #endif
  109578. /*** End of inlined file: smallft.h ***/
  109579. /*** Start of inlined file: backends.h ***/
  109580. /* this is exposed up here because we need it for static modes.
  109581. Lookups for each backend aren't exposed because there's no reason
  109582. to do so */
  109583. #ifndef _vorbis_backend_h_
  109584. #define _vorbis_backend_h_
  109585. /* this would all be simpler/shorter with templates, but.... */
  109586. /* Floor backend generic *****************************************/
  109587. typedef struct{
  109588. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109589. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109590. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109591. void (*free_info) (vorbis_info_floor *);
  109592. void (*free_look) (vorbis_look_floor *);
  109593. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109594. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109595. void *buffer,float *);
  109596. } vorbis_func_floor;
  109597. typedef struct{
  109598. int order;
  109599. long rate;
  109600. long barkmap;
  109601. int ampbits;
  109602. int ampdB;
  109603. int numbooks; /* <= 16 */
  109604. int books[16];
  109605. float lessthan; /* encode-only config setting hacks for libvorbis */
  109606. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109607. } vorbis_info_floor0;
  109608. #define VIF_POSIT 63
  109609. #define VIF_CLASS 16
  109610. #define VIF_PARTS 31
  109611. typedef struct{
  109612. int partitions; /* 0 to 31 */
  109613. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109614. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109615. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109616. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109617. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109618. int mult; /* 1 2 3 or 4 */
  109619. int postlist[VIF_POSIT+2]; /* first two implicit */
  109620. /* encode side analysis parameters */
  109621. float maxover;
  109622. float maxunder;
  109623. float maxerr;
  109624. float twofitweight;
  109625. float twofitatten;
  109626. int n;
  109627. } vorbis_info_floor1;
  109628. /* Residue backend generic *****************************************/
  109629. typedef struct{
  109630. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109631. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109632. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109633. vorbis_info_residue *);
  109634. void (*free_info) (vorbis_info_residue *);
  109635. void (*free_look) (vorbis_look_residue *);
  109636. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109637. float **,int *,int);
  109638. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109639. vorbis_look_residue *,
  109640. float **,float **,int *,int,long **);
  109641. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109642. float **,int *,int);
  109643. } vorbis_func_residue;
  109644. typedef struct vorbis_info_residue0{
  109645. /* block-partitioned VQ coded straight residue */
  109646. long begin;
  109647. long end;
  109648. /* first stage (lossless partitioning) */
  109649. int grouping; /* group n vectors per partition */
  109650. int partitions; /* possible codebooks for a partition */
  109651. int groupbook; /* huffbook for partitioning */
  109652. int secondstages[64]; /* expanded out to pointers in lookup */
  109653. int booklist[256]; /* list of second stage books */
  109654. float classmetric1[64];
  109655. float classmetric2[64];
  109656. } vorbis_info_residue0;
  109657. /* Mapping backend generic *****************************************/
  109658. typedef struct{
  109659. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109660. oggpack_buffer *);
  109661. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109662. void (*free_info) (vorbis_info_mapping *);
  109663. int (*forward) (struct vorbis_block *vb);
  109664. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109665. } vorbis_func_mapping;
  109666. typedef struct vorbis_info_mapping0{
  109667. int submaps; /* <= 16 */
  109668. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109669. int floorsubmap[16]; /* [mux] submap to floors */
  109670. int residuesubmap[16]; /* [mux] submap to residue */
  109671. int coupling_steps;
  109672. int coupling_mag[256];
  109673. int coupling_ang[256];
  109674. } vorbis_info_mapping0;
  109675. #endif
  109676. /*** End of inlined file: backends.h ***/
  109677. #ifndef EHMER_MAX
  109678. #define EHMER_MAX 56
  109679. #endif
  109680. /* psychoacoustic setup ********************************************/
  109681. #define P_BANDS 17 /* 62Hz to 16kHz */
  109682. #define P_LEVELS 8 /* 30dB to 100dB */
  109683. #define P_LEVEL_0 30. /* 30 dB */
  109684. #define P_NOISECURVES 3
  109685. #define NOISE_COMPAND_LEVELS 40
  109686. typedef struct vorbis_info_psy{
  109687. int blockflag;
  109688. float ath_adjatt;
  109689. float ath_maxatt;
  109690. float tone_masteratt[P_NOISECURVES];
  109691. float tone_centerboost;
  109692. float tone_decay;
  109693. float tone_abs_limit;
  109694. float toneatt[P_BANDS];
  109695. int noisemaskp;
  109696. float noisemaxsupp;
  109697. float noisewindowlo;
  109698. float noisewindowhi;
  109699. int noisewindowlomin;
  109700. int noisewindowhimin;
  109701. int noisewindowfixed;
  109702. float noiseoff[P_NOISECURVES][P_BANDS];
  109703. float noisecompand[NOISE_COMPAND_LEVELS];
  109704. float max_curve_dB;
  109705. int normal_channel_p;
  109706. int normal_point_p;
  109707. int normal_start;
  109708. int normal_partition;
  109709. double normal_thresh;
  109710. } vorbis_info_psy;
  109711. typedef struct{
  109712. int eighth_octave_lines;
  109713. /* for block long/short tuning; encode only */
  109714. float preecho_thresh[VE_BANDS];
  109715. float postecho_thresh[VE_BANDS];
  109716. float stretch_penalty;
  109717. float preecho_minenergy;
  109718. float ampmax_att_per_sec;
  109719. /* channel coupling config */
  109720. int coupling_pkHz[PACKETBLOBS];
  109721. int coupling_pointlimit[2][PACKETBLOBS];
  109722. int coupling_prepointamp[PACKETBLOBS];
  109723. int coupling_postpointamp[PACKETBLOBS];
  109724. int sliding_lowpass[2][PACKETBLOBS];
  109725. } vorbis_info_psy_global;
  109726. typedef struct {
  109727. float ampmax;
  109728. int channels;
  109729. vorbis_info_psy_global *gi;
  109730. int coupling_pointlimit[2][P_NOISECURVES];
  109731. } vorbis_look_psy_global;
  109732. typedef struct {
  109733. int n;
  109734. struct vorbis_info_psy *vi;
  109735. float ***tonecurves;
  109736. float **noiseoffset;
  109737. float *ath;
  109738. long *octave; /* in n.ocshift format */
  109739. long *bark;
  109740. long firstoc;
  109741. long shiftoc;
  109742. int eighth_octave_lines; /* power of two, please */
  109743. int total_octave_lines;
  109744. long rate; /* cache it */
  109745. float m_val; /* Masking compensation value */
  109746. } vorbis_look_psy;
  109747. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109748. vorbis_info_psy_global *gi,int n,long rate);
  109749. extern void _vp_psy_clear(vorbis_look_psy *p);
  109750. extern void *_vi_psy_dup(void *source);
  109751. extern void _vi_psy_free(vorbis_info_psy *i);
  109752. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109753. extern void _vp_remove_floor(vorbis_look_psy *p,
  109754. float *mdct,
  109755. int *icodedflr,
  109756. float *residue,
  109757. int sliding_lowpass);
  109758. extern void _vp_noisemask(vorbis_look_psy *p,
  109759. float *logmdct,
  109760. float *logmask);
  109761. extern void _vp_tonemask(vorbis_look_psy *p,
  109762. float *logfft,
  109763. float *logmask,
  109764. float global_specmax,
  109765. float local_specmax);
  109766. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109767. float *noise,
  109768. float *tone,
  109769. int offset_select,
  109770. float *logmask,
  109771. float *mdct,
  109772. float *logmdct);
  109773. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109774. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109775. vorbis_info_psy_global *g,
  109776. vorbis_look_psy *p,
  109777. vorbis_info_mapping0 *vi,
  109778. float **mdct);
  109779. extern void _vp_couple(int blobno,
  109780. vorbis_info_psy_global *g,
  109781. vorbis_look_psy *p,
  109782. vorbis_info_mapping0 *vi,
  109783. float **res,
  109784. float **mag_memo,
  109785. int **mag_sort,
  109786. int **ifloor,
  109787. int *nonzero,
  109788. int sliding_lowpass);
  109789. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109790. float *in,float *out,int *sortedindex);
  109791. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109792. float *magnitudes,int *sortedindex);
  109793. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109794. vorbis_look_psy *p,
  109795. vorbis_info_mapping0 *vi,
  109796. float **mags);
  109797. extern void hf_reduction(vorbis_info_psy_global *g,
  109798. vorbis_look_psy *p,
  109799. vorbis_info_mapping0 *vi,
  109800. float **mdct);
  109801. #endif
  109802. /*** End of inlined file: psy.h ***/
  109803. /*** Start of inlined file: bitrate.h ***/
  109804. #ifndef _V_BITRATE_H_
  109805. #define _V_BITRATE_H_
  109806. /*** Start of inlined file: os.h ***/
  109807. #ifndef _OS_H
  109808. #define _OS_H
  109809. /********************************************************************
  109810. * *
  109811. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109812. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109813. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  109814. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  109815. * *
  109816. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  109817. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  109818. * *
  109819. ********************************************************************
  109820. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  109821. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  109822. ********************************************************************/
  109823. #ifdef HAVE_CONFIG_H
  109824. #include "config.h"
  109825. #endif
  109826. #include <math.h>
  109827. /*** Start of inlined file: misc.h ***/
  109828. #ifndef _V_RANDOM_H_
  109829. #define _V_RANDOM_H_
  109830. extern int analysis_noisy;
  109831. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  109832. extern void _vorbis_block_ripcord(vorbis_block *vb);
  109833. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109834. ogg_int64_t off);
  109835. #ifdef DEBUG_MALLOC
  109836. #define _VDBG_GRAPHFILE "malloc.m"
  109837. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  109838. extern void _VDBG_free(void *ptr,char *file,long line);
  109839. #ifndef MISC_C
  109840. #undef _ogg_malloc
  109841. #undef _ogg_calloc
  109842. #undef _ogg_realloc
  109843. #undef _ogg_free
  109844. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  109845. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  109846. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  109847. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  109848. #endif
  109849. #endif
  109850. #endif
  109851. /*** End of inlined file: misc.h ***/
  109852. #ifndef _V_IFDEFJAIL_H_
  109853. # define _V_IFDEFJAIL_H_
  109854. # ifdef __GNUC__
  109855. # define STIN static __inline__
  109856. # elif _WIN32
  109857. # define STIN static __inline
  109858. # else
  109859. # define STIN static
  109860. # endif
  109861. #ifdef DJGPP
  109862. # define rint(x) (floor((x)+0.5f))
  109863. #endif
  109864. #ifndef M_PI
  109865. # define M_PI (3.1415926536f)
  109866. #endif
  109867. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  109868. # include <malloc.h>
  109869. # define rint(x) (floor((x)+0.5f))
  109870. # define NO_FLOAT_MATH_LIB
  109871. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  109872. #endif
  109873. #if defined(__SYMBIAN32__) && defined(__WINS__)
  109874. void *_alloca(size_t size);
  109875. # define alloca _alloca
  109876. #endif
  109877. #ifndef FAST_HYPOT
  109878. # define FAST_HYPOT hypot
  109879. #endif
  109880. #endif
  109881. #ifdef HAVE_ALLOCA_H
  109882. # include <alloca.h>
  109883. #endif
  109884. #ifdef USE_MEMORY_H
  109885. # include <memory.h>
  109886. #endif
  109887. #ifndef min
  109888. # define min(x,y) ((x)>(y)?(y):(x))
  109889. #endif
  109890. #ifndef max
  109891. # define max(x,y) ((x)<(y)?(y):(x))
  109892. #endif
  109893. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  109894. # define VORBIS_FPU_CONTROL
  109895. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  109896. Because of encapsulation constraints (GCC can't see inside the asm
  109897. block and so we end up doing stupid things like a store/load that
  109898. is collectively a noop), we do it this way */
  109899. /* we must set up the fpu before this works!! */
  109900. typedef ogg_int16_t vorbis_fpu_control;
  109901. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109902. ogg_int16_t ret;
  109903. ogg_int16_t temp;
  109904. __asm__ __volatile__("fnstcw %0\n\t"
  109905. "movw %0,%%dx\n\t"
  109906. "orw $62463,%%dx\n\t"
  109907. "movw %%dx,%1\n\t"
  109908. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  109909. *fpu=ret;
  109910. }
  109911. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109912. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  109913. }
  109914. /* assumes the FPU is in round mode! */
  109915. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  109916. we get extra fst/fld to
  109917. truncate precision */
  109918. int i;
  109919. __asm__("fistl %0": "=m"(i) : "t"(f));
  109920. return(i);
  109921. }
  109922. #endif
  109923. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  109924. # define VORBIS_FPU_CONTROL
  109925. typedef ogg_int16_t vorbis_fpu_control;
  109926. static __inline int vorbis_ftoi(double f){
  109927. int i;
  109928. __asm{
  109929. fld f
  109930. fistp i
  109931. }
  109932. return i;
  109933. }
  109934. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109935. }
  109936. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109937. }
  109938. #endif
  109939. #ifndef VORBIS_FPU_CONTROL
  109940. typedef int vorbis_fpu_control;
  109941. static int vorbis_ftoi(double f){
  109942. return (int)(f+.5);
  109943. }
  109944. /* We don't have special code for this compiler/arch, so do it the slow way */
  109945. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  109946. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  109947. #endif
  109948. #endif /* _OS_H */
  109949. /*** End of inlined file: os.h ***/
  109950. /* encode side bitrate tracking */
  109951. typedef struct bitrate_manager_state {
  109952. int managed;
  109953. long avg_reservoir;
  109954. long minmax_reservoir;
  109955. long avg_bitsper;
  109956. long min_bitsper;
  109957. long max_bitsper;
  109958. long short_per_long;
  109959. double avgfloat;
  109960. vorbis_block *vb;
  109961. int choice;
  109962. } bitrate_manager_state;
  109963. typedef struct bitrate_manager_info{
  109964. long avg_rate;
  109965. long min_rate;
  109966. long max_rate;
  109967. long reservoir_bits;
  109968. double reservoir_bias;
  109969. double slew_damp;
  109970. } bitrate_manager_info;
  109971. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  109972. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  109973. extern int vorbis_bitrate_managed(vorbis_block *vb);
  109974. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  109975. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  109976. #endif
  109977. /*** End of inlined file: bitrate.h ***/
  109978. static int ilog(unsigned int v){
  109979. int ret=0;
  109980. while(v){
  109981. ret++;
  109982. v>>=1;
  109983. }
  109984. return(ret);
  109985. }
  109986. static int ilog2(unsigned int v){
  109987. int ret=0;
  109988. if(v)--v;
  109989. while(v){
  109990. ret++;
  109991. v>>=1;
  109992. }
  109993. return(ret);
  109994. }
  109995. typedef struct private_state {
  109996. /* local lookup storage */
  109997. envelope_lookup *ve; /* envelope lookup */
  109998. int window[2];
  109999. vorbis_look_transform **transform[2]; /* block, type */
  110000. drft_lookup fft_look[2];
  110001. int modebits;
  110002. vorbis_look_floor **flr;
  110003. vorbis_look_residue **residue;
  110004. vorbis_look_psy *psy;
  110005. vorbis_look_psy_global *psy_g_look;
  110006. /* local storage, only used on the encoding side. This way the
  110007. application does not need to worry about freeing some packets'
  110008. memory and not others'; packet storage is always tracked.
  110009. Cleared next call to a _dsp_ function */
  110010. unsigned char *header;
  110011. unsigned char *header1;
  110012. unsigned char *header2;
  110013. bitrate_manager_state bms;
  110014. ogg_int64_t sample_count;
  110015. } private_state;
  110016. /* codec_setup_info contains all the setup information specific to the
  110017. specific compression/decompression mode in progress (eg,
  110018. psychoacoustic settings, channel setup, options, codebook
  110019. etc).
  110020. *********************************************************************/
  110021. /*** Start of inlined file: highlevel.h ***/
  110022. typedef struct highlevel_byblocktype {
  110023. double tone_mask_setting;
  110024. double tone_peaklimit_setting;
  110025. double noise_bias_setting;
  110026. double noise_compand_setting;
  110027. } highlevel_byblocktype;
  110028. typedef struct highlevel_encode_setup {
  110029. void *setup;
  110030. int set_in_stone;
  110031. double base_setting;
  110032. double long_setting;
  110033. double short_setting;
  110034. double impulse_noisetune;
  110035. int managed;
  110036. long bitrate_min;
  110037. long bitrate_av;
  110038. double bitrate_av_damp;
  110039. long bitrate_max;
  110040. long bitrate_reservoir;
  110041. double bitrate_reservoir_bias;
  110042. int impulse_block_p;
  110043. int noise_normalize_p;
  110044. double stereo_point_setting;
  110045. double lowpass_kHz;
  110046. double ath_floating_dB;
  110047. double ath_absolute_dB;
  110048. double amplitude_track_dBpersec;
  110049. double trigger_setting;
  110050. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110051. } highlevel_encode_setup;
  110052. /*** End of inlined file: highlevel.h ***/
  110053. typedef struct codec_setup_info {
  110054. /* Vorbis supports only short and long blocks, but allows the
  110055. encoder to choose the sizes */
  110056. long blocksizes[2];
  110057. /* modes are the primary means of supporting on-the-fly different
  110058. blocksizes, different channel mappings (LR or M/A),
  110059. different residue backends, etc. Each mode consists of a
  110060. blocksize flag and a mapping (along with the mapping setup */
  110061. int modes;
  110062. int maps;
  110063. int floors;
  110064. int residues;
  110065. int books;
  110066. int psys; /* encode only */
  110067. vorbis_info_mode *mode_param[64];
  110068. int map_type[64];
  110069. vorbis_info_mapping *map_param[64];
  110070. int floor_type[64];
  110071. vorbis_info_floor *floor_param[64];
  110072. int residue_type[64];
  110073. vorbis_info_residue *residue_param[64];
  110074. static_codebook *book_param[256];
  110075. codebook *fullbooks;
  110076. vorbis_info_psy *psy_param[4]; /* encode only */
  110077. vorbis_info_psy_global psy_g_param;
  110078. bitrate_manager_info bi;
  110079. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110080. highly redundant structure, but
  110081. improves clarity of program flow. */
  110082. int halfrate_flag; /* painless downsample for decode */
  110083. } codec_setup_info;
  110084. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110085. extern void _vp_global_free(vorbis_look_psy_global *look);
  110086. #endif
  110087. /*** End of inlined file: codec_internal.h ***/
  110088. /*** Start of inlined file: registry.h ***/
  110089. #ifndef _V_REG_H_
  110090. #define _V_REG_H_
  110091. #define VI_TRANSFORMB 1
  110092. #define VI_WINDOWB 1
  110093. #define VI_TIMEB 1
  110094. #define VI_FLOORB 2
  110095. #define VI_RESB 3
  110096. #define VI_MAPB 1
  110097. extern vorbis_func_floor *_floor_P[];
  110098. extern vorbis_func_residue *_residue_P[];
  110099. extern vorbis_func_mapping *_mapping_P[];
  110100. #endif
  110101. /*** End of inlined file: registry.h ***/
  110102. /*** Start of inlined file: scales.h ***/
  110103. #ifndef _V_SCALES_H_
  110104. #define _V_SCALES_H_
  110105. #include <math.h>
  110106. /* 20log10(x) */
  110107. #define VORBIS_IEEE_FLOAT32 1
  110108. #ifdef VORBIS_IEEE_FLOAT32
  110109. static float unitnorm(float x){
  110110. union {
  110111. ogg_uint32_t i;
  110112. float f;
  110113. } ix;
  110114. ix.f = x;
  110115. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110116. return ix.f;
  110117. }
  110118. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110119. static float todB(const float *x){
  110120. union {
  110121. ogg_uint32_t i;
  110122. float f;
  110123. } ix;
  110124. ix.f = *x;
  110125. ix.i = ix.i&0x7fffffff;
  110126. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110127. }
  110128. #define todB_nn(x) todB(x)
  110129. #else
  110130. static float unitnorm(float x){
  110131. if(x<0)return(-1.f);
  110132. return(1.f);
  110133. }
  110134. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110135. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110136. #endif
  110137. #define fromdB(x) (exp((x)*.11512925f))
  110138. /* The bark scale equations are approximations, since the original
  110139. table was somewhat hand rolled. The below are chosen to have the
  110140. best possible fit to the rolled tables, thus their somewhat odd
  110141. appearance (these are more accurate and over a longer range than
  110142. the oft-quoted bark equations found in the texts I have). The
  110143. approximations are valid from 0 - 30kHz (nyquist) or so.
  110144. all f in Hz, z in Bark */
  110145. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110146. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110147. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110148. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110149. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110150. 0.0 */
  110151. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110152. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110153. #endif
  110154. /*** End of inlined file: scales.h ***/
  110155. int analysis_noisy=1;
  110156. /* decides between modes, dispatches to the appropriate mapping. */
  110157. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110158. int ret,i;
  110159. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110160. vb->glue_bits=0;
  110161. vb->time_bits=0;
  110162. vb->floor_bits=0;
  110163. vb->res_bits=0;
  110164. /* first things first. Make sure encode is ready */
  110165. for(i=0;i<PACKETBLOBS;i++)
  110166. oggpack_reset(vbi->packetblob[i]);
  110167. /* we only have one mapping type (0), and we let the mapping code
  110168. itself figure out what soft mode to use. This allows easier
  110169. bitrate management */
  110170. if((ret=_mapping_P[0]->forward(vb)))
  110171. return(ret);
  110172. if(op){
  110173. if(vorbis_bitrate_managed(vb))
  110174. /* The app is using a bitmanaged mode... but not using the
  110175. bitrate management interface. */
  110176. return(OV_EINVAL);
  110177. op->packet=oggpack_get_buffer(&vb->opb);
  110178. op->bytes=oggpack_bytes(&vb->opb);
  110179. op->b_o_s=0;
  110180. op->e_o_s=vb->eofflag;
  110181. op->granulepos=vb->granulepos;
  110182. op->packetno=vb->sequence; /* for sake of completeness */
  110183. }
  110184. return(0);
  110185. }
  110186. /* there was no great place to put this.... */
  110187. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110188. int j;
  110189. FILE *of;
  110190. char buffer[80];
  110191. /* if(i==5870){*/
  110192. sprintf(buffer,"%s_%d.m",base,i);
  110193. of=fopen(buffer,"w");
  110194. if(!of)perror("failed to open data dump file");
  110195. for(j=0;j<n;j++){
  110196. if(bark){
  110197. float b=toBARK((4000.f*j/n)+.25);
  110198. fprintf(of,"%f ",b);
  110199. }else
  110200. if(off!=0)
  110201. fprintf(of,"%f ",(double)(j+off)/8000.);
  110202. else
  110203. fprintf(of,"%f ",(double)j);
  110204. if(dB){
  110205. float val;
  110206. if(v[j]==0.)
  110207. val=-140.;
  110208. else
  110209. val=todB(v+j);
  110210. fprintf(of,"%f\n",val);
  110211. }else{
  110212. fprintf(of,"%f\n",v[j]);
  110213. }
  110214. }
  110215. fclose(of);
  110216. /* } */
  110217. }
  110218. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110219. ogg_int64_t off){
  110220. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110221. }
  110222. #endif
  110223. /*** End of inlined file: analysis.c ***/
  110224. /*** Start of inlined file: bitrate.c ***/
  110225. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110226. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110227. // tasks..
  110228. #if JUCE_MSVC
  110229. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110230. #endif
  110231. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110232. #if JUCE_USE_OGGVORBIS
  110233. #include <stdlib.h>
  110234. #include <string.h>
  110235. #include <math.h>
  110236. /* compute bitrate tracking setup */
  110237. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110238. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110239. bitrate_manager_info *bi=&ci->bi;
  110240. memset(bm,0,sizeof(*bm));
  110241. if(bi && (bi->reservoir_bits>0)){
  110242. long ratesamples=vi->rate;
  110243. int halfsamples=ci->blocksizes[0]>>1;
  110244. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110245. bm->managed=1;
  110246. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110247. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110248. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110249. bm->avgfloat=PACKETBLOBS/2;
  110250. /* not a necessary fix, but one that leads to a more balanced
  110251. typical initialization */
  110252. {
  110253. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110254. bm->minmax_reservoir=desired_fill;
  110255. bm->avg_reservoir=desired_fill;
  110256. }
  110257. }
  110258. }
  110259. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110260. memset(bm,0,sizeof(*bm));
  110261. return;
  110262. }
  110263. int vorbis_bitrate_managed(vorbis_block *vb){
  110264. vorbis_dsp_state *vd=vb->vd;
  110265. private_state *b=(private_state*)vd->backend_state;
  110266. bitrate_manager_state *bm=&b->bms;
  110267. if(bm && bm->managed)return(1);
  110268. return(0);
  110269. }
  110270. /* finish taking in the block we just processed */
  110271. int vorbis_bitrate_addblock(vorbis_block *vb){
  110272. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110273. vorbis_dsp_state *vd=vb->vd;
  110274. private_state *b=(private_state*)vd->backend_state;
  110275. bitrate_manager_state *bm=&b->bms;
  110276. vorbis_info *vi=vd->vi;
  110277. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110278. bitrate_manager_info *bi=&ci->bi;
  110279. int choice=rint(bm->avgfloat);
  110280. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110281. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110282. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110283. int samples=ci->blocksizes[vb->W]>>1;
  110284. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110285. if(!bm->managed){
  110286. /* not a bitrate managed stream, but for API simplicity, we'll
  110287. buffer the packet to keep the code path clean */
  110288. if(bm->vb)return(-1); /* one has been submitted without
  110289. being claimed */
  110290. bm->vb=vb;
  110291. return(0);
  110292. }
  110293. bm->vb=vb;
  110294. /* look ahead for avg floater */
  110295. if(bm->avg_bitsper>0){
  110296. double slew=0.;
  110297. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110298. double slewlimit= 15./bi->slew_damp;
  110299. /* choosing a new floater:
  110300. if we're over target, we slew down
  110301. if we're under target, we slew up
  110302. choose slew as follows: look through packetblobs of this frame
  110303. and set slew as the first in the appropriate direction that
  110304. gives us the slew we want. This may mean no slew if delta is
  110305. already favorable.
  110306. Then limit slew to slew max */
  110307. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110308. while(choice>0 && this_bits>avg_target_bits &&
  110309. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110310. choice--;
  110311. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110312. }
  110313. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110314. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110315. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110316. choice++;
  110317. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110318. }
  110319. }
  110320. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110321. if(slew<-slewlimit)slew=-slewlimit;
  110322. if(slew>slewlimit)slew=slewlimit;
  110323. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110324. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110325. }
  110326. /* enforce min(if used) on the current floater (if used) */
  110327. if(bm->min_bitsper>0){
  110328. /* do we need to force the bitrate up? */
  110329. if(this_bits<min_target_bits){
  110330. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110331. choice++;
  110332. if(choice>=PACKETBLOBS)break;
  110333. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110334. }
  110335. }
  110336. }
  110337. /* enforce max (if used) on the current floater (if used) */
  110338. if(bm->max_bitsper>0){
  110339. /* do we need to force the bitrate down? */
  110340. if(this_bits>max_target_bits){
  110341. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110342. choice--;
  110343. if(choice<0)break;
  110344. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110345. }
  110346. }
  110347. }
  110348. /* Choice of packetblobs now made based on floater, and min/max
  110349. requirements. Now boundary check extreme choices */
  110350. if(choice<0){
  110351. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110352. frame will need to be truncated */
  110353. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110354. bm->choice=choice=0;
  110355. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110356. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110357. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110358. }
  110359. }else{
  110360. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110361. if(choice>=PACKETBLOBS)
  110362. choice=PACKETBLOBS-1;
  110363. bm->choice=choice;
  110364. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110365. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110366. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110367. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110368. }
  110369. /* now we have the final packet and the final packet size. Update statistics */
  110370. /* min and max reservoir */
  110371. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110372. if(max_target_bits>0 && this_bits>max_target_bits){
  110373. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110374. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110375. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110376. }else{
  110377. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110378. if(bm->minmax_reservoir>desired_fill){
  110379. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110380. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110381. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110382. }else{
  110383. bm->minmax_reservoir=desired_fill;
  110384. }
  110385. }else{
  110386. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110387. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110388. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110389. }else{
  110390. bm->minmax_reservoir=desired_fill;
  110391. }
  110392. }
  110393. }
  110394. }
  110395. /* avg reservoir */
  110396. if(bm->avg_bitsper>0){
  110397. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110398. bm->avg_reservoir+=this_bits-avg_target_bits;
  110399. }
  110400. return(0);
  110401. }
  110402. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110403. private_state *b=(private_state*)vd->backend_state;
  110404. bitrate_manager_state *bm=&b->bms;
  110405. vorbis_block *vb=bm->vb;
  110406. int choice=PACKETBLOBS/2;
  110407. if(!vb)return 0;
  110408. if(op){
  110409. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110410. if(vorbis_bitrate_managed(vb))
  110411. choice=bm->choice;
  110412. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110413. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110414. op->b_o_s=0;
  110415. op->e_o_s=vb->eofflag;
  110416. op->granulepos=vb->granulepos;
  110417. op->packetno=vb->sequence; /* for sake of completeness */
  110418. }
  110419. bm->vb=0;
  110420. return(1);
  110421. }
  110422. #endif
  110423. /*** End of inlined file: bitrate.c ***/
  110424. /*** Start of inlined file: block.c ***/
  110425. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110426. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110427. // tasks..
  110428. #if JUCE_MSVC
  110429. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110430. #endif
  110431. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110432. #if JUCE_USE_OGGVORBIS
  110433. #include <stdio.h>
  110434. #include <stdlib.h>
  110435. #include <string.h>
  110436. /*** Start of inlined file: window.h ***/
  110437. #ifndef _V_WINDOW_
  110438. #define _V_WINDOW_
  110439. extern float *_vorbis_window_get(int n);
  110440. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110441. int lW,int W,int nW);
  110442. #endif
  110443. /*** End of inlined file: window.h ***/
  110444. /*** Start of inlined file: lpc.h ***/
  110445. #ifndef _V_LPC_H_
  110446. #define _V_LPC_H_
  110447. /* simple linear scale LPC code */
  110448. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110449. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110450. float *data,long n);
  110451. #endif
  110452. /*** End of inlined file: lpc.h ***/
  110453. /* pcm accumulator examples (not exhaustive):
  110454. <-------------- lW ---------------->
  110455. <--------------- W ---------------->
  110456. : .....|..... _______________ |
  110457. : .''' | '''_--- | |\ |
  110458. :.....''' |_____--- '''......| | \_______|
  110459. :.................|__________________|_______|__|______|
  110460. |<------ Sl ------>| > Sr < |endW
  110461. |beginSl |endSl | |endSr
  110462. |beginW |endlW |beginSr
  110463. |< lW >|
  110464. <--------------- W ---------------->
  110465. | | .. ______________ |
  110466. | | ' `/ | ---_ |
  110467. |___.'___/`. | ---_____|
  110468. |_______|__|_______|_________________|
  110469. | >|Sl|< |<------ Sr ----->|endW
  110470. | | |endSl |beginSr |endSr
  110471. |beginW | |endlW
  110472. mult[0] |beginSl mult[n]
  110473. <-------------- lW ----------------->
  110474. |<--W-->|
  110475. : .............. ___ | |
  110476. : .''' |`/ \ | |
  110477. :.....''' |/`....\|...|
  110478. :.........................|___|___|___|
  110479. |Sl |Sr |endW
  110480. | | |endSr
  110481. | |beginSr
  110482. | |endSl
  110483. |beginSl
  110484. |beginW
  110485. */
  110486. /* block abstraction setup *********************************************/
  110487. #ifndef WORD_ALIGN
  110488. #define WORD_ALIGN 8
  110489. #endif
  110490. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110491. int i;
  110492. memset(vb,0,sizeof(*vb));
  110493. vb->vd=v;
  110494. vb->localalloc=0;
  110495. vb->localstore=NULL;
  110496. if(v->analysisp){
  110497. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110498. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110499. vbi->ampmax=-9999;
  110500. for(i=0;i<PACKETBLOBS;i++){
  110501. if(i==PACKETBLOBS/2){
  110502. vbi->packetblob[i]=&vb->opb;
  110503. }else{
  110504. vbi->packetblob[i]=
  110505. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110506. }
  110507. oggpack_writeinit(vbi->packetblob[i]);
  110508. }
  110509. }
  110510. return(0);
  110511. }
  110512. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110513. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110514. if(bytes+vb->localtop>vb->localalloc){
  110515. /* can't just _ogg_realloc... there are outstanding pointers */
  110516. if(vb->localstore){
  110517. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110518. vb->totaluse+=vb->localtop;
  110519. link->next=vb->reap;
  110520. link->ptr=vb->localstore;
  110521. vb->reap=link;
  110522. }
  110523. /* highly conservative */
  110524. vb->localalloc=bytes;
  110525. vb->localstore=_ogg_malloc(vb->localalloc);
  110526. vb->localtop=0;
  110527. }
  110528. {
  110529. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110530. vb->localtop+=bytes;
  110531. return ret;
  110532. }
  110533. }
  110534. /* reap the chain, pull the ripcord */
  110535. void _vorbis_block_ripcord(vorbis_block *vb){
  110536. /* reap the chain */
  110537. struct alloc_chain *reap=vb->reap;
  110538. while(reap){
  110539. struct alloc_chain *next=reap->next;
  110540. _ogg_free(reap->ptr);
  110541. memset(reap,0,sizeof(*reap));
  110542. _ogg_free(reap);
  110543. reap=next;
  110544. }
  110545. /* consolidate storage */
  110546. if(vb->totaluse){
  110547. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110548. vb->localalloc+=vb->totaluse;
  110549. vb->totaluse=0;
  110550. }
  110551. /* pull the ripcord */
  110552. vb->localtop=0;
  110553. vb->reap=NULL;
  110554. }
  110555. int vorbis_block_clear(vorbis_block *vb){
  110556. int i;
  110557. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110558. _vorbis_block_ripcord(vb);
  110559. if(vb->localstore)_ogg_free(vb->localstore);
  110560. if(vbi){
  110561. for(i=0;i<PACKETBLOBS;i++){
  110562. oggpack_writeclear(vbi->packetblob[i]);
  110563. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110564. }
  110565. _ogg_free(vbi);
  110566. }
  110567. memset(vb,0,sizeof(*vb));
  110568. return(0);
  110569. }
  110570. /* Analysis side code, but directly related to blocking. Thus it's
  110571. here and not in analysis.c (which is for analysis transforms only).
  110572. The init is here because some of it is shared */
  110573. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110574. int i;
  110575. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110576. private_state *b=NULL;
  110577. int hs;
  110578. if(ci==NULL) return 1;
  110579. hs=ci->halfrate_flag;
  110580. memset(v,0,sizeof(*v));
  110581. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110582. v->vi=vi;
  110583. b->modebits=ilog2(ci->modes);
  110584. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110585. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110586. /* MDCT is tranform 0 */
  110587. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110588. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110589. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110590. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110591. /* Vorbis I uses only window type 0 */
  110592. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110593. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110594. if(encp){ /* encode/decode differ here */
  110595. /* analysis always needs an fft */
  110596. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110597. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110598. /* finish the codebooks */
  110599. if(!ci->fullbooks){
  110600. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110601. for(i=0;i<ci->books;i++)
  110602. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110603. }
  110604. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110605. for(i=0;i<ci->psys;i++){
  110606. _vp_psy_init(b->psy+i,
  110607. ci->psy_param[i],
  110608. &ci->psy_g_param,
  110609. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110610. vi->rate);
  110611. }
  110612. v->analysisp=1;
  110613. }else{
  110614. /* finish the codebooks */
  110615. if(!ci->fullbooks){
  110616. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110617. for(i=0;i<ci->books;i++){
  110618. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110619. /* decode codebooks are now standalone after init */
  110620. vorbis_staticbook_destroy(ci->book_param[i]);
  110621. ci->book_param[i]=NULL;
  110622. }
  110623. }
  110624. }
  110625. /* initialize the storage vectors. blocksize[1] is small for encode,
  110626. but the correct size for decode */
  110627. v->pcm_storage=ci->blocksizes[1];
  110628. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110629. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110630. {
  110631. int i;
  110632. for(i=0;i<vi->channels;i++)
  110633. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110634. }
  110635. /* all 1 (large block) or 0 (small block) */
  110636. /* explicitly set for the sake of clarity */
  110637. v->lW=0; /* previous window size */
  110638. v->W=0; /* current window size */
  110639. /* all vector indexes */
  110640. v->centerW=ci->blocksizes[1]/2;
  110641. v->pcm_current=v->centerW;
  110642. /* initialize all the backend lookups */
  110643. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110644. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110645. for(i=0;i<ci->floors;i++)
  110646. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110647. look(v,ci->floor_param[i]);
  110648. for(i=0;i<ci->residues;i++)
  110649. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110650. look(v,ci->residue_param[i]);
  110651. return 0;
  110652. }
  110653. /* arbitrary settings and spec-mandated numbers get filled in here */
  110654. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110655. private_state *b=NULL;
  110656. if(_vds_shared_init(v,vi,1))return 1;
  110657. b=(private_state*)v->backend_state;
  110658. b->psy_g_look=_vp_global_look(vi);
  110659. /* Initialize the envelope state storage */
  110660. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110661. _ve_envelope_init(b->ve,vi);
  110662. vorbis_bitrate_init(vi,&b->bms);
  110663. /* compressed audio packets start after the headers
  110664. with sequence number 3 */
  110665. v->sequence=3;
  110666. return(0);
  110667. }
  110668. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110669. int i;
  110670. if(v){
  110671. vorbis_info *vi=v->vi;
  110672. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110673. private_state *b=(private_state*)v->backend_state;
  110674. if(b){
  110675. if(b->ve){
  110676. _ve_envelope_clear(b->ve);
  110677. _ogg_free(b->ve);
  110678. }
  110679. if(b->transform[0]){
  110680. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110681. _ogg_free(b->transform[0][0]);
  110682. _ogg_free(b->transform[0]);
  110683. }
  110684. if(b->transform[1]){
  110685. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110686. _ogg_free(b->transform[1][0]);
  110687. _ogg_free(b->transform[1]);
  110688. }
  110689. if(b->flr){
  110690. for(i=0;i<ci->floors;i++)
  110691. _floor_P[ci->floor_type[i]]->
  110692. free_look(b->flr[i]);
  110693. _ogg_free(b->flr);
  110694. }
  110695. if(b->residue){
  110696. for(i=0;i<ci->residues;i++)
  110697. _residue_P[ci->residue_type[i]]->
  110698. free_look(b->residue[i]);
  110699. _ogg_free(b->residue);
  110700. }
  110701. if(b->psy){
  110702. for(i=0;i<ci->psys;i++)
  110703. _vp_psy_clear(b->psy+i);
  110704. _ogg_free(b->psy);
  110705. }
  110706. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110707. vorbis_bitrate_clear(&b->bms);
  110708. drft_clear(&b->fft_look[0]);
  110709. drft_clear(&b->fft_look[1]);
  110710. }
  110711. if(v->pcm){
  110712. for(i=0;i<vi->channels;i++)
  110713. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110714. _ogg_free(v->pcm);
  110715. if(v->pcmret)_ogg_free(v->pcmret);
  110716. }
  110717. if(b){
  110718. /* free header, header1, header2 */
  110719. if(b->header)_ogg_free(b->header);
  110720. if(b->header1)_ogg_free(b->header1);
  110721. if(b->header2)_ogg_free(b->header2);
  110722. _ogg_free(b);
  110723. }
  110724. memset(v,0,sizeof(*v));
  110725. }
  110726. }
  110727. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110728. int i;
  110729. vorbis_info *vi=v->vi;
  110730. private_state *b=(private_state*)v->backend_state;
  110731. /* free header, header1, header2 */
  110732. if(b->header)_ogg_free(b->header);b->header=NULL;
  110733. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110734. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110735. /* Do we have enough storage space for the requested buffer? If not,
  110736. expand the PCM (and envelope) storage */
  110737. if(v->pcm_current+vals>=v->pcm_storage){
  110738. v->pcm_storage=v->pcm_current+vals*2;
  110739. for(i=0;i<vi->channels;i++){
  110740. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110741. }
  110742. }
  110743. for(i=0;i<vi->channels;i++)
  110744. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110745. return(v->pcmret);
  110746. }
  110747. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110748. int i;
  110749. int order=32;
  110750. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110751. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110752. long j;
  110753. v->preextrapolate=1;
  110754. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110755. for(i=0;i<v->vi->channels;i++){
  110756. /* need to run the extrapolation in reverse! */
  110757. for(j=0;j<v->pcm_current;j++)
  110758. work[j]=v->pcm[i][v->pcm_current-j-1];
  110759. /* prime as above */
  110760. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110761. /* run the predictor filter */
  110762. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110763. order,
  110764. work+v->pcm_current-v->centerW,
  110765. v->centerW);
  110766. for(j=0;j<v->pcm_current;j++)
  110767. v->pcm[i][v->pcm_current-j-1]=work[j];
  110768. }
  110769. }
  110770. }
  110771. /* call with val<=0 to set eof */
  110772. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110773. vorbis_info *vi=v->vi;
  110774. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110775. if(vals<=0){
  110776. int order=32;
  110777. int i;
  110778. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110779. /* if it wasn't done earlier (very short sample) */
  110780. if(!v->preextrapolate)
  110781. _preextrapolate_helper(v);
  110782. /* We're encoding the end of the stream. Just make sure we have
  110783. [at least] a few full blocks of zeroes at the end. */
  110784. /* actually, we don't want zeroes; that could drop a large
  110785. amplitude off a cliff, creating spread spectrum noise that will
  110786. suck to encode. Extrapolate for the sake of cleanliness. */
  110787. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110788. v->eofflag=v->pcm_current;
  110789. v->pcm_current+=ci->blocksizes[1]*3;
  110790. for(i=0;i<vi->channels;i++){
  110791. if(v->eofflag>order*2){
  110792. /* extrapolate with LPC to fill in */
  110793. long n;
  110794. /* make a predictor filter */
  110795. n=v->eofflag;
  110796. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110797. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110798. /* run the predictor filter */
  110799. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110800. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110801. }else{
  110802. /* not enough data to extrapolate (unlikely to happen due to
  110803. guarding the overlap, but bulletproof in case that
  110804. assumtion goes away). zeroes will do. */
  110805. memset(v->pcm[i]+v->eofflag,0,
  110806. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110807. }
  110808. }
  110809. }else{
  110810. if(v->pcm_current+vals>v->pcm_storage)
  110811. return(OV_EINVAL);
  110812. v->pcm_current+=vals;
  110813. /* we may want to reverse extrapolate the beginning of a stream
  110814. too... in case we're beginning on a cliff! */
  110815. /* clumsy, but simple. It only runs once, so simple is good. */
  110816. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  110817. _preextrapolate_helper(v);
  110818. }
  110819. return(0);
  110820. }
  110821. /* do the deltas, envelope shaping, pre-echo and determine the size of
  110822. the next block on which to continue analysis */
  110823. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  110824. int i;
  110825. vorbis_info *vi=v->vi;
  110826. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110827. private_state *b=(private_state*)v->backend_state;
  110828. vorbis_look_psy_global *g=b->psy_g_look;
  110829. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  110830. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110831. /* check to see if we're started... */
  110832. if(!v->preextrapolate)return(0);
  110833. /* check to see if we're done... */
  110834. if(v->eofflag==-1)return(0);
  110835. /* By our invariant, we have lW, W and centerW set. Search for
  110836. the next boundary so we can determine nW (the next window size)
  110837. which lets us compute the shape of the current block's window */
  110838. /* we do an envelope search even on a single blocksize; we may still
  110839. be throwing more bits at impulses, and envelope search handles
  110840. marking impulses too. */
  110841. {
  110842. long bp=_ve_envelope_search(v);
  110843. if(bp==-1){
  110844. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  110845. full long block */
  110846. v->nW=0;
  110847. }else{
  110848. if(ci->blocksizes[0]==ci->blocksizes[1])
  110849. v->nW=0;
  110850. else
  110851. v->nW=bp;
  110852. }
  110853. }
  110854. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  110855. {
  110856. /* center of next block + next block maximum right side. */
  110857. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  110858. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  110859. although this check is
  110860. less strict that the
  110861. _ve_envelope_search,
  110862. the search is not run
  110863. if we only use one
  110864. block size */
  110865. }
  110866. /* fill in the block. Note that for a short window, lW and nW are *short*
  110867. regardless of actual settings in the stream */
  110868. _vorbis_block_ripcord(vb);
  110869. vb->lW=v->lW;
  110870. vb->W=v->W;
  110871. vb->nW=v->nW;
  110872. if(v->W){
  110873. if(!v->lW || !v->nW){
  110874. vbi->blocktype=BLOCKTYPE_TRANSITION;
  110875. /*fprintf(stderr,"-");*/
  110876. }else{
  110877. vbi->blocktype=BLOCKTYPE_LONG;
  110878. /*fprintf(stderr,"_");*/
  110879. }
  110880. }else{
  110881. if(_ve_envelope_mark(v)){
  110882. vbi->blocktype=BLOCKTYPE_IMPULSE;
  110883. /*fprintf(stderr,"|");*/
  110884. }else{
  110885. vbi->blocktype=BLOCKTYPE_PADDING;
  110886. /*fprintf(stderr,".");*/
  110887. }
  110888. }
  110889. vb->vd=v;
  110890. vb->sequence=v->sequence++;
  110891. vb->granulepos=v->granulepos;
  110892. vb->pcmend=ci->blocksizes[v->W];
  110893. /* copy the vectors; this uses the local storage in vb */
  110894. /* this tracks 'strongest peak' for later psychoacoustics */
  110895. /* moved to the global psy state; clean this mess up */
  110896. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  110897. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  110898. vbi->ampmax=g->ampmax;
  110899. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  110900. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  110901. for(i=0;i<vi->channels;i++){
  110902. vbi->pcmdelay[i]=
  110903. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110904. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110905. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  110906. /* before we added the delay
  110907. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  110908. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  110909. */
  110910. }
  110911. /* handle eof detection: eof==0 means that we've not yet received EOF
  110912. eof>0 marks the last 'real' sample in pcm[]
  110913. eof<0 'no more to do'; doesn't get here */
  110914. if(v->eofflag){
  110915. if(v->centerW>=v->eofflag){
  110916. v->eofflag=-1;
  110917. vb->eofflag=1;
  110918. return(1);
  110919. }
  110920. }
  110921. /* advance storage vectors and clean up */
  110922. {
  110923. int new_centerNext=ci->blocksizes[1]/2;
  110924. int movementW=centerNext-new_centerNext;
  110925. if(movementW>0){
  110926. _ve_envelope_shift(b->ve,movementW);
  110927. v->pcm_current-=movementW;
  110928. for(i=0;i<vi->channels;i++)
  110929. memmove(v->pcm[i],v->pcm[i]+movementW,
  110930. v->pcm_current*sizeof(*v->pcm[i]));
  110931. v->lW=v->W;
  110932. v->W=v->nW;
  110933. v->centerW=new_centerNext;
  110934. if(v->eofflag){
  110935. v->eofflag-=movementW;
  110936. if(v->eofflag<=0)v->eofflag=-1;
  110937. /* do not add padding to end of stream! */
  110938. if(v->centerW>=v->eofflag){
  110939. v->granulepos+=movementW-(v->centerW-v->eofflag);
  110940. }else{
  110941. v->granulepos+=movementW;
  110942. }
  110943. }else{
  110944. v->granulepos+=movementW;
  110945. }
  110946. }
  110947. }
  110948. /* done */
  110949. return(1);
  110950. }
  110951. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  110952. vorbis_info *vi=v->vi;
  110953. codec_setup_info *ci;
  110954. int hs;
  110955. if(!v->backend_state)return -1;
  110956. if(!vi)return -1;
  110957. ci=(codec_setup_info*) vi->codec_setup;
  110958. if(!ci)return -1;
  110959. hs=ci->halfrate_flag;
  110960. v->centerW=ci->blocksizes[1]>>(hs+1);
  110961. v->pcm_current=v->centerW>>hs;
  110962. v->pcm_returned=-1;
  110963. v->granulepos=-1;
  110964. v->sequence=-1;
  110965. v->eofflag=0;
  110966. ((private_state *)(v->backend_state))->sample_count=-1;
  110967. return(0);
  110968. }
  110969. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110970. if(_vds_shared_init(v,vi,0)) return 1;
  110971. vorbis_synthesis_restart(v);
  110972. return 0;
  110973. }
  110974. /* Unlike in analysis, the window is only partially applied for each
  110975. block. The time domain envelope is not yet handled at the point of
  110976. calling (as it relies on the previous block). */
  110977. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  110978. vorbis_info *vi=v->vi;
  110979. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110980. private_state *b=(private_state*)v->backend_state;
  110981. int hs=ci->halfrate_flag;
  110982. int i,j;
  110983. if(!vb)return(OV_EINVAL);
  110984. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  110985. v->lW=v->W;
  110986. v->W=vb->W;
  110987. v->nW=-1;
  110988. if((v->sequence==-1)||
  110989. (v->sequence+1 != vb->sequence)){
  110990. v->granulepos=-1; /* out of sequence; lose count */
  110991. b->sample_count=-1;
  110992. }
  110993. v->sequence=vb->sequence;
  110994. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  110995. was called on block */
  110996. int n=ci->blocksizes[v->W]>>(hs+1);
  110997. int n0=ci->blocksizes[0]>>(hs+1);
  110998. int n1=ci->blocksizes[1]>>(hs+1);
  110999. int thisCenter;
  111000. int prevCenter;
  111001. v->glue_bits+=vb->glue_bits;
  111002. v->time_bits+=vb->time_bits;
  111003. v->floor_bits+=vb->floor_bits;
  111004. v->res_bits+=vb->res_bits;
  111005. if(v->centerW){
  111006. thisCenter=n1;
  111007. prevCenter=0;
  111008. }else{
  111009. thisCenter=0;
  111010. prevCenter=n1;
  111011. }
  111012. /* v->pcm is now used like a two-stage double buffer. We don't want
  111013. to have to constantly shift *or* adjust memory usage. Don't
  111014. accept a new block until the old is shifted out */
  111015. for(j=0;j<vi->channels;j++){
  111016. /* the overlap/add section */
  111017. if(v->lW){
  111018. if(v->W){
  111019. /* large/large */
  111020. float *w=_vorbis_window_get(b->window[1]-hs);
  111021. float *pcm=v->pcm[j]+prevCenter;
  111022. float *p=vb->pcm[j];
  111023. for(i=0;i<n1;i++)
  111024. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111025. }else{
  111026. /* large/small */
  111027. float *w=_vorbis_window_get(b->window[0]-hs);
  111028. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111029. float *p=vb->pcm[j];
  111030. for(i=0;i<n0;i++)
  111031. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111032. }
  111033. }else{
  111034. if(v->W){
  111035. /* small/large */
  111036. float *w=_vorbis_window_get(b->window[0]-hs);
  111037. float *pcm=v->pcm[j]+prevCenter;
  111038. float *p=vb->pcm[j]+n1/2-n0/2;
  111039. for(i=0;i<n0;i++)
  111040. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111041. for(;i<n1/2+n0/2;i++)
  111042. pcm[i]=p[i];
  111043. }else{
  111044. /* small/small */
  111045. float *w=_vorbis_window_get(b->window[0]-hs);
  111046. float *pcm=v->pcm[j]+prevCenter;
  111047. float *p=vb->pcm[j];
  111048. for(i=0;i<n0;i++)
  111049. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111050. }
  111051. }
  111052. /* the copy section */
  111053. {
  111054. float *pcm=v->pcm[j]+thisCenter;
  111055. float *p=vb->pcm[j]+n;
  111056. for(i=0;i<n;i++)
  111057. pcm[i]=p[i];
  111058. }
  111059. }
  111060. if(v->centerW)
  111061. v->centerW=0;
  111062. else
  111063. v->centerW=n1;
  111064. /* deal with initial packet state; we do this using the explicit
  111065. pcm_returned==-1 flag otherwise we're sensitive to first block
  111066. being short or long */
  111067. if(v->pcm_returned==-1){
  111068. v->pcm_returned=thisCenter;
  111069. v->pcm_current=thisCenter;
  111070. }else{
  111071. v->pcm_returned=prevCenter;
  111072. v->pcm_current=prevCenter+
  111073. ((ci->blocksizes[v->lW]/4+
  111074. ci->blocksizes[v->W]/4)>>hs);
  111075. }
  111076. }
  111077. /* track the frame number... This is for convenience, but also
  111078. making sure our last packet doesn't end with added padding. If
  111079. the last packet is partial, the number of samples we'll have to
  111080. return will be past the vb->granulepos.
  111081. This is not foolproof! It will be confused if we begin
  111082. decoding at the last page after a seek or hole. In that case,
  111083. we don't have a starting point to judge where the last frame
  111084. is. For this reason, vorbisfile will always try to make sure
  111085. it reads the last two marked pages in proper sequence */
  111086. if(b->sample_count==-1){
  111087. b->sample_count=0;
  111088. }else{
  111089. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111090. }
  111091. if(v->granulepos==-1){
  111092. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111093. v->granulepos=vb->granulepos;
  111094. /* is this a short page? */
  111095. if(b->sample_count>v->granulepos){
  111096. /* corner case; if this is both the first and last audio page,
  111097. then spec says the end is cut, not beginning */
  111098. if(vb->eofflag){
  111099. /* trim the end */
  111100. /* no preceeding granulepos; assume we started at zero (we'd
  111101. have to in a short single-page stream) */
  111102. /* granulepos could be -1 due to a seek, but that would result
  111103. in a long count, not short count */
  111104. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111105. }else{
  111106. /* trim the beginning */
  111107. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111108. if(v->pcm_returned>v->pcm_current)
  111109. v->pcm_returned=v->pcm_current;
  111110. }
  111111. }
  111112. }
  111113. }else{
  111114. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111115. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111116. if(v->granulepos>vb->granulepos){
  111117. long extra=v->granulepos-vb->granulepos;
  111118. if(extra)
  111119. if(vb->eofflag){
  111120. /* partial last frame. Strip the extra samples off */
  111121. v->pcm_current-=extra>>hs;
  111122. } /* else {Shouldn't happen *unless* the bitstream is out of
  111123. spec. Either way, believe the bitstream } */
  111124. } /* else {Shouldn't happen *unless* the bitstream is out of
  111125. spec. Either way, believe the bitstream } */
  111126. v->granulepos=vb->granulepos;
  111127. }
  111128. }
  111129. /* Update, cleanup */
  111130. if(vb->eofflag)v->eofflag=1;
  111131. return(0);
  111132. }
  111133. /* pcm==NULL indicates we just want the pending samples, no more */
  111134. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111135. vorbis_info *vi=v->vi;
  111136. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111137. if(pcm){
  111138. int i;
  111139. for(i=0;i<vi->channels;i++)
  111140. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111141. *pcm=v->pcmret;
  111142. }
  111143. return(v->pcm_current-v->pcm_returned);
  111144. }
  111145. return(0);
  111146. }
  111147. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111148. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111149. v->pcm_returned+=n;
  111150. return(0);
  111151. }
  111152. /* intended for use with a specific vorbisfile feature; we want access
  111153. to the [usually synthetic/postextrapolated] buffer and lapping at
  111154. the end of a decode cycle, specifically, a half-short-block worth.
  111155. This funtion works like pcmout above, except it will also expose
  111156. this implicit buffer data not normally decoded. */
  111157. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111158. vorbis_info *vi=v->vi;
  111159. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111160. int hs=ci->halfrate_flag;
  111161. int n=ci->blocksizes[v->W]>>(hs+1);
  111162. int n0=ci->blocksizes[0]>>(hs+1);
  111163. int n1=ci->blocksizes[1]>>(hs+1);
  111164. int i,j;
  111165. if(v->pcm_returned<0)return 0;
  111166. /* our returned data ends at pcm_returned; because the synthesis pcm
  111167. buffer is a two-fragment ring, that means our data block may be
  111168. fragmented by buffering, wrapping or a short block not filling
  111169. out a buffer. To simplify things, we unfragment if it's at all
  111170. possibly needed. Otherwise, we'd need to call lapout more than
  111171. once as well as hold additional dsp state. Opt for
  111172. simplicity. */
  111173. /* centerW was advanced by blockin; it would be the center of the
  111174. *next* block */
  111175. if(v->centerW==n1){
  111176. /* the data buffer wraps; swap the halves */
  111177. /* slow, sure, small */
  111178. for(j=0;j<vi->channels;j++){
  111179. float *p=v->pcm[j];
  111180. for(i=0;i<n1;i++){
  111181. float temp=p[i];
  111182. p[i]=p[i+n1];
  111183. p[i+n1]=temp;
  111184. }
  111185. }
  111186. v->pcm_current-=n1;
  111187. v->pcm_returned-=n1;
  111188. v->centerW=0;
  111189. }
  111190. /* solidify buffer into contiguous space */
  111191. if((v->lW^v->W)==1){
  111192. /* long/short or short/long */
  111193. for(j=0;j<vi->channels;j++){
  111194. float *s=v->pcm[j];
  111195. float *d=v->pcm[j]+(n1-n0)/2;
  111196. for(i=(n1+n0)/2-1;i>=0;--i)
  111197. d[i]=s[i];
  111198. }
  111199. v->pcm_returned+=(n1-n0)/2;
  111200. v->pcm_current+=(n1-n0)/2;
  111201. }else{
  111202. if(v->lW==0){
  111203. /* short/short */
  111204. for(j=0;j<vi->channels;j++){
  111205. float *s=v->pcm[j];
  111206. float *d=v->pcm[j]+n1-n0;
  111207. for(i=n0-1;i>=0;--i)
  111208. d[i]=s[i];
  111209. }
  111210. v->pcm_returned+=n1-n0;
  111211. v->pcm_current+=n1-n0;
  111212. }
  111213. }
  111214. if(pcm){
  111215. int i;
  111216. for(i=0;i<vi->channels;i++)
  111217. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111218. *pcm=v->pcmret;
  111219. }
  111220. return(n1+n-v->pcm_returned);
  111221. }
  111222. float *vorbis_window(vorbis_dsp_state *v,int W){
  111223. vorbis_info *vi=v->vi;
  111224. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111225. int hs=ci->halfrate_flag;
  111226. private_state *b=(private_state*)v->backend_state;
  111227. if(b->window[W]-1<0)return NULL;
  111228. return _vorbis_window_get(b->window[W]-hs);
  111229. }
  111230. #endif
  111231. /*** End of inlined file: block.c ***/
  111232. /*** Start of inlined file: codebook.c ***/
  111233. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111234. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111235. // tasks..
  111236. #if JUCE_MSVC
  111237. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111238. #endif
  111239. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111240. #if JUCE_USE_OGGVORBIS
  111241. #include <stdlib.h>
  111242. #include <string.h>
  111243. #include <math.h>
  111244. /* packs the given codebook into the bitstream **************************/
  111245. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111246. long i,j;
  111247. int ordered=0;
  111248. /* first the basic parameters */
  111249. oggpack_write(opb,0x564342,24);
  111250. oggpack_write(opb,c->dim,16);
  111251. oggpack_write(opb,c->entries,24);
  111252. /* pack the codewords. There are two packings; length ordered and
  111253. length random. Decide between the two now. */
  111254. for(i=1;i<c->entries;i++)
  111255. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111256. if(i==c->entries)ordered=1;
  111257. if(ordered){
  111258. /* length ordered. We only need to say how many codewords of
  111259. each length. The actual codewords are generated
  111260. deterministically */
  111261. long count=0;
  111262. oggpack_write(opb,1,1); /* ordered */
  111263. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111264. for(i=1;i<c->entries;i++){
  111265. long thisx=c->lengthlist[i];
  111266. long last=c->lengthlist[i-1];
  111267. if(thisx>last){
  111268. for(j=last;j<thisx;j++){
  111269. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111270. count=i;
  111271. }
  111272. }
  111273. }
  111274. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111275. }else{
  111276. /* length random. Again, we don't code the codeword itself, just
  111277. the length. This time, though, we have to encode each length */
  111278. oggpack_write(opb,0,1); /* unordered */
  111279. /* algortihmic mapping has use for 'unused entries', which we tag
  111280. here. The algorithmic mapping happens as usual, but the unused
  111281. entry has no codeword. */
  111282. for(i=0;i<c->entries;i++)
  111283. if(c->lengthlist[i]==0)break;
  111284. if(i==c->entries){
  111285. oggpack_write(opb,0,1); /* no unused entries */
  111286. for(i=0;i<c->entries;i++)
  111287. oggpack_write(opb,c->lengthlist[i]-1,5);
  111288. }else{
  111289. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111290. for(i=0;i<c->entries;i++){
  111291. if(c->lengthlist[i]==0){
  111292. oggpack_write(opb,0,1);
  111293. }else{
  111294. oggpack_write(opb,1,1);
  111295. oggpack_write(opb,c->lengthlist[i]-1,5);
  111296. }
  111297. }
  111298. }
  111299. }
  111300. /* is the entry number the desired return value, or do we have a
  111301. mapping? If we have a mapping, what type? */
  111302. oggpack_write(opb,c->maptype,4);
  111303. switch(c->maptype){
  111304. case 0:
  111305. /* no mapping */
  111306. break;
  111307. case 1:case 2:
  111308. /* implicitly populated value mapping */
  111309. /* explicitly populated value mapping */
  111310. if(!c->quantlist){
  111311. /* no quantlist? error */
  111312. return(-1);
  111313. }
  111314. /* values that define the dequantization */
  111315. oggpack_write(opb,c->q_min,32);
  111316. oggpack_write(opb,c->q_delta,32);
  111317. oggpack_write(opb,c->q_quant-1,4);
  111318. oggpack_write(opb,c->q_sequencep,1);
  111319. {
  111320. int quantvals;
  111321. switch(c->maptype){
  111322. case 1:
  111323. /* a single column of (c->entries/c->dim) quantized values for
  111324. building a full value list algorithmically (square lattice) */
  111325. quantvals=_book_maptype1_quantvals(c);
  111326. break;
  111327. case 2:
  111328. /* every value (c->entries*c->dim total) specified explicitly */
  111329. quantvals=c->entries*c->dim;
  111330. break;
  111331. default: /* NOT_REACHABLE */
  111332. quantvals=-1;
  111333. }
  111334. /* quantized values */
  111335. for(i=0;i<quantvals;i++)
  111336. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111337. }
  111338. break;
  111339. default:
  111340. /* error case; we don't have any other map types now */
  111341. return(-1);
  111342. }
  111343. return(0);
  111344. }
  111345. /* unpacks a codebook from the packet buffer into the codebook struct,
  111346. readies the codebook auxiliary structures for decode *************/
  111347. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111348. long i,j;
  111349. memset(s,0,sizeof(*s));
  111350. s->allocedp=1;
  111351. /* make sure alignment is correct */
  111352. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111353. /* first the basic parameters */
  111354. s->dim=oggpack_read(opb,16);
  111355. s->entries=oggpack_read(opb,24);
  111356. if(s->entries==-1)goto _eofout;
  111357. /* codeword ordering.... length ordered or unordered? */
  111358. switch((int)oggpack_read(opb,1)){
  111359. case 0:
  111360. /* unordered */
  111361. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111362. /* allocated but unused entries? */
  111363. if(oggpack_read(opb,1)){
  111364. /* yes, unused entries */
  111365. for(i=0;i<s->entries;i++){
  111366. if(oggpack_read(opb,1)){
  111367. long num=oggpack_read(opb,5);
  111368. if(num==-1)goto _eofout;
  111369. s->lengthlist[i]=num+1;
  111370. }else
  111371. s->lengthlist[i]=0;
  111372. }
  111373. }else{
  111374. /* all entries used; no tagging */
  111375. for(i=0;i<s->entries;i++){
  111376. long num=oggpack_read(opb,5);
  111377. if(num==-1)goto _eofout;
  111378. s->lengthlist[i]=num+1;
  111379. }
  111380. }
  111381. break;
  111382. case 1:
  111383. /* ordered */
  111384. {
  111385. long length=oggpack_read(opb,5)+1;
  111386. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111387. for(i=0;i<s->entries;){
  111388. long num=oggpack_read(opb,_ilog(s->entries-i));
  111389. if(num==-1)goto _eofout;
  111390. for(j=0;j<num && i<s->entries;j++,i++)
  111391. s->lengthlist[i]=length;
  111392. length++;
  111393. }
  111394. }
  111395. break;
  111396. default:
  111397. /* EOF */
  111398. return(-1);
  111399. }
  111400. /* Do we have a mapping to unpack? */
  111401. switch((s->maptype=oggpack_read(opb,4))){
  111402. case 0:
  111403. /* no mapping */
  111404. break;
  111405. case 1: case 2:
  111406. /* implicitly populated value mapping */
  111407. /* explicitly populated value mapping */
  111408. s->q_min=oggpack_read(opb,32);
  111409. s->q_delta=oggpack_read(opb,32);
  111410. s->q_quant=oggpack_read(opb,4)+1;
  111411. s->q_sequencep=oggpack_read(opb,1);
  111412. {
  111413. int quantvals=0;
  111414. switch(s->maptype){
  111415. case 1:
  111416. quantvals=_book_maptype1_quantvals(s);
  111417. break;
  111418. case 2:
  111419. quantvals=s->entries*s->dim;
  111420. break;
  111421. }
  111422. /* quantized values */
  111423. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111424. for(i=0;i<quantvals;i++)
  111425. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111426. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111427. }
  111428. break;
  111429. default:
  111430. goto _errout;
  111431. }
  111432. /* all set */
  111433. return(0);
  111434. _errout:
  111435. _eofout:
  111436. vorbis_staticbook_clear(s);
  111437. return(-1);
  111438. }
  111439. /* returns the number of bits ************************************************/
  111440. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111441. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111442. return(book->c->lengthlist[a]);
  111443. }
  111444. /* One the encode side, our vector writers are each designed for a
  111445. specific purpose, and the encoder is not flexible without modification:
  111446. The LSP vector coder uses a single stage nearest-match with no
  111447. interleave, so no step and no error return. This is specced by floor0
  111448. and doesn't change.
  111449. Residue0 encoding interleaves, uses multiple stages, and each stage
  111450. peels of a specific amount of resolution from a lattice (thus we want
  111451. to match by threshold, not nearest match). Residue doesn't *have* to
  111452. be encoded that way, but to change it, one will need to add more
  111453. infrastructure on the encode side (decode side is specced and simpler) */
  111454. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111455. /* returns entry number and *modifies a* to the quantization value *****/
  111456. int vorbis_book_errorv(codebook *book,float *a){
  111457. int dim=book->dim,k;
  111458. int best=_best(book,a,1);
  111459. for(k=0;k<dim;k++)
  111460. a[k]=(book->valuelist+best*dim)[k];
  111461. return(best);
  111462. }
  111463. /* returns the number of bits and *modifies a* to the quantization value *****/
  111464. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111465. int k,dim=book->dim;
  111466. for(k=0;k<dim;k++)
  111467. a[k]=(book->valuelist+best*dim)[k];
  111468. return(vorbis_book_encode(book,best,b));
  111469. }
  111470. /* the 'eliminate the decode tree' optimization actually requires the
  111471. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111472. (and one of the first places where carefully thought out design
  111473. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111474. to an MSb bitpacker), but not actually the huge hit it appears to
  111475. be. The first-stage decode table catches most words so that
  111476. bitreverse is not in the main execution path. */
  111477. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111478. int read=book->dec_maxlength;
  111479. long lo,hi;
  111480. long lok = oggpack_look(b,book->dec_firsttablen);
  111481. if (lok >= 0) {
  111482. long entry = book->dec_firsttable[lok];
  111483. if(entry&0x80000000UL){
  111484. lo=(entry>>15)&0x7fff;
  111485. hi=book->used_entries-(entry&0x7fff);
  111486. }else{
  111487. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111488. return(entry-1);
  111489. }
  111490. }else{
  111491. lo=0;
  111492. hi=book->used_entries;
  111493. }
  111494. lok = oggpack_look(b, read);
  111495. while(lok<0 && read>1)
  111496. lok = oggpack_look(b, --read);
  111497. if(lok<0)return -1;
  111498. /* bisect search for the codeword in the ordered list */
  111499. {
  111500. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111501. while(hi-lo>1){
  111502. long p=(hi-lo)>>1;
  111503. long test=book->codelist[lo+p]>testword;
  111504. lo+=p&(test-1);
  111505. hi-=p&(-test);
  111506. }
  111507. if(book->dec_codelengths[lo]<=read){
  111508. oggpack_adv(b, book->dec_codelengths[lo]);
  111509. return(lo);
  111510. }
  111511. }
  111512. oggpack_adv(b, read);
  111513. return(-1);
  111514. }
  111515. /* Decode side is specced and easier, because we don't need to find
  111516. matches using different criteria; we simply read and map. There are
  111517. two things we need to do 'depending':
  111518. We may need to support interleave. We don't really, but it's
  111519. convenient to do it here rather than rebuild the vector later.
  111520. Cascades may be additive or multiplicitive; this is not inherent in
  111521. the codebook, but set in the code using the codebook. Like
  111522. interleaving, it's easiest to do it here.
  111523. addmul==0 -> declarative (set the value)
  111524. addmul==1 -> additive
  111525. addmul==2 -> multiplicitive */
  111526. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111527. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111528. long packed_entry=decode_packed_entry_number(book,b);
  111529. if(packed_entry>=0)
  111530. return(book->dec_index[packed_entry]);
  111531. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111532. return(packed_entry);
  111533. }
  111534. /* returns 0 on OK or -1 on eof *************************************/
  111535. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111536. int step=n/book->dim;
  111537. long *entry = (long*)alloca(sizeof(*entry)*step);
  111538. float **t = (float**)alloca(sizeof(*t)*step);
  111539. int i,j,o;
  111540. for (i = 0; i < step; i++) {
  111541. entry[i]=decode_packed_entry_number(book,b);
  111542. if(entry[i]==-1)return(-1);
  111543. t[i] = book->valuelist+entry[i]*book->dim;
  111544. }
  111545. for(i=0,o=0;i<book->dim;i++,o+=step)
  111546. for (j=0;j<step;j++)
  111547. a[o+j]+=t[j][i];
  111548. return(0);
  111549. }
  111550. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111551. int i,j,entry;
  111552. float *t;
  111553. if(book->dim>8){
  111554. for(i=0;i<n;){
  111555. entry = decode_packed_entry_number(book,b);
  111556. if(entry==-1)return(-1);
  111557. t = book->valuelist+entry*book->dim;
  111558. for (j=0;j<book->dim;)
  111559. a[i++]+=t[j++];
  111560. }
  111561. }else{
  111562. for(i=0;i<n;){
  111563. entry = decode_packed_entry_number(book,b);
  111564. if(entry==-1)return(-1);
  111565. t = book->valuelist+entry*book->dim;
  111566. j=0;
  111567. switch((int)book->dim){
  111568. case 8:
  111569. a[i++]+=t[j++];
  111570. case 7:
  111571. a[i++]+=t[j++];
  111572. case 6:
  111573. a[i++]+=t[j++];
  111574. case 5:
  111575. a[i++]+=t[j++];
  111576. case 4:
  111577. a[i++]+=t[j++];
  111578. case 3:
  111579. a[i++]+=t[j++];
  111580. case 2:
  111581. a[i++]+=t[j++];
  111582. case 1:
  111583. a[i++]+=t[j++];
  111584. case 0:
  111585. break;
  111586. }
  111587. }
  111588. }
  111589. return(0);
  111590. }
  111591. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111592. int i,j,entry;
  111593. float *t;
  111594. for(i=0;i<n;){
  111595. entry = decode_packed_entry_number(book,b);
  111596. if(entry==-1)return(-1);
  111597. t = book->valuelist+entry*book->dim;
  111598. for (j=0;j<book->dim;)
  111599. a[i++]=t[j++];
  111600. }
  111601. return(0);
  111602. }
  111603. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111604. oggpack_buffer *b,int n){
  111605. long i,j,entry;
  111606. int chptr=0;
  111607. for(i=offset/ch;i<(offset+n)/ch;){
  111608. entry = decode_packed_entry_number(book,b);
  111609. if(entry==-1)return(-1);
  111610. {
  111611. const float *t = book->valuelist+entry*book->dim;
  111612. for (j=0;j<book->dim;j++){
  111613. a[chptr++][i]+=t[j];
  111614. if(chptr==ch){
  111615. chptr=0;
  111616. i++;
  111617. }
  111618. }
  111619. }
  111620. }
  111621. return(0);
  111622. }
  111623. #ifdef _V_SELFTEST
  111624. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111625. number of vectors through (keeping track of the quantized values),
  111626. and decode using the unpacked book. quantized version of in should
  111627. exactly equal out */
  111628. #include <stdio.h>
  111629. #include "vorbis/book/lsp20_0.vqh"
  111630. #include "vorbis/book/res0a_13.vqh"
  111631. #define TESTSIZE 40
  111632. float test1[TESTSIZE]={
  111633. 0.105939f,
  111634. 0.215373f,
  111635. 0.429117f,
  111636. 0.587974f,
  111637. 0.181173f,
  111638. 0.296583f,
  111639. 0.515707f,
  111640. 0.715261f,
  111641. 0.162327f,
  111642. 0.263834f,
  111643. 0.342876f,
  111644. 0.406025f,
  111645. 0.103571f,
  111646. 0.223561f,
  111647. 0.368513f,
  111648. 0.540313f,
  111649. 0.136672f,
  111650. 0.395882f,
  111651. 0.587183f,
  111652. 0.652476f,
  111653. 0.114338f,
  111654. 0.417300f,
  111655. 0.525486f,
  111656. 0.698679f,
  111657. 0.147492f,
  111658. 0.324481f,
  111659. 0.643089f,
  111660. 0.757582f,
  111661. 0.139556f,
  111662. 0.215795f,
  111663. 0.324559f,
  111664. 0.399387f,
  111665. 0.120236f,
  111666. 0.267420f,
  111667. 0.446940f,
  111668. 0.608760f,
  111669. 0.115587f,
  111670. 0.287234f,
  111671. 0.571081f,
  111672. 0.708603f,
  111673. };
  111674. float test3[TESTSIZE]={
  111675. 0,1,-2,3,4,-5,6,7,8,9,
  111676. 8,-2,7,-1,4,6,8,3,1,-9,
  111677. 10,11,12,13,14,15,26,17,18,19,
  111678. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111679. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111680. &_vq_book_res0a_13,NULL};
  111681. float *testvec[]={test1,test3};
  111682. int main(){
  111683. oggpack_buffer write;
  111684. oggpack_buffer read;
  111685. long ptr=0,i;
  111686. oggpack_writeinit(&write);
  111687. fprintf(stderr,"Testing codebook abstraction...:\n");
  111688. while(testlist[ptr]){
  111689. codebook c;
  111690. static_codebook s;
  111691. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111692. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111693. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111694. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111695. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111696. /* pack the codebook, write the testvector */
  111697. oggpack_reset(&write);
  111698. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111699. we can write */
  111700. vorbis_staticbook_pack(testlist[ptr],&write);
  111701. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111702. for(i=0;i<TESTSIZE;i+=c.dim){
  111703. int best=_best(&c,qv+i,1);
  111704. vorbis_book_encodev(&c,best,qv+i,&write);
  111705. }
  111706. vorbis_book_clear(&c);
  111707. fprintf(stderr,"OK.\n");
  111708. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111709. /* transfer the write data to a read buffer and unpack/read */
  111710. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111711. if(vorbis_staticbook_unpack(&read,&s)){
  111712. fprintf(stderr,"Error unpacking codebook.\n");
  111713. exit(1);
  111714. }
  111715. if(vorbis_book_init_decode(&c,&s)){
  111716. fprintf(stderr,"Error initializing codebook.\n");
  111717. exit(1);
  111718. }
  111719. for(i=0;i<TESTSIZE;i+=c.dim)
  111720. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111721. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111722. exit(1);
  111723. }
  111724. for(i=0;i<TESTSIZE;i++)
  111725. if(fabs(qv[i]-iv[i])>.000001){
  111726. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111727. iv[i],qv[i],i);
  111728. exit(1);
  111729. }
  111730. fprintf(stderr,"OK\n");
  111731. ptr++;
  111732. }
  111733. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111734. exit(0);
  111735. }
  111736. #endif
  111737. #endif
  111738. /*** End of inlined file: codebook.c ***/
  111739. /*** Start of inlined file: envelope.c ***/
  111740. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111741. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111742. // tasks..
  111743. #if JUCE_MSVC
  111744. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111745. #endif
  111746. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111747. #if JUCE_USE_OGGVORBIS
  111748. #include <stdlib.h>
  111749. #include <string.h>
  111750. #include <stdio.h>
  111751. #include <math.h>
  111752. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111753. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111754. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111755. int ch=vi->channels;
  111756. int i,j;
  111757. int n=e->winlength=128;
  111758. e->searchstep=64; /* not random */
  111759. e->minenergy=gi->preecho_minenergy;
  111760. e->ch=ch;
  111761. e->storage=128;
  111762. e->cursor=ci->blocksizes[1]/2;
  111763. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111764. mdct_init(&e->mdct,n);
  111765. for(i=0;i<n;i++){
  111766. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111767. e->mdct_win[i]*=e->mdct_win[i];
  111768. }
  111769. /* magic follows */
  111770. e->band[0].begin=2; e->band[0].end=4;
  111771. e->band[1].begin=4; e->band[1].end=5;
  111772. e->band[2].begin=6; e->band[2].end=6;
  111773. e->band[3].begin=9; e->band[3].end=8;
  111774. e->band[4].begin=13; e->band[4].end=8;
  111775. e->band[5].begin=17; e->band[5].end=8;
  111776. e->band[6].begin=22; e->band[6].end=8;
  111777. for(j=0;j<VE_BANDS;j++){
  111778. n=e->band[j].end;
  111779. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111780. for(i=0;i<n;i++){
  111781. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111782. e->band[j].total+=e->band[j].window[i];
  111783. }
  111784. e->band[j].total=1./e->band[j].total;
  111785. }
  111786. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111787. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111788. }
  111789. void _ve_envelope_clear(envelope_lookup *e){
  111790. int i;
  111791. mdct_clear(&e->mdct);
  111792. for(i=0;i<VE_BANDS;i++)
  111793. _ogg_free(e->band[i].window);
  111794. _ogg_free(e->mdct_win);
  111795. _ogg_free(e->filter);
  111796. _ogg_free(e->mark);
  111797. memset(e,0,sizeof(*e));
  111798. }
  111799. /* fairly straight threshhold-by-band based until we find something
  111800. that works better and isn't patented. */
  111801. static int _ve_amp(envelope_lookup *ve,
  111802. vorbis_info_psy_global *gi,
  111803. float *data,
  111804. envelope_band *bands,
  111805. envelope_filter_state *filters,
  111806. long pos){
  111807. long n=ve->winlength;
  111808. int ret=0;
  111809. long i,j;
  111810. float decay;
  111811. /* we want to have a 'minimum bar' for energy, else we're just
  111812. basing blocks on quantization noise that outweighs the signal
  111813. itself (for low power signals) */
  111814. float minV=ve->minenergy;
  111815. float *vec=(float*) alloca(n*sizeof(*vec));
  111816. /* stretch is used to gradually lengthen the number of windows
  111817. considered prevoius-to-potential-trigger */
  111818. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  111819. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  111820. if(penalty<0.f)penalty=0.f;
  111821. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  111822. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  111823. totalshift+pos*ve->searchstep);*/
  111824. /* window and transform */
  111825. for(i=0;i<n;i++)
  111826. vec[i]=data[i]*ve->mdct_win[i];
  111827. mdct_forward(&ve->mdct,vec,vec);
  111828. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  111829. /* near-DC spreading function; this has nothing to do with
  111830. psychoacoustics, just sidelobe leakage and window size */
  111831. {
  111832. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  111833. int ptr=filters->nearptr;
  111834. /* the accumulation is regularly refreshed from scratch to avoid
  111835. floating point creep */
  111836. if(ptr==0){
  111837. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  111838. filters->nearDC_partialacc=temp;
  111839. }else{
  111840. decay=filters->nearDC_acc+=temp;
  111841. filters->nearDC_partialacc+=temp;
  111842. }
  111843. filters->nearDC_acc-=filters->nearDC[ptr];
  111844. filters->nearDC[ptr]=temp;
  111845. decay*=(1./(VE_NEARDC+1));
  111846. filters->nearptr++;
  111847. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  111848. decay=todB(&decay)*.5-15.f;
  111849. }
  111850. /* perform spreading and limiting, also smooth the spectrum. yes,
  111851. the MDCT results in all real coefficients, but it still *behaves*
  111852. like real/imaginary pairs */
  111853. for(i=0;i<n/2;i+=2){
  111854. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  111855. val=todB(&val)*.5f;
  111856. if(val<decay)val=decay;
  111857. if(val<minV)val=minV;
  111858. vec[i>>1]=val;
  111859. decay-=8.;
  111860. }
  111861. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  111862. /* perform preecho/postecho triggering by band */
  111863. for(j=0;j<VE_BANDS;j++){
  111864. float acc=0.;
  111865. float valmax,valmin;
  111866. /* accumulate amplitude */
  111867. for(i=0;i<bands[j].end;i++)
  111868. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  111869. acc*=bands[j].total;
  111870. /* convert amplitude to delta */
  111871. {
  111872. int p,thisx=filters[j].ampptr;
  111873. float postmax,postmin,premax=-99999.f,premin=99999.f;
  111874. p=thisx;
  111875. p--;
  111876. if(p<0)p+=VE_AMP;
  111877. postmax=max(acc,filters[j].ampbuf[p]);
  111878. postmin=min(acc,filters[j].ampbuf[p]);
  111879. for(i=0;i<stretch;i++){
  111880. p--;
  111881. if(p<0)p+=VE_AMP;
  111882. premax=max(premax,filters[j].ampbuf[p]);
  111883. premin=min(premin,filters[j].ampbuf[p]);
  111884. }
  111885. valmin=postmin-premin;
  111886. valmax=postmax-premax;
  111887. /*filters[j].markers[pos]=valmax;*/
  111888. filters[j].ampbuf[thisx]=acc;
  111889. filters[j].ampptr++;
  111890. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  111891. }
  111892. /* look at min/max, decide trigger */
  111893. if(valmax>gi->preecho_thresh[j]+penalty){
  111894. ret|=1;
  111895. ret|=4;
  111896. }
  111897. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  111898. }
  111899. return(ret);
  111900. }
  111901. #if 0
  111902. static int seq=0;
  111903. static ogg_int64_t totalshift=-1024;
  111904. #endif
  111905. long _ve_envelope_search(vorbis_dsp_state *v){
  111906. vorbis_info *vi=v->vi;
  111907. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111908. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111909. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111910. long i,j;
  111911. int first=ve->current/ve->searchstep;
  111912. int last=v->pcm_current/ve->searchstep-VE_WIN;
  111913. if(first<0)first=0;
  111914. /* make sure we have enough storage to match the PCM */
  111915. if(last+VE_WIN+VE_POST>ve->storage){
  111916. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  111917. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  111918. }
  111919. for(j=first;j<last;j++){
  111920. int ret=0;
  111921. ve->stretch++;
  111922. if(ve->stretch>VE_MAXSTRETCH*2)
  111923. ve->stretch=VE_MAXSTRETCH*2;
  111924. for(i=0;i<ve->ch;i++){
  111925. float *pcm=v->pcm[i]+ve->searchstep*(j);
  111926. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  111927. }
  111928. ve->mark[j+VE_POST]=0;
  111929. if(ret&1){
  111930. ve->mark[j]=1;
  111931. ve->mark[j+1]=1;
  111932. }
  111933. if(ret&2){
  111934. ve->mark[j]=1;
  111935. if(j>0)ve->mark[j-1]=1;
  111936. }
  111937. if(ret&4)ve->stretch=-1;
  111938. }
  111939. ve->current=last*ve->searchstep;
  111940. {
  111941. long centerW=v->centerW;
  111942. long testW=
  111943. centerW+
  111944. ci->blocksizes[v->W]/4+
  111945. ci->blocksizes[1]/2+
  111946. ci->blocksizes[0]/4;
  111947. j=ve->cursor;
  111948. while(j<ve->current-(ve->searchstep)){/* account for postecho
  111949. working back one window */
  111950. if(j>=testW)return(1);
  111951. ve->cursor=j;
  111952. if(ve->mark[j/ve->searchstep]){
  111953. if(j>centerW){
  111954. #if 0
  111955. if(j>ve->curmark){
  111956. float *marker=alloca(v->pcm_current*sizeof(*marker));
  111957. int l,m;
  111958. memset(marker,0,sizeof(*marker)*v->pcm_current);
  111959. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  111960. seq,
  111961. (totalshift+ve->cursor)/44100.,
  111962. (totalshift+j)/44100.);
  111963. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  111964. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  111965. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  111966. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  111967. for(m=0;m<VE_BANDS;m++){
  111968. char buf[80];
  111969. sprintf(buf,"delL%d",m);
  111970. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  111971. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111972. }
  111973. for(m=0;m<VE_BANDS;m++){
  111974. char buf[80];
  111975. sprintf(buf,"delR%d",m);
  111976. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  111977. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111978. }
  111979. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  111980. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  111981. seq++;
  111982. }
  111983. #endif
  111984. ve->curmark=j;
  111985. if(j>=testW)return(1);
  111986. return(0);
  111987. }
  111988. }
  111989. j+=ve->searchstep;
  111990. }
  111991. }
  111992. return(-1);
  111993. }
  111994. int _ve_envelope_mark(vorbis_dsp_state *v){
  111995. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111996. vorbis_info *vi=v->vi;
  111997. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111998. long centerW=v->centerW;
  111999. long beginW=centerW-ci->blocksizes[v->W]/4;
  112000. long endW=centerW+ci->blocksizes[v->W]/4;
  112001. if(v->W){
  112002. beginW-=ci->blocksizes[v->lW]/4;
  112003. endW+=ci->blocksizes[v->nW]/4;
  112004. }else{
  112005. beginW-=ci->blocksizes[0]/4;
  112006. endW+=ci->blocksizes[0]/4;
  112007. }
  112008. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112009. {
  112010. long first=beginW/ve->searchstep;
  112011. long last=endW/ve->searchstep;
  112012. long i;
  112013. for(i=first;i<last;i++)
  112014. if(ve->mark[i])return(1);
  112015. }
  112016. return(0);
  112017. }
  112018. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112019. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112020. ahead of ve->current */
  112021. int smallshift=shift/e->searchstep;
  112022. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112023. #if 0
  112024. for(i=0;i<VE_BANDS*e->ch;i++)
  112025. memmove(e->filter[i].markers,
  112026. e->filter[i].markers+smallshift,
  112027. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112028. totalshift+=shift;
  112029. #endif
  112030. e->current-=shift;
  112031. if(e->curmark>=0)
  112032. e->curmark-=shift;
  112033. e->cursor-=shift;
  112034. }
  112035. #endif
  112036. /*** End of inlined file: envelope.c ***/
  112037. /*** Start of inlined file: floor0.c ***/
  112038. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112039. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112040. // tasks..
  112041. #if JUCE_MSVC
  112042. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112043. #endif
  112044. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112045. #if JUCE_USE_OGGVORBIS
  112046. #include <stdlib.h>
  112047. #include <string.h>
  112048. #include <math.h>
  112049. /*** Start of inlined file: lsp.h ***/
  112050. #ifndef _V_LSP_H_
  112051. #define _V_LSP_H_
  112052. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112053. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112054. float *lsp,int m,
  112055. float amp,float ampoffset);
  112056. #endif
  112057. /*** End of inlined file: lsp.h ***/
  112058. #include <stdio.h>
  112059. typedef struct {
  112060. int ln;
  112061. int m;
  112062. int **linearmap;
  112063. int n[2];
  112064. vorbis_info_floor0 *vi;
  112065. long bits;
  112066. long frames;
  112067. } vorbis_look_floor0;
  112068. /***********************************************/
  112069. static void floor0_free_info(vorbis_info_floor *i){
  112070. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112071. if(info){
  112072. memset(info,0,sizeof(*info));
  112073. _ogg_free(info);
  112074. }
  112075. }
  112076. static void floor0_free_look(vorbis_look_floor *i){
  112077. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112078. if(look){
  112079. if(look->linearmap){
  112080. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112081. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112082. _ogg_free(look->linearmap);
  112083. }
  112084. memset(look,0,sizeof(*look));
  112085. _ogg_free(look);
  112086. }
  112087. }
  112088. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112089. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112090. int j;
  112091. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112092. info->order=oggpack_read(opb,8);
  112093. info->rate=oggpack_read(opb,16);
  112094. info->barkmap=oggpack_read(opb,16);
  112095. info->ampbits=oggpack_read(opb,6);
  112096. info->ampdB=oggpack_read(opb,8);
  112097. info->numbooks=oggpack_read(opb,4)+1;
  112098. if(info->order<1)goto err_out;
  112099. if(info->rate<1)goto err_out;
  112100. if(info->barkmap<1)goto err_out;
  112101. if(info->numbooks<1)goto err_out;
  112102. for(j=0;j<info->numbooks;j++){
  112103. info->books[j]=oggpack_read(opb,8);
  112104. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112105. }
  112106. return(info);
  112107. err_out:
  112108. floor0_free_info(info);
  112109. return(NULL);
  112110. }
  112111. /* initialize Bark scale and normalization lookups. We could do this
  112112. with static tables, but Vorbis allows a number of possible
  112113. combinations, so it's best to do it computationally.
  112114. The below is authoritative in terms of defining scale mapping.
  112115. Note that the scale depends on the sampling rate as well as the
  112116. linear block and mapping sizes */
  112117. static void floor0_map_lazy_init(vorbis_block *vb,
  112118. vorbis_info_floor *infoX,
  112119. vorbis_look_floor0 *look){
  112120. if(!look->linearmap[vb->W]){
  112121. vorbis_dsp_state *vd=vb->vd;
  112122. vorbis_info *vi=vd->vi;
  112123. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112124. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112125. int W=vb->W;
  112126. int n=ci->blocksizes[W]/2,j;
  112127. /* we choose a scaling constant so that:
  112128. floor(bark(rate/2-1)*C)=mapped-1
  112129. floor(bark(rate/2)*C)=mapped */
  112130. float scale=look->ln/toBARK(info->rate/2.f);
  112131. /* the mapping from a linear scale to a smaller bark scale is
  112132. straightforward. We do *not* make sure that the linear mapping
  112133. does not skip bark-scale bins; the decoder simply skips them and
  112134. the encoder may do what it wishes in filling them. They're
  112135. necessary in some mapping combinations to keep the scale spacing
  112136. accurate */
  112137. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112138. for(j=0;j<n;j++){
  112139. int val=floor( toBARK((info->rate/2.f)/n*j)
  112140. *scale); /* bark numbers represent band edges */
  112141. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112142. look->linearmap[W][j]=val;
  112143. }
  112144. look->linearmap[W][j]=-1;
  112145. look->n[W]=n;
  112146. }
  112147. }
  112148. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112149. vorbis_info_floor *i){
  112150. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112151. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112152. look->m=info->order;
  112153. look->ln=info->barkmap;
  112154. look->vi=info;
  112155. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112156. return look;
  112157. }
  112158. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112159. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112160. vorbis_info_floor0 *info=look->vi;
  112161. int j,k;
  112162. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112163. if(ampraw>0){ /* also handles the -1 out of data case */
  112164. long maxval=(1<<info->ampbits)-1;
  112165. float amp=(float)ampraw/maxval*info->ampdB;
  112166. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112167. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112168. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112169. codebook *b=ci->fullbooks+info->books[booknum];
  112170. float last=0.f;
  112171. /* the additional b->dim is a guard against any possible stack
  112172. smash; b->dim is provably more than we can overflow the
  112173. vector */
  112174. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112175. for(j=0;j<look->m;j+=b->dim)
  112176. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112177. for(j=0;j<look->m;){
  112178. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112179. last=lsp[j-1];
  112180. }
  112181. lsp[look->m]=amp;
  112182. return(lsp);
  112183. }
  112184. }
  112185. eop:
  112186. return(NULL);
  112187. }
  112188. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112189. void *memo,float *out){
  112190. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112191. vorbis_info_floor0 *info=look->vi;
  112192. floor0_map_lazy_init(vb,info,look);
  112193. if(memo){
  112194. float *lsp=(float *)memo;
  112195. float amp=lsp[look->m];
  112196. /* take the coefficients back to a spectral envelope curve */
  112197. vorbis_lsp_to_curve(out,
  112198. look->linearmap[vb->W],
  112199. look->n[vb->W],
  112200. look->ln,
  112201. lsp,look->m,amp,(float)info->ampdB);
  112202. return(1);
  112203. }
  112204. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112205. return(0);
  112206. }
  112207. /* export hooks */
  112208. vorbis_func_floor floor0_exportbundle={
  112209. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112210. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112211. };
  112212. #endif
  112213. /*** End of inlined file: floor0.c ***/
  112214. /*** Start of inlined file: floor1.c ***/
  112215. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112216. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112217. // tasks..
  112218. #if JUCE_MSVC
  112219. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112220. #endif
  112221. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112222. #if JUCE_USE_OGGVORBIS
  112223. #include <stdlib.h>
  112224. #include <string.h>
  112225. #include <math.h>
  112226. #include <stdio.h>
  112227. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112228. typedef struct {
  112229. int sorted_index[VIF_POSIT+2];
  112230. int forward_index[VIF_POSIT+2];
  112231. int reverse_index[VIF_POSIT+2];
  112232. int hineighbor[VIF_POSIT];
  112233. int loneighbor[VIF_POSIT];
  112234. int posts;
  112235. int n;
  112236. int quant_q;
  112237. vorbis_info_floor1 *vi;
  112238. long phrasebits;
  112239. long postbits;
  112240. long frames;
  112241. } vorbis_look_floor1;
  112242. typedef struct lsfit_acc{
  112243. long x0;
  112244. long x1;
  112245. long xa;
  112246. long ya;
  112247. long x2a;
  112248. long y2a;
  112249. long xya;
  112250. long an;
  112251. } lsfit_acc;
  112252. /***********************************************/
  112253. static void floor1_free_info(vorbis_info_floor *i){
  112254. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112255. if(info){
  112256. memset(info,0,sizeof(*info));
  112257. _ogg_free(info);
  112258. }
  112259. }
  112260. static void floor1_free_look(vorbis_look_floor *i){
  112261. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112262. if(look){
  112263. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112264. (float)look->phrasebits/look->frames,
  112265. (float)look->postbits/look->frames,
  112266. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112267. memset(look,0,sizeof(*look));
  112268. _ogg_free(look);
  112269. }
  112270. }
  112271. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112272. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112273. int j,k;
  112274. int count=0;
  112275. int rangebits;
  112276. int maxposit=info->postlist[1];
  112277. int maxclass=-1;
  112278. /* save out partitions */
  112279. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112280. for(j=0;j<info->partitions;j++){
  112281. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112282. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112283. }
  112284. /* save out partition classes */
  112285. for(j=0;j<maxclass+1;j++){
  112286. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112287. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112288. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112289. for(k=0;k<(1<<info->class_subs[j]);k++)
  112290. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112291. }
  112292. /* save out the post list */
  112293. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112294. oggpack_write(opb,ilog2(maxposit),4);
  112295. rangebits=ilog2(maxposit);
  112296. for(j=0,k=0;j<info->partitions;j++){
  112297. count+=info->class_dim[info->partitionclass[j]];
  112298. for(;k<count;k++)
  112299. oggpack_write(opb,info->postlist[k+2],rangebits);
  112300. }
  112301. }
  112302. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112303. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112304. int j,k,count=0,maxclass=-1,rangebits;
  112305. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112306. /* read partitions */
  112307. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112308. for(j=0;j<info->partitions;j++){
  112309. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112310. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112311. }
  112312. /* read partition classes */
  112313. for(j=0;j<maxclass+1;j++){
  112314. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112315. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112316. if(info->class_subs[j]<0)
  112317. goto err_out;
  112318. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112319. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112320. goto err_out;
  112321. for(k=0;k<(1<<info->class_subs[j]);k++){
  112322. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112323. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112324. goto err_out;
  112325. }
  112326. }
  112327. /* read the post list */
  112328. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112329. rangebits=oggpack_read(opb,4);
  112330. for(j=0,k=0;j<info->partitions;j++){
  112331. count+=info->class_dim[info->partitionclass[j]];
  112332. for(;k<count;k++){
  112333. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112334. if(t<0 || t>=(1<<rangebits))
  112335. goto err_out;
  112336. }
  112337. }
  112338. info->postlist[0]=0;
  112339. info->postlist[1]=1<<rangebits;
  112340. return(info);
  112341. err_out:
  112342. floor1_free_info(info);
  112343. return(NULL);
  112344. }
  112345. static int icomp(const void *a,const void *b){
  112346. return(**(int **)a-**(int **)b);
  112347. }
  112348. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112349. vorbis_info_floor *in){
  112350. int *sortpointer[VIF_POSIT+2];
  112351. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112352. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112353. int i,j,n=0;
  112354. look->vi=info;
  112355. look->n=info->postlist[1];
  112356. /* we drop each position value in-between already decoded values,
  112357. and use linear interpolation to predict each new value past the
  112358. edges. The positions are read in the order of the position
  112359. list... we precompute the bounding positions in the lookup. Of
  112360. course, the neighbors can change (if a position is declined), but
  112361. this is an initial mapping */
  112362. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112363. n+=2;
  112364. look->posts=n;
  112365. /* also store a sorted position index */
  112366. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112367. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112368. /* points from sort order back to range number */
  112369. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112370. /* points from range order to sorted position */
  112371. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112372. /* we actually need the post values too */
  112373. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112374. /* quantize values to multiplier spec */
  112375. switch(info->mult){
  112376. case 1: /* 1024 -> 256 */
  112377. look->quant_q=256;
  112378. break;
  112379. case 2: /* 1024 -> 128 */
  112380. look->quant_q=128;
  112381. break;
  112382. case 3: /* 1024 -> 86 */
  112383. look->quant_q=86;
  112384. break;
  112385. case 4: /* 1024 -> 64 */
  112386. look->quant_q=64;
  112387. break;
  112388. }
  112389. /* discover our neighbors for decode where we don't use fit flags
  112390. (that would push the neighbors outward) */
  112391. for(i=0;i<n-2;i++){
  112392. int lo=0;
  112393. int hi=1;
  112394. int lx=0;
  112395. int hx=look->n;
  112396. int currentx=info->postlist[i+2];
  112397. for(j=0;j<i+2;j++){
  112398. int x=info->postlist[j];
  112399. if(x>lx && x<currentx){
  112400. lo=j;
  112401. lx=x;
  112402. }
  112403. if(x<hx && x>currentx){
  112404. hi=j;
  112405. hx=x;
  112406. }
  112407. }
  112408. look->loneighbor[i]=lo;
  112409. look->hineighbor[i]=hi;
  112410. }
  112411. return(look);
  112412. }
  112413. static int render_point(int x0,int x1,int y0,int y1,int x){
  112414. y0&=0x7fff; /* mask off flag */
  112415. y1&=0x7fff;
  112416. {
  112417. int dy=y1-y0;
  112418. int adx=x1-x0;
  112419. int ady=abs(dy);
  112420. int err=ady*(x-x0);
  112421. int off=err/adx;
  112422. if(dy<0)return(y0-off);
  112423. return(y0+off);
  112424. }
  112425. }
  112426. static int vorbis_dBquant(const float *x){
  112427. int i= *x*7.3142857f+1023.5f;
  112428. if(i>1023)return(1023);
  112429. if(i<0)return(0);
  112430. return i;
  112431. }
  112432. static float FLOOR1_fromdB_LOOKUP[256]={
  112433. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112434. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112435. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112436. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112437. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112438. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112439. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112440. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112441. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112442. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112443. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112444. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112445. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112446. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112447. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112448. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112449. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112450. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112451. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112452. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112453. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112454. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112455. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112456. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112457. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112458. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112459. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112460. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112461. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112462. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112463. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112464. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112465. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112466. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112467. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112468. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112469. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112470. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112471. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112472. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112473. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112474. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112475. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112476. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112477. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112478. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112479. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112480. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112481. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112482. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112483. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112484. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112485. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112486. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112487. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112488. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112489. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112490. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112491. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112492. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112493. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112494. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112495. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112496. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112497. };
  112498. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112499. int dy=y1-y0;
  112500. int adx=x1-x0;
  112501. int ady=abs(dy);
  112502. int base=dy/adx;
  112503. int sy=(dy<0?base-1:base+1);
  112504. int x=x0;
  112505. int y=y0;
  112506. int err=0;
  112507. ady-=abs(base*adx);
  112508. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112509. while(++x<x1){
  112510. err=err+ady;
  112511. if(err>=adx){
  112512. err-=adx;
  112513. y+=sy;
  112514. }else{
  112515. y+=base;
  112516. }
  112517. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112518. }
  112519. }
  112520. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112521. int dy=y1-y0;
  112522. int adx=x1-x0;
  112523. int ady=abs(dy);
  112524. int base=dy/adx;
  112525. int sy=(dy<0?base-1:base+1);
  112526. int x=x0;
  112527. int y=y0;
  112528. int err=0;
  112529. ady-=abs(base*adx);
  112530. d[x]=y;
  112531. while(++x<x1){
  112532. err=err+ady;
  112533. if(err>=adx){
  112534. err-=adx;
  112535. y+=sy;
  112536. }else{
  112537. y+=base;
  112538. }
  112539. d[x]=y;
  112540. }
  112541. }
  112542. /* the floor has already been filtered to only include relevant sections */
  112543. static int accumulate_fit(const float *flr,const float *mdct,
  112544. int x0, int x1,lsfit_acc *a,
  112545. int n,vorbis_info_floor1 *info){
  112546. long i;
  112547. 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;
  112548. memset(a,0,sizeof(*a));
  112549. a->x0=x0;
  112550. a->x1=x1;
  112551. if(x1>=n)x1=n-1;
  112552. for(i=x0;i<=x1;i++){
  112553. int quantized=vorbis_dBquant(flr+i);
  112554. if(quantized){
  112555. if(mdct[i]+info->twofitatten>=flr[i]){
  112556. xa += i;
  112557. ya += quantized;
  112558. x2a += i*i;
  112559. y2a += quantized*quantized;
  112560. xya += i*quantized;
  112561. na++;
  112562. }else{
  112563. xb += i;
  112564. yb += quantized;
  112565. x2b += i*i;
  112566. y2b += quantized*quantized;
  112567. xyb += i*quantized;
  112568. nb++;
  112569. }
  112570. }
  112571. }
  112572. xb+=xa;
  112573. yb+=ya;
  112574. x2b+=x2a;
  112575. y2b+=y2a;
  112576. xyb+=xya;
  112577. nb+=na;
  112578. /* weight toward the actually used frequencies if we meet the threshhold */
  112579. {
  112580. int weight=nb*info->twofitweight/(na+1);
  112581. a->xa=xa*weight+xb;
  112582. a->ya=ya*weight+yb;
  112583. a->x2a=x2a*weight+x2b;
  112584. a->y2a=y2a*weight+y2b;
  112585. a->xya=xya*weight+xyb;
  112586. a->an=na*weight+nb;
  112587. }
  112588. return(na);
  112589. }
  112590. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112591. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112592. long x0=a[0].x0;
  112593. long x1=a[fits-1].x1;
  112594. for(i=0;i<fits;i++){
  112595. x+=a[i].xa;
  112596. y+=a[i].ya;
  112597. x2+=a[i].x2a;
  112598. y2+=a[i].y2a;
  112599. xy+=a[i].xya;
  112600. an+=a[i].an;
  112601. }
  112602. if(*y0>=0){
  112603. x+= x0;
  112604. y+= *y0;
  112605. x2+= x0 * x0;
  112606. y2+= *y0 * *y0;
  112607. xy+= *y0 * x0;
  112608. an++;
  112609. }
  112610. if(*y1>=0){
  112611. x+= x1;
  112612. y+= *y1;
  112613. x2+= x1 * x1;
  112614. y2+= *y1 * *y1;
  112615. xy+= *y1 * x1;
  112616. an++;
  112617. }
  112618. if(an){
  112619. /* need 64 bit multiplies, which C doesn't give portably as int */
  112620. double fx=x;
  112621. double fy=y;
  112622. double fx2=x2;
  112623. double fxy=xy;
  112624. double denom=1./(an*fx2-fx*fx);
  112625. double a=(fy*fx2-fxy*fx)*denom;
  112626. double b=(an*fxy-fx*fy)*denom;
  112627. *y0=rint(a+b*x0);
  112628. *y1=rint(a+b*x1);
  112629. /* limit to our range! */
  112630. if(*y0>1023)*y0=1023;
  112631. if(*y1>1023)*y1=1023;
  112632. if(*y0<0)*y0=0;
  112633. if(*y1<0)*y1=0;
  112634. }else{
  112635. *y0=0;
  112636. *y1=0;
  112637. }
  112638. }
  112639. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112640. long y=0;
  112641. int i;
  112642. for(i=0;i<fits && y==0;i++)
  112643. y+=a[i].ya;
  112644. *y0=*y1=y;
  112645. }*/
  112646. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112647. const float *mdct,
  112648. vorbis_info_floor1 *info){
  112649. int dy=y1-y0;
  112650. int adx=x1-x0;
  112651. int ady=abs(dy);
  112652. int base=dy/adx;
  112653. int sy=(dy<0?base-1:base+1);
  112654. int x=x0;
  112655. int y=y0;
  112656. int err=0;
  112657. int val=vorbis_dBquant(mask+x);
  112658. int mse=0;
  112659. int n=0;
  112660. ady-=abs(base*adx);
  112661. mse=(y-val);
  112662. mse*=mse;
  112663. n++;
  112664. if(mdct[x]+info->twofitatten>=mask[x]){
  112665. if(y+info->maxover<val)return(1);
  112666. if(y-info->maxunder>val)return(1);
  112667. }
  112668. while(++x<x1){
  112669. err=err+ady;
  112670. if(err>=adx){
  112671. err-=adx;
  112672. y+=sy;
  112673. }else{
  112674. y+=base;
  112675. }
  112676. val=vorbis_dBquant(mask+x);
  112677. mse+=((y-val)*(y-val));
  112678. n++;
  112679. if(mdct[x]+info->twofitatten>=mask[x]){
  112680. if(val){
  112681. if(y+info->maxover<val)return(1);
  112682. if(y-info->maxunder>val)return(1);
  112683. }
  112684. }
  112685. }
  112686. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112687. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112688. if(mse/n>info->maxerr)return(1);
  112689. return(0);
  112690. }
  112691. static int post_Y(int *A,int *B,int pos){
  112692. if(A[pos]<0)
  112693. return B[pos];
  112694. if(B[pos]<0)
  112695. return A[pos];
  112696. return (A[pos]+B[pos])>>1;
  112697. }
  112698. int *floor1_fit(vorbis_block *vb,void *look_,
  112699. const float *logmdct, /* in */
  112700. const float *logmask){
  112701. long i,j;
  112702. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112703. vorbis_info_floor1 *info=look->vi;
  112704. long n=look->n;
  112705. long posts=look->posts;
  112706. long nonzero=0;
  112707. lsfit_acc fits[VIF_POSIT+1];
  112708. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112709. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112710. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112711. int hineighbor[VIF_POSIT+2];
  112712. int *output=NULL;
  112713. int memo[VIF_POSIT+2];
  112714. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112715. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112716. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112717. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112718. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112719. /* quantize the relevant floor points and collect them into line fit
  112720. structures (one per minimal division) at the same time */
  112721. if(posts==0){
  112722. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112723. }else{
  112724. for(i=0;i<posts-1;i++)
  112725. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112726. look->sorted_index[i+1],fits+i,
  112727. n,info);
  112728. }
  112729. if(nonzero){
  112730. /* start by fitting the implicit base case.... */
  112731. int y0=-200;
  112732. int y1=-200;
  112733. fit_line(fits,posts-1,&y0,&y1);
  112734. fit_valueA[0]=y0;
  112735. fit_valueB[0]=y0;
  112736. fit_valueB[1]=y1;
  112737. fit_valueA[1]=y1;
  112738. /* Non degenerate case */
  112739. /* start progressive splitting. This is a greedy, non-optimal
  112740. algorithm, but simple and close enough to the best
  112741. answer. */
  112742. for(i=2;i<posts;i++){
  112743. int sortpos=look->reverse_index[i];
  112744. int ln=loneighbor[sortpos];
  112745. int hn=hineighbor[sortpos];
  112746. /* eliminate repeat searches of a particular range with a memo */
  112747. if(memo[ln]!=hn){
  112748. /* haven't performed this error search yet */
  112749. int lsortpos=look->reverse_index[ln];
  112750. int hsortpos=look->reverse_index[hn];
  112751. memo[ln]=hn;
  112752. {
  112753. /* A note: we want to bound/minimize *local*, not global, error */
  112754. int lx=info->postlist[ln];
  112755. int hx=info->postlist[hn];
  112756. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112757. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112758. if(ly==-1 || hy==-1){
  112759. exit(1);
  112760. }
  112761. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112762. /* outside error bounds/begin search area. Split it. */
  112763. int ly0=-200;
  112764. int ly1=-200;
  112765. int hy0=-200;
  112766. int hy1=-200;
  112767. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112768. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112769. /* store new edge values */
  112770. fit_valueB[ln]=ly0;
  112771. if(ln==0)fit_valueA[ln]=ly0;
  112772. fit_valueA[i]=ly1;
  112773. fit_valueB[i]=hy0;
  112774. fit_valueA[hn]=hy1;
  112775. if(hn==1)fit_valueB[hn]=hy1;
  112776. if(ly1>=0 || hy0>=0){
  112777. /* store new neighbor values */
  112778. for(j=sortpos-1;j>=0;j--)
  112779. if(hineighbor[j]==hn)
  112780. hineighbor[j]=i;
  112781. else
  112782. break;
  112783. for(j=sortpos+1;j<posts;j++)
  112784. if(loneighbor[j]==ln)
  112785. loneighbor[j]=i;
  112786. else
  112787. break;
  112788. }
  112789. }else{
  112790. fit_valueA[i]=-200;
  112791. fit_valueB[i]=-200;
  112792. }
  112793. }
  112794. }
  112795. }
  112796. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112797. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112798. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112799. /* fill in posts marked as not using a fit; we will zero
  112800. back out to 'unused' when encoding them so long as curve
  112801. interpolation doesn't force them into use */
  112802. for(i=2;i<posts;i++){
  112803. int ln=look->loneighbor[i-2];
  112804. int hn=look->hineighbor[i-2];
  112805. int x0=info->postlist[ln];
  112806. int x1=info->postlist[hn];
  112807. int y0=output[ln];
  112808. int y1=output[hn];
  112809. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112810. int vx=post_Y(fit_valueA,fit_valueB,i);
  112811. if(vx>=0 && predicted!=vx){
  112812. output[i]=vx;
  112813. }else{
  112814. output[i]= predicted|0x8000;
  112815. }
  112816. }
  112817. }
  112818. return(output);
  112819. }
  112820. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  112821. int *A,int *B,
  112822. int del){
  112823. long i;
  112824. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  112825. long posts=look->posts;
  112826. int *output=NULL;
  112827. if(A && B){
  112828. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112829. for(i=0;i<posts;i++){
  112830. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  112831. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  112832. }
  112833. }
  112834. return(output);
  112835. }
  112836. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112837. void*look_,
  112838. int *post,int *ilogmask){
  112839. long i,j;
  112840. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  112841. vorbis_info_floor1 *info=look->vi;
  112842. long posts=look->posts;
  112843. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112844. int out[VIF_POSIT+2];
  112845. static_codebook **sbooks=ci->book_param;
  112846. codebook *books=ci->fullbooks;
  112847. static long seq=0;
  112848. /* quantize values to multiplier spec */
  112849. if(post){
  112850. for(i=0;i<posts;i++){
  112851. int val=post[i]&0x7fff;
  112852. switch(info->mult){
  112853. case 1: /* 1024 -> 256 */
  112854. val>>=2;
  112855. break;
  112856. case 2: /* 1024 -> 128 */
  112857. val>>=3;
  112858. break;
  112859. case 3: /* 1024 -> 86 */
  112860. val/=12;
  112861. break;
  112862. case 4: /* 1024 -> 64 */
  112863. val>>=4;
  112864. break;
  112865. }
  112866. post[i]=val | (post[i]&0x8000);
  112867. }
  112868. out[0]=post[0];
  112869. out[1]=post[1];
  112870. /* find prediction values for each post and subtract them */
  112871. for(i=2;i<posts;i++){
  112872. int ln=look->loneighbor[i-2];
  112873. int hn=look->hineighbor[i-2];
  112874. int x0=info->postlist[ln];
  112875. int x1=info->postlist[hn];
  112876. int y0=post[ln];
  112877. int y1=post[hn];
  112878. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112879. if((post[i]&0x8000) || (predicted==post[i])){
  112880. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  112881. in interpolation */
  112882. out[i]=0;
  112883. }else{
  112884. int headroom=(look->quant_q-predicted<predicted?
  112885. look->quant_q-predicted:predicted);
  112886. int val=post[i]-predicted;
  112887. /* at this point the 'deviation' value is in the range +/- max
  112888. range, but the real, unique range can always be mapped to
  112889. only [0-maxrange). So we want to wrap the deviation into
  112890. this limited range, but do it in the way that least screws
  112891. an essentially gaussian probability distribution. */
  112892. if(val<0)
  112893. if(val<-headroom)
  112894. val=headroom-val-1;
  112895. else
  112896. val=-1-(val<<1);
  112897. else
  112898. if(val>=headroom)
  112899. val= val+headroom;
  112900. else
  112901. val<<=1;
  112902. out[i]=val;
  112903. post[ln]&=0x7fff;
  112904. post[hn]&=0x7fff;
  112905. }
  112906. }
  112907. /* we have everything we need. pack it out */
  112908. /* mark nontrivial floor */
  112909. oggpack_write(opb,1,1);
  112910. /* beginning/end post */
  112911. look->frames++;
  112912. look->postbits+=ilog(look->quant_q-1)*2;
  112913. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  112914. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  112915. /* partition by partition */
  112916. for(i=0,j=2;i<info->partitions;i++){
  112917. int classx=info->partitionclass[i];
  112918. int cdim=info->class_dim[classx];
  112919. int csubbits=info->class_subs[classx];
  112920. int csub=1<<csubbits;
  112921. int bookas[8]={0,0,0,0,0,0,0,0};
  112922. int cval=0;
  112923. int cshift=0;
  112924. int k,l;
  112925. /* generate the partition's first stage cascade value */
  112926. if(csubbits){
  112927. int maxval[8];
  112928. for(k=0;k<csub;k++){
  112929. int booknum=info->class_subbook[classx][k];
  112930. if(booknum<0){
  112931. maxval[k]=1;
  112932. }else{
  112933. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  112934. }
  112935. }
  112936. for(k=0;k<cdim;k++){
  112937. for(l=0;l<csub;l++){
  112938. int val=out[j+k];
  112939. if(val<maxval[l]){
  112940. bookas[k]=l;
  112941. break;
  112942. }
  112943. }
  112944. cval|= bookas[k]<<cshift;
  112945. cshift+=csubbits;
  112946. }
  112947. /* write it */
  112948. look->phrasebits+=
  112949. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  112950. #ifdef TRAIN_FLOOR1
  112951. {
  112952. FILE *of;
  112953. char buffer[80];
  112954. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  112955. vb->pcmend/2,posts-2,class);
  112956. of=fopen(buffer,"a");
  112957. fprintf(of,"%d\n",cval);
  112958. fclose(of);
  112959. }
  112960. #endif
  112961. }
  112962. /* write post values */
  112963. for(k=0;k<cdim;k++){
  112964. int book=info->class_subbook[classx][bookas[k]];
  112965. if(book>=0){
  112966. /* hack to allow training with 'bad' books */
  112967. if(out[j+k]<(books+book)->entries)
  112968. look->postbits+=vorbis_book_encode(books+book,
  112969. out[j+k],opb);
  112970. /*else
  112971. fprintf(stderr,"+!");*/
  112972. #ifdef TRAIN_FLOOR1
  112973. {
  112974. FILE *of;
  112975. char buffer[80];
  112976. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  112977. vb->pcmend/2,posts-2,class,bookas[k]);
  112978. of=fopen(buffer,"a");
  112979. fprintf(of,"%d\n",out[j+k]);
  112980. fclose(of);
  112981. }
  112982. #endif
  112983. }
  112984. }
  112985. j+=cdim;
  112986. }
  112987. {
  112988. /* generate quantized floor equivalent to what we'd unpack in decode */
  112989. /* render the lines */
  112990. int hx=0;
  112991. int lx=0;
  112992. int ly=post[0]*info->mult;
  112993. for(j=1;j<look->posts;j++){
  112994. int current=look->forward_index[j];
  112995. int hy=post[current]&0x7fff;
  112996. if(hy==post[current]){
  112997. hy*=info->mult;
  112998. hx=info->postlist[current];
  112999. render_line0(lx,hx,ly,hy,ilogmask);
  113000. lx=hx;
  113001. ly=hy;
  113002. }
  113003. }
  113004. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113005. seq++;
  113006. return(1);
  113007. }
  113008. }else{
  113009. oggpack_write(opb,0,1);
  113010. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113011. seq++;
  113012. return(0);
  113013. }
  113014. }
  113015. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113016. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113017. vorbis_info_floor1 *info=look->vi;
  113018. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113019. int i,j,k;
  113020. codebook *books=ci->fullbooks;
  113021. /* unpack wrapped/predicted values from stream */
  113022. if(oggpack_read(&vb->opb,1)==1){
  113023. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113024. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113025. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113026. /* partition by partition */
  113027. for(i=0,j=2;i<info->partitions;i++){
  113028. int classx=info->partitionclass[i];
  113029. int cdim=info->class_dim[classx];
  113030. int csubbits=info->class_subs[classx];
  113031. int csub=1<<csubbits;
  113032. int cval=0;
  113033. /* decode the partition's first stage cascade value */
  113034. if(csubbits){
  113035. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113036. if(cval==-1)goto eop;
  113037. }
  113038. for(k=0;k<cdim;k++){
  113039. int book=info->class_subbook[classx][cval&(csub-1)];
  113040. cval>>=csubbits;
  113041. if(book>=0){
  113042. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113043. goto eop;
  113044. }else{
  113045. fit_value[j+k]=0;
  113046. }
  113047. }
  113048. j+=cdim;
  113049. }
  113050. /* unwrap positive values and reconsitute via linear interpolation */
  113051. for(i=2;i<look->posts;i++){
  113052. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113053. info->postlist[look->hineighbor[i-2]],
  113054. fit_value[look->loneighbor[i-2]],
  113055. fit_value[look->hineighbor[i-2]],
  113056. info->postlist[i]);
  113057. int hiroom=look->quant_q-predicted;
  113058. int loroom=predicted;
  113059. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113060. int val=fit_value[i];
  113061. if(val){
  113062. if(val>=room){
  113063. if(hiroom>loroom){
  113064. val = val-loroom;
  113065. }else{
  113066. val = -1-(val-hiroom);
  113067. }
  113068. }else{
  113069. if(val&1){
  113070. val= -((val+1)>>1);
  113071. }else{
  113072. val>>=1;
  113073. }
  113074. }
  113075. fit_value[i]=val+predicted;
  113076. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113077. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113078. }else{
  113079. fit_value[i]=predicted|0x8000;
  113080. }
  113081. }
  113082. return(fit_value);
  113083. }
  113084. eop:
  113085. return(NULL);
  113086. }
  113087. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113088. float *out){
  113089. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113090. vorbis_info_floor1 *info=look->vi;
  113091. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113092. int n=ci->blocksizes[vb->W]/2;
  113093. int j;
  113094. if(memo){
  113095. /* render the lines */
  113096. int *fit_value=(int *)memo;
  113097. int hx=0;
  113098. int lx=0;
  113099. int ly=fit_value[0]*info->mult;
  113100. for(j=1;j<look->posts;j++){
  113101. int current=look->forward_index[j];
  113102. int hy=fit_value[current]&0x7fff;
  113103. if(hy==fit_value[current]){
  113104. hy*=info->mult;
  113105. hx=info->postlist[current];
  113106. render_line(lx,hx,ly,hy,out);
  113107. lx=hx;
  113108. ly=hy;
  113109. }
  113110. }
  113111. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113112. return(1);
  113113. }
  113114. memset(out,0,sizeof(*out)*n);
  113115. return(0);
  113116. }
  113117. /* export hooks */
  113118. vorbis_func_floor floor1_exportbundle={
  113119. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113120. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113121. };
  113122. #endif
  113123. /*** End of inlined file: floor1.c ***/
  113124. /*** Start of inlined file: info.c ***/
  113125. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113126. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113127. // tasks..
  113128. #if JUCE_MSVC
  113129. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113130. #endif
  113131. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113132. #if JUCE_USE_OGGVORBIS
  113133. /* general handling of the header and the vorbis_info structure (and
  113134. substructures) */
  113135. #include <stdlib.h>
  113136. #include <string.h>
  113137. #include <ctype.h>
  113138. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113139. while(bytes--){
  113140. oggpack_write(o,*s++,8);
  113141. }
  113142. }
  113143. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113144. while(bytes--){
  113145. *buf++=oggpack_read(o,8);
  113146. }
  113147. }
  113148. void vorbis_comment_init(vorbis_comment *vc){
  113149. memset(vc,0,sizeof(*vc));
  113150. }
  113151. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113152. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113153. (vc->comments+2)*sizeof(*vc->user_comments));
  113154. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113155. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113156. vc->comment_lengths[vc->comments]=strlen(comment);
  113157. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113158. strcpy(vc->user_comments[vc->comments], comment);
  113159. vc->comments++;
  113160. vc->user_comments[vc->comments]=NULL;
  113161. }
  113162. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113163. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113164. strcpy(comment, tag);
  113165. strcat(comment, "=");
  113166. strcat(comment, contents);
  113167. vorbis_comment_add(vc, comment);
  113168. }
  113169. /* This is more or less the same as strncasecmp - but that doesn't exist
  113170. * everywhere, and this is a fairly trivial function, so we include it */
  113171. static int tagcompare(const char *s1, const char *s2, int n){
  113172. int c=0;
  113173. while(c < n){
  113174. if(toupper(s1[c]) != toupper(s2[c]))
  113175. return !0;
  113176. c++;
  113177. }
  113178. return 0;
  113179. }
  113180. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113181. long i;
  113182. int found = 0;
  113183. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113184. char *fulltag = (char*)alloca(taglen+ 1);
  113185. strcpy(fulltag, tag);
  113186. strcat(fulltag, "=");
  113187. for(i=0;i<vc->comments;i++){
  113188. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113189. if(count == found)
  113190. /* We return a pointer to the data, not a copy */
  113191. return vc->user_comments[i] + taglen;
  113192. else
  113193. found++;
  113194. }
  113195. }
  113196. return NULL; /* didn't find anything */
  113197. }
  113198. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113199. int i,count=0;
  113200. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113201. char *fulltag = (char*)alloca(taglen+1);
  113202. strcpy(fulltag,tag);
  113203. strcat(fulltag, "=");
  113204. for(i=0;i<vc->comments;i++){
  113205. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113206. count++;
  113207. }
  113208. return count;
  113209. }
  113210. void vorbis_comment_clear(vorbis_comment *vc){
  113211. if(vc){
  113212. long i;
  113213. for(i=0;i<vc->comments;i++)
  113214. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113215. if(vc->user_comments)_ogg_free(vc->user_comments);
  113216. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113217. if(vc->vendor)_ogg_free(vc->vendor);
  113218. }
  113219. memset(vc,0,sizeof(*vc));
  113220. }
  113221. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113222. They may be equal, but short will never ge greater than long */
  113223. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113224. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113225. return ci ? ci->blocksizes[zo] : -1;
  113226. }
  113227. /* used by synthesis, which has a full, alloced vi */
  113228. void vorbis_info_init(vorbis_info *vi){
  113229. memset(vi,0,sizeof(*vi));
  113230. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113231. }
  113232. void vorbis_info_clear(vorbis_info *vi){
  113233. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113234. int i;
  113235. if(ci){
  113236. for(i=0;i<ci->modes;i++)
  113237. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113238. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113239. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113240. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113241. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113242. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113243. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113244. for(i=0;i<ci->books;i++){
  113245. if(ci->book_param[i]){
  113246. /* knows if the book was not alloced */
  113247. vorbis_staticbook_destroy(ci->book_param[i]);
  113248. }
  113249. if(ci->fullbooks)
  113250. vorbis_book_clear(ci->fullbooks+i);
  113251. }
  113252. if(ci->fullbooks)
  113253. _ogg_free(ci->fullbooks);
  113254. for(i=0;i<ci->psys;i++)
  113255. _vi_psy_free(ci->psy_param[i]);
  113256. _ogg_free(ci);
  113257. }
  113258. memset(vi,0,sizeof(*vi));
  113259. }
  113260. /* Header packing/unpacking ********************************************/
  113261. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113262. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113263. if(!ci)return(OV_EFAULT);
  113264. vi->version=oggpack_read(opb,32);
  113265. if(vi->version!=0)return(OV_EVERSION);
  113266. vi->channels=oggpack_read(opb,8);
  113267. vi->rate=oggpack_read(opb,32);
  113268. vi->bitrate_upper=oggpack_read(opb,32);
  113269. vi->bitrate_nominal=oggpack_read(opb,32);
  113270. vi->bitrate_lower=oggpack_read(opb,32);
  113271. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113272. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113273. if(vi->rate<1)goto err_out;
  113274. if(vi->channels<1)goto err_out;
  113275. if(ci->blocksizes[0]<8)goto err_out;
  113276. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113277. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113278. return(0);
  113279. err_out:
  113280. vorbis_info_clear(vi);
  113281. return(OV_EBADHEADER);
  113282. }
  113283. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113284. int i;
  113285. int vendorlen=oggpack_read(opb,32);
  113286. if(vendorlen<0)goto err_out;
  113287. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113288. _v_readstring(opb,vc->vendor,vendorlen);
  113289. vc->comments=oggpack_read(opb,32);
  113290. if(vc->comments<0)goto err_out;
  113291. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113292. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113293. for(i=0;i<vc->comments;i++){
  113294. int len=oggpack_read(opb,32);
  113295. if(len<0)goto err_out;
  113296. vc->comment_lengths[i]=len;
  113297. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113298. _v_readstring(opb,vc->user_comments[i],len);
  113299. }
  113300. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113301. return(0);
  113302. err_out:
  113303. vorbis_comment_clear(vc);
  113304. return(OV_EBADHEADER);
  113305. }
  113306. /* all of the real encoding details are here. The modes, books,
  113307. everything */
  113308. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113309. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113310. int i;
  113311. if(!ci)return(OV_EFAULT);
  113312. /* codebooks */
  113313. ci->books=oggpack_read(opb,8)+1;
  113314. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113315. for(i=0;i<ci->books;i++){
  113316. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113317. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113318. }
  113319. /* time backend settings; hooks are unused */
  113320. {
  113321. int times=oggpack_read(opb,6)+1;
  113322. for(i=0;i<times;i++){
  113323. int test=oggpack_read(opb,16);
  113324. if(test<0 || test>=VI_TIMEB)goto err_out;
  113325. }
  113326. }
  113327. /* floor backend settings */
  113328. ci->floors=oggpack_read(opb,6)+1;
  113329. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113330. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113331. for(i=0;i<ci->floors;i++){
  113332. ci->floor_type[i]=oggpack_read(opb,16);
  113333. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113334. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113335. if(!ci->floor_param[i])goto err_out;
  113336. }
  113337. /* residue backend settings */
  113338. ci->residues=oggpack_read(opb,6)+1;
  113339. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113340. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113341. for(i=0;i<ci->residues;i++){
  113342. ci->residue_type[i]=oggpack_read(opb,16);
  113343. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113344. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113345. if(!ci->residue_param[i])goto err_out;
  113346. }
  113347. /* map backend settings */
  113348. ci->maps=oggpack_read(opb,6)+1;
  113349. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113350. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113351. for(i=0;i<ci->maps;i++){
  113352. ci->map_type[i]=oggpack_read(opb,16);
  113353. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113354. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113355. if(!ci->map_param[i])goto err_out;
  113356. }
  113357. /* mode settings */
  113358. ci->modes=oggpack_read(opb,6)+1;
  113359. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113360. for(i=0;i<ci->modes;i++){
  113361. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113362. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113363. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113364. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113365. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113366. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113367. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113368. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113369. }
  113370. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113371. return(0);
  113372. err_out:
  113373. vorbis_info_clear(vi);
  113374. return(OV_EBADHEADER);
  113375. }
  113376. /* The Vorbis header is in three packets; the initial small packet in
  113377. the first page that identifies basic parameters, a second packet
  113378. with bitstream comments and a third packet that holds the
  113379. codebook. */
  113380. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113381. oggpack_buffer opb;
  113382. if(op){
  113383. oggpack_readinit(&opb,op->packet,op->bytes);
  113384. /* Which of the three types of header is this? */
  113385. /* Also verify header-ness, vorbis */
  113386. {
  113387. char buffer[6];
  113388. int packtype=oggpack_read(&opb,8);
  113389. memset(buffer,0,6);
  113390. _v_readstring(&opb,buffer,6);
  113391. if(memcmp(buffer,"vorbis",6)){
  113392. /* not a vorbis header */
  113393. return(OV_ENOTVORBIS);
  113394. }
  113395. switch(packtype){
  113396. case 0x01: /* least significant *bit* is read first */
  113397. if(!op->b_o_s){
  113398. /* Not the initial packet */
  113399. return(OV_EBADHEADER);
  113400. }
  113401. if(vi->rate!=0){
  113402. /* previously initialized info header */
  113403. return(OV_EBADHEADER);
  113404. }
  113405. return(_vorbis_unpack_info(vi,&opb));
  113406. case 0x03: /* least significant *bit* is read first */
  113407. if(vi->rate==0){
  113408. /* um... we didn't get the initial header */
  113409. return(OV_EBADHEADER);
  113410. }
  113411. return(_vorbis_unpack_comment(vc,&opb));
  113412. case 0x05: /* least significant *bit* is read first */
  113413. if(vi->rate==0 || vc->vendor==NULL){
  113414. /* um... we didn;t get the initial header or comments yet */
  113415. return(OV_EBADHEADER);
  113416. }
  113417. return(_vorbis_unpack_books(vi,&opb));
  113418. default:
  113419. /* Not a valid vorbis header type */
  113420. return(OV_EBADHEADER);
  113421. break;
  113422. }
  113423. }
  113424. }
  113425. return(OV_EBADHEADER);
  113426. }
  113427. /* pack side **********************************************************/
  113428. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113429. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113430. if(!ci)return(OV_EFAULT);
  113431. /* preamble */
  113432. oggpack_write(opb,0x01,8);
  113433. _v_writestring(opb,"vorbis", 6);
  113434. /* basic information about the stream */
  113435. oggpack_write(opb,0x00,32);
  113436. oggpack_write(opb,vi->channels,8);
  113437. oggpack_write(opb,vi->rate,32);
  113438. oggpack_write(opb,vi->bitrate_upper,32);
  113439. oggpack_write(opb,vi->bitrate_nominal,32);
  113440. oggpack_write(opb,vi->bitrate_lower,32);
  113441. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113442. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113443. oggpack_write(opb,1,1);
  113444. return(0);
  113445. }
  113446. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113447. char temp[]="Xiph.Org libVorbis I 20050304";
  113448. int bytes = strlen(temp);
  113449. /* preamble */
  113450. oggpack_write(opb,0x03,8);
  113451. _v_writestring(opb,"vorbis", 6);
  113452. /* vendor */
  113453. oggpack_write(opb,bytes,32);
  113454. _v_writestring(opb,temp, bytes);
  113455. /* comments */
  113456. oggpack_write(opb,vc->comments,32);
  113457. if(vc->comments){
  113458. int i;
  113459. for(i=0;i<vc->comments;i++){
  113460. if(vc->user_comments[i]){
  113461. oggpack_write(opb,vc->comment_lengths[i],32);
  113462. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113463. }else{
  113464. oggpack_write(opb,0,32);
  113465. }
  113466. }
  113467. }
  113468. oggpack_write(opb,1,1);
  113469. return(0);
  113470. }
  113471. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113472. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113473. int i;
  113474. if(!ci)return(OV_EFAULT);
  113475. oggpack_write(opb,0x05,8);
  113476. _v_writestring(opb,"vorbis", 6);
  113477. /* books */
  113478. oggpack_write(opb,ci->books-1,8);
  113479. for(i=0;i<ci->books;i++)
  113480. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113481. /* times; hook placeholders */
  113482. oggpack_write(opb,0,6);
  113483. oggpack_write(opb,0,16);
  113484. /* floors */
  113485. oggpack_write(opb,ci->floors-1,6);
  113486. for(i=0;i<ci->floors;i++){
  113487. oggpack_write(opb,ci->floor_type[i],16);
  113488. if(_floor_P[ci->floor_type[i]]->pack)
  113489. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113490. else
  113491. goto err_out;
  113492. }
  113493. /* residues */
  113494. oggpack_write(opb,ci->residues-1,6);
  113495. for(i=0;i<ci->residues;i++){
  113496. oggpack_write(opb,ci->residue_type[i],16);
  113497. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113498. }
  113499. /* maps */
  113500. oggpack_write(opb,ci->maps-1,6);
  113501. for(i=0;i<ci->maps;i++){
  113502. oggpack_write(opb,ci->map_type[i],16);
  113503. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113504. }
  113505. /* modes */
  113506. oggpack_write(opb,ci->modes-1,6);
  113507. for(i=0;i<ci->modes;i++){
  113508. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113509. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113510. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113511. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113512. }
  113513. oggpack_write(opb,1,1);
  113514. return(0);
  113515. err_out:
  113516. return(-1);
  113517. }
  113518. int vorbis_commentheader_out(vorbis_comment *vc,
  113519. ogg_packet *op){
  113520. oggpack_buffer opb;
  113521. oggpack_writeinit(&opb);
  113522. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113523. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113524. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113525. op->bytes=oggpack_bytes(&opb);
  113526. op->b_o_s=0;
  113527. op->e_o_s=0;
  113528. op->granulepos=0;
  113529. op->packetno=1;
  113530. return 0;
  113531. }
  113532. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113533. vorbis_comment *vc,
  113534. ogg_packet *op,
  113535. ogg_packet *op_comm,
  113536. ogg_packet *op_code){
  113537. int ret=OV_EIMPL;
  113538. vorbis_info *vi=v->vi;
  113539. oggpack_buffer opb;
  113540. private_state *b=(private_state*)v->backend_state;
  113541. if(!b){
  113542. ret=OV_EFAULT;
  113543. goto err_out;
  113544. }
  113545. /* first header packet **********************************************/
  113546. oggpack_writeinit(&opb);
  113547. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113548. /* build the packet */
  113549. if(b->header)_ogg_free(b->header);
  113550. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113551. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113552. op->packet=b->header;
  113553. op->bytes=oggpack_bytes(&opb);
  113554. op->b_o_s=1;
  113555. op->e_o_s=0;
  113556. op->granulepos=0;
  113557. op->packetno=0;
  113558. /* second header packet (comments) **********************************/
  113559. oggpack_reset(&opb);
  113560. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113561. if(b->header1)_ogg_free(b->header1);
  113562. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113563. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113564. op_comm->packet=b->header1;
  113565. op_comm->bytes=oggpack_bytes(&opb);
  113566. op_comm->b_o_s=0;
  113567. op_comm->e_o_s=0;
  113568. op_comm->granulepos=0;
  113569. op_comm->packetno=1;
  113570. /* third header packet (modes/codebooks) ****************************/
  113571. oggpack_reset(&opb);
  113572. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113573. if(b->header2)_ogg_free(b->header2);
  113574. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113575. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113576. op_code->packet=b->header2;
  113577. op_code->bytes=oggpack_bytes(&opb);
  113578. op_code->b_o_s=0;
  113579. op_code->e_o_s=0;
  113580. op_code->granulepos=0;
  113581. op_code->packetno=2;
  113582. oggpack_writeclear(&opb);
  113583. return(0);
  113584. err_out:
  113585. oggpack_writeclear(&opb);
  113586. memset(op,0,sizeof(*op));
  113587. memset(op_comm,0,sizeof(*op_comm));
  113588. memset(op_code,0,sizeof(*op_code));
  113589. if(b->header)_ogg_free(b->header);
  113590. if(b->header1)_ogg_free(b->header1);
  113591. if(b->header2)_ogg_free(b->header2);
  113592. b->header=NULL;
  113593. b->header1=NULL;
  113594. b->header2=NULL;
  113595. return(ret);
  113596. }
  113597. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113598. if(granulepos>=0)
  113599. return((double)granulepos/v->vi->rate);
  113600. return(-1);
  113601. }
  113602. #endif
  113603. /*** End of inlined file: info.c ***/
  113604. /*** Start of inlined file: lpc.c ***/
  113605. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113606. are derived from code written by Jutta Degener and Carsten Bormann;
  113607. thus we include their copyright below. The entirety of this file
  113608. is freely redistributable on the condition that both of these
  113609. copyright notices are preserved without modification. */
  113610. /* Preserved Copyright: *********************************************/
  113611. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113612. Technische Universita"t Berlin
  113613. Any use of this software is permitted provided that this notice is not
  113614. removed and that neither the authors nor the Technische Universita"t
  113615. Berlin are deemed to have made any representations as to the
  113616. suitability of this software for any purpose nor are held responsible
  113617. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113618. THIS SOFTWARE.
  113619. As a matter of courtesy, the authors request to be informed about uses
  113620. this software has found, about bugs in this software, and about any
  113621. improvements that may be of general interest.
  113622. Berlin, 28.11.1994
  113623. Jutta Degener
  113624. Carsten Bormann
  113625. *********************************************************************/
  113626. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113627. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113628. // tasks..
  113629. #if JUCE_MSVC
  113630. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113631. #endif
  113632. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113633. #if JUCE_USE_OGGVORBIS
  113634. #include <stdlib.h>
  113635. #include <string.h>
  113636. #include <math.h>
  113637. /* Autocorrelation LPC coeff generation algorithm invented by
  113638. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113639. /* Input : n elements of time doamin data
  113640. Output: m lpc coefficients, excitation energy */
  113641. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113642. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113643. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113644. double error;
  113645. int i,j;
  113646. /* autocorrelation, p+1 lag coefficients */
  113647. j=m+1;
  113648. while(j--){
  113649. double d=0; /* double needed for accumulator depth */
  113650. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113651. aut[j]=d;
  113652. }
  113653. /* Generate lpc coefficients from autocorr values */
  113654. error=aut[0];
  113655. for(i=0;i<m;i++){
  113656. double r= -aut[i+1];
  113657. if(error==0){
  113658. memset(lpci,0,m*sizeof(*lpci));
  113659. return 0;
  113660. }
  113661. /* Sum up this iteration's reflection coefficient; note that in
  113662. Vorbis we don't save it. If anyone wants to recycle this code
  113663. and needs reflection coefficients, save the results of 'r' from
  113664. each iteration. */
  113665. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113666. r/=error;
  113667. /* Update LPC coefficients and total error */
  113668. lpc[i]=r;
  113669. for(j=0;j<i/2;j++){
  113670. double tmp=lpc[j];
  113671. lpc[j]+=r*lpc[i-1-j];
  113672. lpc[i-1-j]+=r*tmp;
  113673. }
  113674. if(i%2)lpc[j]+=lpc[j]*r;
  113675. error*=1.f-r*r;
  113676. }
  113677. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113678. /* we need the error value to know how big an impulse to hit the
  113679. filter with later */
  113680. return error;
  113681. }
  113682. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113683. float *data,long n){
  113684. /* in: coeff[0...m-1] LPC coefficients
  113685. prime[0...m-1] initial values (allocated size of n+m-1)
  113686. out: data[0...n-1] data samples */
  113687. long i,j,o,p;
  113688. float y;
  113689. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113690. if(!prime)
  113691. for(i=0;i<m;i++)
  113692. work[i]=0.f;
  113693. else
  113694. for(i=0;i<m;i++)
  113695. work[i]=prime[i];
  113696. for(i=0;i<n;i++){
  113697. y=0;
  113698. o=i;
  113699. p=m;
  113700. for(j=0;j<m;j++)
  113701. y-=work[o++]*coeff[--p];
  113702. data[i]=work[o]=y;
  113703. }
  113704. }
  113705. #endif
  113706. /*** End of inlined file: lpc.c ***/
  113707. /*** Start of inlined file: lsp.c ***/
  113708. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113709. an iterative root polisher (CACM algorithm 283). It *is* possible
  113710. to confuse this algorithm into not converging; that should only
  113711. happen with absurdly closely spaced roots (very sharp peaks in the
  113712. LPC f response) which in turn should be impossible in our use of
  113713. the code. If this *does* happen anyway, it's a bug in the floor
  113714. finder; find the cause of the confusion (probably a single bin
  113715. spike or accidental near-float-limit resolution problems) and
  113716. correct it. */
  113717. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113718. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113719. // tasks..
  113720. #if JUCE_MSVC
  113721. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113722. #endif
  113723. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113724. #if JUCE_USE_OGGVORBIS
  113725. #include <math.h>
  113726. #include <string.h>
  113727. #include <stdlib.h>
  113728. /*** Start of inlined file: lookup.h ***/
  113729. #ifndef _V_LOOKUP_H_
  113730. #ifdef FLOAT_LOOKUP
  113731. extern float vorbis_coslook(float a);
  113732. extern float vorbis_invsqlook(float a);
  113733. extern float vorbis_invsq2explook(int a);
  113734. extern float vorbis_fromdBlook(float a);
  113735. #endif
  113736. #ifdef INT_LOOKUP
  113737. extern long vorbis_invsqlook_i(long a,long e);
  113738. extern long vorbis_coslook_i(long a);
  113739. extern float vorbis_fromdBlook_i(long a);
  113740. #endif
  113741. #endif
  113742. /*** End of inlined file: lookup.h ***/
  113743. /* three possible LSP to f curve functions; the exact computation
  113744. (float), a lookup based float implementation, and an integer
  113745. implementation. The float lookup is likely the optimal choice on
  113746. any machine with an FPU. The integer implementation is *not* fixed
  113747. point (due to the need for a large dynamic range and thus a
  113748. seperately tracked exponent) and thus much more complex than the
  113749. relatively simple float implementations. It's mostly for future
  113750. work on a fully fixed point implementation for processors like the
  113751. ARM family. */
  113752. /* undefine both for the 'old' but more precise implementation */
  113753. #define FLOAT_LOOKUP
  113754. #undef INT_LOOKUP
  113755. #ifdef FLOAT_LOOKUP
  113756. /*** Start of inlined file: lookup.c ***/
  113757. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113758. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113759. // tasks..
  113760. #if JUCE_MSVC
  113761. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113762. #endif
  113763. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113764. #if JUCE_USE_OGGVORBIS
  113765. #include <math.h>
  113766. /*** Start of inlined file: lookup.h ***/
  113767. #ifndef _V_LOOKUP_H_
  113768. #ifdef FLOAT_LOOKUP
  113769. extern float vorbis_coslook(float a);
  113770. extern float vorbis_invsqlook(float a);
  113771. extern float vorbis_invsq2explook(int a);
  113772. extern float vorbis_fromdBlook(float a);
  113773. #endif
  113774. #ifdef INT_LOOKUP
  113775. extern long vorbis_invsqlook_i(long a,long e);
  113776. extern long vorbis_coslook_i(long a);
  113777. extern float vorbis_fromdBlook_i(long a);
  113778. #endif
  113779. #endif
  113780. /*** End of inlined file: lookup.h ***/
  113781. /*** Start of inlined file: lookup_data.h ***/
  113782. #ifndef _V_LOOKUP_DATA_H_
  113783. #ifdef FLOAT_LOOKUP
  113784. #define COS_LOOKUP_SZ 128
  113785. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113786. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113787. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113788. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113789. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113790. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113791. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113792. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113793. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113794. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113795. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113796. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113797. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113798. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113799. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113800. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113801. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113802. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113803. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113804. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113805. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113806. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113807. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113808. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113809. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113810. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113811. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113812. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113813. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113814. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113815. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113816. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113817. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113818. -1.0000000000000f,
  113819. };
  113820. #define INVSQ_LOOKUP_SZ 32
  113821. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113822. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113823. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113824. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113825. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113826. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113827. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113828. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113829. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113830. 1.000000000000f,
  113831. };
  113832. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113833. #define INVSQ2EXP_LOOKUP_MAX 32
  113834. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113835. INVSQ2EXP_LOOKUP_MIN+1]={
  113836. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113837. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113838. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113839. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113840. 256.f, 181.019336f, 128.f, 90.50966799f,
  113841. 64.f, 45.254834f, 32.f, 22.627417f,
  113842. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113843. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113844. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113845. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113846. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113847. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113848. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113849. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113850. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113851. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113852. 1.525878906e-05f,
  113853. };
  113854. #endif
  113855. #define FROMdB_LOOKUP_SZ 35
  113856. #define FROMdB2_LOOKUP_SZ 32
  113857. #define FROMdB_SHIFT 5
  113858. #define FROMdB2_SHIFT 3
  113859. #define FROMdB2_MASK 31
  113860. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113861. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113862. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113863. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113864. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113865. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113866. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113867. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113868. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113869. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113870. };
  113871. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113872. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113873. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113874. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113875. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113876. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113877. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113878. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113879. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113880. };
  113881. #ifdef INT_LOOKUP
  113882. #define INVSQ_LOOKUP_I_SHIFT 10
  113883. #define INVSQ_LOOKUP_I_MASK 1023
  113884. static long INVSQ_LOOKUP_I[64+1]={
  113885. 92682l, 91966l, 91267l, 90583l,
  113886. 89915l, 89261l, 88621l, 87995l,
  113887. 87381l, 86781l, 86192l, 85616l,
  113888. 85051l, 84497l, 83953l, 83420l,
  113889. 82897l, 82384l, 81880l, 81385l,
  113890. 80899l, 80422l, 79953l, 79492l,
  113891. 79039l, 78594l, 78156l, 77726l,
  113892. 77302l, 76885l, 76475l, 76072l,
  113893. 75674l, 75283l, 74898l, 74519l,
  113894. 74146l, 73778l, 73415l, 73058l,
  113895. 72706l, 72359l, 72016l, 71679l,
  113896. 71347l, 71019l, 70695l, 70376l,
  113897. 70061l, 69750l, 69444l, 69141l,
  113898. 68842l, 68548l, 68256l, 67969l,
  113899. 67685l, 67405l, 67128l, 66855l,
  113900. 66585l, 66318l, 66054l, 65794l,
  113901. 65536l,
  113902. };
  113903. #define COS_LOOKUP_I_SHIFT 9
  113904. #define COS_LOOKUP_I_MASK 511
  113905. #define COS_LOOKUP_I_SZ 128
  113906. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113907. 16384l, 16379l, 16364l, 16340l,
  113908. 16305l, 16261l, 16207l, 16143l,
  113909. 16069l, 15986l, 15893l, 15791l,
  113910. 15679l, 15557l, 15426l, 15286l,
  113911. 15137l, 14978l, 14811l, 14635l,
  113912. 14449l, 14256l, 14053l, 13842l,
  113913. 13623l, 13395l, 13160l, 12916l,
  113914. 12665l, 12406l, 12140l, 11866l,
  113915. 11585l, 11297l, 11003l, 10702l,
  113916. 10394l, 10080l, 9760l, 9434l,
  113917. 9102l, 8765l, 8423l, 8076l,
  113918. 7723l, 7366l, 7005l, 6639l,
  113919. 6270l, 5897l, 5520l, 5139l,
  113920. 4756l, 4370l, 3981l, 3590l,
  113921. 3196l, 2801l, 2404l, 2006l,
  113922. 1606l, 1205l, 804l, 402l,
  113923. 0l, -401l, -803l, -1204l,
  113924. -1605l, -2005l, -2403l, -2800l,
  113925. -3195l, -3589l, -3980l, -4369l,
  113926. -4755l, -5138l, -5519l, -5896l,
  113927. -6269l, -6638l, -7004l, -7365l,
  113928. -7722l, -8075l, -8422l, -8764l,
  113929. -9101l, -9433l, -9759l, -10079l,
  113930. -10393l, -10701l, -11002l, -11296l,
  113931. -11584l, -11865l, -12139l, -12405l,
  113932. -12664l, -12915l, -13159l, -13394l,
  113933. -13622l, -13841l, -14052l, -14255l,
  113934. -14448l, -14634l, -14810l, -14977l,
  113935. -15136l, -15285l, -15425l, -15556l,
  113936. -15678l, -15790l, -15892l, -15985l,
  113937. -16068l, -16142l, -16206l, -16260l,
  113938. -16304l, -16339l, -16363l, -16378l,
  113939. -16383l,
  113940. };
  113941. #endif
  113942. #endif
  113943. /*** End of inlined file: lookup_data.h ***/
  113944. #ifdef FLOAT_LOOKUP
  113945. /* interpolated lookup based cos function, domain 0 to PI only */
  113946. float vorbis_coslook(float a){
  113947. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113948. int i=vorbis_ftoi(d-.5);
  113949. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113950. }
  113951. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113952. float vorbis_invsqlook(float a){
  113953. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113954. int i=vorbis_ftoi(d-.5f);
  113955. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113956. }
  113957. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113958. float vorbis_invsq2explook(int a){
  113959. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113960. }
  113961. #include <stdio.h>
  113962. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113963. float vorbis_fromdBlook(float a){
  113964. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113965. return (i<0)?1.f:
  113966. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113967. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113968. }
  113969. #endif
  113970. #ifdef INT_LOOKUP
  113971. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113972. 16.16 format
  113973. returns in m.8 format */
  113974. long vorbis_invsqlook_i(long a,long e){
  113975. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113976. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113977. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113978. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113979. d)>>16); /* result 1.16 */
  113980. e+=32;
  113981. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113982. e=(e>>1)-8;
  113983. return(val>>e);
  113984. }
  113985. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113986. /* a is in n.12 format */
  113987. float vorbis_fromdBlook_i(long a){
  113988. int i=(-a)>>(12-FROMdB2_SHIFT);
  113989. return (i<0)?1.f:
  113990. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113991. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113992. }
  113993. /* interpolated lookup based cos function, domain 0 to PI only */
  113994. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113995. long vorbis_coslook_i(long a){
  113996. int i=a>>COS_LOOKUP_I_SHIFT;
  113997. int d=a&COS_LOOKUP_I_MASK;
  113998. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113999. COS_LOOKUP_I_SHIFT);
  114000. }
  114001. #endif
  114002. #endif
  114003. /*** End of inlined file: lookup.c ***/
  114004. /* catch this in the build system; we #include for
  114005. compilers (like gcc) that can't inline across
  114006. modules */
  114007. /* side effect: changes *lsp to cosines of lsp */
  114008. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114009. float amp,float ampoffset){
  114010. int i;
  114011. float wdel=M_PI/ln;
  114012. vorbis_fpu_control fpu;
  114013. (void) fpu; // to avoid an unused variable warning
  114014. vorbis_fpu_setround(&fpu);
  114015. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114016. i=0;
  114017. while(i<n){
  114018. int k=map[i];
  114019. int qexp;
  114020. float p=.7071067812f;
  114021. float q=.7071067812f;
  114022. float w=vorbis_coslook(wdel*k);
  114023. float *ftmp=lsp;
  114024. int c=m>>1;
  114025. do{
  114026. q*=ftmp[0]-w;
  114027. p*=ftmp[1]-w;
  114028. ftmp+=2;
  114029. }while(--c);
  114030. if(m&1){
  114031. /* odd order filter; slightly assymetric */
  114032. /* the last coefficient */
  114033. q*=ftmp[0]-w;
  114034. q*=q;
  114035. p*=p*(1.f-w*w);
  114036. }else{
  114037. /* even order filter; still symmetric */
  114038. q*=q*(1.f+w);
  114039. p*=p*(1.f-w);
  114040. }
  114041. q=frexp(p+q,&qexp);
  114042. q=vorbis_fromdBlook(amp*
  114043. vorbis_invsqlook(q)*
  114044. vorbis_invsq2explook(qexp+m)-
  114045. ampoffset);
  114046. do{
  114047. curve[i++]*=q;
  114048. }while(map[i]==k);
  114049. }
  114050. vorbis_fpu_restore(fpu);
  114051. }
  114052. #else
  114053. #ifdef INT_LOOKUP
  114054. /*** Start of inlined file: lookup.c ***/
  114055. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114056. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114057. // tasks..
  114058. #if JUCE_MSVC
  114059. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114060. #endif
  114061. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114062. #if JUCE_USE_OGGVORBIS
  114063. #include <math.h>
  114064. /*** Start of inlined file: lookup.h ***/
  114065. #ifndef _V_LOOKUP_H_
  114066. #ifdef FLOAT_LOOKUP
  114067. extern float vorbis_coslook(float a);
  114068. extern float vorbis_invsqlook(float a);
  114069. extern float vorbis_invsq2explook(int a);
  114070. extern float vorbis_fromdBlook(float a);
  114071. #endif
  114072. #ifdef INT_LOOKUP
  114073. extern long vorbis_invsqlook_i(long a,long e);
  114074. extern long vorbis_coslook_i(long a);
  114075. extern float vorbis_fromdBlook_i(long a);
  114076. #endif
  114077. #endif
  114078. /*** End of inlined file: lookup.h ***/
  114079. /*** Start of inlined file: lookup_data.h ***/
  114080. #ifndef _V_LOOKUP_DATA_H_
  114081. #ifdef FLOAT_LOOKUP
  114082. #define COS_LOOKUP_SZ 128
  114083. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114084. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114085. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114086. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114087. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114088. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114089. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114090. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114091. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114092. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114093. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114094. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114095. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114096. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114097. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114098. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114099. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114100. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114101. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114102. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114103. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114104. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114105. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114106. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114107. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114108. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114109. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114110. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114111. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114112. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114113. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114114. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114115. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114116. -1.0000000000000f,
  114117. };
  114118. #define INVSQ_LOOKUP_SZ 32
  114119. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114120. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114121. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114122. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114123. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114124. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114125. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114126. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114127. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114128. 1.000000000000f,
  114129. };
  114130. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114131. #define INVSQ2EXP_LOOKUP_MAX 32
  114132. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114133. INVSQ2EXP_LOOKUP_MIN+1]={
  114134. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114135. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114136. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114137. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114138. 256.f, 181.019336f, 128.f, 90.50966799f,
  114139. 64.f, 45.254834f, 32.f, 22.627417f,
  114140. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114141. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114142. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114143. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114144. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114145. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114146. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114147. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114148. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114149. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114150. 1.525878906e-05f,
  114151. };
  114152. #endif
  114153. #define FROMdB_LOOKUP_SZ 35
  114154. #define FROMdB2_LOOKUP_SZ 32
  114155. #define FROMdB_SHIFT 5
  114156. #define FROMdB2_SHIFT 3
  114157. #define FROMdB2_MASK 31
  114158. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114159. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114160. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114161. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114162. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114163. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114164. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114165. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114166. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114167. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114168. };
  114169. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114170. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114171. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114172. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114173. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114174. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114175. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114176. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114177. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114178. };
  114179. #ifdef INT_LOOKUP
  114180. #define INVSQ_LOOKUP_I_SHIFT 10
  114181. #define INVSQ_LOOKUP_I_MASK 1023
  114182. static long INVSQ_LOOKUP_I[64+1]={
  114183. 92682l, 91966l, 91267l, 90583l,
  114184. 89915l, 89261l, 88621l, 87995l,
  114185. 87381l, 86781l, 86192l, 85616l,
  114186. 85051l, 84497l, 83953l, 83420l,
  114187. 82897l, 82384l, 81880l, 81385l,
  114188. 80899l, 80422l, 79953l, 79492l,
  114189. 79039l, 78594l, 78156l, 77726l,
  114190. 77302l, 76885l, 76475l, 76072l,
  114191. 75674l, 75283l, 74898l, 74519l,
  114192. 74146l, 73778l, 73415l, 73058l,
  114193. 72706l, 72359l, 72016l, 71679l,
  114194. 71347l, 71019l, 70695l, 70376l,
  114195. 70061l, 69750l, 69444l, 69141l,
  114196. 68842l, 68548l, 68256l, 67969l,
  114197. 67685l, 67405l, 67128l, 66855l,
  114198. 66585l, 66318l, 66054l, 65794l,
  114199. 65536l,
  114200. };
  114201. #define COS_LOOKUP_I_SHIFT 9
  114202. #define COS_LOOKUP_I_MASK 511
  114203. #define COS_LOOKUP_I_SZ 128
  114204. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114205. 16384l, 16379l, 16364l, 16340l,
  114206. 16305l, 16261l, 16207l, 16143l,
  114207. 16069l, 15986l, 15893l, 15791l,
  114208. 15679l, 15557l, 15426l, 15286l,
  114209. 15137l, 14978l, 14811l, 14635l,
  114210. 14449l, 14256l, 14053l, 13842l,
  114211. 13623l, 13395l, 13160l, 12916l,
  114212. 12665l, 12406l, 12140l, 11866l,
  114213. 11585l, 11297l, 11003l, 10702l,
  114214. 10394l, 10080l, 9760l, 9434l,
  114215. 9102l, 8765l, 8423l, 8076l,
  114216. 7723l, 7366l, 7005l, 6639l,
  114217. 6270l, 5897l, 5520l, 5139l,
  114218. 4756l, 4370l, 3981l, 3590l,
  114219. 3196l, 2801l, 2404l, 2006l,
  114220. 1606l, 1205l, 804l, 402l,
  114221. 0l, -401l, -803l, -1204l,
  114222. -1605l, -2005l, -2403l, -2800l,
  114223. -3195l, -3589l, -3980l, -4369l,
  114224. -4755l, -5138l, -5519l, -5896l,
  114225. -6269l, -6638l, -7004l, -7365l,
  114226. -7722l, -8075l, -8422l, -8764l,
  114227. -9101l, -9433l, -9759l, -10079l,
  114228. -10393l, -10701l, -11002l, -11296l,
  114229. -11584l, -11865l, -12139l, -12405l,
  114230. -12664l, -12915l, -13159l, -13394l,
  114231. -13622l, -13841l, -14052l, -14255l,
  114232. -14448l, -14634l, -14810l, -14977l,
  114233. -15136l, -15285l, -15425l, -15556l,
  114234. -15678l, -15790l, -15892l, -15985l,
  114235. -16068l, -16142l, -16206l, -16260l,
  114236. -16304l, -16339l, -16363l, -16378l,
  114237. -16383l,
  114238. };
  114239. #endif
  114240. #endif
  114241. /*** End of inlined file: lookup_data.h ***/
  114242. #ifdef FLOAT_LOOKUP
  114243. /* interpolated lookup based cos function, domain 0 to PI only */
  114244. float vorbis_coslook(float a){
  114245. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114246. int i=vorbis_ftoi(d-.5);
  114247. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114248. }
  114249. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114250. float vorbis_invsqlook(float a){
  114251. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114252. int i=vorbis_ftoi(d-.5f);
  114253. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114254. }
  114255. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114256. float vorbis_invsq2explook(int a){
  114257. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114258. }
  114259. #include <stdio.h>
  114260. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114261. float vorbis_fromdBlook(float a){
  114262. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114263. return (i<0)?1.f:
  114264. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114265. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114266. }
  114267. #endif
  114268. #ifdef INT_LOOKUP
  114269. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114270. 16.16 format
  114271. returns in m.8 format */
  114272. long vorbis_invsqlook_i(long a,long e){
  114273. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114274. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114275. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114276. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114277. d)>>16); /* result 1.16 */
  114278. e+=32;
  114279. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114280. e=(e>>1)-8;
  114281. return(val>>e);
  114282. }
  114283. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114284. /* a is in n.12 format */
  114285. float vorbis_fromdBlook_i(long a){
  114286. int i=(-a)>>(12-FROMdB2_SHIFT);
  114287. return (i<0)?1.f:
  114288. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114289. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114290. }
  114291. /* interpolated lookup based cos function, domain 0 to PI only */
  114292. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114293. long vorbis_coslook_i(long a){
  114294. int i=a>>COS_LOOKUP_I_SHIFT;
  114295. int d=a&COS_LOOKUP_I_MASK;
  114296. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114297. COS_LOOKUP_I_SHIFT);
  114298. }
  114299. #endif
  114300. #endif
  114301. /*** End of inlined file: lookup.c ***/
  114302. /* catch this in the build system; we #include for
  114303. compilers (like gcc) that can't inline across
  114304. modules */
  114305. static int MLOOP_1[64]={
  114306. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114307. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114308. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114309. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114310. };
  114311. static int MLOOP_2[64]={
  114312. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114313. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114314. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114315. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114316. };
  114317. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114318. /* side effect: changes *lsp to cosines of lsp */
  114319. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114320. float amp,float ampoffset){
  114321. /* 0 <= m < 256 */
  114322. /* set up for using all int later */
  114323. int i;
  114324. int ampoffseti=rint(ampoffset*4096.f);
  114325. int ampi=rint(amp*16.f);
  114326. long *ilsp=alloca(m*sizeof(*ilsp));
  114327. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114328. i=0;
  114329. while(i<n){
  114330. int j,k=map[i];
  114331. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114332. unsigned long qi=46341;
  114333. int qexp=0,shift;
  114334. long wi=vorbis_coslook_i(k*65536/ln);
  114335. qi*=labs(ilsp[0]-wi);
  114336. pi*=labs(ilsp[1]-wi);
  114337. for(j=3;j<m;j+=2){
  114338. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114339. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114340. shift=MLOOP_3[(pi|qi)>>16];
  114341. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114342. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114343. qexp+=shift;
  114344. }
  114345. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114346. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114347. shift=MLOOP_3[(pi|qi)>>16];
  114348. /* pi,qi normalized collectively, both tracked using qexp */
  114349. if(m&1){
  114350. /* odd order filter; slightly assymetric */
  114351. /* the last coefficient */
  114352. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114353. pi=(pi>>shift)<<14;
  114354. qexp+=shift;
  114355. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114356. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114357. shift=MLOOP_3[(pi|qi)>>16];
  114358. pi>>=shift;
  114359. qi>>=shift;
  114360. qexp+=shift-14*((m+1)>>1);
  114361. pi=((pi*pi)>>16);
  114362. qi=((qi*qi)>>16);
  114363. qexp=qexp*2+m;
  114364. pi*=(1<<14)-((wi*wi)>>14);
  114365. qi+=pi>>14;
  114366. }else{
  114367. /* even order filter; still symmetric */
  114368. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114369. worth tracking step by step */
  114370. pi>>=shift;
  114371. qi>>=shift;
  114372. qexp+=shift-7*m;
  114373. pi=((pi*pi)>>16);
  114374. qi=((qi*qi)>>16);
  114375. qexp=qexp*2+m;
  114376. pi*=(1<<14)-wi;
  114377. qi*=(1<<14)+wi;
  114378. qi=(qi+pi)>>14;
  114379. }
  114380. /* we've let the normalization drift because it wasn't important;
  114381. however, for the lookup, things must be normalized again. We
  114382. need at most one right shift or a number of left shifts */
  114383. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114384. qi>>=1; qexp++;
  114385. }else
  114386. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114387. qi<<=1; qexp--;
  114388. }
  114389. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114390. vorbis_invsqlook_i(qi,qexp)-
  114391. /* m.8, m+n<=8 */
  114392. ampoffseti); /* 8.12[0] */
  114393. curve[i]*=amp;
  114394. while(map[++i]==k)curve[i]*=amp;
  114395. }
  114396. }
  114397. #else
  114398. /* old, nonoptimized but simple version for any poor sap who needs to
  114399. figure out what the hell this code does, or wants the other
  114400. fraction of a dB precision */
  114401. /* side effect: changes *lsp to cosines of lsp */
  114402. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114403. float amp,float ampoffset){
  114404. int i;
  114405. float wdel=M_PI/ln;
  114406. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114407. i=0;
  114408. while(i<n){
  114409. int j,k=map[i];
  114410. float p=.5f;
  114411. float q=.5f;
  114412. float w=2.f*cos(wdel*k);
  114413. for(j=1;j<m;j+=2){
  114414. q *= w-lsp[j-1];
  114415. p *= w-lsp[j];
  114416. }
  114417. if(j==m){
  114418. /* odd order filter; slightly assymetric */
  114419. /* the last coefficient */
  114420. q*=w-lsp[j-1];
  114421. p*=p*(4.f-w*w);
  114422. q*=q;
  114423. }else{
  114424. /* even order filter; still symmetric */
  114425. p*=p*(2.f-w);
  114426. q*=q*(2.f+w);
  114427. }
  114428. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114429. curve[i]*=q;
  114430. while(map[++i]==k)curve[i]*=q;
  114431. }
  114432. }
  114433. #endif
  114434. #endif
  114435. static void cheby(float *g, int ord) {
  114436. int i, j;
  114437. g[0] *= .5f;
  114438. for(i=2; i<= ord; i++) {
  114439. for(j=ord; j >= i; j--) {
  114440. g[j-2] -= g[j];
  114441. g[j] += g[j];
  114442. }
  114443. }
  114444. }
  114445. static int comp(const void *a,const void *b){
  114446. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114447. }
  114448. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114449. but there are root sets for which it gets into limit cycles
  114450. (exacerbated by zero suppression) and fails. We can't afford to
  114451. fail, even if the failure is 1 in 100,000,000, so we now use
  114452. Laguerre and later polish with Newton-Raphson (which can then
  114453. afford to fail) */
  114454. #define EPSILON 10e-7
  114455. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114456. int i,m;
  114457. double lastdelta=0.f;
  114458. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114459. for(i=0;i<=ord;i++)defl[i]=a[i];
  114460. for(m=ord;m>0;m--){
  114461. double newx=0.f,delta;
  114462. /* iterate a root */
  114463. while(1){
  114464. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114465. /* eval the polynomial and its first two derivatives */
  114466. for(i=m;i>0;i--){
  114467. ppp = newx*ppp + pp;
  114468. pp = newx*pp + p;
  114469. p = newx*p + defl[i-1];
  114470. }
  114471. /* Laguerre's method */
  114472. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114473. if(denom<0)
  114474. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114475. if(pp>0){
  114476. denom = pp + sqrt(denom);
  114477. if(denom<EPSILON)denom=EPSILON;
  114478. }else{
  114479. denom = pp - sqrt(denom);
  114480. if(denom>-(EPSILON))denom=-(EPSILON);
  114481. }
  114482. delta = m*p/denom;
  114483. newx -= delta;
  114484. if(delta<0.f)delta*=-1;
  114485. if(fabs(delta/newx)<10e-12)break;
  114486. lastdelta=delta;
  114487. }
  114488. r[m-1]=newx;
  114489. /* forward deflation */
  114490. for(i=m;i>0;i--)
  114491. defl[i-1]+=newx*defl[i];
  114492. defl++;
  114493. }
  114494. return(0);
  114495. }
  114496. /* for spit-and-polish only */
  114497. static int Newton_Raphson(float *a,int ord,float *r){
  114498. int i, k, count=0;
  114499. double error=1.f;
  114500. double *root=(double*)alloca(ord*sizeof(*root));
  114501. for(i=0; i<ord;i++) root[i] = r[i];
  114502. while(error>1e-20){
  114503. error=0;
  114504. for(i=0; i<ord; i++) { /* Update each point. */
  114505. double pp=0.,delta;
  114506. double rooti=root[i];
  114507. double p=a[ord];
  114508. for(k=ord-1; k>= 0; k--) {
  114509. pp= pp* rooti + p;
  114510. p = p * rooti + a[k];
  114511. }
  114512. delta = p/pp;
  114513. root[i] -= delta;
  114514. error+= delta*delta;
  114515. }
  114516. if(count>40)return(-1);
  114517. count++;
  114518. }
  114519. /* Replaced the original bubble sort with a real sort. With your
  114520. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114521. for(i=0; i<ord;i++) r[i] = root[i];
  114522. return(0);
  114523. }
  114524. /* Convert lpc coefficients to lsp coefficients */
  114525. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114526. int order2=(m+1)>>1;
  114527. int g1_order,g2_order;
  114528. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114529. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114530. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114531. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114532. int i;
  114533. /* even and odd are slightly different base cases */
  114534. g1_order=(m+1)>>1;
  114535. g2_order=(m) >>1;
  114536. /* Compute the lengths of the x polynomials. */
  114537. /* Compute the first half of K & R F1 & F2 polynomials. */
  114538. /* Compute half of the symmetric and antisymmetric polynomials. */
  114539. /* Remove the roots at +1 and -1. */
  114540. g1[g1_order] = 1.f;
  114541. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114542. g2[g2_order] = 1.f;
  114543. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114544. if(g1_order>g2_order){
  114545. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114546. }else{
  114547. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114548. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114549. }
  114550. /* Convert into polynomials in cos(alpha) */
  114551. cheby(g1,g1_order);
  114552. cheby(g2,g2_order);
  114553. /* Find the roots of the 2 even polynomials.*/
  114554. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114555. Laguerre_With_Deflation(g2,g2_order,g2r))
  114556. return(-1);
  114557. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114558. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114559. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114560. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114561. for(i=0;i<g1_order;i++)
  114562. lsp[i*2] = acos(g1r[i]);
  114563. for(i=0;i<g2_order;i++)
  114564. lsp[i*2+1] = acos(g2r[i]);
  114565. return(0);
  114566. }
  114567. #endif
  114568. /*** End of inlined file: lsp.c ***/
  114569. /*** Start of inlined file: mapping0.c ***/
  114570. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114571. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114572. // tasks..
  114573. #if JUCE_MSVC
  114574. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114575. #endif
  114576. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114577. #if JUCE_USE_OGGVORBIS
  114578. #include <stdlib.h>
  114579. #include <stdio.h>
  114580. #include <string.h>
  114581. #include <math.h>
  114582. /* simplistic, wasteful way of doing this (unique lookup for each
  114583. mode/submapping); there should be a central repository for
  114584. identical lookups. That will require minor work, so I'm putting it
  114585. off as low priority.
  114586. Why a lookup for each backend in a given mode? Because the
  114587. blocksize is set by the mode, and low backend lookups may require
  114588. parameters from other areas of the mode/mapping */
  114589. static void mapping0_free_info(vorbis_info_mapping *i){
  114590. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114591. if(info){
  114592. memset(info,0,sizeof(*info));
  114593. _ogg_free(info);
  114594. }
  114595. }
  114596. static int ilog3(unsigned int v){
  114597. int ret=0;
  114598. if(v)--v;
  114599. while(v){
  114600. ret++;
  114601. v>>=1;
  114602. }
  114603. return(ret);
  114604. }
  114605. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114606. oggpack_buffer *opb){
  114607. int i;
  114608. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114609. /* another 'we meant to do it this way' hack... up to beta 4, we
  114610. packed 4 binary zeros here to signify one submapping in use. We
  114611. now redefine that to mean four bitflags that indicate use of
  114612. deeper features; bit0:submappings, bit1:coupling,
  114613. bit2,3:reserved. This is backward compatable with all actual uses
  114614. of the beta code. */
  114615. if(info->submaps>1){
  114616. oggpack_write(opb,1,1);
  114617. oggpack_write(opb,info->submaps-1,4);
  114618. }else
  114619. oggpack_write(opb,0,1);
  114620. if(info->coupling_steps>0){
  114621. oggpack_write(opb,1,1);
  114622. oggpack_write(opb,info->coupling_steps-1,8);
  114623. for(i=0;i<info->coupling_steps;i++){
  114624. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114625. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114626. }
  114627. }else
  114628. oggpack_write(opb,0,1);
  114629. oggpack_write(opb,0,2); /* 2,3:reserved */
  114630. /* we don't write the channel submappings if we only have one... */
  114631. if(info->submaps>1){
  114632. for(i=0;i<vi->channels;i++)
  114633. oggpack_write(opb,info->chmuxlist[i],4);
  114634. }
  114635. for(i=0;i<info->submaps;i++){
  114636. oggpack_write(opb,0,8); /* time submap unused */
  114637. oggpack_write(opb,info->floorsubmap[i],8);
  114638. oggpack_write(opb,info->residuesubmap[i],8);
  114639. }
  114640. }
  114641. /* also responsible for range checking */
  114642. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114643. int i;
  114644. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114645. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114646. memset(info,0,sizeof(*info));
  114647. if(oggpack_read(opb,1))
  114648. info->submaps=oggpack_read(opb,4)+1;
  114649. else
  114650. info->submaps=1;
  114651. if(oggpack_read(opb,1)){
  114652. info->coupling_steps=oggpack_read(opb,8)+1;
  114653. for(i=0;i<info->coupling_steps;i++){
  114654. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114655. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114656. if(testM<0 ||
  114657. testA<0 ||
  114658. testM==testA ||
  114659. testM>=vi->channels ||
  114660. testA>=vi->channels) goto err_out;
  114661. }
  114662. }
  114663. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114664. if(info->submaps>1){
  114665. for(i=0;i<vi->channels;i++){
  114666. info->chmuxlist[i]=oggpack_read(opb,4);
  114667. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114668. }
  114669. }
  114670. for(i=0;i<info->submaps;i++){
  114671. oggpack_read(opb,8); /* time submap unused */
  114672. info->floorsubmap[i]=oggpack_read(opb,8);
  114673. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114674. info->residuesubmap[i]=oggpack_read(opb,8);
  114675. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114676. }
  114677. return info;
  114678. err_out:
  114679. mapping0_free_info(info);
  114680. return(NULL);
  114681. }
  114682. #if 0
  114683. static long seq=0;
  114684. static ogg_int64_t total=0;
  114685. static float FLOOR1_fromdB_LOOKUP[256]={
  114686. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114687. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114688. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114689. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114690. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114691. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114692. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114693. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114694. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114695. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114696. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114697. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114698. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114699. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114700. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114701. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114702. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114703. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114704. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114705. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114706. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114707. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114708. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114709. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114710. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114711. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114712. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114713. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114714. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114715. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114716. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114717. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114718. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114719. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114720. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114721. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114722. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114723. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114724. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114725. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114726. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114727. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114728. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114729. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114730. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114731. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114732. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114733. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114734. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114735. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114736. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114737. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114738. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114739. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114740. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114741. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114742. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114743. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114744. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114745. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114746. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114747. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114748. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114749. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114750. };
  114751. #endif
  114752. extern int *floor1_fit(vorbis_block *vb,void *look,
  114753. const float *logmdct, /* in */
  114754. const float *logmask);
  114755. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114756. int *A,int *B,
  114757. int del);
  114758. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114759. void*look,
  114760. int *post,int *ilogmask);
  114761. static int mapping0_forward(vorbis_block *vb){
  114762. vorbis_dsp_state *vd=vb->vd;
  114763. vorbis_info *vi=vd->vi;
  114764. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114765. private_state *b=(private_state*)vb->vd->backend_state;
  114766. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114767. int n=vb->pcmend;
  114768. int i,j,k;
  114769. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114770. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114771. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114772. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114773. float global_ampmax=vbi->ampmax;
  114774. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114775. int blocktype=vbi->blocktype;
  114776. int modenumber=vb->W;
  114777. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114778. vorbis_look_psy *psy_look=
  114779. b->psy+blocktype+(vb->W?2:0);
  114780. vb->mode=modenumber;
  114781. for(i=0;i<vi->channels;i++){
  114782. float scale=4.f/n;
  114783. float scale_dB;
  114784. float *pcm =vb->pcm[i];
  114785. float *logfft =pcm;
  114786. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114787. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114788. todB estimation used on IEEE 754
  114789. compliant machines had a bug that
  114790. returned dB values about a third
  114791. of a decibel too high. The bug
  114792. was harmless because tunings
  114793. implicitly took that into
  114794. account. However, fixing the bug
  114795. in the estimator requires
  114796. changing all the tunings as well.
  114797. For now, it's easier to sync
  114798. things back up here, and
  114799. recalibrate the tunings in the
  114800. next major model upgrade. */
  114801. #if 0
  114802. if(vi->channels==2)
  114803. if(i==0)
  114804. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114805. else
  114806. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114807. #endif
  114808. /* window the PCM data */
  114809. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114810. #if 0
  114811. if(vi->channels==2)
  114812. if(i==0)
  114813. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114814. else
  114815. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114816. #endif
  114817. /* transform the PCM data */
  114818. /* only MDCT right now.... */
  114819. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114820. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114821. drft_forward(&b->fft_look[vb->W],pcm);
  114822. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114823. original todB estimation used on
  114824. IEEE 754 compliant machines had a
  114825. bug that returned dB values about
  114826. a third of a decibel too high.
  114827. The bug was harmless because
  114828. tunings implicitly took that into
  114829. account. However, fixing the bug
  114830. in the estimator requires
  114831. changing all the tunings as well.
  114832. For now, it's easier to sync
  114833. things back up here, and
  114834. recalibrate the tunings in the
  114835. next major model upgrade. */
  114836. local_ampmax[i]=logfft[0];
  114837. for(j=1;j<n-1;j+=2){
  114838. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114839. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114840. .345 is a hack; the original todB
  114841. estimation used on IEEE 754
  114842. compliant machines had a bug that
  114843. returned dB values about a third
  114844. of a decibel too high. The bug
  114845. was harmless because tunings
  114846. implicitly took that into
  114847. account. However, fixing the bug
  114848. in the estimator requires
  114849. changing all the tunings as well.
  114850. For now, it's easier to sync
  114851. things back up here, and
  114852. recalibrate the tunings in the
  114853. next major model upgrade. */
  114854. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114855. }
  114856. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114857. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114858. #if 0
  114859. if(vi->channels==2){
  114860. if(i==0){
  114861. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114862. }else{
  114863. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114864. }
  114865. }
  114866. #endif
  114867. }
  114868. {
  114869. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114870. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114871. for(i=0;i<vi->channels;i++){
  114872. /* the encoder setup assumes that all the modes used by any
  114873. specific bitrate tweaking use the same floor */
  114874. int submap=info->chmuxlist[i];
  114875. /* the following makes things clearer to *me* anyway */
  114876. float *mdct =gmdct[i];
  114877. float *logfft =vb->pcm[i];
  114878. float *logmdct =logfft+n/2;
  114879. float *logmask =logfft;
  114880. vb->mode=modenumber;
  114881. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114882. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114883. for(j=0;j<n/2;j++)
  114884. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114885. todB estimation used on IEEE 754
  114886. compliant machines had a bug that
  114887. returned dB values about a third
  114888. of a decibel too high. The bug
  114889. was harmless because tunings
  114890. implicitly took that into
  114891. account. However, fixing the bug
  114892. in the estimator requires
  114893. changing all the tunings as well.
  114894. For now, it's easier to sync
  114895. things back up here, and
  114896. recalibrate the tunings in the
  114897. next major model upgrade. */
  114898. #if 0
  114899. if(vi->channels==2){
  114900. if(i==0)
  114901. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114902. else
  114903. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114904. }else{
  114905. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114906. }
  114907. #endif
  114908. /* first step; noise masking. Not only does 'noise masking'
  114909. give us curves from which we can decide how much resolution
  114910. to give noise parts of the spectrum, it also implicitly hands
  114911. us a tonality estimate (the larger the value in the
  114912. 'noise_depth' vector, the more tonal that area is) */
  114913. _vp_noisemask(psy_look,
  114914. logmdct,
  114915. noise); /* noise does not have by-frequency offset
  114916. bias applied yet */
  114917. #if 0
  114918. if(vi->channels==2){
  114919. if(i==0)
  114920. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114921. else
  114922. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114923. }
  114924. #endif
  114925. /* second step: 'all the other crap'; all the stuff that isn't
  114926. computed/fit for bitrate management goes in the second psy
  114927. vector. This includes tone masking, peak limiting and ATH */
  114928. _vp_tonemask(psy_look,
  114929. logfft,
  114930. tone,
  114931. global_ampmax,
  114932. local_ampmax[i]);
  114933. #if 0
  114934. if(vi->channels==2){
  114935. if(i==0)
  114936. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114937. else
  114938. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114939. }
  114940. #endif
  114941. /* third step; we offset the noise vectors, overlay tone
  114942. masking. We then do a floor1-specific line fit. If we're
  114943. performing bitrate management, the line fit is performed
  114944. multiple times for up/down tweakage on demand. */
  114945. #if 0
  114946. {
  114947. float aotuv[psy_look->n];
  114948. #endif
  114949. _vp_offset_and_mix(psy_look,
  114950. noise,
  114951. tone,
  114952. 1,
  114953. logmask,
  114954. mdct,
  114955. logmdct);
  114956. #if 0
  114957. if(vi->channels==2){
  114958. if(i==0)
  114959. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114960. else
  114961. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114962. }
  114963. }
  114964. #endif
  114965. #if 0
  114966. if(vi->channels==2){
  114967. if(i==0)
  114968. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  114969. else
  114970. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  114971. }
  114972. #endif
  114973. /* this algorithm is hardwired to floor 1 for now; abort out if
  114974. we're *not* floor1. This won't happen unless someone has
  114975. broken the encode setup lib. Guard it anyway. */
  114976. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  114977. floor_posts[i][PACKETBLOBS/2]=
  114978. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114979. logmdct,
  114980. logmask);
  114981. /* are we managing bitrate? If so, perform two more fits for
  114982. later rate tweaking (fits represent hi/lo) */
  114983. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  114984. /* higher rate by way of lower noise curve */
  114985. _vp_offset_and_mix(psy_look,
  114986. noise,
  114987. tone,
  114988. 2,
  114989. logmask,
  114990. mdct,
  114991. logmdct);
  114992. #if 0
  114993. if(vi->channels==2){
  114994. if(i==0)
  114995. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  114996. else
  114997. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  114998. }
  114999. #endif
  115000. floor_posts[i][PACKETBLOBS-1]=
  115001. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115002. logmdct,
  115003. logmask);
  115004. /* lower rate by way of higher noise curve */
  115005. _vp_offset_and_mix(psy_look,
  115006. noise,
  115007. tone,
  115008. 0,
  115009. logmask,
  115010. mdct,
  115011. logmdct);
  115012. #if 0
  115013. if(vi->channels==2)
  115014. if(i==0)
  115015. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115016. else
  115017. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115018. #endif
  115019. floor_posts[i][0]=
  115020. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115021. logmdct,
  115022. logmask);
  115023. /* we also interpolate a range of intermediate curves for
  115024. intermediate rates */
  115025. for(k=1;k<PACKETBLOBS/2;k++)
  115026. floor_posts[i][k]=
  115027. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115028. floor_posts[i][0],
  115029. floor_posts[i][PACKETBLOBS/2],
  115030. k*65536/(PACKETBLOBS/2));
  115031. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115032. floor_posts[i][k]=
  115033. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115034. floor_posts[i][PACKETBLOBS/2],
  115035. floor_posts[i][PACKETBLOBS-1],
  115036. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115037. }
  115038. }
  115039. }
  115040. vbi->ampmax=global_ampmax;
  115041. /*
  115042. the next phases are performed once for vbr-only and PACKETBLOB
  115043. times for bitrate managed modes.
  115044. 1) encode actual mode being used
  115045. 2) encode the floor for each channel, compute coded mask curve/res
  115046. 3) normalize and couple.
  115047. 4) encode residue
  115048. 5) save packet bytes to the packetblob vector
  115049. */
  115050. /* iterate over the many masking curve fits we've created */
  115051. {
  115052. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115053. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115054. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115055. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115056. float **mag_memo;
  115057. int **mag_sort;
  115058. if(info->coupling_steps){
  115059. mag_memo=_vp_quantize_couple_memo(vb,
  115060. &ci->psy_g_param,
  115061. psy_look,
  115062. info,
  115063. gmdct);
  115064. mag_sort=_vp_quantize_couple_sort(vb,
  115065. psy_look,
  115066. info,
  115067. mag_memo);
  115068. hf_reduction(&ci->psy_g_param,
  115069. psy_look,
  115070. info,
  115071. mag_memo);
  115072. }
  115073. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115074. if(psy_look->vi->normal_channel_p){
  115075. for(i=0;i<vi->channels;i++){
  115076. float *mdct =gmdct[i];
  115077. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115078. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115079. }
  115080. }
  115081. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115082. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115083. k++){
  115084. oggpack_buffer *opb=vbi->packetblob[k];
  115085. /* start out our new packet blob with packet type and mode */
  115086. /* Encode the packet type */
  115087. oggpack_write(opb,0,1);
  115088. /* Encode the modenumber */
  115089. /* Encode frame mode, pre,post windowsize, then dispatch */
  115090. oggpack_write(opb,modenumber,b->modebits);
  115091. if(vb->W){
  115092. oggpack_write(opb,vb->lW,1);
  115093. oggpack_write(opb,vb->nW,1);
  115094. }
  115095. /* encode floor, compute masking curve, sep out residue */
  115096. for(i=0;i<vi->channels;i++){
  115097. int submap=info->chmuxlist[i];
  115098. float *mdct =gmdct[i];
  115099. float *res =vb->pcm[i];
  115100. int *ilogmask=ilogmaskch[i]=
  115101. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115102. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115103. floor_posts[i][k],
  115104. ilogmask);
  115105. #if 0
  115106. {
  115107. char buf[80];
  115108. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115109. float work[n/2];
  115110. for(j=0;j<n/2;j++)
  115111. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115112. _analysis_output(buf,seq,work,n/2,1,1,0);
  115113. }
  115114. #endif
  115115. _vp_remove_floor(psy_look,
  115116. mdct,
  115117. ilogmask,
  115118. res,
  115119. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115120. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115121. #if 0
  115122. {
  115123. char buf[80];
  115124. float work[n/2];
  115125. for(j=0;j<n/2;j++)
  115126. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115127. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115128. _analysis_output(buf,seq,work,n/2,1,1,0);
  115129. }
  115130. #endif
  115131. }
  115132. /* our iteration is now based on masking curve, not prequant and
  115133. coupling. Only one prequant/coupling step */
  115134. /* quantize/couple */
  115135. /* incomplete implementation that assumes the tree is all depth
  115136. one, or no tree at all */
  115137. if(info->coupling_steps){
  115138. _vp_couple(k,
  115139. &ci->psy_g_param,
  115140. psy_look,
  115141. info,
  115142. vb->pcm,
  115143. mag_memo,
  115144. mag_sort,
  115145. ilogmaskch,
  115146. nonzero,
  115147. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115148. }
  115149. /* classify and encode by submap */
  115150. for(i=0;i<info->submaps;i++){
  115151. int ch_in_bundle=0;
  115152. long **classifications;
  115153. int resnum=info->residuesubmap[i];
  115154. for(j=0;j<vi->channels;j++){
  115155. if(info->chmuxlist[j]==i){
  115156. zerobundle[ch_in_bundle]=0;
  115157. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115158. res_bundle[ch_in_bundle]=vb->pcm[j];
  115159. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115160. }
  115161. }
  115162. classifications=_residue_P[ci->residue_type[resnum]]->
  115163. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115164. _residue_P[ci->residue_type[resnum]]->
  115165. forward(opb,vb,b->residue[resnum],
  115166. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115167. }
  115168. /* ok, done encoding. Next protopacket. */
  115169. }
  115170. }
  115171. #if 0
  115172. seq++;
  115173. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115174. #endif
  115175. return(0);
  115176. }
  115177. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115178. vorbis_dsp_state *vd=vb->vd;
  115179. vorbis_info *vi=vd->vi;
  115180. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115181. private_state *b=(private_state*)vd->backend_state;
  115182. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115183. int i,j;
  115184. long n=vb->pcmend=ci->blocksizes[vb->W];
  115185. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115186. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115187. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115188. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115189. /* recover the spectral envelope; store it in the PCM vector for now */
  115190. for(i=0;i<vi->channels;i++){
  115191. int submap=info->chmuxlist[i];
  115192. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115193. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115194. if(floormemo[i])
  115195. nonzero[i]=1;
  115196. else
  115197. nonzero[i]=0;
  115198. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115199. }
  115200. /* channel coupling can 'dirty' the nonzero listing */
  115201. for(i=0;i<info->coupling_steps;i++){
  115202. if(nonzero[info->coupling_mag[i]] ||
  115203. nonzero[info->coupling_ang[i]]){
  115204. nonzero[info->coupling_mag[i]]=1;
  115205. nonzero[info->coupling_ang[i]]=1;
  115206. }
  115207. }
  115208. /* recover the residue into our working vectors */
  115209. for(i=0;i<info->submaps;i++){
  115210. int ch_in_bundle=0;
  115211. for(j=0;j<vi->channels;j++){
  115212. if(info->chmuxlist[j]==i){
  115213. if(nonzero[j])
  115214. zerobundle[ch_in_bundle]=1;
  115215. else
  115216. zerobundle[ch_in_bundle]=0;
  115217. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115218. }
  115219. }
  115220. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115221. inverse(vb,b->residue[info->residuesubmap[i]],
  115222. pcmbundle,zerobundle,ch_in_bundle);
  115223. }
  115224. /* channel coupling */
  115225. for(i=info->coupling_steps-1;i>=0;i--){
  115226. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115227. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115228. for(j=0;j<n/2;j++){
  115229. float mag=pcmM[j];
  115230. float ang=pcmA[j];
  115231. if(mag>0)
  115232. if(ang>0){
  115233. pcmM[j]=mag;
  115234. pcmA[j]=mag-ang;
  115235. }else{
  115236. pcmA[j]=mag;
  115237. pcmM[j]=mag+ang;
  115238. }
  115239. else
  115240. if(ang>0){
  115241. pcmM[j]=mag;
  115242. pcmA[j]=mag+ang;
  115243. }else{
  115244. pcmA[j]=mag;
  115245. pcmM[j]=mag-ang;
  115246. }
  115247. }
  115248. }
  115249. /* compute and apply spectral envelope */
  115250. for(i=0;i<vi->channels;i++){
  115251. float *pcm=vb->pcm[i];
  115252. int submap=info->chmuxlist[i];
  115253. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115254. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115255. floormemo[i],pcm);
  115256. }
  115257. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115258. /* only MDCT right now.... */
  115259. for(i=0;i<vi->channels;i++){
  115260. float *pcm=vb->pcm[i];
  115261. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115262. }
  115263. /* all done! */
  115264. return(0);
  115265. }
  115266. /* export hooks */
  115267. vorbis_func_mapping mapping0_exportbundle={
  115268. &mapping0_pack,
  115269. &mapping0_unpack,
  115270. &mapping0_free_info,
  115271. &mapping0_forward,
  115272. &mapping0_inverse
  115273. };
  115274. #endif
  115275. /*** End of inlined file: mapping0.c ***/
  115276. /*** Start of inlined file: mdct.c ***/
  115277. /* this can also be run as an integer transform by uncommenting a
  115278. define in mdct.h; the integerization is a first pass and although
  115279. it's likely stable for Vorbis, the dynamic range is constrained and
  115280. roundoff isn't done (so it's noisy). Consider it functional, but
  115281. only a starting point. There's no point on a machine with an FPU */
  115282. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115283. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115284. // tasks..
  115285. #if JUCE_MSVC
  115286. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115287. #endif
  115288. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115289. #if JUCE_USE_OGGVORBIS
  115290. #include <stdio.h>
  115291. #include <stdlib.h>
  115292. #include <string.h>
  115293. #include <math.h>
  115294. /* build lookups for trig functions; also pre-figure scaling and
  115295. some window function algebra. */
  115296. void mdct_init(mdct_lookup *lookup,int n){
  115297. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115298. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115299. int i;
  115300. int n2=n>>1;
  115301. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115302. lookup->n=n;
  115303. lookup->trig=T;
  115304. lookup->bitrev=bitrev;
  115305. /* trig lookups... */
  115306. for(i=0;i<n/4;i++){
  115307. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115308. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115309. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115310. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115311. }
  115312. for(i=0;i<n/8;i++){
  115313. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115314. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115315. }
  115316. /* bitreverse lookup... */
  115317. {
  115318. int mask=(1<<(log2n-1))-1,i,j;
  115319. int msb=1<<(log2n-2);
  115320. for(i=0;i<n/8;i++){
  115321. int acc=0;
  115322. for(j=0;msb>>j;j++)
  115323. if((msb>>j)&i)acc|=1<<j;
  115324. bitrev[i*2]=((~acc)&mask)-1;
  115325. bitrev[i*2+1]=acc;
  115326. }
  115327. }
  115328. lookup->scale=FLOAT_CONV(4.f/n);
  115329. }
  115330. /* 8 point butterfly (in place, 4 register) */
  115331. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115332. REG_TYPE r0 = x[6] + x[2];
  115333. REG_TYPE r1 = x[6] - x[2];
  115334. REG_TYPE r2 = x[4] + x[0];
  115335. REG_TYPE r3 = x[4] - x[0];
  115336. x[6] = r0 + r2;
  115337. x[4] = r0 - r2;
  115338. r0 = x[5] - x[1];
  115339. r2 = x[7] - x[3];
  115340. x[0] = r1 + r0;
  115341. x[2] = r1 - r0;
  115342. r0 = x[5] + x[1];
  115343. r1 = x[7] + x[3];
  115344. x[3] = r2 + r3;
  115345. x[1] = r2 - r3;
  115346. x[7] = r1 + r0;
  115347. x[5] = r1 - r0;
  115348. }
  115349. /* 16 point butterfly (in place, 4 register) */
  115350. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115351. REG_TYPE r0 = x[1] - x[9];
  115352. REG_TYPE r1 = x[0] - x[8];
  115353. x[8] += x[0];
  115354. x[9] += x[1];
  115355. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115356. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115357. r0 = x[3] - x[11];
  115358. r1 = x[10] - x[2];
  115359. x[10] += x[2];
  115360. x[11] += x[3];
  115361. x[2] = r0;
  115362. x[3] = r1;
  115363. r0 = x[12] - x[4];
  115364. r1 = x[13] - x[5];
  115365. x[12] += x[4];
  115366. x[13] += x[5];
  115367. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115368. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115369. r0 = x[14] - x[6];
  115370. r1 = x[15] - x[7];
  115371. x[14] += x[6];
  115372. x[15] += x[7];
  115373. x[6] = r0;
  115374. x[7] = r1;
  115375. mdct_butterfly_8(x);
  115376. mdct_butterfly_8(x+8);
  115377. }
  115378. /* 32 point butterfly (in place, 4 register) */
  115379. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115380. REG_TYPE r0 = x[30] - x[14];
  115381. REG_TYPE r1 = x[31] - x[15];
  115382. x[30] += x[14];
  115383. x[31] += x[15];
  115384. x[14] = r0;
  115385. x[15] = r1;
  115386. r0 = x[28] - x[12];
  115387. r1 = x[29] - x[13];
  115388. x[28] += x[12];
  115389. x[29] += x[13];
  115390. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115391. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115392. r0 = x[26] - x[10];
  115393. r1 = x[27] - x[11];
  115394. x[26] += x[10];
  115395. x[27] += x[11];
  115396. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115397. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115398. r0 = x[24] - x[8];
  115399. r1 = x[25] - x[9];
  115400. x[24] += x[8];
  115401. x[25] += x[9];
  115402. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115403. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115404. r0 = x[22] - x[6];
  115405. r1 = x[7] - x[23];
  115406. x[22] += x[6];
  115407. x[23] += x[7];
  115408. x[6] = r1;
  115409. x[7] = r0;
  115410. r0 = x[4] - x[20];
  115411. r1 = x[5] - x[21];
  115412. x[20] += x[4];
  115413. x[21] += x[5];
  115414. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115415. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115416. r0 = x[2] - x[18];
  115417. r1 = x[3] - x[19];
  115418. x[18] += x[2];
  115419. x[19] += x[3];
  115420. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115421. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115422. r0 = x[0] - x[16];
  115423. r1 = x[1] - x[17];
  115424. x[16] += x[0];
  115425. x[17] += x[1];
  115426. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115427. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115428. mdct_butterfly_16(x);
  115429. mdct_butterfly_16(x+16);
  115430. }
  115431. /* N point first stage butterfly (in place, 2 register) */
  115432. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115433. DATA_TYPE *x,
  115434. int points){
  115435. DATA_TYPE *x1 = x + points - 8;
  115436. DATA_TYPE *x2 = x + (points>>1) - 8;
  115437. REG_TYPE r0;
  115438. REG_TYPE r1;
  115439. do{
  115440. r0 = x1[6] - x2[6];
  115441. r1 = x1[7] - x2[7];
  115442. x1[6] += x2[6];
  115443. x1[7] += x2[7];
  115444. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115445. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115446. r0 = x1[4] - x2[4];
  115447. r1 = x1[5] - x2[5];
  115448. x1[4] += x2[4];
  115449. x1[5] += x2[5];
  115450. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115451. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115452. r0 = x1[2] - x2[2];
  115453. r1 = x1[3] - x2[3];
  115454. x1[2] += x2[2];
  115455. x1[3] += x2[3];
  115456. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115457. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115458. r0 = x1[0] - x2[0];
  115459. r1 = x1[1] - x2[1];
  115460. x1[0] += x2[0];
  115461. x1[1] += x2[1];
  115462. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115463. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115464. x1-=8;
  115465. x2-=8;
  115466. T+=16;
  115467. }while(x2>=x);
  115468. }
  115469. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115470. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115471. DATA_TYPE *x,
  115472. int points,
  115473. int trigint){
  115474. DATA_TYPE *x1 = x + points - 8;
  115475. DATA_TYPE *x2 = x + (points>>1) - 8;
  115476. REG_TYPE r0;
  115477. REG_TYPE r1;
  115478. do{
  115479. r0 = x1[6] - x2[6];
  115480. r1 = x1[7] - x2[7];
  115481. x1[6] += x2[6];
  115482. x1[7] += x2[7];
  115483. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115484. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115485. T+=trigint;
  115486. r0 = x1[4] - x2[4];
  115487. r1 = x1[5] - x2[5];
  115488. x1[4] += x2[4];
  115489. x1[5] += x2[5];
  115490. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115491. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115492. T+=trigint;
  115493. r0 = x1[2] - x2[2];
  115494. r1 = x1[3] - x2[3];
  115495. x1[2] += x2[2];
  115496. x1[3] += x2[3];
  115497. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115498. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115499. T+=trigint;
  115500. r0 = x1[0] - x2[0];
  115501. r1 = x1[1] - x2[1];
  115502. x1[0] += x2[0];
  115503. x1[1] += x2[1];
  115504. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115505. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115506. T+=trigint;
  115507. x1-=8;
  115508. x2-=8;
  115509. }while(x2>=x);
  115510. }
  115511. STIN void mdct_butterflies(mdct_lookup *init,
  115512. DATA_TYPE *x,
  115513. int points){
  115514. DATA_TYPE *T=init->trig;
  115515. int stages=init->log2n-5;
  115516. int i,j;
  115517. if(--stages>0){
  115518. mdct_butterfly_first(T,x,points);
  115519. }
  115520. for(i=1;--stages>0;i++){
  115521. for(j=0;j<(1<<i);j++)
  115522. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115523. }
  115524. for(j=0;j<points;j+=32)
  115525. mdct_butterfly_32(x+j);
  115526. }
  115527. void mdct_clear(mdct_lookup *l){
  115528. if(l){
  115529. if(l->trig)_ogg_free(l->trig);
  115530. if(l->bitrev)_ogg_free(l->bitrev);
  115531. memset(l,0,sizeof(*l));
  115532. }
  115533. }
  115534. STIN void mdct_bitreverse(mdct_lookup *init,
  115535. DATA_TYPE *x){
  115536. int n = init->n;
  115537. int *bit = init->bitrev;
  115538. DATA_TYPE *w0 = x;
  115539. DATA_TYPE *w1 = x = w0+(n>>1);
  115540. DATA_TYPE *T = init->trig+n;
  115541. do{
  115542. DATA_TYPE *x0 = x+bit[0];
  115543. DATA_TYPE *x1 = x+bit[1];
  115544. REG_TYPE r0 = x0[1] - x1[1];
  115545. REG_TYPE r1 = x0[0] + x1[0];
  115546. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115547. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115548. w1 -= 4;
  115549. r0 = HALVE(x0[1] + x1[1]);
  115550. r1 = HALVE(x0[0] - x1[0]);
  115551. w0[0] = r0 + r2;
  115552. w1[2] = r0 - r2;
  115553. w0[1] = r1 + r3;
  115554. w1[3] = r3 - r1;
  115555. x0 = x+bit[2];
  115556. x1 = x+bit[3];
  115557. r0 = x0[1] - x1[1];
  115558. r1 = x0[0] + x1[0];
  115559. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115560. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115561. r0 = HALVE(x0[1] + x1[1]);
  115562. r1 = HALVE(x0[0] - x1[0]);
  115563. w0[2] = r0 + r2;
  115564. w1[0] = r0 - r2;
  115565. w0[3] = r1 + r3;
  115566. w1[1] = r3 - r1;
  115567. T += 4;
  115568. bit += 4;
  115569. w0 += 4;
  115570. }while(w0<w1);
  115571. }
  115572. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115573. int n=init->n;
  115574. int n2=n>>1;
  115575. int n4=n>>2;
  115576. /* rotate */
  115577. DATA_TYPE *iX = in+n2-7;
  115578. DATA_TYPE *oX = out+n2+n4;
  115579. DATA_TYPE *T = init->trig+n4;
  115580. do{
  115581. oX -= 4;
  115582. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115583. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115584. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115585. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115586. iX -= 8;
  115587. T += 4;
  115588. }while(iX>=in);
  115589. iX = in+n2-8;
  115590. oX = out+n2+n4;
  115591. T = init->trig+n4;
  115592. do{
  115593. T -= 4;
  115594. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115595. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115596. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115597. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115598. iX -= 8;
  115599. oX += 4;
  115600. }while(iX>=in);
  115601. mdct_butterflies(init,out+n2,n2);
  115602. mdct_bitreverse(init,out);
  115603. /* roatate + window */
  115604. {
  115605. DATA_TYPE *oX1=out+n2+n4;
  115606. DATA_TYPE *oX2=out+n2+n4;
  115607. DATA_TYPE *iX =out;
  115608. T =init->trig+n2;
  115609. do{
  115610. oX1-=4;
  115611. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115612. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115613. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115614. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115615. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115616. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115617. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115618. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115619. oX2+=4;
  115620. iX += 8;
  115621. T += 8;
  115622. }while(iX<oX1);
  115623. iX=out+n2+n4;
  115624. oX1=out+n4;
  115625. oX2=oX1;
  115626. do{
  115627. oX1-=4;
  115628. iX-=4;
  115629. oX2[0] = -(oX1[3] = iX[3]);
  115630. oX2[1] = -(oX1[2] = iX[2]);
  115631. oX2[2] = -(oX1[1] = iX[1]);
  115632. oX2[3] = -(oX1[0] = iX[0]);
  115633. oX2+=4;
  115634. }while(oX2<iX);
  115635. iX=out+n2+n4;
  115636. oX1=out+n2+n4;
  115637. oX2=out+n2;
  115638. do{
  115639. oX1-=4;
  115640. oX1[0]= iX[3];
  115641. oX1[1]= iX[2];
  115642. oX1[2]= iX[1];
  115643. oX1[3]= iX[0];
  115644. iX+=4;
  115645. }while(oX1>oX2);
  115646. }
  115647. }
  115648. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115649. int n=init->n;
  115650. int n2=n>>1;
  115651. int n4=n>>2;
  115652. int n8=n>>3;
  115653. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115654. DATA_TYPE *w2=w+n2;
  115655. /* rotate */
  115656. /* window + rotate + step 1 */
  115657. REG_TYPE r0;
  115658. REG_TYPE r1;
  115659. DATA_TYPE *x0=in+n2+n4;
  115660. DATA_TYPE *x1=x0+1;
  115661. DATA_TYPE *T=init->trig+n2;
  115662. int i=0;
  115663. for(i=0;i<n8;i+=2){
  115664. x0 -=4;
  115665. T-=2;
  115666. r0= x0[2] + x1[0];
  115667. r1= x0[0] + x1[2];
  115668. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115669. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115670. x1 +=4;
  115671. }
  115672. x1=in+1;
  115673. for(;i<n2-n8;i+=2){
  115674. T-=2;
  115675. x0 -=4;
  115676. r0= x0[2] - x1[0];
  115677. r1= x0[0] - x1[2];
  115678. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115679. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115680. x1 +=4;
  115681. }
  115682. x0=in+n;
  115683. for(;i<n2;i+=2){
  115684. T-=2;
  115685. x0 -=4;
  115686. r0= -x0[2] - x1[0];
  115687. r1= -x0[0] - x1[2];
  115688. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115689. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115690. x1 +=4;
  115691. }
  115692. mdct_butterflies(init,w+n2,n2);
  115693. mdct_bitreverse(init,w);
  115694. /* roatate + window */
  115695. T=init->trig+n2;
  115696. x0=out+n2;
  115697. for(i=0;i<n4;i++){
  115698. x0--;
  115699. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115700. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115701. w+=2;
  115702. T+=2;
  115703. }
  115704. }
  115705. #endif
  115706. /*** End of inlined file: mdct.c ***/
  115707. /*** Start of inlined file: psy.c ***/
  115708. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115709. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115710. // tasks..
  115711. #if JUCE_MSVC
  115712. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115713. #endif
  115714. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115715. #if JUCE_USE_OGGVORBIS
  115716. #include <stdlib.h>
  115717. #include <math.h>
  115718. #include <string.h>
  115719. /*** Start of inlined file: masking.h ***/
  115720. #ifndef _V_MASKING_H_
  115721. #define _V_MASKING_H_
  115722. /* more detailed ATH; the bass if flat to save stressing the floor
  115723. overly for only a bin or two of savings. */
  115724. #define MAX_ATH 88
  115725. static float ATH[]={
  115726. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115727. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115728. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115729. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115730. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115731. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115732. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115733. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115734. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115735. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115736. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115737. };
  115738. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115739. replaced by an empirically collected data set. The previously
  115740. published values were, far too often, simply on crack. */
  115741. #define EHMER_OFFSET 16
  115742. #define EHMER_MAX 56
  115743. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115744. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115745. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115746. for collection of these curves) */
  115747. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115748. /* 62.5 Hz */
  115749. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115750. -60, -60, -60, -60, -62, -62, -65, -73,
  115751. -69, -68, -68, -67, -70, -70, -72, -74,
  115752. -75, -79, -79, -80, -83, -88, -93, -100,
  115753. -110, -999, -999, -999, -999, -999, -999, -999,
  115754. -999, -999, -999, -999, -999, -999, -999, -999,
  115755. -999, -999, -999, -999, -999, -999, -999, -999},
  115756. { -48, -48, -48, -48, -48, -48, -48, -48,
  115757. -48, -48, -48, -48, -48, -53, -61, -66,
  115758. -66, -68, -67, -70, -76, -76, -72, -73,
  115759. -75, -76, -78, -79, -83, -88, -93, -100,
  115760. -110, -999, -999, -999, -999, -999, -999, -999,
  115761. -999, -999, -999, -999, -999, -999, -999, -999,
  115762. -999, -999, -999, -999, -999, -999, -999, -999},
  115763. { -37, -37, -37, -37, -37, -37, -37, -37,
  115764. -38, -40, -42, -46, -48, -53, -55, -62,
  115765. -65, -58, -56, -56, -61, -60, -65, -67,
  115766. -69, -71, -77, -77, -78, -80, -82, -84,
  115767. -88, -93, -98, -106, -112, -999, -999, -999,
  115768. -999, -999, -999, -999, -999, -999, -999, -999,
  115769. -999, -999, -999, -999, -999, -999, -999, -999},
  115770. { -25, -25, -25, -25, -25, -25, -25, -25,
  115771. -25, -26, -27, -29, -32, -38, -48, -52,
  115772. -52, -50, -48, -48, -51, -52, -54, -60,
  115773. -67, -67, -66, -68, -69, -73, -73, -76,
  115774. -80, -81, -81, -85, -85, -86, -88, -93,
  115775. -100, -110, -999, -999, -999, -999, -999, -999,
  115776. -999, -999, -999, -999, -999, -999, -999, -999},
  115777. { -16, -16, -16, -16, -16, -16, -16, -16,
  115778. -17, -19, -20, -22, -26, -28, -31, -40,
  115779. -47, -39, -39, -40, -42, -43, -47, -51,
  115780. -57, -52, -55, -55, -60, -58, -62, -63,
  115781. -70, -67, -69, -72, -73, -77, -80, -82,
  115782. -83, -87, -90, -94, -98, -104, -115, -999,
  115783. -999, -999, -999, -999, -999, -999, -999, -999},
  115784. { -8, -8, -8, -8, -8, -8, -8, -8,
  115785. -8, -8, -10, -11, -15, -19, -25, -30,
  115786. -34, -31, -30, -31, -29, -32, -35, -42,
  115787. -48, -42, -44, -46, -50, -50, -51, -52,
  115788. -59, -54, -55, -55, -58, -62, -63, -66,
  115789. -72, -73, -76, -75, -78, -80, -80, -81,
  115790. -84, -88, -90, -94, -98, -101, -106, -110}},
  115791. /* 88Hz */
  115792. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115793. -66, -66, -66, -66, -66, -67, -67, -67,
  115794. -76, -72, -71, -74, -76, -76, -75, -78,
  115795. -79, -79, -81, -83, -86, -89, -93, -97,
  115796. -100, -105, -110, -999, -999, -999, -999, -999,
  115797. -999, -999, -999, -999, -999, -999, -999, -999,
  115798. -999, -999, -999, -999, -999, -999, -999, -999},
  115799. { -47, -47, -47, -47, -47, -47, -47, -47,
  115800. -47, -47, -47, -48, -51, -55, -59, -66,
  115801. -66, -66, -67, -66, -68, -69, -70, -74,
  115802. -79, -77, -77, -78, -80, -81, -82, -84,
  115803. -86, -88, -91, -95, -100, -108, -116, -999,
  115804. -999, -999, -999, -999, -999, -999, -999, -999,
  115805. -999, -999, -999, -999, -999, -999, -999, -999},
  115806. { -36, -36, -36, -36, -36, -36, -36, -36,
  115807. -36, -37, -37, -41, -44, -48, -51, -58,
  115808. -62, -60, -57, -59, -59, -60, -63, -65,
  115809. -72, -71, -70, -72, -74, -77, -76, -78,
  115810. -81, -81, -80, -83, -86, -91, -96, -100,
  115811. -105, -110, -999, -999, -999, -999, -999, -999,
  115812. -999, -999, -999, -999, -999, -999, -999, -999},
  115813. { -28, -28, -28, -28, -28, -28, -28, -28,
  115814. -28, -30, -32, -32, -33, -35, -41, -49,
  115815. -50, -49, -47, -48, -48, -52, -51, -57,
  115816. -65, -61, -59, -61, -64, -69, -70, -74,
  115817. -77, -77, -78, -81, -84, -85, -87, -90,
  115818. -92, -96, -100, -107, -112, -999, -999, -999,
  115819. -999, -999, -999, -999, -999, -999, -999, -999},
  115820. { -19, -19, -19, -19, -19, -19, -19, -19,
  115821. -20, -21, -23, -27, -30, -35, -36, -41,
  115822. -46, -44, -42, -40, -41, -41, -43, -48,
  115823. -55, -53, -52, -53, -56, -59, -58, -60,
  115824. -67, -66, -69, -71, -72, -75, -79, -81,
  115825. -84, -87, -90, -93, -97, -101, -107, -114,
  115826. -999, -999, -999, -999, -999, -999, -999, -999},
  115827. { -9, -9, -9, -9, -9, -9, -9, -9,
  115828. -11, -12, -12, -15, -16, -20, -23, -30,
  115829. -37, -34, -33, -34, -31, -32, -32, -38,
  115830. -47, -44, -41, -40, -47, -49, -46, -46,
  115831. -58, -50, -50, -54, -58, -62, -64, -67,
  115832. -67, -70, -72, -76, -79, -83, -87, -91,
  115833. -96, -100, -104, -110, -999, -999, -999, -999}},
  115834. /* 125 Hz */
  115835. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  115836. -62, -62, -63, -64, -66, -67, -66, -68,
  115837. -75, -72, -76, -75, -76, -78, -79, -82,
  115838. -84, -85, -90, -94, -101, -110, -999, -999,
  115839. -999, -999, -999, -999, -999, -999, -999, -999,
  115840. -999, -999, -999, -999, -999, -999, -999, -999,
  115841. -999, -999, -999, -999, -999, -999, -999, -999},
  115842. { -59, -59, -59, -59, -59, -59, -59, -59,
  115843. -59, -59, -59, -60, -60, -61, -63, -66,
  115844. -71, -68, -70, -70, -71, -72, -72, -75,
  115845. -81, -78, -79, -82, -83, -86, -90, -97,
  115846. -103, -113, -999, -999, -999, -999, -999, -999,
  115847. -999, -999, -999, -999, -999, -999, -999, -999,
  115848. -999, -999, -999, -999, -999, -999, -999, -999},
  115849. { -53, -53, -53, -53, -53, -53, -53, -53,
  115850. -53, -54, -55, -57, -56, -57, -55, -61,
  115851. -65, -60, -60, -62, -63, -63, -66, -68,
  115852. -74, -73, -75, -75, -78, -80, -80, -82,
  115853. -85, -90, -96, -101, -108, -999, -999, -999,
  115854. -999, -999, -999, -999, -999, -999, -999, -999,
  115855. -999, -999, -999, -999, -999, -999, -999, -999},
  115856. { -46, -46, -46, -46, -46, -46, -46, -46,
  115857. -46, -46, -47, -47, -47, -47, -48, -51,
  115858. -57, -51, -49, -50, -51, -53, -54, -59,
  115859. -66, -60, -62, -67, -67, -70, -72, -75,
  115860. -76, -78, -81, -85, -88, -94, -97, -104,
  115861. -112, -999, -999, -999, -999, -999, -999, -999,
  115862. -999, -999, -999, -999, -999, -999, -999, -999},
  115863. { -36, -36, -36, -36, -36, -36, -36, -36,
  115864. -39, -41, -42, -42, -39, -38, -41, -43,
  115865. -52, -44, -40, -39, -37, -37, -40, -47,
  115866. -54, -50, -48, -50, -55, -61, -59, -62,
  115867. -66, -66, -66, -69, -69, -73, -74, -74,
  115868. -75, -77, -79, -82, -87, -91, -95, -100,
  115869. -108, -115, -999, -999, -999, -999, -999, -999},
  115870. { -28, -26, -24, -22, -20, -20, -23, -29,
  115871. -30, -31, -28, -27, -28, -28, -28, -35,
  115872. -40, -33, -32, -29, -30, -30, -30, -37,
  115873. -45, -41, -37, -38, -45, -47, -47, -48,
  115874. -53, -49, -48, -50, -49, -49, -51, -52,
  115875. -58, -56, -57, -56, -60, -61, -62, -70,
  115876. -72, -74, -78, -83, -88, -93, -100, -106}},
  115877. /* 177 Hz */
  115878. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115879. -999, -110, -105, -100, -95, -91, -87, -83,
  115880. -80, -78, -76, -78, -78, -81, -83, -85,
  115881. -86, -85, -86, -87, -90, -97, -107, -999,
  115882. -999, -999, -999, -999, -999, -999, -999, -999,
  115883. -999, -999, -999, -999, -999, -999, -999, -999,
  115884. -999, -999, -999, -999, -999, -999, -999, -999},
  115885. {-999, -999, -999, -110, -105, -100, -95, -90,
  115886. -85, -81, -77, -73, -70, -67, -67, -68,
  115887. -75, -73, -70, -69, -70, -72, -75, -79,
  115888. -84, -83, -84, -86, -88, -89, -89, -93,
  115889. -98, -105, -112, -999, -999, -999, -999, -999,
  115890. -999, -999, -999, -999, -999, -999, -999, -999,
  115891. -999, -999, -999, -999, -999, -999, -999, -999},
  115892. {-105, -100, -95, -90, -85, -80, -76, -71,
  115893. -68, -68, -65, -63, -63, -62, -62, -64,
  115894. -65, -64, -61, -62, -63, -64, -66, -68,
  115895. -73, -73, -74, -75, -76, -81, -83, -85,
  115896. -88, -89, -92, -95, -100, -108, -999, -999,
  115897. -999, -999, -999, -999, -999, -999, -999, -999,
  115898. -999, -999, -999, -999, -999, -999, -999, -999},
  115899. { -80, -75, -71, -68, -65, -63, -62, -61,
  115900. -61, -61, -61, -59, -56, -57, -53, -50,
  115901. -58, -52, -50, -50, -52, -53, -54, -58,
  115902. -67, -63, -67, -68, -72, -75, -78, -80,
  115903. -81, -81, -82, -85, -89, -90, -93, -97,
  115904. -101, -107, -114, -999, -999, -999, -999, -999,
  115905. -999, -999, -999, -999, -999, -999, -999, -999},
  115906. { -65, -61, -59, -57, -56, -55, -55, -56,
  115907. -56, -57, -55, -53, -52, -47, -44, -44,
  115908. -50, -44, -41, -39, -39, -42, -40, -46,
  115909. -51, -49, -50, -53, -54, -63, -60, -61,
  115910. -62, -66, -66, -66, -70, -73, -74, -75,
  115911. -76, -75, -79, -85, -89, -91, -96, -102,
  115912. -110, -999, -999, -999, -999, -999, -999, -999},
  115913. { -52, -50, -49, -49, -48, -48, -48, -49,
  115914. -50, -50, -49, -46, -43, -39, -35, -33,
  115915. -38, -36, -32, -29, -32, -32, -32, -35,
  115916. -44, -39, -38, -38, -46, -50, -45, -46,
  115917. -53, -50, -50, -50, -54, -54, -53, -53,
  115918. -56, -57, -59, -66, -70, -72, -74, -79,
  115919. -83, -85, -90, -97, -114, -999, -999, -999}},
  115920. /* 250 Hz */
  115921. {{-999, -999, -999, -999, -999, -999, -110, -105,
  115922. -100, -95, -90, -86, -80, -75, -75, -79,
  115923. -80, -79, -80, -81, -82, -88, -95, -103,
  115924. -110, -999, -999, -999, -999, -999, -999, -999,
  115925. -999, -999, -999, -999, -999, -999, -999, -999,
  115926. -999, -999, -999, -999, -999, -999, -999, -999,
  115927. -999, -999, -999, -999, -999, -999, -999, -999},
  115928. {-999, -999, -999, -999, -108, -103, -98, -93,
  115929. -88, -83, -79, -78, -75, -71, -67, -68,
  115930. -73, -73, -72, -73, -75, -77, -80, -82,
  115931. -88, -93, -100, -107, -114, -999, -999, -999,
  115932. -999, -999, -999, -999, -999, -999, -999, -999,
  115933. -999, -999, -999, -999, -999, -999, -999, -999,
  115934. -999, -999, -999, -999, -999, -999, -999, -999},
  115935. {-999, -999, -999, -110, -105, -101, -96, -90,
  115936. -86, -81, -77, -73, -69, -66, -61, -62,
  115937. -66, -64, -62, -65, -66, -70, -72, -76,
  115938. -81, -80, -84, -90, -95, -102, -110, -999,
  115939. -999, -999, -999, -999, -999, -999, -999, -999,
  115940. -999, -999, -999, -999, -999, -999, -999, -999,
  115941. -999, -999, -999, -999, -999, -999, -999, -999},
  115942. {-999, -999, -999, -107, -103, -97, -92, -88,
  115943. -83, -79, -74, -70, -66, -59, -53, -58,
  115944. -62, -55, -54, -54, -54, -58, -61, -62,
  115945. -72, -70, -72, -75, -78, -80, -81, -80,
  115946. -83, -83, -88, -93, -100, -107, -115, -999,
  115947. -999, -999, -999, -999, -999, -999, -999, -999,
  115948. -999, -999, -999, -999, -999, -999, -999, -999},
  115949. {-999, -999, -999, -105, -100, -95, -90, -85,
  115950. -80, -75, -70, -66, -62, -56, -48, -44,
  115951. -48, -46, -46, -43, -46, -48, -48, -51,
  115952. -58, -58, -59, -60, -62, -62, -61, -61,
  115953. -65, -64, -65, -68, -70, -74, -75, -78,
  115954. -81, -86, -95, -110, -999, -999, -999, -999,
  115955. -999, -999, -999, -999, -999, -999, -999, -999},
  115956. {-999, -999, -105, -100, -95, -90, -85, -80,
  115957. -75, -70, -65, -61, -55, -49, -39, -33,
  115958. -40, -35, -32, -38, -40, -33, -35, -37,
  115959. -46, -41, -45, -44, -46, -42, -45, -46,
  115960. -52, -50, -50, -50, -54, -54, -55, -57,
  115961. -62, -64, -66, -68, -70, -76, -81, -90,
  115962. -100, -110, -999, -999, -999, -999, -999, -999}},
  115963. /* 354 hz */
  115964. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115965. -105, -98, -90, -85, -82, -83, -80, -78,
  115966. -84, -79, -80, -83, -87, -89, -91, -93,
  115967. -99, -106, -117, -999, -999, -999, -999, -999,
  115968. -999, -999, -999, -999, -999, -999, -999, -999,
  115969. -999, -999, -999, -999, -999, -999, -999, -999,
  115970. -999, -999, -999, -999, -999, -999, -999, -999},
  115971. {-999, -999, -999, -999, -999, -999, -999, -999,
  115972. -105, -98, -90, -85, -80, -75, -70, -68,
  115973. -74, -72, -74, -77, -80, -82, -85, -87,
  115974. -92, -89, -91, -95, -100, -106, -112, -999,
  115975. -999, -999, -999, -999, -999, -999, -999, -999,
  115976. -999, -999, -999, -999, -999, -999, -999, -999,
  115977. -999, -999, -999, -999, -999, -999, -999, -999},
  115978. {-999, -999, -999, -999, -999, -999, -999, -999,
  115979. -105, -98, -90, -83, -75, -71, -63, -64,
  115980. -67, -62, -64, -67, -70, -73, -77, -81,
  115981. -84, -83, -85, -89, -90, -93, -98, -104,
  115982. -109, -114, -999, -999, -999, -999, -999, -999,
  115983. -999, -999, -999, -999, -999, -999, -999, -999,
  115984. -999, -999, -999, -999, -999, -999, -999, -999},
  115985. {-999, -999, -999, -999, -999, -999, -999, -999,
  115986. -103, -96, -88, -81, -75, -68, -58, -54,
  115987. -56, -54, -56, -56, -58, -60, -63, -66,
  115988. -74, -69, -72, -72, -75, -74, -77, -81,
  115989. -81, -82, -84, -87, -93, -96, -99, -104,
  115990. -110, -999, -999, -999, -999, -999, -999, -999,
  115991. -999, -999, -999, -999, -999, -999, -999, -999},
  115992. {-999, -999, -999, -999, -999, -108, -102, -96,
  115993. -91, -85, -80, -74, -68, -60, -51, -46,
  115994. -48, -46, -43, -45, -47, -47, -49, -48,
  115995. -56, -53, -55, -58, -57, -63, -58, -60,
  115996. -66, -64, -67, -70, -70, -74, -77, -84,
  115997. -86, -89, -91, -93, -94, -101, -109, -118,
  115998. -999, -999, -999, -999, -999, -999, -999, -999},
  115999. {-999, -999, -999, -108, -103, -98, -93, -88,
  116000. -83, -78, -73, -68, -60, -53, -44, -35,
  116001. -38, -38, -34, -34, -36, -40, -41, -44,
  116002. -51, -45, -46, -47, -46, -54, -50, -49,
  116003. -50, -50, -50, -51, -54, -57, -58, -60,
  116004. -66, -66, -66, -64, -65, -68, -77, -82,
  116005. -87, -95, -110, -999, -999, -999, -999, -999}},
  116006. /* 500 Hz */
  116007. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116008. -107, -102, -97, -92, -87, -83, -78, -75,
  116009. -82, -79, -83, -85, -89, -92, -95, -98,
  116010. -101, -105, -109, -113, -999, -999, -999, -999,
  116011. -999, -999, -999, -999, -999, -999, -999, -999,
  116012. -999, -999, -999, -999, -999, -999, -999, -999,
  116013. -999, -999, -999, -999, -999, -999, -999, -999},
  116014. {-999, -999, -999, -999, -999, -999, -999, -106,
  116015. -100, -95, -90, -86, -81, -78, -74, -69,
  116016. -74, -74, -76, -79, -83, -84, -86, -89,
  116017. -92, -97, -93, -100, -103, -107, -110, -999,
  116018. -999, -999, -999, -999, -999, -999, -999, -999,
  116019. -999, -999, -999, -999, -999, -999, -999, -999,
  116020. -999, -999, -999, -999, -999, -999, -999, -999},
  116021. {-999, -999, -999, -999, -999, -999, -106, -100,
  116022. -95, -90, -87, -83, -80, -75, -69, -60,
  116023. -66, -66, -68, -70, -74, -78, -79, -81,
  116024. -81, -83, -84, -87, -93, -96, -99, -103,
  116025. -107, -110, -999, -999, -999, -999, -999, -999,
  116026. -999, -999, -999, -999, -999, -999, -999, -999,
  116027. -999, -999, -999, -999, -999, -999, -999, -999},
  116028. {-999, -999, -999, -999, -999, -108, -103, -98,
  116029. -93, -89, -85, -82, -78, -71, -62, -55,
  116030. -58, -58, -54, -54, -55, -59, -61, -62,
  116031. -70, -66, -66, -67, -70, -72, -75, -78,
  116032. -84, -84, -84, -88, -91, -90, -95, -98,
  116033. -102, -103, -106, -110, -999, -999, -999, -999,
  116034. -999, -999, -999, -999, -999, -999, -999, -999},
  116035. {-999, -999, -999, -999, -108, -103, -98, -94,
  116036. -90, -87, -82, -79, -73, -67, -58, -47,
  116037. -50, -45, -41, -45, -48, -44, -44, -49,
  116038. -54, -51, -48, -47, -49, -50, -51, -57,
  116039. -58, -60, -63, -69, -70, -69, -71, -74,
  116040. -78, -82, -90, -95, -101, -105, -110, -999,
  116041. -999, -999, -999, -999, -999, -999, -999, -999},
  116042. {-999, -999, -999, -105, -101, -97, -93, -90,
  116043. -85, -80, -77, -72, -65, -56, -48, -37,
  116044. -40, -36, -34, -40, -50, -47, -38, -41,
  116045. -47, -38, -35, -39, -38, -43, -40, -45,
  116046. -50, -45, -44, -47, -50, -55, -48, -48,
  116047. -52, -66, -70, -76, -82, -90, -97, -105,
  116048. -110, -999, -999, -999, -999, -999, -999, -999}},
  116049. /* 707 Hz */
  116050. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116051. -999, -108, -103, -98, -93, -86, -79, -76,
  116052. -83, -81, -85, -87, -89, -93, -98, -102,
  116053. -107, -112, -999, -999, -999, -999, -999, -999,
  116054. -999, -999, -999, -999, -999, -999, -999, -999,
  116055. -999, -999, -999, -999, -999, -999, -999, -999,
  116056. -999, -999, -999, -999, -999, -999, -999, -999},
  116057. {-999, -999, -999, -999, -999, -999, -999, -999,
  116058. -999, -108, -103, -98, -93, -86, -79, -71,
  116059. -77, -74, -77, -79, -81, -84, -85, -90,
  116060. -92, -93, -92, -98, -101, -108, -112, -999,
  116061. -999, -999, -999, -999, -999, -999, -999, -999,
  116062. -999, -999, -999, -999, -999, -999, -999, -999,
  116063. -999, -999, -999, -999, -999, -999, -999, -999},
  116064. {-999, -999, -999, -999, -999, -999, -999, -999,
  116065. -108, -103, -98, -93, -87, -78, -68, -65,
  116066. -66, -62, -65, -67, -70, -73, -75, -78,
  116067. -82, -82, -83, -84, -91, -93, -98, -102,
  116068. -106, -110, -999, -999, -999, -999, -999, -999,
  116069. -999, -999, -999, -999, -999, -999, -999, -999,
  116070. -999, -999, -999, -999, -999, -999, -999, -999},
  116071. {-999, -999, -999, -999, -999, -999, -999, -999,
  116072. -105, -100, -95, -90, -82, -74, -62, -57,
  116073. -58, -56, -51, -52, -52, -54, -54, -58,
  116074. -66, -59, -60, -63, -66, -69, -73, -79,
  116075. -83, -84, -80, -81, -81, -82, -88, -92,
  116076. -98, -105, -113, -999, -999, -999, -999, -999,
  116077. -999, -999, -999, -999, -999, -999, -999, -999},
  116078. {-999, -999, -999, -999, -999, -999, -999, -107,
  116079. -102, -97, -92, -84, -79, -69, -57, -47,
  116080. -52, -47, -44, -45, -50, -52, -42, -42,
  116081. -53, -43, -43, -48, -51, -56, -55, -52,
  116082. -57, -59, -61, -62, -67, -71, -78, -83,
  116083. -86, -94, -98, -103, -110, -999, -999, -999,
  116084. -999, -999, -999, -999, -999, -999, -999, -999},
  116085. {-999, -999, -999, -999, -999, -999, -105, -100,
  116086. -95, -90, -84, -78, -70, -61, -51, -41,
  116087. -40, -38, -40, -46, -52, -51, -41, -40,
  116088. -46, -40, -38, -38, -41, -46, -41, -46,
  116089. -47, -43, -43, -45, -41, -45, -56, -67,
  116090. -68, -83, -87, -90, -95, -102, -107, -113,
  116091. -999, -999, -999, -999, -999, -999, -999, -999}},
  116092. /* 1000 Hz */
  116093. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116094. -999, -109, -105, -101, -96, -91, -84, -77,
  116095. -82, -82, -85, -89, -94, -100, -106, -110,
  116096. -999, -999, -999, -999, -999, -999, -999, -999,
  116097. -999, -999, -999, -999, -999, -999, -999, -999,
  116098. -999, -999, -999, -999, -999, -999, -999, -999,
  116099. -999, -999, -999, -999, -999, -999, -999, -999},
  116100. {-999, -999, -999, -999, -999, -999, -999, -999,
  116101. -999, -106, -103, -98, -92, -85, -80, -71,
  116102. -75, -72, -76, -80, -84, -86, -89, -93,
  116103. -100, -107, -113, -999, -999, -999, -999, -999,
  116104. -999, -999, -999, -999, -999, -999, -999, -999,
  116105. -999, -999, -999, -999, -999, -999, -999, -999,
  116106. -999, -999, -999, -999, -999, -999, -999, -999},
  116107. {-999, -999, -999, -999, -999, -999, -999, -107,
  116108. -104, -101, -97, -92, -88, -84, -80, -64,
  116109. -66, -63, -64, -66, -69, -73, -77, -83,
  116110. -83, -86, -91, -98, -104, -111, -999, -999,
  116111. -999, -999, -999, -999, -999, -999, -999, -999,
  116112. -999, -999, -999, -999, -999, -999, -999, -999,
  116113. -999, -999, -999, -999, -999, -999, -999, -999},
  116114. {-999, -999, -999, -999, -999, -999, -999, -107,
  116115. -104, -101, -97, -92, -90, -84, -74, -57,
  116116. -58, -52, -55, -54, -50, -52, -50, -52,
  116117. -63, -62, -69, -76, -77, -78, -78, -79,
  116118. -82, -88, -94, -100, -106, -111, -999, -999,
  116119. -999, -999, -999, -999, -999, -999, -999, -999,
  116120. -999, -999, -999, -999, -999, -999, -999, -999},
  116121. {-999, -999, -999, -999, -999, -999, -106, -102,
  116122. -98, -95, -90, -85, -83, -78, -70, -50,
  116123. -50, -41, -44, -49, -47, -50, -50, -44,
  116124. -55, -46, -47, -48, -48, -54, -49, -49,
  116125. -58, -62, -71, -81, -87, -92, -97, -102,
  116126. -108, -114, -999, -999, -999, -999, -999, -999,
  116127. -999, -999, -999, -999, -999, -999, -999, -999},
  116128. {-999, -999, -999, -999, -999, -999, -106, -102,
  116129. -98, -95, -90, -85, -83, -78, -70, -45,
  116130. -43, -41, -47, -50, -51, -50, -49, -45,
  116131. -47, -41, -44, -41, -39, -43, -38, -37,
  116132. -40, -41, -44, -50, -58, -65, -73, -79,
  116133. -85, -92, -97, -101, -105, -109, -113, -999,
  116134. -999, -999, -999, -999, -999, -999, -999, -999}},
  116135. /* 1414 Hz */
  116136. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116137. -999, -999, -999, -107, -100, -95, -87, -81,
  116138. -85, -83, -88, -93, -100, -107, -114, -999,
  116139. -999, -999, -999, -999, -999, -999, -999, -999,
  116140. -999, -999, -999, -999, -999, -999, -999, -999,
  116141. -999, -999, -999, -999, -999, -999, -999, -999,
  116142. -999, -999, -999, -999, -999, -999, -999, -999},
  116143. {-999, -999, -999, -999, -999, -999, -999, -999,
  116144. -999, -999, -107, -101, -95, -88, -83, -76,
  116145. -73, -72, -79, -84, -90, -95, -100, -105,
  116146. -110, -115, -999, -999, -999, -999, -999, -999,
  116147. -999, -999, -999, -999, -999, -999, -999, -999,
  116148. -999, -999, -999, -999, -999, -999, -999, -999,
  116149. -999, -999, -999, -999, -999, -999, -999, -999},
  116150. {-999, -999, -999, -999, -999, -999, -999, -999,
  116151. -999, -999, -104, -98, -92, -87, -81, -70,
  116152. -65, -62, -67, -71, -74, -80, -85, -91,
  116153. -95, -99, -103, -108, -111, -114, -999, -999,
  116154. -999, -999, -999, -999, -999, -999, -999, -999,
  116155. -999, -999, -999, -999, -999, -999, -999, -999,
  116156. -999, -999, -999, -999, -999, -999, -999, -999},
  116157. {-999, -999, -999, -999, -999, -999, -999, -999,
  116158. -999, -999, -103, -97, -90, -85, -76, -60,
  116159. -56, -54, -60, -62, -61, -56, -63, -65,
  116160. -73, -74, -77, -75, -78, -81, -86, -87,
  116161. -88, -91, -94, -98, -103, -110, -999, -999,
  116162. -999, -999, -999, -999, -999, -999, -999, -999,
  116163. -999, -999, -999, -999, -999, -999, -999, -999},
  116164. {-999, -999, -999, -999, -999, -999, -999, -105,
  116165. -100, -97, -92, -86, -81, -79, -70, -57,
  116166. -51, -47, -51, -58, -60, -56, -53, -50,
  116167. -58, -52, -50, -50, -53, -55, -64, -69,
  116168. -71, -85, -82, -78, -81, -85, -95, -102,
  116169. -112, -999, -999, -999, -999, -999, -999, -999,
  116170. -999, -999, -999, -999, -999, -999, -999, -999},
  116171. {-999, -999, -999, -999, -999, -999, -999, -105,
  116172. -100, -97, -92, -85, -83, -79, -72, -49,
  116173. -40, -43, -43, -54, -56, -51, -50, -40,
  116174. -43, -38, -36, -35, -37, -38, -37, -44,
  116175. -54, -60, -57, -60, -70, -75, -84, -92,
  116176. -103, -112, -999, -999, -999, -999, -999, -999,
  116177. -999, -999, -999, -999, -999, -999, -999, -999}},
  116178. /* 2000 Hz */
  116179. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116180. -999, -999, -999, -110, -102, -95, -89, -82,
  116181. -83, -84, -90, -92, -99, -107, -113, -999,
  116182. -999, -999, -999, -999, -999, -999, -999, -999,
  116183. -999, -999, -999, -999, -999, -999, -999, -999,
  116184. -999, -999, -999, -999, -999, -999, -999, -999,
  116185. -999, -999, -999, -999, -999, -999, -999, -999},
  116186. {-999, -999, -999, -999, -999, -999, -999, -999,
  116187. -999, -999, -107, -101, -95, -89, -83, -72,
  116188. -74, -78, -85, -88, -88, -90, -92, -98,
  116189. -105, -111, -999, -999, -999, -999, -999, -999,
  116190. -999, -999, -999, -999, -999, -999, -999, -999,
  116191. -999, -999, -999, -999, -999, -999, -999, -999,
  116192. -999, -999, -999, -999, -999, -999, -999, -999},
  116193. {-999, -999, -999, -999, -999, -999, -999, -999,
  116194. -999, -109, -103, -97, -93, -87, -81, -70,
  116195. -70, -67, -75, -73, -76, -79, -81, -83,
  116196. -88, -89, -97, -103, -110, -999, -999, -999,
  116197. -999, -999, -999, -999, -999, -999, -999, -999,
  116198. -999, -999, -999, -999, -999, -999, -999, -999,
  116199. -999, -999, -999, -999, -999, -999, -999, -999},
  116200. {-999, -999, -999, -999, -999, -999, -999, -999,
  116201. -999, -107, -100, -94, -88, -83, -75, -63,
  116202. -59, -59, -63, -66, -60, -62, -67, -67,
  116203. -77, -76, -81, -88, -86, -92, -96, -102,
  116204. -109, -116, -999, -999, -999, -999, -999, -999,
  116205. -999, -999, -999, -999, -999, -999, -999, -999,
  116206. -999, -999, -999, -999, -999, -999, -999, -999},
  116207. {-999, -999, -999, -999, -999, -999, -999, -999,
  116208. -999, -105, -98, -92, -86, -81, -73, -56,
  116209. -52, -47, -55, -60, -58, -52, -51, -45,
  116210. -49, -50, -53, -54, -61, -71, -70, -69,
  116211. -78, -79, -87, -90, -96, -104, -112, -999,
  116212. -999, -999, -999, -999, -999, -999, -999, -999,
  116213. -999, -999, -999, -999, -999, -999, -999, -999},
  116214. {-999, -999, -999, -999, -999, -999, -999, -999,
  116215. -999, -103, -96, -90, -86, -78, -70, -51,
  116216. -42, -47, -48, -55, -54, -54, -53, -42,
  116217. -35, -28, -33, -38, -37, -44, -47, -49,
  116218. -54, -63, -68, -78, -82, -89, -94, -99,
  116219. -104, -109, -114, -999, -999, -999, -999, -999,
  116220. -999, -999, -999, -999, -999, -999, -999, -999}},
  116221. /* 2828 Hz */
  116222. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116223. -999, -999, -999, -999, -110, -100, -90, -79,
  116224. -85, -81, -82, -82, -89, -94, -99, -103,
  116225. -109, -115, -999, -999, -999, -999, -999, -999,
  116226. -999, -999, -999, -999, -999, -999, -999, -999,
  116227. -999, -999, -999, -999, -999, -999, -999, -999,
  116228. -999, -999, -999, -999, -999, -999, -999, -999},
  116229. {-999, -999, -999, -999, -999, -999, -999, -999,
  116230. -999, -999, -999, -999, -105, -97, -85, -72,
  116231. -74, -70, -70, -70, -76, -85, -91, -93,
  116232. -97, -103, -109, -115, -999, -999, -999, -999,
  116233. -999, -999, -999, -999, -999, -999, -999, -999,
  116234. -999, -999, -999, -999, -999, -999, -999, -999,
  116235. -999, -999, -999, -999, -999, -999, -999, -999},
  116236. {-999, -999, -999, -999, -999, -999, -999, -999,
  116237. -999, -999, -999, -999, -112, -93, -81, -68,
  116238. -62, -60, -60, -57, -63, -70, -77, -82,
  116239. -90, -93, -98, -104, -109, -113, -999, -999,
  116240. -999, -999, -999, -999, -999, -999, -999, -999,
  116241. -999, -999, -999, -999, -999, -999, -999, -999,
  116242. -999, -999, -999, -999, -999, -999, -999, -999},
  116243. {-999, -999, -999, -999, -999, -999, -999, -999,
  116244. -999, -999, -999, -113, -100, -93, -84, -63,
  116245. -58, -48, -53, -54, -52, -52, -57, -64,
  116246. -66, -76, -83, -81, -85, -85, -90, -95,
  116247. -98, -101, -103, -106, -108, -111, -999, -999,
  116248. -999, -999, -999, -999, -999, -999, -999, -999,
  116249. -999, -999, -999, -999, -999, -999, -999, -999},
  116250. {-999, -999, -999, -999, -999, -999, -999, -999,
  116251. -999, -999, -999, -105, -95, -86, -74, -53,
  116252. -50, -38, -43, -49, -43, -42, -39, -39,
  116253. -46, -52, -57, -56, -72, -69, -74, -81,
  116254. -87, -92, -94, -97, -99, -102, -105, -108,
  116255. -999, -999, -999, -999, -999, -999, -999, -999,
  116256. -999, -999, -999, -999, -999, -999, -999, -999},
  116257. {-999, -999, -999, -999, -999, -999, -999, -999,
  116258. -999, -999, -108, -99, -90, -76, -66, -45,
  116259. -43, -41, -44, -47, -43, -47, -40, -30,
  116260. -31, -31, -39, -33, -40, -41, -43, -53,
  116261. -59, -70, -73, -77, -79, -82, -84, -87,
  116262. -999, -999, -999, -999, -999, -999, -999, -999,
  116263. -999, -999, -999, -999, -999, -999, -999, -999}},
  116264. /* 4000 Hz */
  116265. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116266. -999, -999, -999, -999, -999, -110, -91, -76,
  116267. -75, -85, -93, -98, -104, -110, -999, -999,
  116268. -999, -999, -999, -999, -999, -999, -999, -999,
  116269. -999, -999, -999, -999, -999, -999, -999, -999,
  116270. -999, -999, -999, -999, -999, -999, -999, -999,
  116271. -999, -999, -999, -999, -999, -999, -999, -999},
  116272. {-999, -999, -999, -999, -999, -999, -999, -999,
  116273. -999, -999, -999, -999, -999, -110, -91, -70,
  116274. -70, -75, -86, -89, -94, -98, -101, -106,
  116275. -110, -999, -999, -999, -999, -999, -999, -999,
  116276. -999, -999, -999, -999, -999, -999, -999, -999,
  116277. -999, -999, -999, -999, -999, -999, -999, -999,
  116278. -999, -999, -999, -999, -999, -999, -999, -999},
  116279. {-999, -999, -999, -999, -999, -999, -999, -999,
  116280. -999, -999, -999, -999, -110, -95, -80, -60,
  116281. -65, -64, -74, -83, -88, -91, -95, -99,
  116282. -103, -107, -110, -999, -999, -999, -999, -999,
  116283. -999, -999, -999, -999, -999, -999, -999, -999,
  116284. -999, -999, -999, -999, -999, -999, -999, -999,
  116285. -999, -999, -999, -999, -999, -999, -999, -999},
  116286. {-999, -999, -999, -999, -999, -999, -999, -999,
  116287. -999, -999, -999, -999, -110, -95, -80, -58,
  116288. -55, -49, -66, -68, -71, -78, -78, -80,
  116289. -88, -85, -89, -97, -100, -105, -110, -999,
  116290. -999, -999, -999, -999, -999, -999, -999, -999,
  116291. -999, -999, -999, -999, -999, -999, -999, -999,
  116292. -999, -999, -999, -999, -999, -999, -999, -999},
  116293. {-999, -999, -999, -999, -999, -999, -999, -999,
  116294. -999, -999, -999, -999, -110, -95, -80, -53,
  116295. -52, -41, -59, -59, -49, -58, -56, -63,
  116296. -86, -79, -90, -93, -98, -103, -107, -112,
  116297. -999, -999, -999, -999, -999, -999, -999, -999,
  116298. -999, -999, -999, -999, -999, -999, -999, -999,
  116299. -999, -999, -999, -999, -999, -999, -999, -999},
  116300. {-999, -999, -999, -999, -999, -999, -999, -999,
  116301. -999, -999, -999, -110, -97, -91, -73, -45,
  116302. -40, -33, -53, -61, -49, -54, -50, -50,
  116303. -60, -52, -67, -74, -81, -92, -96, -100,
  116304. -105, -110, -999, -999, -999, -999, -999, -999,
  116305. -999, -999, -999, -999, -999, -999, -999, -999,
  116306. -999, -999, -999, -999, -999, -999, -999, -999}},
  116307. /* 5657 Hz */
  116308. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116309. -999, -999, -999, -113, -106, -99, -92, -77,
  116310. -80, -88, -97, -106, -115, -999, -999, -999,
  116311. -999, -999, -999, -999, -999, -999, -999, -999,
  116312. -999, -999, -999, -999, -999, -999, -999, -999,
  116313. -999, -999, -999, -999, -999, -999, -999, -999,
  116314. -999, -999, -999, -999, -999, -999, -999, -999},
  116315. {-999, -999, -999, -999, -999, -999, -999, -999,
  116316. -999, -999, -116, -109, -102, -95, -89, -74,
  116317. -72, -88, -87, -95, -102, -109, -116, -999,
  116318. -999, -999, -999, -999, -999, -999, -999, -999,
  116319. -999, -999, -999, -999, -999, -999, -999, -999,
  116320. -999, -999, -999, -999, -999, -999, -999, -999,
  116321. -999, -999, -999, -999, -999, -999, -999, -999},
  116322. {-999, -999, -999, -999, -999, -999, -999, -999,
  116323. -999, -999, -116, -109, -102, -95, -89, -75,
  116324. -66, -74, -77, -78, -86, -87, -90, -96,
  116325. -105, -115, -999, -999, -999, -999, -999, -999,
  116326. -999, -999, -999, -999, -999, -999, -999, -999,
  116327. -999, -999, -999, -999, -999, -999, -999, -999,
  116328. -999, -999, -999, -999, -999, -999, -999, -999},
  116329. {-999, -999, -999, -999, -999, -999, -999, -999,
  116330. -999, -999, -115, -108, -101, -94, -88, -66,
  116331. -56, -61, -70, -65, -78, -72, -83, -84,
  116332. -93, -98, -105, -110, -999, -999, -999, -999,
  116333. -999, -999, -999, -999, -999, -999, -999, -999,
  116334. -999, -999, -999, -999, -999, -999, -999, -999,
  116335. -999, -999, -999, -999, -999, -999, -999, -999},
  116336. {-999, -999, -999, -999, -999, -999, -999, -999,
  116337. -999, -999, -110, -105, -95, -89, -82, -57,
  116338. -52, -52, -59, -56, -59, -58, -69, -67,
  116339. -88, -82, -82, -89, -94, -100, -108, -999,
  116340. -999, -999, -999, -999, -999, -999, -999, -999,
  116341. -999, -999, -999, -999, -999, -999, -999, -999,
  116342. -999, -999, -999, -999, -999, -999, -999, -999},
  116343. {-999, -999, -999, -999, -999, -999, -999, -999,
  116344. -999, -110, -101, -96, -90, -83, -77, -54,
  116345. -43, -38, -50, -48, -52, -48, -42, -42,
  116346. -51, -52, -53, -59, -65, -71, -78, -85,
  116347. -95, -999, -999, -999, -999, -999, -999, -999,
  116348. -999, -999, -999, -999, -999, -999, -999, -999,
  116349. -999, -999, -999, -999, -999, -999, -999, -999}},
  116350. /* 8000 Hz */
  116351. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116352. -999, -999, -999, -999, -120, -105, -86, -68,
  116353. -78, -79, -90, -100, -110, -999, -999, -999,
  116354. -999, -999, -999, -999, -999, -999, -999, -999,
  116355. -999, -999, -999, -999, -999, -999, -999, -999,
  116356. -999, -999, -999, -999, -999, -999, -999, -999,
  116357. -999, -999, -999, -999, -999, -999, -999, -999},
  116358. {-999, -999, -999, -999, -999, -999, -999, -999,
  116359. -999, -999, -999, -999, -120, -105, -86, -66,
  116360. -73, -77, -88, -96, -105, -115, -999, -999,
  116361. -999, -999, -999, -999, -999, -999, -999, -999,
  116362. -999, -999, -999, -999, -999, -999, -999, -999,
  116363. -999, -999, -999, -999, -999, -999, -999, -999,
  116364. -999, -999, -999, -999, -999, -999, -999, -999},
  116365. {-999, -999, -999, -999, -999, -999, -999, -999,
  116366. -999, -999, -999, -120, -105, -92, -80, -61,
  116367. -64, -68, -80, -87, -92, -100, -110, -999,
  116368. -999, -999, -999, -999, -999, -999, -999, -999,
  116369. -999, -999, -999, -999, -999, -999, -999, -999,
  116370. -999, -999, -999, -999, -999, -999, -999, -999,
  116371. -999, -999, -999, -999, -999, -999, -999, -999},
  116372. {-999, -999, -999, -999, -999, -999, -999, -999,
  116373. -999, -999, -999, -120, -104, -91, -79, -52,
  116374. -60, -54, -64, -69, -77, -80, -82, -84,
  116375. -85, -87, -88, -90, -999, -999, -999, -999,
  116376. -999, -999, -999, -999, -999, -999, -999, -999,
  116377. -999, -999, -999, -999, -999, -999, -999, -999,
  116378. -999, -999, -999, -999, -999, -999, -999, -999},
  116379. {-999, -999, -999, -999, -999, -999, -999, -999,
  116380. -999, -999, -999, -118, -100, -87, -77, -49,
  116381. -50, -44, -58, -61, -61, -67, -65, -62,
  116382. -62, -62, -65, -68, -999, -999, -999, -999,
  116383. -999, -999, -999, -999, -999, -999, -999, -999,
  116384. -999, -999, -999, -999, -999, -999, -999, -999,
  116385. -999, -999, -999, -999, -999, -999, -999, -999},
  116386. {-999, -999, -999, -999, -999, -999, -999, -999,
  116387. -999, -999, -999, -115, -98, -84, -62, -49,
  116388. -44, -38, -46, -49, -49, -46, -39, -37,
  116389. -39, -40, -42, -43, -999, -999, -999, -999,
  116390. -999, -999, -999, -999, -999, -999, -999, -999,
  116391. -999, -999, -999, -999, -999, -999, -999, -999,
  116392. -999, -999, -999, -999, -999, -999, -999, -999}},
  116393. /* 11314 Hz */
  116394. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116395. -999, -999, -999, -999, -999, -110, -88, -74,
  116396. -77, -82, -82, -85, -90, -94, -99, -104,
  116397. -999, -999, -999, -999, -999, -999, -999, -999,
  116398. -999, -999, -999, -999, -999, -999, -999, -999,
  116399. -999, -999, -999, -999, -999, -999, -999, -999,
  116400. -999, -999, -999, -999, -999, -999, -999, -999},
  116401. {-999, -999, -999, -999, -999, -999, -999, -999,
  116402. -999, -999, -999, -999, -999, -110, -88, -66,
  116403. -70, -81, -80, -81, -84, -88, -91, -93,
  116404. -999, -999, -999, -999, -999, -999, -999, -999,
  116405. -999, -999, -999, -999, -999, -999, -999, -999,
  116406. -999, -999, -999, -999, -999, -999, -999, -999,
  116407. -999, -999, -999, -999, -999, -999, -999, -999},
  116408. {-999, -999, -999, -999, -999, -999, -999, -999,
  116409. -999, -999, -999, -999, -999, -110, -88, -61,
  116410. -63, -70, -71, -74, -77, -80, -83, -85,
  116411. -999, -999, -999, -999, -999, -999, -999, -999,
  116412. -999, -999, -999, -999, -999, -999, -999, -999,
  116413. -999, -999, -999, -999, -999, -999, -999, -999,
  116414. -999, -999, -999, -999, -999, -999, -999, -999},
  116415. {-999, -999, -999, -999, -999, -999, -999, -999,
  116416. -999, -999, -999, -999, -999, -110, -86, -62,
  116417. -63, -62, -62, -58, -52, -50, -50, -52,
  116418. -54, -999, -999, -999, -999, -999, -999, -999,
  116419. -999, -999, -999, -999, -999, -999, -999, -999,
  116420. -999, -999, -999, -999, -999, -999, -999, -999,
  116421. -999, -999, -999, -999, -999, -999, -999, -999},
  116422. {-999, -999, -999, -999, -999, -999, -999, -999,
  116423. -999, -999, -999, -999, -118, -108, -84, -53,
  116424. -50, -50, -50, -55, -47, -45, -40, -40,
  116425. -40, -999, -999, -999, -999, -999, -999, -999,
  116426. -999, -999, -999, -999, -999, -999, -999, -999,
  116427. -999, -999, -999, -999, -999, -999, -999, -999,
  116428. -999, -999, -999, -999, -999, -999, -999, -999},
  116429. {-999, -999, -999, -999, -999, -999, -999, -999,
  116430. -999, -999, -999, -999, -118, -100, -73, -43,
  116431. -37, -42, -43, -53, -38, -37, -35, -35,
  116432. -38, -999, -999, -999, -999, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -999, -999, -999,
  116434. -999, -999, -999, -999, -999, -999, -999, -999,
  116435. -999, -999, -999, -999, -999, -999, -999, -999}},
  116436. /* 16000 Hz */
  116437. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116438. -999, -999, -999, -110, -100, -91, -84, -74,
  116439. -80, -80, -80, -80, -80, -999, -999, -999,
  116440. -999, -999, -999, -999, -999, -999, -999, -999,
  116441. -999, -999, -999, -999, -999, -999, -999, -999,
  116442. -999, -999, -999, -999, -999, -999, -999, -999,
  116443. -999, -999, -999, -999, -999, -999, -999, -999},
  116444. {-999, -999, -999, -999, -999, -999, -999, -999,
  116445. -999, -999, -999, -110, -100, -91, -84, -74,
  116446. -68, -68, -68, -68, -68, -999, -999, -999,
  116447. -999, -999, -999, -999, -999, -999, -999, -999,
  116448. -999, -999, -999, -999, -999, -999, -999, -999,
  116449. -999, -999, -999, -999, -999, -999, -999, -999,
  116450. -999, -999, -999, -999, -999, -999, -999, -999},
  116451. {-999, -999, -999, -999, -999, -999, -999, -999,
  116452. -999, -999, -999, -110, -100, -86, -78, -70,
  116453. -60, -45, -30, -21, -999, -999, -999, -999,
  116454. -999, -999, -999, -999, -999, -999, -999, -999,
  116455. -999, -999, -999, -999, -999, -999, -999, -999,
  116456. -999, -999, -999, -999, -999, -999, -999, -999,
  116457. -999, -999, -999, -999, -999, -999, -999, -999},
  116458. {-999, -999, -999, -999, -999, -999, -999, -999,
  116459. -999, -999, -999, -110, -100, -87, -78, -67,
  116460. -48, -38, -29, -21, -999, -999, -999, -999,
  116461. -999, -999, -999, -999, -999, -999, -999, -999,
  116462. -999, -999, -999, -999, -999, -999, -999, -999,
  116463. -999, -999, -999, -999, -999, -999, -999, -999,
  116464. -999, -999, -999, -999, -999, -999, -999, -999},
  116465. {-999, -999, -999, -999, -999, -999, -999, -999,
  116466. -999, -999, -999, -110, -100, -86, -69, -56,
  116467. -45, -35, -33, -29, -999, -999, -999, -999,
  116468. -999, -999, -999, -999, -999, -999, -999, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999,
  116470. -999, -999, -999, -999, -999, -999, -999, -999,
  116471. -999, -999, -999, -999, -999, -999, -999, -999},
  116472. {-999, -999, -999, -999, -999, -999, -999, -999,
  116473. -999, -999, -999, -110, -100, -83, -71, -48,
  116474. -27, -38, -37, -34, -999, -999, -999, -999,
  116475. -999, -999, -999, -999, -999, -999, -999, -999,
  116476. -999, -999, -999, -999, -999, -999, -999, -999,
  116477. -999, -999, -999, -999, -999, -999, -999, -999,
  116478. -999, -999, -999, -999, -999, -999, -999, -999}}
  116479. };
  116480. #endif
  116481. /*** End of inlined file: masking.h ***/
  116482. #define NEGINF -9999.f
  116483. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116484. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116485. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116486. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116487. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116488. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116489. look->channels=vi->channels;
  116490. look->ampmax=-9999.;
  116491. look->gi=gi;
  116492. return(look);
  116493. }
  116494. void _vp_global_free(vorbis_look_psy_global *look){
  116495. if(look){
  116496. memset(look,0,sizeof(*look));
  116497. _ogg_free(look);
  116498. }
  116499. }
  116500. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116501. if(i){
  116502. memset(i,0,sizeof(*i));
  116503. _ogg_free(i);
  116504. }
  116505. }
  116506. void _vi_psy_free(vorbis_info_psy *i){
  116507. if(i){
  116508. memset(i,0,sizeof(*i));
  116509. _ogg_free(i);
  116510. }
  116511. }
  116512. static void min_curve(float *c,
  116513. float *c2){
  116514. int i;
  116515. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116516. }
  116517. static void max_curve(float *c,
  116518. float *c2){
  116519. int i;
  116520. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116521. }
  116522. static void attenuate_curve(float *c,float att){
  116523. int i;
  116524. for(i=0;i<EHMER_MAX;i++)
  116525. c[i]+=att;
  116526. }
  116527. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116528. float center_boost, float center_decay_rate){
  116529. int i,j,k,m;
  116530. float ath[EHMER_MAX];
  116531. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116532. float athc[P_LEVELS][EHMER_MAX];
  116533. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116534. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116535. memset(workc,0,sizeof(workc));
  116536. for(i=0;i<P_BANDS;i++){
  116537. /* we add back in the ATH to avoid low level curves falling off to
  116538. -infinity and unnecessarily cutting off high level curves in the
  116539. curve limiting (last step). */
  116540. /* A half-band's settings must be valid over the whole band, and
  116541. it's better to mask too little than too much */
  116542. int ath_offset=i*4;
  116543. for(j=0;j<EHMER_MAX;j++){
  116544. float min=999.;
  116545. for(k=0;k<4;k++)
  116546. if(j+k+ath_offset<MAX_ATH){
  116547. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116548. }else{
  116549. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116550. }
  116551. ath[j]=min;
  116552. }
  116553. /* copy curves into working space, replicate the 50dB curve to 30
  116554. and 40, replicate the 100dB curve to 110 */
  116555. for(j=0;j<6;j++)
  116556. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116557. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116558. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116559. /* apply centered curve boost/decay */
  116560. for(j=0;j<P_LEVELS;j++){
  116561. for(k=0;k<EHMER_MAX;k++){
  116562. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116563. if(adj<0. && center_boost>0)adj=0.;
  116564. if(adj>0. && center_boost<0)adj=0.;
  116565. workc[i][j][k]+=adj;
  116566. }
  116567. }
  116568. /* normalize curves so the driving amplitude is 0dB */
  116569. /* make temp curves with the ATH overlayed */
  116570. for(j=0;j<P_LEVELS;j++){
  116571. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116572. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116573. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116574. max_curve(athc[j],workc[i][j]);
  116575. }
  116576. /* Now limit the louder curves.
  116577. the idea is this: We don't know what the playback attenuation
  116578. will be; 0dB SL moves every time the user twiddles the volume
  116579. knob. So that means we have to use a single 'most pessimal' curve
  116580. for all masking amplitudes, right? Wrong. The *loudest* sound
  116581. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116582. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116583. etc... */
  116584. for(j=1;j<P_LEVELS;j++){
  116585. min_curve(athc[j],athc[j-1]);
  116586. min_curve(workc[i][j],athc[j]);
  116587. }
  116588. }
  116589. for(i=0;i<P_BANDS;i++){
  116590. int hi_curve,lo_curve,bin;
  116591. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116592. /* low frequency curves are measured with greater resolution than
  116593. the MDCT/FFT will actually give us; we want the curve applied
  116594. to the tone data to be pessimistic and thus apply the minimum
  116595. masking possible for a given bin. That means that a single bin
  116596. could span more than one octave and that the curve will be a
  116597. composite of multiple octaves. It also may mean that a single
  116598. bin may span > an eighth of an octave and that the eighth
  116599. octave values may also be composited. */
  116600. /* which octave curves will we be compositing? */
  116601. bin=floor(fromOC(i*.5)/binHz);
  116602. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116603. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116604. if(lo_curve>i)lo_curve=i;
  116605. if(lo_curve<0)lo_curve=0;
  116606. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116607. for(m=0;m<P_LEVELS;m++){
  116608. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116609. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116610. /* render the curve into bins, then pull values back into curve.
  116611. The point is that any inherent subsampling aliasing results in
  116612. a safe minimum */
  116613. for(k=lo_curve;k<=hi_curve;k++){
  116614. int l=0;
  116615. for(j=0;j<EHMER_MAX;j++){
  116616. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116617. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116618. if(lo_bin<0)lo_bin=0;
  116619. if(lo_bin>n)lo_bin=n;
  116620. if(lo_bin<l)l=lo_bin;
  116621. if(hi_bin<0)hi_bin=0;
  116622. if(hi_bin>n)hi_bin=n;
  116623. for(;l<hi_bin && l<n;l++)
  116624. if(brute_buffer[l]>workc[k][m][j])
  116625. brute_buffer[l]=workc[k][m][j];
  116626. }
  116627. for(;l<n;l++)
  116628. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116629. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116630. }
  116631. /* be equally paranoid about being valid up to next half ocatve */
  116632. if(i+1<P_BANDS){
  116633. int l=0;
  116634. k=i+1;
  116635. for(j=0;j<EHMER_MAX;j++){
  116636. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116637. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116638. if(lo_bin<0)lo_bin=0;
  116639. if(lo_bin>n)lo_bin=n;
  116640. if(lo_bin<l)l=lo_bin;
  116641. if(hi_bin<0)hi_bin=0;
  116642. if(hi_bin>n)hi_bin=n;
  116643. for(;l<hi_bin && l<n;l++)
  116644. if(brute_buffer[l]>workc[k][m][j])
  116645. brute_buffer[l]=workc[k][m][j];
  116646. }
  116647. for(;l<n;l++)
  116648. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116649. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116650. }
  116651. for(j=0;j<EHMER_MAX;j++){
  116652. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116653. if(bin<0){
  116654. ret[i][m][j+2]=-999.;
  116655. }else{
  116656. if(bin>=n){
  116657. ret[i][m][j+2]=-999.;
  116658. }else{
  116659. ret[i][m][j+2]=brute_buffer[bin];
  116660. }
  116661. }
  116662. }
  116663. /* add fenceposts */
  116664. for(j=0;j<EHMER_OFFSET;j++)
  116665. if(ret[i][m][j+2]>-200.f)break;
  116666. ret[i][m][0]=j;
  116667. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116668. if(ret[i][m][j+2]>-200.f)
  116669. break;
  116670. ret[i][m][1]=j;
  116671. }
  116672. }
  116673. return(ret);
  116674. }
  116675. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116676. vorbis_info_psy_global *gi,int n,long rate){
  116677. long i,j,lo=-99,hi=1;
  116678. long maxoc;
  116679. memset(p,0,sizeof(*p));
  116680. p->eighth_octave_lines=gi->eighth_octave_lines;
  116681. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116682. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116683. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116684. p->total_octave_lines=maxoc-p->firstoc+1;
  116685. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116686. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116687. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116688. p->vi=vi;
  116689. p->n=n;
  116690. p->rate=rate;
  116691. /* AoTuV HF weighting */
  116692. p->m_val = 1.;
  116693. if(rate < 26000) p->m_val = 0;
  116694. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116695. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116696. /* set up the lookups for a given blocksize and sample rate */
  116697. for(i=0,j=0;i<MAX_ATH-1;i++){
  116698. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116699. float base=ATH[i];
  116700. if(j<endpos){
  116701. float delta=(ATH[i+1]-base)/(endpos-j);
  116702. for(;j<endpos && j<n;j++){
  116703. p->ath[j]=base+100.;
  116704. base+=delta;
  116705. }
  116706. }
  116707. }
  116708. for(i=0;i<n;i++){
  116709. float bark=toBARK(rate/(2*n)*i);
  116710. for(;lo+vi->noisewindowlomin<i &&
  116711. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116712. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116713. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116714. p->bark[i]=((lo-1)<<16)+(hi-1);
  116715. }
  116716. for(i=0;i<n;i++)
  116717. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116718. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116719. vi->tone_centerboost,vi->tone_decay);
  116720. /* set up rolling noise median */
  116721. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116722. for(i=0;i<P_NOISECURVES;i++)
  116723. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116724. for(i=0;i<n;i++){
  116725. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116726. int inthalfoc;
  116727. float del;
  116728. if(halfoc<0)halfoc=0;
  116729. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116730. inthalfoc=(int)halfoc;
  116731. del=halfoc-inthalfoc;
  116732. for(j=0;j<P_NOISECURVES;j++)
  116733. p->noiseoffset[j][i]=
  116734. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116735. p->vi->noiseoff[j][inthalfoc+1]*del;
  116736. }
  116737. #if 0
  116738. {
  116739. static int ls=0;
  116740. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116741. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116742. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116743. }
  116744. #endif
  116745. }
  116746. void _vp_psy_clear(vorbis_look_psy *p){
  116747. int i,j;
  116748. if(p){
  116749. if(p->ath)_ogg_free(p->ath);
  116750. if(p->octave)_ogg_free(p->octave);
  116751. if(p->bark)_ogg_free(p->bark);
  116752. if(p->tonecurves){
  116753. for(i=0;i<P_BANDS;i++){
  116754. for(j=0;j<P_LEVELS;j++){
  116755. _ogg_free(p->tonecurves[i][j]);
  116756. }
  116757. _ogg_free(p->tonecurves[i]);
  116758. }
  116759. _ogg_free(p->tonecurves);
  116760. }
  116761. if(p->noiseoffset){
  116762. for(i=0;i<P_NOISECURVES;i++){
  116763. _ogg_free(p->noiseoffset[i]);
  116764. }
  116765. _ogg_free(p->noiseoffset);
  116766. }
  116767. memset(p,0,sizeof(*p));
  116768. }
  116769. }
  116770. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116771. static void seed_curve(float *seed,
  116772. const float **curves,
  116773. float amp,
  116774. int oc, int n,
  116775. int linesper,float dBoffset){
  116776. int i,post1;
  116777. int seedptr;
  116778. const float *posts,*curve;
  116779. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116780. choice=max(choice,0);
  116781. choice=min(choice,P_LEVELS-1);
  116782. posts=curves[choice];
  116783. curve=posts+2;
  116784. post1=(int)posts[1];
  116785. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116786. for(i=posts[0];i<post1;i++){
  116787. if(seedptr>0){
  116788. float lin=amp+curve[i];
  116789. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116790. }
  116791. seedptr+=linesper;
  116792. if(seedptr>=n)break;
  116793. }
  116794. }
  116795. static void seed_loop(vorbis_look_psy *p,
  116796. const float ***curves,
  116797. const float *f,
  116798. const float *flr,
  116799. float *seed,
  116800. float specmax){
  116801. vorbis_info_psy *vi=p->vi;
  116802. long n=p->n,i;
  116803. float dBoffset=vi->max_curve_dB-specmax;
  116804. /* prime the working vector with peak values */
  116805. for(i=0;i<n;i++){
  116806. float max=f[i];
  116807. long oc=p->octave[i];
  116808. while(i+1<n && p->octave[i+1]==oc){
  116809. i++;
  116810. if(f[i]>max)max=f[i];
  116811. }
  116812. if(max+6.f>flr[i]){
  116813. oc=oc>>p->shiftoc;
  116814. if(oc>=P_BANDS)oc=P_BANDS-1;
  116815. if(oc<0)oc=0;
  116816. seed_curve(seed,
  116817. curves[oc],
  116818. max,
  116819. p->octave[i]-p->firstoc,
  116820. p->total_octave_lines,
  116821. p->eighth_octave_lines,
  116822. dBoffset);
  116823. }
  116824. }
  116825. }
  116826. static void seed_chase(float *seeds, int linesper, long n){
  116827. long *posstack=(long*)alloca(n*sizeof(*posstack));
  116828. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  116829. long stack=0;
  116830. long pos=0;
  116831. long i;
  116832. for(i=0;i<n;i++){
  116833. if(stack<2){
  116834. posstack[stack]=i;
  116835. ampstack[stack++]=seeds[i];
  116836. }else{
  116837. while(1){
  116838. if(seeds[i]<ampstack[stack-1]){
  116839. posstack[stack]=i;
  116840. ampstack[stack++]=seeds[i];
  116841. break;
  116842. }else{
  116843. if(i<posstack[stack-1]+linesper){
  116844. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  116845. i<posstack[stack-2]+linesper){
  116846. /* we completely overlap, making stack-1 irrelevant. pop it */
  116847. stack--;
  116848. continue;
  116849. }
  116850. }
  116851. posstack[stack]=i;
  116852. ampstack[stack++]=seeds[i];
  116853. break;
  116854. }
  116855. }
  116856. }
  116857. }
  116858. /* the stack now contains only the positions that are relevant. Scan
  116859. 'em straight through */
  116860. for(i=0;i<stack;i++){
  116861. long endpos;
  116862. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  116863. endpos=posstack[i+1];
  116864. }else{
  116865. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  116866. discarded in short frames */
  116867. }
  116868. if(endpos>n)endpos=n;
  116869. for(;pos<endpos;pos++)
  116870. seeds[pos]=ampstack[i];
  116871. }
  116872. /* there. Linear time. I now remember this was on a problem set I
  116873. had in Grad Skool... I didn't solve it at the time ;-) */
  116874. }
  116875. /* bleaugh, this is more complicated than it needs to be */
  116876. #include<stdio.h>
  116877. static void max_seeds(vorbis_look_psy *p,
  116878. float *seed,
  116879. float *flr){
  116880. long n=p->total_octave_lines;
  116881. int linesper=p->eighth_octave_lines;
  116882. long linpos=0;
  116883. long pos;
  116884. seed_chase(seed,linesper,n); /* for masking */
  116885. pos=p->octave[0]-p->firstoc-(linesper>>1);
  116886. while(linpos+1<p->n){
  116887. float minV=seed[pos];
  116888. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  116889. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  116890. while(pos+1<=end){
  116891. pos++;
  116892. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  116893. minV=seed[pos];
  116894. }
  116895. end=pos+p->firstoc;
  116896. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  116897. if(flr[linpos]<minV)flr[linpos]=minV;
  116898. }
  116899. {
  116900. float minV=seed[p->total_octave_lines-1];
  116901. for(;linpos<p->n;linpos++)
  116902. if(flr[linpos]<minV)flr[linpos]=minV;
  116903. }
  116904. }
  116905. static void bark_noise_hybridmp(int n,const long *b,
  116906. const float *f,
  116907. float *noise,
  116908. const float offset,
  116909. const int fixed){
  116910. float *N=(float*) alloca(n*sizeof(*N));
  116911. float *X=(float*) alloca(n*sizeof(*N));
  116912. float *XX=(float*) alloca(n*sizeof(*N));
  116913. float *Y=(float*) alloca(n*sizeof(*N));
  116914. float *XY=(float*) alloca(n*sizeof(*N));
  116915. float tN, tX, tXX, tY, tXY;
  116916. int i;
  116917. int lo, hi;
  116918. float R, A, B, D;
  116919. float w, x, y;
  116920. tN = tX = tXX = tY = tXY = 0.f;
  116921. y = f[0] + offset;
  116922. if (y < 1.f) y = 1.f;
  116923. w = y * y * .5;
  116924. tN += w;
  116925. tX += w;
  116926. tY += w * y;
  116927. N[0] = tN;
  116928. X[0] = tX;
  116929. XX[0] = tXX;
  116930. Y[0] = tY;
  116931. XY[0] = tXY;
  116932. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  116933. y = f[i] + offset;
  116934. if (y < 1.f) y = 1.f;
  116935. w = y * y;
  116936. tN += w;
  116937. tX += w * x;
  116938. tXX += w * x * x;
  116939. tY += w * y;
  116940. tXY += w * x * y;
  116941. N[i] = tN;
  116942. X[i] = tX;
  116943. XX[i] = tXX;
  116944. Y[i] = tY;
  116945. XY[i] = tXY;
  116946. }
  116947. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116948. lo = b[i] >> 16;
  116949. if( lo>=0 ) break;
  116950. hi = b[i] & 0xffff;
  116951. tN = N[hi] + N[-lo];
  116952. tX = X[hi] - X[-lo];
  116953. tXX = XX[hi] + XX[-lo];
  116954. tY = Y[hi] + Y[-lo];
  116955. tXY = XY[hi] - XY[-lo];
  116956. A = tY * tXX - tX * tXY;
  116957. B = tN * tXY - tX * tY;
  116958. D = tN * tXX - tX * tX;
  116959. R = (A + x * B) / D;
  116960. if (R < 0.f)
  116961. R = 0.f;
  116962. noise[i] = R - offset;
  116963. }
  116964. for ( ;; i++, x += 1.f) {
  116965. lo = b[i] >> 16;
  116966. hi = b[i] & 0xffff;
  116967. if(hi>=n)break;
  116968. tN = N[hi] - N[lo];
  116969. tX = X[hi] - X[lo];
  116970. tXX = XX[hi] - XX[lo];
  116971. tY = Y[hi] - Y[lo];
  116972. tXY = XY[hi] - XY[lo];
  116973. A = tY * tXX - tX * tXY;
  116974. B = tN * tXY - tX * tY;
  116975. D = tN * tXX - tX * tX;
  116976. R = (A + x * B) / D;
  116977. if (R < 0.f) R = 0.f;
  116978. noise[i] = R - offset;
  116979. }
  116980. for ( ; i < n; i++, x += 1.f) {
  116981. R = (A + x * B) / D;
  116982. if (R < 0.f) R = 0.f;
  116983. noise[i] = R - offset;
  116984. }
  116985. if (fixed <= 0) return;
  116986. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116987. hi = i + fixed / 2;
  116988. lo = hi - fixed;
  116989. if(lo>=0)break;
  116990. tN = N[hi] + N[-lo];
  116991. tX = X[hi] - X[-lo];
  116992. tXX = XX[hi] + XX[-lo];
  116993. tY = Y[hi] + Y[-lo];
  116994. tXY = XY[hi] - XY[-lo];
  116995. A = tY * tXX - tX * tXY;
  116996. B = tN * tXY - tX * tY;
  116997. D = tN * tXX - tX * tX;
  116998. R = (A + x * B) / D;
  116999. if (R - offset < noise[i]) noise[i] = R - offset;
  117000. }
  117001. for ( ;; i++, x += 1.f) {
  117002. hi = i + fixed / 2;
  117003. lo = hi - fixed;
  117004. if(hi>=n)break;
  117005. tN = N[hi] - N[lo];
  117006. tX = X[hi] - X[lo];
  117007. tXX = XX[hi] - XX[lo];
  117008. tY = Y[hi] - Y[lo];
  117009. tXY = XY[hi] - XY[lo];
  117010. A = tY * tXX - tX * tXY;
  117011. B = tN * tXY - tX * tY;
  117012. D = tN * tXX - tX * tX;
  117013. R = (A + x * B) / D;
  117014. if (R - offset < noise[i]) noise[i] = R - offset;
  117015. }
  117016. for ( ; i < n; i++, x += 1.f) {
  117017. R = (A + x * B) / D;
  117018. if (R - offset < noise[i]) noise[i] = R - offset;
  117019. }
  117020. }
  117021. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117022. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117023. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117024. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117025. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117026. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117027. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117028. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117029. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117030. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117031. 973377.F, 913981.F, 858210.F, 805842.F,
  117032. 756669.F, 710497.F, 667142.F, 626433.F,
  117033. 588208.F, 552316.F, 518613.F, 486967.F,
  117034. 457252.F, 429351.F, 403152.F, 378551.F,
  117035. 355452.F, 333762.F, 313396.F, 294273.F,
  117036. 276316.F, 259455.F, 243623.F, 228757.F,
  117037. 214798.F, 201691.F, 189384.F, 177828.F,
  117038. 166977.F, 156788.F, 147221.F, 138237.F,
  117039. 129802.F, 121881.F, 114444.F, 107461.F,
  117040. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117041. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117042. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117043. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117044. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117045. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117046. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117047. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117048. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117049. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117050. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117051. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117052. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117053. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117054. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117055. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117056. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117057. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117058. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117059. 842.910F, 791.475F, 743.179F, 697.830F,
  117060. 655.249F, 615.265F, 577.722F, 542.469F,
  117061. 509.367F, 478.286F, 449.101F, 421.696F,
  117062. 395.964F, 371.803F, 349.115F, 327.812F,
  117063. 307.809F, 289.026F, 271.390F, 254.830F,
  117064. 239.280F, 224.679F, 210.969F, 198.096F,
  117065. 186.008F, 174.658F, 164.000F, 153.993F,
  117066. 144.596F, 135.773F, 127.488F, 119.708F,
  117067. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117068. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117069. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117070. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117071. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117072. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117073. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117074. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117075. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117076. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117077. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117078. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117079. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117080. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117081. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117082. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117083. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117084. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117085. 1.20790F, 1.13419F, 1.06499F, 1.F
  117086. };
  117087. void _vp_remove_floor(vorbis_look_psy *p,
  117088. float *mdct,
  117089. int *codedflr,
  117090. float *residue,
  117091. int sliding_lowpass){
  117092. int i,n=p->n;
  117093. if(sliding_lowpass>n)sliding_lowpass=n;
  117094. for(i=0;i<sliding_lowpass;i++){
  117095. residue[i]=
  117096. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117097. }
  117098. for(;i<n;i++)
  117099. residue[i]=0.;
  117100. }
  117101. void _vp_noisemask(vorbis_look_psy *p,
  117102. float *logmdct,
  117103. float *logmask){
  117104. int i,n=p->n;
  117105. float *work=(float*) alloca(n*sizeof(*work));
  117106. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117107. 140.,-1);
  117108. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117109. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117110. p->vi->noisewindowfixed);
  117111. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117112. #if 0
  117113. {
  117114. static int seq=0;
  117115. float work2[n];
  117116. for(i=0;i<n;i++){
  117117. work2[i]=logmask[i]+work[i];
  117118. }
  117119. if(seq&1)
  117120. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117121. else
  117122. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117123. if(seq&1)
  117124. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117125. else
  117126. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117127. seq++;
  117128. }
  117129. #endif
  117130. for(i=0;i<n;i++){
  117131. int dB=logmask[i]+.5;
  117132. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117133. if(dB<0)dB=0;
  117134. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117135. }
  117136. }
  117137. void _vp_tonemask(vorbis_look_psy *p,
  117138. float *logfft,
  117139. float *logmask,
  117140. float global_specmax,
  117141. float local_specmax){
  117142. int i,n=p->n;
  117143. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117144. float att=local_specmax+p->vi->ath_adjatt;
  117145. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117146. /* set the ATH (floating below localmax, not global max by a
  117147. specified att) */
  117148. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117149. for(i=0;i<n;i++)
  117150. logmask[i]=p->ath[i]+att;
  117151. /* tone masking */
  117152. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117153. max_seeds(p,seed,logmask);
  117154. }
  117155. void _vp_offset_and_mix(vorbis_look_psy *p,
  117156. float *noise,
  117157. float *tone,
  117158. int offset_select,
  117159. float *logmask,
  117160. float *mdct,
  117161. float *logmdct){
  117162. int i,n=p->n;
  117163. float de, coeffi, cx;/* AoTuV */
  117164. float toneatt=p->vi->tone_masteratt[offset_select];
  117165. cx = p->m_val;
  117166. for(i=0;i<n;i++){
  117167. float val= noise[i]+p->noiseoffset[offset_select][i];
  117168. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117169. logmask[i]=max(val,tone[i]+toneatt);
  117170. /* AoTuV */
  117171. /** @ M1 **
  117172. The following codes improve a noise problem.
  117173. A fundamental idea uses the value of masking and carries out
  117174. the relative compensation of the MDCT.
  117175. However, this code is not perfect and all noise problems cannot be solved.
  117176. by Aoyumi @ 2004/04/18
  117177. */
  117178. if(offset_select == 1) {
  117179. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117180. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117181. if(val > coeffi){
  117182. /* mdct value is > -17.2 dB below floor */
  117183. de = 1.0-((val-coeffi)*0.005*cx);
  117184. /* pro-rated attenuation:
  117185. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117186. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117187. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117188. etc... */
  117189. if(de < 0) de = 0.0001;
  117190. }else
  117191. /* mdct value is <= -17.2 dB below floor */
  117192. de = 1.0-((val-coeffi)*0.0003*cx);
  117193. /* pro-rated attenuation:
  117194. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117195. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117196. etc... */
  117197. mdct[i] *= de;
  117198. }
  117199. }
  117200. }
  117201. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117202. vorbis_info *vi=vd->vi;
  117203. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117204. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117205. int n=ci->blocksizes[vd->W]/2;
  117206. float secs=(float)n/vi->rate;
  117207. amp+=secs*gi->ampmax_att_per_sec;
  117208. if(amp<-9999)amp=-9999;
  117209. return(amp);
  117210. }
  117211. static void couple_lossless(float A, float B,
  117212. float *qA, float *qB){
  117213. int test1=fabs(*qA)>fabs(*qB);
  117214. test1-= fabs(*qA)<fabs(*qB);
  117215. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117216. if(test1==1){
  117217. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117218. }else{
  117219. float temp=*qB;
  117220. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117221. *qA=temp;
  117222. }
  117223. if(*qB>fabs(*qA)*1.9999f){
  117224. *qB= -fabs(*qA)*2.f;
  117225. *qA= -*qA;
  117226. }
  117227. }
  117228. static float hypot_lookup[32]={
  117229. -0.009935, -0.011245, -0.012726, -0.014397,
  117230. -0.016282, -0.018407, -0.020800, -0.023494,
  117231. -0.026522, -0.029923, -0.033737, -0.038010,
  117232. -0.042787, -0.048121, -0.054064, -0.060671,
  117233. -0.068000, -0.076109, -0.085054, -0.094892,
  117234. -0.105675, -0.117451, -0.130260, -0.144134,
  117235. -0.159093, -0.175146, -0.192286, -0.210490,
  117236. -0.229718, -0.249913, -0.271001, -0.292893};
  117237. static void precomputed_couple_point(float premag,
  117238. int floorA,int floorB,
  117239. float *mag, float *ang){
  117240. int test=(floorA>floorB)-1;
  117241. int offset=31-abs(floorA-floorB);
  117242. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117243. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117244. *mag=premag*floormag;
  117245. *ang=0.f;
  117246. }
  117247. /* just like below, this is currently set up to only do
  117248. single-step-depth coupling. Otherwise, we'd have to do more
  117249. copying (which will be inevitable later) */
  117250. /* doing the real circular magnitude calculation is audibly superior
  117251. to (A+B)/sqrt(2) */
  117252. static float dipole_hypot(float a, float b){
  117253. if(a>0.){
  117254. if(b>0.)return sqrt(a*a+b*b);
  117255. if(a>-b)return sqrt(a*a-b*b);
  117256. return -sqrt(b*b-a*a);
  117257. }
  117258. if(b<0.)return -sqrt(a*a+b*b);
  117259. if(-a>b)return -sqrt(a*a-b*b);
  117260. return sqrt(b*b-a*a);
  117261. }
  117262. static float round_hypot(float a, float b){
  117263. if(a>0.){
  117264. if(b>0.)return sqrt(a*a+b*b);
  117265. if(a>-b)return sqrt(a*a+b*b);
  117266. return -sqrt(b*b+a*a);
  117267. }
  117268. if(b<0.)return -sqrt(a*a+b*b);
  117269. if(-a>b)return -sqrt(a*a+b*b);
  117270. return sqrt(b*b+a*a);
  117271. }
  117272. /* revert to round hypot for now */
  117273. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117274. vorbis_info_psy_global *g,
  117275. vorbis_look_psy *p,
  117276. vorbis_info_mapping0 *vi,
  117277. float **mdct){
  117278. int i,j,n=p->n;
  117279. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117280. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117281. for(i=0;i<vi->coupling_steps;i++){
  117282. float *mdctM=mdct[vi->coupling_mag[i]];
  117283. float *mdctA=mdct[vi->coupling_ang[i]];
  117284. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117285. for(j=0;j<limit;j++)
  117286. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117287. for(;j<n;j++)
  117288. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117289. }
  117290. return(ret);
  117291. }
  117292. /* this is for per-channel noise normalization */
  117293. static int apsort(const void *a, const void *b){
  117294. float f1=fabs(**(float**)a);
  117295. float f2=fabs(**(float**)b);
  117296. return (f1<f2)-(f1>f2);
  117297. }
  117298. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117299. vorbis_look_psy *p,
  117300. vorbis_info_mapping0 *vi,
  117301. float **mags){
  117302. if(p->vi->normal_point_p){
  117303. int i,j,k,n=p->n;
  117304. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117305. int partition=p->vi->normal_partition;
  117306. float **work=(float**) alloca(sizeof(*work)*partition);
  117307. for(i=0;i<vi->coupling_steps;i++){
  117308. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117309. for(j=0;j<n;j+=partition){
  117310. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117311. qsort(work,partition,sizeof(*work),apsort);
  117312. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117313. }
  117314. }
  117315. return(ret);
  117316. }
  117317. return(NULL);
  117318. }
  117319. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117320. float *magnitudes,int *sortedindex){
  117321. int i,j,n=p->n;
  117322. vorbis_info_psy *vi=p->vi;
  117323. int partition=vi->normal_partition;
  117324. float **work=(float**) alloca(sizeof(*work)*partition);
  117325. int start=vi->normal_start;
  117326. for(j=start;j<n;j+=partition){
  117327. if(j+partition>n)partition=n-j;
  117328. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117329. qsort(work,partition,sizeof(*work),apsort);
  117330. for(i=0;i<partition;i++){
  117331. sortedindex[i+j-start]=work[i]-magnitudes;
  117332. }
  117333. }
  117334. }
  117335. void _vp_noise_normalize(vorbis_look_psy *p,
  117336. float *in,float *out,int *sortedindex){
  117337. int flag=0,i,j=0,n=p->n;
  117338. vorbis_info_psy *vi=p->vi;
  117339. int partition=vi->normal_partition;
  117340. int start=vi->normal_start;
  117341. if(start>n)start=n;
  117342. if(vi->normal_channel_p){
  117343. for(;j<start;j++)
  117344. out[j]=rint(in[j]);
  117345. for(;j+partition<=n;j+=partition){
  117346. float acc=0.;
  117347. int k;
  117348. for(i=j;i<j+partition;i++)
  117349. acc+=in[i]*in[i];
  117350. for(i=0;i<partition;i++){
  117351. k=sortedindex[i+j-start];
  117352. if(in[k]*in[k]>=.25f){
  117353. out[k]=rint(in[k]);
  117354. acc-=in[k]*in[k];
  117355. flag=1;
  117356. }else{
  117357. if(acc<vi->normal_thresh)break;
  117358. out[k]=unitnorm(in[k]);
  117359. acc-=1.;
  117360. }
  117361. }
  117362. for(;i<partition;i++){
  117363. k=sortedindex[i+j-start];
  117364. out[k]=0.;
  117365. }
  117366. }
  117367. }
  117368. for(;j<n;j++)
  117369. out[j]=rint(in[j]);
  117370. }
  117371. void _vp_couple(int blobno,
  117372. vorbis_info_psy_global *g,
  117373. vorbis_look_psy *p,
  117374. vorbis_info_mapping0 *vi,
  117375. float **res,
  117376. float **mag_memo,
  117377. int **mag_sort,
  117378. int **ifloor,
  117379. int *nonzero,
  117380. int sliding_lowpass){
  117381. int i,j,k,n=p->n;
  117382. /* perform any requested channel coupling */
  117383. /* point stereo can only be used in a first stage (in this encoder)
  117384. because of the dependency on floor lookups */
  117385. for(i=0;i<vi->coupling_steps;i++){
  117386. /* once we're doing multistage coupling in which a channel goes
  117387. through more than one coupling step, the floor vector
  117388. magnitudes will also have to be recalculated an propogated
  117389. along with PCM. Right now, we're not (that will wait until 5.1
  117390. most likely), so the code isn't here yet. The memory management
  117391. here is all assuming single depth couplings anyway. */
  117392. /* make sure coupling a zero and a nonzero channel results in two
  117393. nonzero channels. */
  117394. if(nonzero[vi->coupling_mag[i]] ||
  117395. nonzero[vi->coupling_ang[i]]){
  117396. float *rM=res[vi->coupling_mag[i]];
  117397. float *rA=res[vi->coupling_ang[i]];
  117398. float *qM=rM+n;
  117399. float *qA=rA+n;
  117400. int *floorM=ifloor[vi->coupling_mag[i]];
  117401. int *floorA=ifloor[vi->coupling_ang[i]];
  117402. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117403. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117404. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117405. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117406. int pointlimit=limit;
  117407. nonzero[vi->coupling_mag[i]]=1;
  117408. nonzero[vi->coupling_ang[i]]=1;
  117409. /* The threshold of a stereo is changed with the size of n */
  117410. if(n > 1000)
  117411. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117412. for(j=0;j<p->n;j+=partition){
  117413. float acc=0.f;
  117414. for(k=0;k<partition;k++){
  117415. int l=k+j;
  117416. if(l<sliding_lowpass){
  117417. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117418. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117419. precomputed_couple_point(mag_memo[i][l],
  117420. floorM[l],floorA[l],
  117421. qM+l,qA+l);
  117422. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117423. }else{
  117424. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117425. }
  117426. }else{
  117427. qM[l]=0.;
  117428. qA[l]=0.;
  117429. }
  117430. }
  117431. if(p->vi->normal_point_p){
  117432. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117433. int l=mag_sort[i][j+k];
  117434. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117435. qM[l]=unitnorm(qM[l]);
  117436. acc-=1.f;
  117437. }
  117438. }
  117439. }
  117440. }
  117441. }
  117442. }
  117443. }
  117444. /* AoTuV */
  117445. /** @ M2 **
  117446. The boost problem by the combination of noise normalization and point stereo is eased.
  117447. However, this is a temporary patch.
  117448. by Aoyumi @ 2004/04/18
  117449. */
  117450. void hf_reduction(vorbis_info_psy_global *g,
  117451. vorbis_look_psy *p,
  117452. vorbis_info_mapping0 *vi,
  117453. float **mdct){
  117454. int i,j,n=p->n, de=0.3*p->m_val;
  117455. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117456. for(i=0; i<vi->coupling_steps; i++){
  117457. /* for(j=start; j<limit; j++){} // ???*/
  117458. for(j=limit; j<n; j++)
  117459. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117460. }
  117461. }
  117462. #endif
  117463. /*** End of inlined file: psy.c ***/
  117464. /*** Start of inlined file: registry.c ***/
  117465. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117466. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117467. // tasks..
  117468. #if JUCE_MSVC
  117469. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117470. #endif
  117471. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117472. #if JUCE_USE_OGGVORBIS
  117473. /* seems like major overkill now; the backend numbers will grow into
  117474. the infrastructure soon enough */
  117475. extern vorbis_func_floor floor0_exportbundle;
  117476. extern vorbis_func_floor floor1_exportbundle;
  117477. extern vorbis_func_residue residue0_exportbundle;
  117478. extern vorbis_func_residue residue1_exportbundle;
  117479. extern vorbis_func_residue residue2_exportbundle;
  117480. extern vorbis_func_mapping mapping0_exportbundle;
  117481. vorbis_func_floor *_floor_P[]={
  117482. &floor0_exportbundle,
  117483. &floor1_exportbundle,
  117484. };
  117485. vorbis_func_residue *_residue_P[]={
  117486. &residue0_exportbundle,
  117487. &residue1_exportbundle,
  117488. &residue2_exportbundle,
  117489. };
  117490. vorbis_func_mapping *_mapping_P[]={
  117491. &mapping0_exportbundle,
  117492. };
  117493. #endif
  117494. /*** End of inlined file: registry.c ***/
  117495. /*** Start of inlined file: res0.c ***/
  117496. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117497. encode/decode loops are coded for clarity and performance is not
  117498. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117499. it's slow. */
  117500. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117501. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117502. // tasks..
  117503. #if JUCE_MSVC
  117504. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117505. #endif
  117506. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117507. #if JUCE_USE_OGGVORBIS
  117508. #include <stdlib.h>
  117509. #include <string.h>
  117510. #include <math.h>
  117511. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117512. #include <stdio.h>
  117513. #endif
  117514. typedef struct {
  117515. vorbis_info_residue0 *info;
  117516. int parts;
  117517. int stages;
  117518. codebook *fullbooks;
  117519. codebook *phrasebook;
  117520. codebook ***partbooks;
  117521. int partvals;
  117522. int **decodemap;
  117523. long postbits;
  117524. long phrasebits;
  117525. long frames;
  117526. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117527. int train_seq;
  117528. long *training_data[8][64];
  117529. float training_max[8][64];
  117530. float training_min[8][64];
  117531. float tmin;
  117532. float tmax;
  117533. #endif
  117534. } vorbis_look_residue0;
  117535. void res0_free_info(vorbis_info_residue *i){
  117536. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117537. if(info){
  117538. memset(info,0,sizeof(*info));
  117539. _ogg_free(info);
  117540. }
  117541. }
  117542. void res0_free_look(vorbis_look_residue *i){
  117543. int j;
  117544. if(i){
  117545. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117546. #ifdef TRAIN_RES
  117547. {
  117548. int j,k,l;
  117549. for(j=0;j<look->parts;j++){
  117550. /*fprintf(stderr,"partition %d: ",j);*/
  117551. for(k=0;k<8;k++)
  117552. if(look->training_data[k][j]){
  117553. char buffer[80];
  117554. FILE *of;
  117555. codebook *statebook=look->partbooks[j][k];
  117556. /* long and short into the same bucket by current convention */
  117557. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117558. of=fopen(buffer,"a");
  117559. for(l=0;l<statebook->entries;l++)
  117560. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117561. fclose(of);
  117562. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117563. look->training_min[k][j],look->training_max[k][j]);*/
  117564. _ogg_free(look->training_data[k][j]);
  117565. look->training_data[k][j]=NULL;
  117566. }
  117567. /*fprintf(stderr,"\n");*/
  117568. }
  117569. }
  117570. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117571. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117572. (float)look->phrasebits/look->frames,
  117573. (float)look->postbits/look->frames,
  117574. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117575. #endif
  117576. /*vorbis_info_residue0 *info=look->info;
  117577. fprintf(stderr,
  117578. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117579. "(%g/frame) \n",look->frames,look->phrasebits,
  117580. look->resbitsflat,
  117581. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117582. for(j=0;j<look->parts;j++){
  117583. long acc=0;
  117584. fprintf(stderr,"\t[%d] == ",j);
  117585. for(k=0;k<look->stages;k++)
  117586. if((info->secondstages[j]>>k)&1){
  117587. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117588. acc+=look->resbits[j][k];
  117589. }
  117590. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117591. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117592. }
  117593. fprintf(stderr,"\n");*/
  117594. for(j=0;j<look->parts;j++)
  117595. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117596. _ogg_free(look->partbooks);
  117597. for(j=0;j<look->partvals;j++)
  117598. _ogg_free(look->decodemap[j]);
  117599. _ogg_free(look->decodemap);
  117600. memset(look,0,sizeof(*look));
  117601. _ogg_free(look);
  117602. }
  117603. }
  117604. static int icount(unsigned int v){
  117605. int ret=0;
  117606. while(v){
  117607. ret+=v&1;
  117608. v>>=1;
  117609. }
  117610. return(ret);
  117611. }
  117612. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117613. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117614. int j,acc=0;
  117615. oggpack_write(opb,info->begin,24);
  117616. oggpack_write(opb,info->end,24);
  117617. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117618. code with a partitioned book */
  117619. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117620. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117621. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117622. bitmask of one indicates this partition class has bits to write
  117623. this pass */
  117624. for(j=0;j<info->partitions;j++){
  117625. if(ilog(info->secondstages[j])>3){
  117626. /* yes, this is a minor hack due to not thinking ahead */
  117627. oggpack_write(opb,info->secondstages[j],3);
  117628. oggpack_write(opb,1,1);
  117629. oggpack_write(opb,info->secondstages[j]>>3,5);
  117630. }else
  117631. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117632. acc+=icount(info->secondstages[j]);
  117633. }
  117634. for(j=0;j<acc;j++)
  117635. oggpack_write(opb,info->booklist[j],8);
  117636. }
  117637. /* vorbis_info is for range checking */
  117638. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117639. int j,acc=0;
  117640. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117641. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117642. info->begin=oggpack_read(opb,24);
  117643. info->end=oggpack_read(opb,24);
  117644. info->grouping=oggpack_read(opb,24)+1;
  117645. info->partitions=oggpack_read(opb,6)+1;
  117646. info->groupbook=oggpack_read(opb,8);
  117647. for(j=0;j<info->partitions;j++){
  117648. int cascade=oggpack_read(opb,3);
  117649. if(oggpack_read(opb,1))
  117650. cascade|=(oggpack_read(opb,5)<<3);
  117651. info->secondstages[j]=cascade;
  117652. acc+=icount(cascade);
  117653. }
  117654. for(j=0;j<acc;j++)
  117655. info->booklist[j]=oggpack_read(opb,8);
  117656. if(info->groupbook>=ci->books)goto errout;
  117657. for(j=0;j<acc;j++)
  117658. if(info->booklist[j]>=ci->books)goto errout;
  117659. return(info);
  117660. errout:
  117661. res0_free_info(info);
  117662. return(NULL);
  117663. }
  117664. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117665. vorbis_info_residue *vr){
  117666. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117667. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117668. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117669. int j,k,acc=0;
  117670. int dim;
  117671. int maxstage=0;
  117672. look->info=info;
  117673. look->parts=info->partitions;
  117674. look->fullbooks=ci->fullbooks;
  117675. look->phrasebook=ci->fullbooks+info->groupbook;
  117676. dim=look->phrasebook->dim;
  117677. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117678. for(j=0;j<look->parts;j++){
  117679. int stages=ilog(info->secondstages[j]);
  117680. if(stages){
  117681. if(stages>maxstage)maxstage=stages;
  117682. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117683. for(k=0;k<stages;k++)
  117684. if(info->secondstages[j]&(1<<k)){
  117685. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117686. #ifdef TRAIN_RES
  117687. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117688. sizeof(***look->training_data));
  117689. #endif
  117690. }
  117691. }
  117692. }
  117693. look->partvals=rint(pow((float)look->parts,(float)dim));
  117694. look->stages=maxstage;
  117695. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117696. for(j=0;j<look->partvals;j++){
  117697. long val=j;
  117698. long mult=look->partvals/look->parts;
  117699. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117700. for(k=0;k<dim;k++){
  117701. long deco=val/mult;
  117702. val-=deco*mult;
  117703. mult/=look->parts;
  117704. look->decodemap[j][k]=deco;
  117705. }
  117706. }
  117707. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117708. {
  117709. static int train_seq=0;
  117710. look->train_seq=train_seq++;
  117711. }
  117712. #endif
  117713. return(look);
  117714. }
  117715. /* break an abstraction and copy some code for performance purposes */
  117716. static int local_book_besterror(codebook *book,float *a){
  117717. int dim=book->dim,i,k,o;
  117718. int best=0;
  117719. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117720. /* find the quant val of each scalar */
  117721. for(k=0,o=dim;k<dim;++k){
  117722. float val=a[--o];
  117723. i=tt->threshvals>>1;
  117724. if(val<tt->quantthresh[i]){
  117725. if(val<tt->quantthresh[i-1]){
  117726. for(--i;i>0;--i)
  117727. if(val>=tt->quantthresh[i-1])
  117728. break;
  117729. }
  117730. }else{
  117731. for(++i;i<tt->threshvals-1;++i)
  117732. if(val<tt->quantthresh[i])break;
  117733. }
  117734. best=(best*tt->quantvals)+tt->quantmap[i];
  117735. }
  117736. /* regular lattices are easy :-) */
  117737. if(book->c->lengthlist[best]<=0){
  117738. const static_codebook *c=book->c;
  117739. int i,j;
  117740. float bestf=0.f;
  117741. float *e=book->valuelist;
  117742. best=-1;
  117743. for(i=0;i<book->entries;i++){
  117744. if(c->lengthlist[i]>0){
  117745. float thisx=0.f;
  117746. for(j=0;j<dim;j++){
  117747. float val=(e[j]-a[j]);
  117748. thisx+=val*val;
  117749. }
  117750. if(best==-1 || thisx<bestf){
  117751. bestf=thisx;
  117752. best=i;
  117753. }
  117754. }
  117755. e+=dim;
  117756. }
  117757. }
  117758. {
  117759. float *ptr=book->valuelist+best*dim;
  117760. for(i=0;i<dim;i++)
  117761. *a++ -= *ptr++;
  117762. }
  117763. return(best);
  117764. }
  117765. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117766. codebook *book,long *acc){
  117767. int i,bits=0;
  117768. int dim=book->dim;
  117769. int step=n/dim;
  117770. for(i=0;i<step;i++){
  117771. int entry=local_book_besterror(book,vec+i*dim);
  117772. #ifdef TRAIN_RES
  117773. acc[entry]++;
  117774. #endif
  117775. bits+=vorbis_book_encode(book,entry,opb);
  117776. }
  117777. return(bits);
  117778. }
  117779. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117780. float **in,int ch){
  117781. long i,j,k;
  117782. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117783. vorbis_info_residue0 *info=look->info;
  117784. /* move all this setup out later */
  117785. int samples_per_partition=info->grouping;
  117786. int possible_partitions=info->partitions;
  117787. int n=info->end-info->begin;
  117788. int partvals=n/samples_per_partition;
  117789. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117790. float scale=100./samples_per_partition;
  117791. /* we find the partition type for each partition of each
  117792. channel. We'll go back and do the interleaved encoding in a
  117793. bit. For now, clarity */
  117794. for(i=0;i<ch;i++){
  117795. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117796. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117797. }
  117798. for(i=0;i<partvals;i++){
  117799. int offset=i*samples_per_partition+info->begin;
  117800. for(j=0;j<ch;j++){
  117801. float max=0.;
  117802. float ent=0.;
  117803. for(k=0;k<samples_per_partition;k++){
  117804. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117805. ent+=fabs(rint(in[j][offset+k]));
  117806. }
  117807. ent*=scale;
  117808. for(k=0;k<possible_partitions-1;k++)
  117809. if(max<=info->classmetric1[k] &&
  117810. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117811. break;
  117812. partword[j][i]=k;
  117813. }
  117814. }
  117815. #ifdef TRAIN_RESAUX
  117816. {
  117817. FILE *of;
  117818. char buffer[80];
  117819. for(i=0;i<ch;i++){
  117820. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117821. of=fopen(buffer,"a");
  117822. for(j=0;j<partvals;j++)
  117823. fprintf(of,"%ld, ",partword[i][j]);
  117824. fprintf(of,"\n");
  117825. fclose(of);
  117826. }
  117827. }
  117828. #endif
  117829. look->frames++;
  117830. return(partword);
  117831. }
  117832. /* designed for stereo or other modes where the partition size is an
  117833. integer multiple of the number of channels encoded in the current
  117834. submap */
  117835. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  117836. int ch){
  117837. long i,j,k,l;
  117838. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117839. vorbis_info_residue0 *info=look->info;
  117840. /* move all this setup out later */
  117841. int samples_per_partition=info->grouping;
  117842. int possible_partitions=info->partitions;
  117843. int n=info->end-info->begin;
  117844. int partvals=n/samples_per_partition;
  117845. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  117846. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117847. FILE *of;
  117848. char buffer[80];
  117849. #endif
  117850. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  117851. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  117852. for(i=0,l=info->begin/ch;i<partvals;i++){
  117853. float magmax=0.f;
  117854. float angmax=0.f;
  117855. for(j=0;j<samples_per_partition;j+=ch){
  117856. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  117857. for(k=1;k<ch;k++)
  117858. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  117859. l++;
  117860. }
  117861. for(j=0;j<possible_partitions-1;j++)
  117862. if(magmax<=info->classmetric1[j] &&
  117863. angmax<=info->classmetric2[j])
  117864. break;
  117865. partword[0][i]=j;
  117866. }
  117867. #ifdef TRAIN_RESAUX
  117868. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117869. of=fopen(buffer,"a");
  117870. for(i=0;i<partvals;i++)
  117871. fprintf(of,"%ld, ",partword[0][i]);
  117872. fprintf(of,"\n");
  117873. fclose(of);
  117874. #endif
  117875. look->frames++;
  117876. return(partword);
  117877. }
  117878. static int _01forward(oggpack_buffer *opb,
  117879. vorbis_block *vb,vorbis_look_residue *vl,
  117880. float **in,int ch,
  117881. long **partword,
  117882. int (*encode)(oggpack_buffer *,float *,int,
  117883. codebook *,long *)){
  117884. long i,j,k,s;
  117885. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117886. vorbis_info_residue0 *info=look->info;
  117887. /* move all this setup out later */
  117888. int samples_per_partition=info->grouping;
  117889. int possible_partitions=info->partitions;
  117890. int partitions_per_word=look->phrasebook->dim;
  117891. int n=info->end-info->begin;
  117892. int partvals=n/samples_per_partition;
  117893. long resbits[128];
  117894. long resvals[128];
  117895. #ifdef TRAIN_RES
  117896. for(i=0;i<ch;i++)
  117897. for(j=info->begin;j<info->end;j++){
  117898. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  117899. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  117900. }
  117901. #endif
  117902. memset(resbits,0,sizeof(resbits));
  117903. memset(resvals,0,sizeof(resvals));
  117904. /* we code the partition words for each channel, then the residual
  117905. words for a partition per channel until we've written all the
  117906. residual words for that partition word. Then write the next
  117907. partition channel words... */
  117908. for(s=0;s<look->stages;s++){
  117909. for(i=0;i<partvals;){
  117910. /* first we encode a partition codeword for each channel */
  117911. if(s==0){
  117912. for(j=0;j<ch;j++){
  117913. long val=partword[j][i];
  117914. for(k=1;k<partitions_per_word;k++){
  117915. val*=possible_partitions;
  117916. if(i+k<partvals)
  117917. val+=partword[j][i+k];
  117918. }
  117919. /* training hack */
  117920. if(val<look->phrasebook->entries)
  117921. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  117922. #if 0 /*def TRAIN_RES*/
  117923. else
  117924. fprintf(stderr,"!");
  117925. #endif
  117926. }
  117927. }
  117928. /* now we encode interleaved residual values for the partitions */
  117929. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  117930. long offset=i*samples_per_partition+info->begin;
  117931. for(j=0;j<ch;j++){
  117932. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  117933. if(info->secondstages[partword[j][i]]&(1<<s)){
  117934. codebook *statebook=look->partbooks[partword[j][i]][s];
  117935. if(statebook){
  117936. int ret;
  117937. long *accumulator=NULL;
  117938. #ifdef TRAIN_RES
  117939. accumulator=look->training_data[s][partword[j][i]];
  117940. {
  117941. int l;
  117942. float *samples=in[j]+offset;
  117943. for(l=0;l<samples_per_partition;l++){
  117944. if(samples[l]<look->training_min[s][partword[j][i]])
  117945. look->training_min[s][partword[j][i]]=samples[l];
  117946. if(samples[l]>look->training_max[s][partword[j][i]])
  117947. look->training_max[s][partword[j][i]]=samples[l];
  117948. }
  117949. }
  117950. #endif
  117951. ret=encode(opb,in[j]+offset,samples_per_partition,
  117952. statebook,accumulator);
  117953. look->postbits+=ret;
  117954. resbits[partword[j][i]]+=ret;
  117955. }
  117956. }
  117957. }
  117958. }
  117959. }
  117960. }
  117961. /*{
  117962. long total=0;
  117963. long totalbits=0;
  117964. fprintf(stderr,"%d :: ",vb->mode);
  117965. for(k=0;k<possible_partitions;k++){
  117966. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  117967. total+=resvals[k];
  117968. totalbits+=resbits[k];
  117969. }
  117970. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  117971. }*/
  117972. return(0);
  117973. }
  117974. /* a truncated packet here just means 'stop working'; it's not an error */
  117975. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117976. float **in,int ch,
  117977. long (*decodepart)(codebook *, float *,
  117978. oggpack_buffer *,int)){
  117979. long i,j,k,l,s;
  117980. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117981. vorbis_info_residue0 *info=look->info;
  117982. /* move all this setup out later */
  117983. int samples_per_partition=info->grouping;
  117984. int partitions_per_word=look->phrasebook->dim;
  117985. int n=info->end-info->begin;
  117986. int partvals=n/samples_per_partition;
  117987. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117988. int ***partword=(int***)alloca(ch*sizeof(*partword));
  117989. for(j=0;j<ch;j++)
  117990. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  117991. for(s=0;s<look->stages;s++){
  117992. /* each loop decodes on partition codeword containing
  117993. partitions_pre_word partitions */
  117994. for(i=0,l=0;i<partvals;l++){
  117995. if(s==0){
  117996. /* fetch the partition word for each channel */
  117997. for(j=0;j<ch;j++){
  117998. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117999. if(temp==-1)goto eopbreak;
  118000. partword[j][l]=look->decodemap[temp];
  118001. if(partword[j][l]==NULL)goto errout;
  118002. }
  118003. }
  118004. /* now we decode residual values for the partitions */
  118005. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118006. for(j=0;j<ch;j++){
  118007. long offset=info->begin+i*samples_per_partition;
  118008. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118009. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118010. if(stagebook){
  118011. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118012. samples_per_partition)==-1)goto eopbreak;
  118013. }
  118014. }
  118015. }
  118016. }
  118017. }
  118018. errout:
  118019. eopbreak:
  118020. return(0);
  118021. }
  118022. #if 0
  118023. /* residue 0 and 1 are just slight variants of one another. 0 is
  118024. interleaved, 1 is not */
  118025. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118026. float **in,int *nonzero,int ch){
  118027. /* we encode only the nonzero parts of a bundle */
  118028. int i,used=0;
  118029. for(i=0;i<ch;i++)
  118030. if(nonzero[i])
  118031. in[used++]=in[i];
  118032. if(used)
  118033. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118034. return(_01class(vb,vl,in,used));
  118035. else
  118036. return(0);
  118037. }
  118038. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118039. float **in,float **out,int *nonzero,int ch,
  118040. long **partword){
  118041. /* we encode only the nonzero parts of a bundle */
  118042. int i,j,used=0,n=vb->pcmend/2;
  118043. for(i=0;i<ch;i++)
  118044. if(nonzero[i]){
  118045. if(out)
  118046. for(j=0;j<n;j++)
  118047. out[i][j]+=in[i][j];
  118048. in[used++]=in[i];
  118049. }
  118050. if(used){
  118051. int ret=_01forward(vb,vl,in,used,partword,
  118052. _interleaved_encodepart);
  118053. if(out){
  118054. used=0;
  118055. for(i=0;i<ch;i++)
  118056. if(nonzero[i]){
  118057. for(j=0;j<n;j++)
  118058. out[i][j]-=in[used][j];
  118059. used++;
  118060. }
  118061. }
  118062. return(ret);
  118063. }else{
  118064. return(0);
  118065. }
  118066. }
  118067. #endif
  118068. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118069. float **in,int *nonzero,int ch){
  118070. int i,used=0;
  118071. for(i=0;i<ch;i++)
  118072. if(nonzero[i])
  118073. in[used++]=in[i];
  118074. if(used)
  118075. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118076. else
  118077. return(0);
  118078. }
  118079. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118080. float **in,float **out,int *nonzero,int ch,
  118081. long **partword){
  118082. int i,j,used=0,n=vb->pcmend/2;
  118083. for(i=0;i<ch;i++)
  118084. if(nonzero[i]){
  118085. if(out)
  118086. for(j=0;j<n;j++)
  118087. out[i][j]+=in[i][j];
  118088. in[used++]=in[i];
  118089. }
  118090. if(used){
  118091. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118092. if(out){
  118093. used=0;
  118094. for(i=0;i<ch;i++)
  118095. if(nonzero[i]){
  118096. for(j=0;j<n;j++)
  118097. out[i][j]-=in[used][j];
  118098. used++;
  118099. }
  118100. }
  118101. return(ret);
  118102. }else{
  118103. return(0);
  118104. }
  118105. }
  118106. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118107. float **in,int *nonzero,int ch){
  118108. int i,used=0;
  118109. for(i=0;i<ch;i++)
  118110. if(nonzero[i])
  118111. in[used++]=in[i];
  118112. if(used)
  118113. return(_01class(vb,vl,in,used));
  118114. else
  118115. return(0);
  118116. }
  118117. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118118. float **in,int *nonzero,int ch){
  118119. int i,used=0;
  118120. for(i=0;i<ch;i++)
  118121. if(nonzero[i])
  118122. in[used++]=in[i];
  118123. if(used)
  118124. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118125. else
  118126. return(0);
  118127. }
  118128. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118129. float **in,int *nonzero,int ch){
  118130. int i,used=0;
  118131. for(i=0;i<ch;i++)
  118132. if(nonzero[i])used++;
  118133. if(used)
  118134. return(_2class(vb,vl,in,ch));
  118135. else
  118136. return(0);
  118137. }
  118138. /* res2 is slightly more different; all the channels are interleaved
  118139. into a single vector and encoded. */
  118140. int res2_forward(oggpack_buffer *opb,
  118141. vorbis_block *vb,vorbis_look_residue *vl,
  118142. float **in,float **out,int *nonzero,int ch,
  118143. long **partword){
  118144. long i,j,k,n=vb->pcmend/2,used=0;
  118145. /* don't duplicate the code; use a working vector hack for now and
  118146. reshape ourselves into a single channel res1 */
  118147. /* ugly; reallocs for each coupling pass :-( */
  118148. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118149. for(i=0;i<ch;i++){
  118150. float *pcm=in[i];
  118151. if(nonzero[i])used++;
  118152. for(j=0,k=i;j<n;j++,k+=ch)
  118153. work[k]=pcm[j];
  118154. }
  118155. if(used){
  118156. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118157. /* update the sofar vector */
  118158. if(out){
  118159. for(i=0;i<ch;i++){
  118160. float *pcm=in[i];
  118161. float *sofar=out[i];
  118162. for(j=0,k=i;j<n;j++,k+=ch)
  118163. sofar[j]+=pcm[j]-work[k];
  118164. }
  118165. }
  118166. return(ret);
  118167. }else{
  118168. return(0);
  118169. }
  118170. }
  118171. /* duplicate code here as speed is somewhat more important */
  118172. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118173. float **in,int *nonzero,int ch){
  118174. long i,k,l,s;
  118175. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118176. vorbis_info_residue0 *info=look->info;
  118177. /* move all this setup out later */
  118178. int samples_per_partition=info->grouping;
  118179. int partitions_per_word=look->phrasebook->dim;
  118180. int n=info->end-info->begin;
  118181. int partvals=n/samples_per_partition;
  118182. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118183. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118184. for(i=0;i<ch;i++)if(nonzero[i])break;
  118185. if(i==ch)return(0); /* no nonzero vectors */
  118186. for(s=0;s<look->stages;s++){
  118187. for(i=0,l=0;i<partvals;l++){
  118188. if(s==0){
  118189. /* fetch the partition word */
  118190. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118191. if(temp==-1)goto eopbreak;
  118192. partword[l]=look->decodemap[temp];
  118193. if(partword[l]==NULL)goto errout;
  118194. }
  118195. /* now we decode residual values for the partitions */
  118196. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118197. if(info->secondstages[partword[l][k]]&(1<<s)){
  118198. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118199. if(stagebook){
  118200. if(vorbis_book_decodevv_add(stagebook,in,
  118201. i*samples_per_partition+info->begin,ch,
  118202. &vb->opb,samples_per_partition)==-1)
  118203. goto eopbreak;
  118204. }
  118205. }
  118206. }
  118207. }
  118208. errout:
  118209. eopbreak:
  118210. return(0);
  118211. }
  118212. vorbis_func_residue residue0_exportbundle={
  118213. NULL,
  118214. &res0_unpack,
  118215. &res0_look,
  118216. &res0_free_info,
  118217. &res0_free_look,
  118218. NULL,
  118219. NULL,
  118220. &res0_inverse
  118221. };
  118222. vorbis_func_residue residue1_exportbundle={
  118223. &res0_pack,
  118224. &res0_unpack,
  118225. &res0_look,
  118226. &res0_free_info,
  118227. &res0_free_look,
  118228. &res1_class,
  118229. &res1_forward,
  118230. &res1_inverse
  118231. };
  118232. vorbis_func_residue residue2_exportbundle={
  118233. &res0_pack,
  118234. &res0_unpack,
  118235. &res0_look,
  118236. &res0_free_info,
  118237. &res0_free_look,
  118238. &res2_class,
  118239. &res2_forward,
  118240. &res2_inverse
  118241. };
  118242. #endif
  118243. /*** End of inlined file: res0.c ***/
  118244. /*** Start of inlined file: sharedbook.c ***/
  118245. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118246. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118247. // tasks..
  118248. #if JUCE_MSVC
  118249. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118250. #endif
  118251. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118252. #if JUCE_USE_OGGVORBIS
  118253. #include <stdlib.h>
  118254. #include <math.h>
  118255. #include <string.h>
  118256. /**** pack/unpack helpers ******************************************/
  118257. int _ilog(unsigned int v){
  118258. int ret=0;
  118259. while(v){
  118260. ret++;
  118261. v>>=1;
  118262. }
  118263. return(ret);
  118264. }
  118265. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118266. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118267. Why not IEEE? It's just not that important here. */
  118268. #define VQ_FEXP 10
  118269. #define VQ_FMAN 21
  118270. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118271. /* doesn't currently guard under/overflow */
  118272. long _float32_pack(float val){
  118273. int sign=0;
  118274. long exp;
  118275. long mant;
  118276. if(val<0){
  118277. sign=0x80000000;
  118278. val= -val;
  118279. }
  118280. exp= floor(log(val)/log(2.f));
  118281. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118282. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118283. return(sign|exp|mant);
  118284. }
  118285. float _float32_unpack(long val){
  118286. double mant=val&0x1fffff;
  118287. int sign=val&0x80000000;
  118288. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118289. if(sign)mant= -mant;
  118290. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118291. }
  118292. /* given a list of word lengths, generate a list of codewords. Works
  118293. for length ordered or unordered, always assigns the lowest valued
  118294. codewords first. Extended to handle unused entries (length 0) */
  118295. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118296. long i,j,count=0;
  118297. ogg_uint32_t marker[33];
  118298. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118299. memset(marker,0,sizeof(marker));
  118300. for(i=0;i<n;i++){
  118301. long length=l[i];
  118302. if(length>0){
  118303. ogg_uint32_t entry=marker[length];
  118304. /* when we claim a node for an entry, we also claim the nodes
  118305. below it (pruning off the imagined tree that may have dangled
  118306. from it) as well as blocking the use of any nodes directly
  118307. above for leaves */
  118308. /* update ourself */
  118309. if(length<32 && (entry>>length)){
  118310. /* error condition; the lengths must specify an overpopulated tree */
  118311. _ogg_free(r);
  118312. return(NULL);
  118313. }
  118314. r[count++]=entry;
  118315. /* Look to see if the next shorter marker points to the node
  118316. above. if so, update it and repeat. */
  118317. {
  118318. for(j=length;j>0;j--){
  118319. if(marker[j]&1){
  118320. /* have to jump branches */
  118321. if(j==1)
  118322. marker[1]++;
  118323. else
  118324. marker[j]=marker[j-1]<<1;
  118325. break; /* invariant says next upper marker would already
  118326. have been moved if it was on the same path */
  118327. }
  118328. marker[j]++;
  118329. }
  118330. }
  118331. /* prune the tree; the implicit invariant says all the longer
  118332. markers were dangling from our just-taken node. Dangle them
  118333. from our *new* node. */
  118334. for(j=length+1;j<33;j++)
  118335. if((marker[j]>>1) == entry){
  118336. entry=marker[j];
  118337. marker[j]=marker[j-1]<<1;
  118338. }else
  118339. break;
  118340. }else
  118341. if(sparsecount==0)count++;
  118342. }
  118343. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118344. endian */
  118345. for(i=0,count=0;i<n;i++){
  118346. ogg_uint32_t temp=0;
  118347. for(j=0;j<l[i];j++){
  118348. temp<<=1;
  118349. temp|=(r[count]>>j)&1;
  118350. }
  118351. if(sparsecount){
  118352. if(l[i])
  118353. r[count++]=temp;
  118354. }else
  118355. r[count++]=temp;
  118356. }
  118357. return(r);
  118358. }
  118359. /* there might be a straightforward one-line way to do the below
  118360. that's portable and totally safe against roundoff, but I haven't
  118361. thought of it. Therefore, we opt on the side of caution */
  118362. long _book_maptype1_quantvals(const static_codebook *b){
  118363. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118364. /* the above *should* be reliable, but we'll not assume that FP is
  118365. ever reliable when bitstream sync is at stake; verify via integer
  118366. means that vals really is the greatest value of dim for which
  118367. vals^b->bim <= b->entries */
  118368. /* treat the above as an initial guess */
  118369. while(1){
  118370. long acc=1;
  118371. long acc1=1;
  118372. int i;
  118373. for(i=0;i<b->dim;i++){
  118374. acc*=vals;
  118375. acc1*=vals+1;
  118376. }
  118377. if(acc<=b->entries && acc1>b->entries){
  118378. return(vals);
  118379. }else{
  118380. if(acc>b->entries){
  118381. vals--;
  118382. }else{
  118383. vals++;
  118384. }
  118385. }
  118386. }
  118387. }
  118388. /* unpack the quantized list of values for encode/decode ***********/
  118389. /* we need to deal with two map types: in map type 1, the values are
  118390. generated algorithmically (each column of the vector counts through
  118391. the values in the quant vector). in map type 2, all the values came
  118392. in in an explicit list. Both value lists must be unpacked */
  118393. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118394. long j,k,count=0;
  118395. if(b->maptype==1 || b->maptype==2){
  118396. int quantvals;
  118397. float mindel=_float32_unpack(b->q_min);
  118398. float delta=_float32_unpack(b->q_delta);
  118399. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118400. /* maptype 1 and 2 both use a quantized value vector, but
  118401. different sizes */
  118402. switch(b->maptype){
  118403. case 1:
  118404. /* most of the time, entries%dimensions == 0, but we need to be
  118405. well defined. We define that the possible vales at each
  118406. scalar is values == entries/dim. If entries%dim != 0, we'll
  118407. have 'too few' values (values*dim<entries), which means that
  118408. we'll have 'left over' entries; left over entries use zeroed
  118409. values (and are wasted). So don't generate codebooks like
  118410. that */
  118411. quantvals=_book_maptype1_quantvals(b);
  118412. for(j=0;j<b->entries;j++){
  118413. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118414. float last=0.f;
  118415. int indexdiv=1;
  118416. for(k=0;k<b->dim;k++){
  118417. int index= (j/indexdiv)%quantvals;
  118418. float val=b->quantlist[index];
  118419. val=fabs(val)*delta+mindel+last;
  118420. if(b->q_sequencep)last=val;
  118421. if(sparsemap)
  118422. r[sparsemap[count]*b->dim+k]=val;
  118423. else
  118424. r[count*b->dim+k]=val;
  118425. indexdiv*=quantvals;
  118426. }
  118427. count++;
  118428. }
  118429. }
  118430. break;
  118431. case 2:
  118432. for(j=0;j<b->entries;j++){
  118433. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118434. float last=0.f;
  118435. for(k=0;k<b->dim;k++){
  118436. float val=b->quantlist[j*b->dim+k];
  118437. val=fabs(val)*delta+mindel+last;
  118438. if(b->q_sequencep)last=val;
  118439. if(sparsemap)
  118440. r[sparsemap[count]*b->dim+k]=val;
  118441. else
  118442. r[count*b->dim+k]=val;
  118443. }
  118444. count++;
  118445. }
  118446. }
  118447. break;
  118448. }
  118449. return(r);
  118450. }
  118451. return(NULL);
  118452. }
  118453. void vorbis_staticbook_clear(static_codebook *b){
  118454. if(b->allocedp){
  118455. if(b->quantlist)_ogg_free(b->quantlist);
  118456. if(b->lengthlist)_ogg_free(b->lengthlist);
  118457. if(b->nearest_tree){
  118458. _ogg_free(b->nearest_tree->ptr0);
  118459. _ogg_free(b->nearest_tree->ptr1);
  118460. _ogg_free(b->nearest_tree->p);
  118461. _ogg_free(b->nearest_tree->q);
  118462. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118463. _ogg_free(b->nearest_tree);
  118464. }
  118465. if(b->thresh_tree){
  118466. _ogg_free(b->thresh_tree->quantthresh);
  118467. _ogg_free(b->thresh_tree->quantmap);
  118468. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118469. _ogg_free(b->thresh_tree);
  118470. }
  118471. memset(b,0,sizeof(*b));
  118472. }
  118473. }
  118474. void vorbis_staticbook_destroy(static_codebook *b){
  118475. if(b->allocedp){
  118476. vorbis_staticbook_clear(b);
  118477. _ogg_free(b);
  118478. }
  118479. }
  118480. void vorbis_book_clear(codebook *b){
  118481. /* static book is not cleared; we're likely called on the lookup and
  118482. the static codebook belongs to the info struct */
  118483. if(b->valuelist)_ogg_free(b->valuelist);
  118484. if(b->codelist)_ogg_free(b->codelist);
  118485. if(b->dec_index)_ogg_free(b->dec_index);
  118486. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118487. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118488. memset(b,0,sizeof(*b));
  118489. }
  118490. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118491. memset(c,0,sizeof(*c));
  118492. c->c=s;
  118493. c->entries=s->entries;
  118494. c->used_entries=s->entries;
  118495. c->dim=s->dim;
  118496. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118497. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118498. return(0);
  118499. }
  118500. static int sort32a(const void *a,const void *b){
  118501. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118502. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118503. }
  118504. /* decode codebook arrangement is more heavily optimized than encode */
  118505. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118506. int i,j,n=0,tabn;
  118507. int *sortindex;
  118508. memset(c,0,sizeof(*c));
  118509. /* count actually used entries */
  118510. for(i=0;i<s->entries;i++)
  118511. if(s->lengthlist[i]>0)
  118512. n++;
  118513. c->entries=s->entries;
  118514. c->used_entries=n;
  118515. c->dim=s->dim;
  118516. /* two different remappings go on here.
  118517. First, we collapse the likely sparse codebook down only to
  118518. actually represented values/words. This collapsing needs to be
  118519. indexed as map-valueless books are used to encode original entry
  118520. positions as integers.
  118521. Second, we reorder all vectors, including the entry index above,
  118522. by sorted bitreversed codeword to allow treeless decode. */
  118523. {
  118524. /* perform sort */
  118525. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118526. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118527. if(codes==NULL)goto err_out;
  118528. for(i=0;i<n;i++){
  118529. codes[i]=ogg_bitreverse(codes[i]);
  118530. codep[i]=codes+i;
  118531. }
  118532. qsort(codep,n,sizeof(*codep),sort32a);
  118533. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118534. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118535. /* the index is a reverse index */
  118536. for(i=0;i<n;i++){
  118537. int position=codep[i]-codes;
  118538. sortindex[position]=i;
  118539. }
  118540. for(i=0;i<n;i++)
  118541. c->codelist[sortindex[i]]=codes[i];
  118542. _ogg_free(codes);
  118543. }
  118544. c->valuelist=_book_unquantize(s,n,sortindex);
  118545. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118546. for(n=0,i=0;i<s->entries;i++)
  118547. if(s->lengthlist[i]>0)
  118548. c->dec_index[sortindex[n++]]=i;
  118549. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118550. for(n=0,i=0;i<s->entries;i++)
  118551. if(s->lengthlist[i]>0)
  118552. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118553. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118554. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118555. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118556. tabn=1<<c->dec_firsttablen;
  118557. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118558. c->dec_maxlength=0;
  118559. for(i=0;i<n;i++){
  118560. if(c->dec_maxlength<c->dec_codelengths[i])
  118561. c->dec_maxlength=c->dec_codelengths[i];
  118562. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118563. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118564. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118565. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118566. }
  118567. }
  118568. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118569. hints for the non-direct-hits */
  118570. {
  118571. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118572. long lo=0,hi=0;
  118573. for(i=0;i<tabn;i++){
  118574. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118575. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118576. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118577. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118578. /* we only actually have 15 bits per hint to play with here.
  118579. In order to overflow gracefully (nothing breaks, efficiency
  118580. just drops), encode as the difference from the extremes. */
  118581. {
  118582. unsigned long loval=lo;
  118583. unsigned long hival=n-hi;
  118584. if(loval>0x7fff)loval=0x7fff;
  118585. if(hival>0x7fff)hival=0x7fff;
  118586. c->dec_firsttable[ogg_bitreverse(word)]=
  118587. 0x80000000UL | (loval<<15) | hival;
  118588. }
  118589. }
  118590. }
  118591. }
  118592. return(0);
  118593. err_out:
  118594. vorbis_book_clear(c);
  118595. return(-1);
  118596. }
  118597. static float _dist(int el,float *ref, float *b,int step){
  118598. int i;
  118599. float acc=0.f;
  118600. for(i=0;i<el;i++){
  118601. float val=(ref[i]-b[i*step]);
  118602. acc+=val*val;
  118603. }
  118604. return(acc);
  118605. }
  118606. int _best(codebook *book, float *a, int step){
  118607. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118608. #if 0
  118609. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118610. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118611. #endif
  118612. int dim=book->dim;
  118613. int k,o;
  118614. /*int savebest=-1;
  118615. float saverr;*/
  118616. /* do we have a threshhold encode hint? */
  118617. if(tt){
  118618. int index=0,i;
  118619. /* find the quant val of each scalar */
  118620. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118621. i=tt->threshvals>>1;
  118622. if(a[o]<tt->quantthresh[i]){
  118623. for(;i>0;i--)
  118624. if(a[o]>=tt->quantthresh[i-1])
  118625. break;
  118626. }else{
  118627. for(i++;i<tt->threshvals-1;i++)
  118628. if(a[o]<tt->quantthresh[i])break;
  118629. }
  118630. index=(index*tt->quantvals)+tt->quantmap[i];
  118631. }
  118632. /* regular lattices are easy :-) */
  118633. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118634. use a decision tree after all
  118635. and fall through*/
  118636. return(index);
  118637. }
  118638. #if 0
  118639. /* do we have a pigeonhole encode hint? */
  118640. if(pt){
  118641. const static_codebook *c=book->c;
  118642. int i,besti=-1;
  118643. float best=0.f;
  118644. int entry=0;
  118645. /* dealing with sequentialness is a pain in the ass */
  118646. if(c->q_sequencep){
  118647. int pv;
  118648. long mul=1;
  118649. float qlast=0;
  118650. for(k=0,o=0;k<dim;k++,o+=step){
  118651. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118652. if(pv<0 || pv>=pt->mapentries)break;
  118653. entry+=pt->pigeonmap[pv]*mul;
  118654. mul*=pt->quantvals;
  118655. qlast+=pv*pt->del+pt->min;
  118656. }
  118657. }else{
  118658. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118659. int pv=(int)((a[o]-pt->min)/pt->del);
  118660. if(pv<0 || pv>=pt->mapentries)break;
  118661. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118662. }
  118663. }
  118664. /* must be within the pigeonholable range; if we quant outside (or
  118665. in an entry that we define no list for), brute force it */
  118666. if(k==dim && pt->fitlength[entry]){
  118667. /* search the abbreviated list */
  118668. long *list=pt->fitlist+pt->fitmap[entry];
  118669. for(i=0;i<pt->fitlength[entry];i++){
  118670. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118671. if(besti==-1 || this<best){
  118672. best=this;
  118673. besti=list[i];
  118674. }
  118675. }
  118676. return(besti);
  118677. }
  118678. }
  118679. if(nt){
  118680. /* optimized using the decision tree */
  118681. while(1){
  118682. float c=0.f;
  118683. float *p=book->valuelist+nt->p[ptr];
  118684. float *q=book->valuelist+nt->q[ptr];
  118685. for(k=0,o=0;k<dim;k++,o+=step)
  118686. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118687. if(c>0.f) /* in A */
  118688. ptr= -nt->ptr0[ptr];
  118689. else /* in B */
  118690. ptr= -nt->ptr1[ptr];
  118691. if(ptr<=0)break;
  118692. }
  118693. return(-ptr);
  118694. }
  118695. #endif
  118696. /* brute force it! */
  118697. {
  118698. const static_codebook *c=book->c;
  118699. int i,besti=-1;
  118700. float best=0.f;
  118701. float *e=book->valuelist;
  118702. for(i=0;i<book->entries;i++){
  118703. if(c->lengthlist[i]>0){
  118704. float thisx=_dist(dim,e,a,step);
  118705. if(besti==-1 || thisx<best){
  118706. best=thisx;
  118707. besti=i;
  118708. }
  118709. }
  118710. e+=dim;
  118711. }
  118712. /*if(savebest!=-1 && savebest!=besti){
  118713. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118714. "original:");
  118715. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118716. fprintf(stderr,"\n"
  118717. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118718. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118719. (book->valuelist+savebest*dim)[i]);
  118720. fprintf(stderr,"\n"
  118721. "bruteforce (entry %d, err %g):",besti,best);
  118722. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118723. (book->valuelist+besti*dim)[i]);
  118724. fprintf(stderr,"\n");
  118725. }*/
  118726. return(besti);
  118727. }
  118728. }
  118729. long vorbis_book_codeword(codebook *book,int entry){
  118730. if(book->c) /* only use with encode; decode optimizations are
  118731. allowed to break this */
  118732. return book->codelist[entry];
  118733. return -1;
  118734. }
  118735. long vorbis_book_codelen(codebook *book,int entry){
  118736. if(book->c) /* only use with encode; decode optimizations are
  118737. allowed to break this */
  118738. return book->c->lengthlist[entry];
  118739. return -1;
  118740. }
  118741. #ifdef _V_SELFTEST
  118742. /* Unit tests of the dequantizer; this stuff will be OK
  118743. cross-platform, I simply want to be sure that special mapping cases
  118744. actually work properly; a bug could go unnoticed for a while */
  118745. #include <stdio.h>
  118746. /* cases:
  118747. no mapping
  118748. full, explicit mapping
  118749. algorithmic mapping
  118750. nonsequential
  118751. sequential
  118752. */
  118753. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118754. static long partial_quantlist1[]={0,7,2};
  118755. /* no mapping */
  118756. static_codebook test1={
  118757. 4,16,
  118758. NULL,
  118759. 0,
  118760. 0,0,0,0,
  118761. NULL,
  118762. NULL,NULL
  118763. };
  118764. static float *test1_result=NULL;
  118765. /* linear, full mapping, nonsequential */
  118766. static_codebook test2={
  118767. 4,3,
  118768. NULL,
  118769. 2,
  118770. -533200896,1611661312,4,0,
  118771. full_quantlist1,
  118772. NULL,NULL
  118773. };
  118774. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118775. /* linear, full mapping, sequential */
  118776. static_codebook test3={
  118777. 4,3,
  118778. NULL,
  118779. 2,
  118780. -533200896,1611661312,4,1,
  118781. full_quantlist1,
  118782. NULL,NULL
  118783. };
  118784. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118785. /* linear, algorithmic mapping, nonsequential */
  118786. static_codebook test4={
  118787. 3,27,
  118788. NULL,
  118789. 1,
  118790. -533200896,1611661312,4,0,
  118791. partial_quantlist1,
  118792. NULL,NULL
  118793. };
  118794. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118795. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118796. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118797. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118798. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118799. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118800. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118801. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118802. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118803. /* linear, algorithmic mapping, sequential */
  118804. static_codebook test5={
  118805. 3,27,
  118806. NULL,
  118807. 1,
  118808. -533200896,1611661312,4,1,
  118809. partial_quantlist1,
  118810. NULL,NULL
  118811. };
  118812. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118813. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  118814. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  118815. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  118816. -3, 1, 5, 4, 8,12, -1, 3, 7,
  118817. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  118818. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  118819. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  118820. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  118821. void run_test(static_codebook *b,float *comp){
  118822. float *out=_book_unquantize(b,b->entries,NULL);
  118823. int i;
  118824. if(comp){
  118825. if(!out){
  118826. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  118827. exit(1);
  118828. }
  118829. for(i=0;i<b->entries*b->dim;i++)
  118830. if(fabs(out[i]-comp[i])>.0001){
  118831. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  118832. "position %d, %g != %g\n",i,out[i],comp[i]);
  118833. exit(1);
  118834. }
  118835. }else{
  118836. if(out){
  118837. fprintf(stderr,"_book_unquantize returned a value array: \n"
  118838. " correct result should have been NULL\n");
  118839. exit(1);
  118840. }
  118841. }
  118842. }
  118843. int main(){
  118844. /* run the nine dequant tests, and compare to the hand-rolled results */
  118845. fprintf(stderr,"Dequant test 1... ");
  118846. run_test(&test1,test1_result);
  118847. fprintf(stderr,"OK\nDequant test 2... ");
  118848. run_test(&test2,test2_result);
  118849. fprintf(stderr,"OK\nDequant test 3... ");
  118850. run_test(&test3,test3_result);
  118851. fprintf(stderr,"OK\nDequant test 4... ");
  118852. run_test(&test4,test4_result);
  118853. fprintf(stderr,"OK\nDequant test 5... ");
  118854. run_test(&test5,test5_result);
  118855. fprintf(stderr,"OK\n\n");
  118856. return(0);
  118857. }
  118858. #endif
  118859. #endif
  118860. /*** End of inlined file: sharedbook.c ***/
  118861. /*** Start of inlined file: smallft.c ***/
  118862. /* FFT implementation from OggSquish, minus cosine transforms,
  118863. * minus all but radix 2/4 case. In Vorbis we only need this
  118864. * cut-down version.
  118865. *
  118866. * To do more than just power-of-two sized vectors, see the full
  118867. * version I wrote for NetLib.
  118868. *
  118869. * Note that the packing is a little strange; rather than the FFT r/i
  118870. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  118871. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  118872. * FORTRAN version
  118873. */
  118874. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118875. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118876. // tasks..
  118877. #if JUCE_MSVC
  118878. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118879. #endif
  118880. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118881. #if JUCE_USE_OGGVORBIS
  118882. #include <stdlib.h>
  118883. #include <string.h>
  118884. #include <math.h>
  118885. static void drfti1(int n, float *wa, int *ifac){
  118886. static int ntryh[4] = { 4,2,3,5 };
  118887. static float tpi = 6.28318530717958648f;
  118888. float arg,argh,argld,fi;
  118889. int ntry=0,i,j=-1;
  118890. int k1, l1, l2, ib;
  118891. int ld, ii, ip, is, nq, nr;
  118892. int ido, ipm, nfm1;
  118893. int nl=n;
  118894. int nf=0;
  118895. L101:
  118896. j++;
  118897. if (j < 4)
  118898. ntry=ntryh[j];
  118899. else
  118900. ntry+=2;
  118901. L104:
  118902. nq=nl/ntry;
  118903. nr=nl-ntry*nq;
  118904. if (nr!=0) goto L101;
  118905. nf++;
  118906. ifac[nf+1]=ntry;
  118907. nl=nq;
  118908. if(ntry!=2)goto L107;
  118909. if(nf==1)goto L107;
  118910. for (i=1;i<nf;i++){
  118911. ib=nf-i+1;
  118912. ifac[ib+1]=ifac[ib];
  118913. }
  118914. ifac[2] = 2;
  118915. L107:
  118916. if(nl!=1)goto L104;
  118917. ifac[0]=n;
  118918. ifac[1]=nf;
  118919. argh=tpi/n;
  118920. is=0;
  118921. nfm1=nf-1;
  118922. l1=1;
  118923. if(nfm1==0)return;
  118924. for (k1=0;k1<nfm1;k1++){
  118925. ip=ifac[k1+2];
  118926. ld=0;
  118927. l2=l1*ip;
  118928. ido=n/l2;
  118929. ipm=ip-1;
  118930. for (j=0;j<ipm;j++){
  118931. ld+=l1;
  118932. i=is;
  118933. argld=(float)ld*argh;
  118934. fi=0.f;
  118935. for (ii=2;ii<ido;ii+=2){
  118936. fi+=1.f;
  118937. arg=fi*argld;
  118938. wa[i++]=cos(arg);
  118939. wa[i++]=sin(arg);
  118940. }
  118941. is+=ido;
  118942. }
  118943. l1=l2;
  118944. }
  118945. }
  118946. static void fdrffti(int n, float *wsave, int *ifac){
  118947. if (n == 1) return;
  118948. drfti1(n, wsave+n, ifac);
  118949. }
  118950. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  118951. int i,k;
  118952. float ti2,tr2;
  118953. int t0,t1,t2,t3,t4,t5,t6;
  118954. t1=0;
  118955. t0=(t2=l1*ido);
  118956. t3=ido<<1;
  118957. for(k=0;k<l1;k++){
  118958. ch[t1<<1]=cc[t1]+cc[t2];
  118959. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  118960. t1+=ido;
  118961. t2+=ido;
  118962. }
  118963. if(ido<2)return;
  118964. if(ido==2)goto L105;
  118965. t1=0;
  118966. t2=t0;
  118967. for(k=0;k<l1;k++){
  118968. t3=t2;
  118969. t4=(t1<<1)+(ido<<1);
  118970. t5=t1;
  118971. t6=t1+t1;
  118972. for(i=2;i<ido;i+=2){
  118973. t3+=2;
  118974. t4-=2;
  118975. t5+=2;
  118976. t6+=2;
  118977. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118978. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118979. ch[t6]=cc[t5]+ti2;
  118980. ch[t4]=ti2-cc[t5];
  118981. ch[t6-1]=cc[t5-1]+tr2;
  118982. ch[t4-1]=cc[t5-1]-tr2;
  118983. }
  118984. t1+=ido;
  118985. t2+=ido;
  118986. }
  118987. if(ido%2==1)return;
  118988. L105:
  118989. t3=(t2=(t1=ido)-1);
  118990. t2+=t0;
  118991. for(k=0;k<l1;k++){
  118992. ch[t1]=-cc[t2];
  118993. ch[t1-1]=cc[t3];
  118994. t1+=ido<<1;
  118995. t2+=ido;
  118996. t3+=ido;
  118997. }
  118998. }
  118999. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119000. float *wa2,float *wa3){
  119001. static float hsqt2 = .70710678118654752f;
  119002. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119003. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119004. t0=l1*ido;
  119005. t1=t0;
  119006. t4=t1<<1;
  119007. t2=t1+(t1<<1);
  119008. t3=0;
  119009. for(k=0;k<l1;k++){
  119010. tr1=cc[t1]+cc[t2];
  119011. tr2=cc[t3]+cc[t4];
  119012. ch[t5=t3<<2]=tr1+tr2;
  119013. ch[(ido<<2)+t5-1]=tr2-tr1;
  119014. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119015. ch[t5]=cc[t2]-cc[t1];
  119016. t1+=ido;
  119017. t2+=ido;
  119018. t3+=ido;
  119019. t4+=ido;
  119020. }
  119021. if(ido<2)return;
  119022. if(ido==2)goto L105;
  119023. t1=0;
  119024. for(k=0;k<l1;k++){
  119025. t2=t1;
  119026. t4=t1<<2;
  119027. t5=(t6=ido<<1)+t4;
  119028. for(i=2;i<ido;i+=2){
  119029. t3=(t2+=2);
  119030. t4+=2;
  119031. t5-=2;
  119032. t3+=t0;
  119033. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119034. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119035. t3+=t0;
  119036. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119037. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119038. t3+=t0;
  119039. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119040. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119041. tr1=cr2+cr4;
  119042. tr4=cr4-cr2;
  119043. ti1=ci2+ci4;
  119044. ti4=ci2-ci4;
  119045. ti2=cc[t2]+ci3;
  119046. ti3=cc[t2]-ci3;
  119047. tr2=cc[t2-1]+cr3;
  119048. tr3=cc[t2-1]-cr3;
  119049. ch[t4-1]=tr1+tr2;
  119050. ch[t4]=ti1+ti2;
  119051. ch[t5-1]=tr3-ti4;
  119052. ch[t5]=tr4-ti3;
  119053. ch[t4+t6-1]=ti4+tr3;
  119054. ch[t4+t6]=tr4+ti3;
  119055. ch[t5+t6-1]=tr2-tr1;
  119056. ch[t5+t6]=ti1-ti2;
  119057. }
  119058. t1+=ido;
  119059. }
  119060. if(ido&1)return;
  119061. L105:
  119062. t2=(t1=t0+ido-1)+(t0<<1);
  119063. t3=ido<<2;
  119064. t4=ido;
  119065. t5=ido<<1;
  119066. t6=ido;
  119067. for(k=0;k<l1;k++){
  119068. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119069. tr1=hsqt2*(cc[t1]-cc[t2]);
  119070. ch[t4-1]=tr1+cc[t6-1];
  119071. ch[t4+t5-1]=cc[t6-1]-tr1;
  119072. ch[t4]=ti1-cc[t1+t0];
  119073. ch[t4+t5]=ti1+cc[t1+t0];
  119074. t1+=ido;
  119075. t2+=ido;
  119076. t4+=t3;
  119077. t6+=ido;
  119078. }
  119079. }
  119080. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119081. float *c2,float *ch,float *ch2,float *wa){
  119082. static float tpi=6.283185307179586f;
  119083. int idij,ipph,i,j,k,l,ic,ik,is;
  119084. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119085. float dc2,ai1,ai2,ar1,ar2,ds2;
  119086. int nbd;
  119087. float dcp,arg,dsp,ar1h,ar2h;
  119088. int idp2,ipp2;
  119089. arg=tpi/(float)ip;
  119090. dcp=cos(arg);
  119091. dsp=sin(arg);
  119092. ipph=(ip+1)>>1;
  119093. ipp2=ip;
  119094. idp2=ido;
  119095. nbd=(ido-1)>>1;
  119096. t0=l1*ido;
  119097. t10=ip*ido;
  119098. if(ido==1)goto L119;
  119099. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119100. t1=0;
  119101. for(j=1;j<ip;j++){
  119102. t1+=t0;
  119103. t2=t1;
  119104. for(k=0;k<l1;k++){
  119105. ch[t2]=c1[t2];
  119106. t2+=ido;
  119107. }
  119108. }
  119109. is=-ido;
  119110. t1=0;
  119111. if(nbd>l1){
  119112. for(j=1;j<ip;j++){
  119113. t1+=t0;
  119114. is+=ido;
  119115. t2= -ido+t1;
  119116. for(k=0;k<l1;k++){
  119117. idij=is-1;
  119118. t2+=ido;
  119119. t3=t2;
  119120. for(i=2;i<ido;i+=2){
  119121. idij+=2;
  119122. t3+=2;
  119123. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119124. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119125. }
  119126. }
  119127. }
  119128. }else{
  119129. for(j=1;j<ip;j++){
  119130. is+=ido;
  119131. idij=is-1;
  119132. t1+=t0;
  119133. t2=t1;
  119134. for(i=2;i<ido;i+=2){
  119135. idij+=2;
  119136. t2+=2;
  119137. t3=t2;
  119138. for(k=0;k<l1;k++){
  119139. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119140. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119141. t3+=ido;
  119142. }
  119143. }
  119144. }
  119145. }
  119146. t1=0;
  119147. t2=ipp2*t0;
  119148. if(nbd<l1){
  119149. for(j=1;j<ipph;j++){
  119150. t1+=t0;
  119151. t2-=t0;
  119152. t3=t1;
  119153. t4=t2;
  119154. for(i=2;i<ido;i+=2){
  119155. t3+=2;
  119156. t4+=2;
  119157. t5=t3-ido;
  119158. t6=t4-ido;
  119159. for(k=0;k<l1;k++){
  119160. t5+=ido;
  119161. t6+=ido;
  119162. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119163. c1[t6-1]=ch[t5]-ch[t6];
  119164. c1[t5]=ch[t5]+ch[t6];
  119165. c1[t6]=ch[t6-1]-ch[t5-1];
  119166. }
  119167. }
  119168. }
  119169. }else{
  119170. for(j=1;j<ipph;j++){
  119171. t1+=t0;
  119172. t2-=t0;
  119173. t3=t1;
  119174. t4=t2;
  119175. for(k=0;k<l1;k++){
  119176. t5=t3;
  119177. t6=t4;
  119178. for(i=2;i<ido;i+=2){
  119179. t5+=2;
  119180. t6+=2;
  119181. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119182. c1[t6-1]=ch[t5]-ch[t6];
  119183. c1[t5]=ch[t5]+ch[t6];
  119184. c1[t6]=ch[t6-1]-ch[t5-1];
  119185. }
  119186. t3+=ido;
  119187. t4+=ido;
  119188. }
  119189. }
  119190. }
  119191. L119:
  119192. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119193. t1=0;
  119194. t2=ipp2*idl1;
  119195. for(j=1;j<ipph;j++){
  119196. t1+=t0;
  119197. t2-=t0;
  119198. t3=t1-ido;
  119199. t4=t2-ido;
  119200. for(k=0;k<l1;k++){
  119201. t3+=ido;
  119202. t4+=ido;
  119203. c1[t3]=ch[t3]+ch[t4];
  119204. c1[t4]=ch[t4]-ch[t3];
  119205. }
  119206. }
  119207. ar1=1.f;
  119208. ai1=0.f;
  119209. t1=0;
  119210. t2=ipp2*idl1;
  119211. t3=(ip-1)*idl1;
  119212. for(l=1;l<ipph;l++){
  119213. t1+=idl1;
  119214. t2-=idl1;
  119215. ar1h=dcp*ar1-dsp*ai1;
  119216. ai1=dcp*ai1+dsp*ar1;
  119217. ar1=ar1h;
  119218. t4=t1;
  119219. t5=t2;
  119220. t6=t3;
  119221. t7=idl1;
  119222. for(ik=0;ik<idl1;ik++){
  119223. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119224. ch2[t5++]=ai1*c2[t6++];
  119225. }
  119226. dc2=ar1;
  119227. ds2=ai1;
  119228. ar2=ar1;
  119229. ai2=ai1;
  119230. t4=idl1;
  119231. t5=(ipp2-1)*idl1;
  119232. for(j=2;j<ipph;j++){
  119233. t4+=idl1;
  119234. t5-=idl1;
  119235. ar2h=dc2*ar2-ds2*ai2;
  119236. ai2=dc2*ai2+ds2*ar2;
  119237. ar2=ar2h;
  119238. t6=t1;
  119239. t7=t2;
  119240. t8=t4;
  119241. t9=t5;
  119242. for(ik=0;ik<idl1;ik++){
  119243. ch2[t6++]+=ar2*c2[t8++];
  119244. ch2[t7++]+=ai2*c2[t9++];
  119245. }
  119246. }
  119247. }
  119248. t1=0;
  119249. for(j=1;j<ipph;j++){
  119250. t1+=idl1;
  119251. t2=t1;
  119252. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119253. }
  119254. if(ido<l1)goto L132;
  119255. t1=0;
  119256. t2=0;
  119257. for(k=0;k<l1;k++){
  119258. t3=t1;
  119259. t4=t2;
  119260. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119261. t1+=ido;
  119262. t2+=t10;
  119263. }
  119264. goto L135;
  119265. L132:
  119266. for(i=0;i<ido;i++){
  119267. t1=i;
  119268. t2=i;
  119269. for(k=0;k<l1;k++){
  119270. cc[t2]=ch[t1];
  119271. t1+=ido;
  119272. t2+=t10;
  119273. }
  119274. }
  119275. L135:
  119276. t1=0;
  119277. t2=ido<<1;
  119278. t3=0;
  119279. t4=ipp2*t0;
  119280. for(j=1;j<ipph;j++){
  119281. t1+=t2;
  119282. t3+=t0;
  119283. t4-=t0;
  119284. t5=t1;
  119285. t6=t3;
  119286. t7=t4;
  119287. for(k=0;k<l1;k++){
  119288. cc[t5-1]=ch[t6];
  119289. cc[t5]=ch[t7];
  119290. t5+=t10;
  119291. t6+=ido;
  119292. t7+=ido;
  119293. }
  119294. }
  119295. if(ido==1)return;
  119296. if(nbd<l1)goto L141;
  119297. t1=-ido;
  119298. t3=0;
  119299. t4=0;
  119300. t5=ipp2*t0;
  119301. for(j=1;j<ipph;j++){
  119302. t1+=t2;
  119303. t3+=t2;
  119304. t4+=t0;
  119305. t5-=t0;
  119306. t6=t1;
  119307. t7=t3;
  119308. t8=t4;
  119309. t9=t5;
  119310. for(k=0;k<l1;k++){
  119311. for(i=2;i<ido;i+=2){
  119312. ic=idp2-i;
  119313. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119314. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119315. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119316. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119317. }
  119318. t6+=t10;
  119319. t7+=t10;
  119320. t8+=ido;
  119321. t9+=ido;
  119322. }
  119323. }
  119324. return;
  119325. L141:
  119326. t1=-ido;
  119327. t3=0;
  119328. t4=0;
  119329. t5=ipp2*t0;
  119330. for(j=1;j<ipph;j++){
  119331. t1+=t2;
  119332. t3+=t2;
  119333. t4+=t0;
  119334. t5-=t0;
  119335. for(i=2;i<ido;i+=2){
  119336. t6=idp2+t1-i;
  119337. t7=i+t3;
  119338. t8=i+t4;
  119339. t9=i+t5;
  119340. for(k=0;k<l1;k++){
  119341. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119342. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119343. cc[t7]=ch[t8]+ch[t9];
  119344. cc[t6]=ch[t9]-ch[t8];
  119345. t6+=t10;
  119346. t7+=t10;
  119347. t8+=ido;
  119348. t9+=ido;
  119349. }
  119350. }
  119351. }
  119352. }
  119353. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119354. int i,k1,l1,l2;
  119355. int na,kh,nf;
  119356. int ip,iw,ido,idl1,ix2,ix3;
  119357. nf=ifac[1];
  119358. na=1;
  119359. l2=n;
  119360. iw=n;
  119361. for(k1=0;k1<nf;k1++){
  119362. kh=nf-k1;
  119363. ip=ifac[kh+1];
  119364. l1=l2/ip;
  119365. ido=n/l2;
  119366. idl1=ido*l1;
  119367. iw-=(ip-1)*ido;
  119368. na=1-na;
  119369. if(ip!=4)goto L102;
  119370. ix2=iw+ido;
  119371. ix3=ix2+ido;
  119372. if(na!=0)
  119373. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119374. else
  119375. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119376. goto L110;
  119377. L102:
  119378. if(ip!=2)goto L104;
  119379. if(na!=0)goto L103;
  119380. dradf2(ido,l1,c,ch,wa+iw-1);
  119381. goto L110;
  119382. L103:
  119383. dradf2(ido,l1,ch,c,wa+iw-1);
  119384. goto L110;
  119385. L104:
  119386. if(ido==1)na=1-na;
  119387. if(na!=0)goto L109;
  119388. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119389. na=1;
  119390. goto L110;
  119391. L109:
  119392. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119393. na=0;
  119394. L110:
  119395. l2=l1;
  119396. }
  119397. if(na==1)return;
  119398. for(i=0;i<n;i++)c[i]=ch[i];
  119399. }
  119400. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119401. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119402. float ti2,tr2;
  119403. t0=l1*ido;
  119404. t1=0;
  119405. t2=0;
  119406. t3=(ido<<1)-1;
  119407. for(k=0;k<l1;k++){
  119408. ch[t1]=cc[t2]+cc[t3+t2];
  119409. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119410. t2=(t1+=ido)<<1;
  119411. }
  119412. if(ido<2)return;
  119413. if(ido==2)goto L105;
  119414. t1=0;
  119415. t2=0;
  119416. for(k=0;k<l1;k++){
  119417. t3=t1;
  119418. t5=(t4=t2)+(ido<<1);
  119419. t6=t0+t1;
  119420. for(i=2;i<ido;i+=2){
  119421. t3+=2;
  119422. t4+=2;
  119423. t5-=2;
  119424. t6+=2;
  119425. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119426. tr2=cc[t4-1]-cc[t5-1];
  119427. ch[t3]=cc[t4]-cc[t5];
  119428. ti2=cc[t4]+cc[t5];
  119429. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119430. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119431. }
  119432. t2=(t1+=ido)<<1;
  119433. }
  119434. if(ido%2==1)return;
  119435. L105:
  119436. t1=ido-1;
  119437. t2=ido-1;
  119438. for(k=0;k<l1;k++){
  119439. ch[t1]=cc[t2]+cc[t2];
  119440. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119441. t1+=ido;
  119442. t2+=ido<<1;
  119443. }
  119444. }
  119445. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119446. float *wa2){
  119447. static float taur = -.5f;
  119448. static float taui = .8660254037844386f;
  119449. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119450. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119451. t0=l1*ido;
  119452. t1=0;
  119453. t2=t0<<1;
  119454. t3=ido<<1;
  119455. t4=ido+(ido<<1);
  119456. t5=0;
  119457. for(k=0;k<l1;k++){
  119458. tr2=cc[t3-1]+cc[t3-1];
  119459. cr2=cc[t5]+(taur*tr2);
  119460. ch[t1]=cc[t5]+tr2;
  119461. ci3=taui*(cc[t3]+cc[t3]);
  119462. ch[t1+t0]=cr2-ci3;
  119463. ch[t1+t2]=cr2+ci3;
  119464. t1+=ido;
  119465. t3+=t4;
  119466. t5+=t4;
  119467. }
  119468. if(ido==1)return;
  119469. t1=0;
  119470. t3=ido<<1;
  119471. for(k=0;k<l1;k++){
  119472. t7=t1+(t1<<1);
  119473. t6=(t5=t7+t3);
  119474. t8=t1;
  119475. t10=(t9=t1+t0)+t0;
  119476. for(i=2;i<ido;i+=2){
  119477. t5+=2;
  119478. t6-=2;
  119479. t7+=2;
  119480. t8+=2;
  119481. t9+=2;
  119482. t10+=2;
  119483. tr2=cc[t5-1]+cc[t6-1];
  119484. cr2=cc[t7-1]+(taur*tr2);
  119485. ch[t8-1]=cc[t7-1]+tr2;
  119486. ti2=cc[t5]-cc[t6];
  119487. ci2=cc[t7]+(taur*ti2);
  119488. ch[t8]=cc[t7]+ti2;
  119489. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119490. ci3=taui*(cc[t5]+cc[t6]);
  119491. dr2=cr2-ci3;
  119492. dr3=cr2+ci3;
  119493. di2=ci2+cr3;
  119494. di3=ci2-cr3;
  119495. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119496. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119497. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119498. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119499. }
  119500. t1+=ido;
  119501. }
  119502. }
  119503. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119504. float *wa2,float *wa3){
  119505. static float sqrt2=1.414213562373095f;
  119506. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119507. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119508. t0=l1*ido;
  119509. t1=0;
  119510. t2=ido<<2;
  119511. t3=0;
  119512. t6=ido<<1;
  119513. for(k=0;k<l1;k++){
  119514. t4=t3+t6;
  119515. t5=t1;
  119516. tr3=cc[t4-1]+cc[t4-1];
  119517. tr4=cc[t4]+cc[t4];
  119518. tr1=cc[t3]-cc[(t4+=t6)-1];
  119519. tr2=cc[t3]+cc[t4-1];
  119520. ch[t5]=tr2+tr3;
  119521. ch[t5+=t0]=tr1-tr4;
  119522. ch[t5+=t0]=tr2-tr3;
  119523. ch[t5+=t0]=tr1+tr4;
  119524. t1+=ido;
  119525. t3+=t2;
  119526. }
  119527. if(ido<2)return;
  119528. if(ido==2)goto L105;
  119529. t1=0;
  119530. for(k=0;k<l1;k++){
  119531. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119532. t7=t1;
  119533. for(i=2;i<ido;i+=2){
  119534. t2+=2;
  119535. t3+=2;
  119536. t4-=2;
  119537. t5-=2;
  119538. t7+=2;
  119539. ti1=cc[t2]+cc[t5];
  119540. ti2=cc[t2]-cc[t5];
  119541. ti3=cc[t3]-cc[t4];
  119542. tr4=cc[t3]+cc[t4];
  119543. tr1=cc[t2-1]-cc[t5-1];
  119544. tr2=cc[t2-1]+cc[t5-1];
  119545. ti4=cc[t3-1]-cc[t4-1];
  119546. tr3=cc[t3-1]+cc[t4-1];
  119547. ch[t7-1]=tr2+tr3;
  119548. cr3=tr2-tr3;
  119549. ch[t7]=ti2+ti3;
  119550. ci3=ti2-ti3;
  119551. cr2=tr1-tr4;
  119552. cr4=tr1+tr4;
  119553. ci2=ti1+ti4;
  119554. ci4=ti1-ti4;
  119555. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119556. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119557. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119558. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119559. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119560. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119561. }
  119562. t1+=ido;
  119563. }
  119564. if(ido%2 == 1)return;
  119565. L105:
  119566. t1=ido;
  119567. t2=ido<<2;
  119568. t3=ido-1;
  119569. t4=ido+(ido<<1);
  119570. for(k=0;k<l1;k++){
  119571. t5=t3;
  119572. ti1=cc[t1]+cc[t4];
  119573. ti2=cc[t4]-cc[t1];
  119574. tr1=cc[t1-1]-cc[t4-1];
  119575. tr2=cc[t1-1]+cc[t4-1];
  119576. ch[t5]=tr2+tr2;
  119577. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119578. ch[t5+=t0]=ti2+ti2;
  119579. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119580. t3+=ido;
  119581. t1+=t2;
  119582. t4+=t2;
  119583. }
  119584. }
  119585. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119586. float *c2,float *ch,float *ch2,float *wa){
  119587. static float tpi=6.283185307179586f;
  119588. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119589. t11,t12;
  119590. float dc2,ai1,ai2,ar1,ar2,ds2;
  119591. int nbd;
  119592. float dcp,arg,dsp,ar1h,ar2h;
  119593. int ipp2;
  119594. t10=ip*ido;
  119595. t0=l1*ido;
  119596. arg=tpi/(float)ip;
  119597. dcp=cos(arg);
  119598. dsp=sin(arg);
  119599. nbd=(ido-1)>>1;
  119600. ipp2=ip;
  119601. ipph=(ip+1)>>1;
  119602. if(ido<l1)goto L103;
  119603. t1=0;
  119604. t2=0;
  119605. for(k=0;k<l1;k++){
  119606. t3=t1;
  119607. t4=t2;
  119608. for(i=0;i<ido;i++){
  119609. ch[t3]=cc[t4];
  119610. t3++;
  119611. t4++;
  119612. }
  119613. t1+=ido;
  119614. t2+=t10;
  119615. }
  119616. goto L106;
  119617. L103:
  119618. t1=0;
  119619. for(i=0;i<ido;i++){
  119620. t2=t1;
  119621. t3=t1;
  119622. for(k=0;k<l1;k++){
  119623. ch[t2]=cc[t3];
  119624. t2+=ido;
  119625. t3+=t10;
  119626. }
  119627. t1++;
  119628. }
  119629. L106:
  119630. t1=0;
  119631. t2=ipp2*t0;
  119632. t7=(t5=ido<<1);
  119633. for(j=1;j<ipph;j++){
  119634. t1+=t0;
  119635. t2-=t0;
  119636. t3=t1;
  119637. t4=t2;
  119638. t6=t5;
  119639. for(k=0;k<l1;k++){
  119640. ch[t3]=cc[t6-1]+cc[t6-1];
  119641. ch[t4]=cc[t6]+cc[t6];
  119642. t3+=ido;
  119643. t4+=ido;
  119644. t6+=t10;
  119645. }
  119646. t5+=t7;
  119647. }
  119648. if (ido == 1)goto L116;
  119649. if(nbd<l1)goto L112;
  119650. t1=0;
  119651. t2=ipp2*t0;
  119652. t7=0;
  119653. for(j=1;j<ipph;j++){
  119654. t1+=t0;
  119655. t2-=t0;
  119656. t3=t1;
  119657. t4=t2;
  119658. t7+=(ido<<1);
  119659. t8=t7;
  119660. for(k=0;k<l1;k++){
  119661. t5=t3;
  119662. t6=t4;
  119663. t9=t8;
  119664. t11=t8;
  119665. for(i=2;i<ido;i+=2){
  119666. t5+=2;
  119667. t6+=2;
  119668. t9+=2;
  119669. t11-=2;
  119670. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119671. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119672. ch[t5]=cc[t9]-cc[t11];
  119673. ch[t6]=cc[t9]+cc[t11];
  119674. }
  119675. t3+=ido;
  119676. t4+=ido;
  119677. t8+=t10;
  119678. }
  119679. }
  119680. goto L116;
  119681. L112:
  119682. t1=0;
  119683. t2=ipp2*t0;
  119684. t7=0;
  119685. for(j=1;j<ipph;j++){
  119686. t1+=t0;
  119687. t2-=t0;
  119688. t3=t1;
  119689. t4=t2;
  119690. t7+=(ido<<1);
  119691. t8=t7;
  119692. t9=t7;
  119693. for(i=2;i<ido;i+=2){
  119694. t3+=2;
  119695. t4+=2;
  119696. t8+=2;
  119697. t9-=2;
  119698. t5=t3;
  119699. t6=t4;
  119700. t11=t8;
  119701. t12=t9;
  119702. for(k=0;k<l1;k++){
  119703. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119704. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119705. ch[t5]=cc[t11]-cc[t12];
  119706. ch[t6]=cc[t11]+cc[t12];
  119707. t5+=ido;
  119708. t6+=ido;
  119709. t11+=t10;
  119710. t12+=t10;
  119711. }
  119712. }
  119713. }
  119714. L116:
  119715. ar1=1.f;
  119716. ai1=0.f;
  119717. t1=0;
  119718. t9=(t2=ipp2*idl1);
  119719. t3=(ip-1)*idl1;
  119720. for(l=1;l<ipph;l++){
  119721. t1+=idl1;
  119722. t2-=idl1;
  119723. ar1h=dcp*ar1-dsp*ai1;
  119724. ai1=dcp*ai1+dsp*ar1;
  119725. ar1=ar1h;
  119726. t4=t1;
  119727. t5=t2;
  119728. t6=0;
  119729. t7=idl1;
  119730. t8=t3;
  119731. for(ik=0;ik<idl1;ik++){
  119732. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119733. c2[t5++]=ai1*ch2[t8++];
  119734. }
  119735. dc2=ar1;
  119736. ds2=ai1;
  119737. ar2=ar1;
  119738. ai2=ai1;
  119739. t6=idl1;
  119740. t7=t9-idl1;
  119741. for(j=2;j<ipph;j++){
  119742. t6+=idl1;
  119743. t7-=idl1;
  119744. ar2h=dc2*ar2-ds2*ai2;
  119745. ai2=dc2*ai2+ds2*ar2;
  119746. ar2=ar2h;
  119747. t4=t1;
  119748. t5=t2;
  119749. t11=t6;
  119750. t12=t7;
  119751. for(ik=0;ik<idl1;ik++){
  119752. c2[t4++]+=ar2*ch2[t11++];
  119753. c2[t5++]+=ai2*ch2[t12++];
  119754. }
  119755. }
  119756. }
  119757. t1=0;
  119758. for(j=1;j<ipph;j++){
  119759. t1+=idl1;
  119760. t2=t1;
  119761. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119762. }
  119763. t1=0;
  119764. t2=ipp2*t0;
  119765. for(j=1;j<ipph;j++){
  119766. t1+=t0;
  119767. t2-=t0;
  119768. t3=t1;
  119769. t4=t2;
  119770. for(k=0;k<l1;k++){
  119771. ch[t3]=c1[t3]-c1[t4];
  119772. ch[t4]=c1[t3]+c1[t4];
  119773. t3+=ido;
  119774. t4+=ido;
  119775. }
  119776. }
  119777. if(ido==1)goto L132;
  119778. if(nbd<l1)goto L128;
  119779. t1=0;
  119780. t2=ipp2*t0;
  119781. for(j=1;j<ipph;j++){
  119782. t1+=t0;
  119783. t2-=t0;
  119784. t3=t1;
  119785. t4=t2;
  119786. for(k=0;k<l1;k++){
  119787. t5=t3;
  119788. t6=t4;
  119789. for(i=2;i<ido;i+=2){
  119790. t5+=2;
  119791. t6+=2;
  119792. ch[t5-1]=c1[t5-1]-c1[t6];
  119793. ch[t6-1]=c1[t5-1]+c1[t6];
  119794. ch[t5]=c1[t5]+c1[t6-1];
  119795. ch[t6]=c1[t5]-c1[t6-1];
  119796. }
  119797. t3+=ido;
  119798. t4+=ido;
  119799. }
  119800. }
  119801. goto L132;
  119802. L128:
  119803. t1=0;
  119804. t2=ipp2*t0;
  119805. for(j=1;j<ipph;j++){
  119806. t1+=t0;
  119807. t2-=t0;
  119808. t3=t1;
  119809. t4=t2;
  119810. for(i=2;i<ido;i+=2){
  119811. t3+=2;
  119812. t4+=2;
  119813. t5=t3;
  119814. t6=t4;
  119815. for(k=0;k<l1;k++){
  119816. ch[t5-1]=c1[t5-1]-c1[t6];
  119817. ch[t6-1]=c1[t5-1]+c1[t6];
  119818. ch[t5]=c1[t5]+c1[t6-1];
  119819. ch[t6]=c1[t5]-c1[t6-1];
  119820. t5+=ido;
  119821. t6+=ido;
  119822. }
  119823. }
  119824. }
  119825. L132:
  119826. if(ido==1)return;
  119827. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119828. t1=0;
  119829. for(j=1;j<ip;j++){
  119830. t2=(t1+=t0);
  119831. for(k=0;k<l1;k++){
  119832. c1[t2]=ch[t2];
  119833. t2+=ido;
  119834. }
  119835. }
  119836. if(nbd>l1)goto L139;
  119837. is= -ido-1;
  119838. t1=0;
  119839. for(j=1;j<ip;j++){
  119840. is+=ido;
  119841. t1+=t0;
  119842. idij=is;
  119843. t2=t1;
  119844. for(i=2;i<ido;i+=2){
  119845. t2+=2;
  119846. idij+=2;
  119847. t3=t2;
  119848. for(k=0;k<l1;k++){
  119849. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119850. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119851. t3+=ido;
  119852. }
  119853. }
  119854. }
  119855. return;
  119856. L139:
  119857. is= -ido-1;
  119858. t1=0;
  119859. for(j=1;j<ip;j++){
  119860. is+=ido;
  119861. t1+=t0;
  119862. t2=t1;
  119863. for(k=0;k<l1;k++){
  119864. idij=is;
  119865. t3=t2;
  119866. for(i=2;i<ido;i+=2){
  119867. idij+=2;
  119868. t3+=2;
  119869. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119870. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119871. }
  119872. t2+=ido;
  119873. }
  119874. }
  119875. }
  119876. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  119877. int i,k1,l1,l2;
  119878. int na;
  119879. int nf,ip,iw,ix2,ix3,ido,idl1;
  119880. nf=ifac[1];
  119881. na=0;
  119882. l1=1;
  119883. iw=1;
  119884. for(k1=0;k1<nf;k1++){
  119885. ip=ifac[k1 + 2];
  119886. l2=ip*l1;
  119887. ido=n/l2;
  119888. idl1=ido*l1;
  119889. if(ip!=4)goto L103;
  119890. ix2=iw+ido;
  119891. ix3=ix2+ido;
  119892. if(na!=0)
  119893. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119894. else
  119895. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119896. na=1-na;
  119897. goto L115;
  119898. L103:
  119899. if(ip!=2)goto L106;
  119900. if(na!=0)
  119901. dradb2(ido,l1,ch,c,wa+iw-1);
  119902. else
  119903. dradb2(ido,l1,c,ch,wa+iw-1);
  119904. na=1-na;
  119905. goto L115;
  119906. L106:
  119907. if(ip!=3)goto L109;
  119908. ix2=iw+ido;
  119909. if(na!=0)
  119910. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  119911. else
  119912. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  119913. na=1-na;
  119914. goto L115;
  119915. L109:
  119916. /* The radix five case can be translated later..... */
  119917. /* if(ip!=5)goto L112;
  119918. ix2=iw+ido;
  119919. ix3=ix2+ido;
  119920. ix4=ix3+ido;
  119921. if(na!=0)
  119922. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119923. else
  119924. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119925. na=1-na;
  119926. goto L115;
  119927. L112:*/
  119928. if(na!=0)
  119929. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119930. else
  119931. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119932. if(ido==1)na=1-na;
  119933. L115:
  119934. l1=l2;
  119935. iw+=(ip-1)*ido;
  119936. }
  119937. if(na==0)return;
  119938. for(i=0;i<n;i++)c[i]=ch[i];
  119939. }
  119940. void drft_forward(drft_lookup *l,float *data){
  119941. if(l->n==1)return;
  119942. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119943. }
  119944. void drft_backward(drft_lookup *l,float *data){
  119945. if (l->n==1)return;
  119946. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119947. }
  119948. void drft_init(drft_lookup *l,int n){
  119949. l->n=n;
  119950. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  119951. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  119952. fdrffti(n, l->trigcache, l->splitcache);
  119953. }
  119954. void drft_clear(drft_lookup *l){
  119955. if(l){
  119956. if(l->trigcache)_ogg_free(l->trigcache);
  119957. if(l->splitcache)_ogg_free(l->splitcache);
  119958. memset(l,0,sizeof(*l));
  119959. }
  119960. }
  119961. #endif
  119962. /*** End of inlined file: smallft.c ***/
  119963. /*** Start of inlined file: synthesis.c ***/
  119964. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119965. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119966. // tasks..
  119967. #if JUCE_MSVC
  119968. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119969. #endif
  119970. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119971. #if JUCE_USE_OGGVORBIS
  119972. #include <stdio.h>
  119973. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  119974. vorbis_dsp_state *vd=vb->vd;
  119975. private_state *b=(private_state*)vd->backend_state;
  119976. vorbis_info *vi=vd->vi;
  119977. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  119978. oggpack_buffer *opb=&vb->opb;
  119979. int type,mode,i;
  119980. /* first things first. Make sure decode is ready */
  119981. _vorbis_block_ripcord(vb);
  119982. oggpack_readinit(opb,op->packet,op->bytes);
  119983. /* Check the packet type */
  119984. if(oggpack_read(opb,1)!=0){
  119985. /* Oops. This is not an audio data packet */
  119986. return(OV_ENOTAUDIO);
  119987. }
  119988. /* read our mode and pre/post windowsize */
  119989. mode=oggpack_read(opb,b->modebits);
  119990. if(mode==-1)return(OV_EBADPACKET);
  119991. vb->mode=mode;
  119992. vb->W=ci->mode_param[mode]->blockflag;
  119993. if(vb->W){
  119994. /* this doesn;t get mapped through mode selection as it's used
  119995. only for window selection */
  119996. vb->lW=oggpack_read(opb,1);
  119997. vb->nW=oggpack_read(opb,1);
  119998. if(vb->nW==-1) return(OV_EBADPACKET);
  119999. }else{
  120000. vb->lW=0;
  120001. vb->nW=0;
  120002. }
  120003. /* more setup */
  120004. vb->granulepos=op->granulepos;
  120005. vb->sequence=op->packetno;
  120006. vb->eofflag=op->e_o_s;
  120007. /* alloc pcm passback storage */
  120008. vb->pcmend=ci->blocksizes[vb->W];
  120009. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120010. for(i=0;i<vi->channels;i++)
  120011. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120012. /* unpack_header enforces range checking */
  120013. type=ci->map_type[ci->mode_param[mode]->mapping];
  120014. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120015. mapping]));
  120016. }
  120017. /* used to track pcm position without actually performing decode.
  120018. Useful for sequential 'fast forward' */
  120019. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120020. vorbis_dsp_state *vd=vb->vd;
  120021. private_state *b=(private_state*)vd->backend_state;
  120022. vorbis_info *vi=vd->vi;
  120023. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120024. oggpack_buffer *opb=&vb->opb;
  120025. int mode;
  120026. /* first things first. Make sure decode is ready */
  120027. _vorbis_block_ripcord(vb);
  120028. oggpack_readinit(opb,op->packet,op->bytes);
  120029. /* Check the packet type */
  120030. if(oggpack_read(opb,1)!=0){
  120031. /* Oops. This is not an audio data packet */
  120032. return(OV_ENOTAUDIO);
  120033. }
  120034. /* read our mode and pre/post windowsize */
  120035. mode=oggpack_read(opb,b->modebits);
  120036. if(mode==-1)return(OV_EBADPACKET);
  120037. vb->mode=mode;
  120038. vb->W=ci->mode_param[mode]->blockflag;
  120039. if(vb->W){
  120040. vb->lW=oggpack_read(opb,1);
  120041. vb->nW=oggpack_read(opb,1);
  120042. if(vb->nW==-1) return(OV_EBADPACKET);
  120043. }else{
  120044. vb->lW=0;
  120045. vb->nW=0;
  120046. }
  120047. /* more setup */
  120048. vb->granulepos=op->granulepos;
  120049. vb->sequence=op->packetno;
  120050. vb->eofflag=op->e_o_s;
  120051. /* no pcm */
  120052. vb->pcmend=0;
  120053. vb->pcm=NULL;
  120054. return(0);
  120055. }
  120056. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120057. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120058. oggpack_buffer opb;
  120059. int mode;
  120060. oggpack_readinit(&opb,op->packet,op->bytes);
  120061. /* Check the packet type */
  120062. if(oggpack_read(&opb,1)!=0){
  120063. /* Oops. This is not an audio data packet */
  120064. return(OV_ENOTAUDIO);
  120065. }
  120066. {
  120067. int modebits=0;
  120068. int v=ci->modes;
  120069. while(v>1){
  120070. modebits++;
  120071. v>>=1;
  120072. }
  120073. /* read our mode and pre/post windowsize */
  120074. mode=oggpack_read(&opb,modebits);
  120075. }
  120076. if(mode==-1)return(OV_EBADPACKET);
  120077. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120078. }
  120079. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120080. /* set / clear half-sample-rate mode */
  120081. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120082. /* right now, our MDCT can't handle < 64 sample windows. */
  120083. if(ci->blocksizes[0]<=64 && flag)return -1;
  120084. ci->halfrate_flag=(flag?1:0);
  120085. return 0;
  120086. }
  120087. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120088. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120089. return ci->halfrate_flag;
  120090. }
  120091. #endif
  120092. /*** End of inlined file: synthesis.c ***/
  120093. /*** Start of inlined file: vorbisenc.c ***/
  120094. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120095. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120096. // tasks..
  120097. #if JUCE_MSVC
  120098. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120099. #endif
  120100. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120101. #if JUCE_USE_OGGVORBIS
  120102. #include <stdlib.h>
  120103. #include <string.h>
  120104. #include <math.h>
  120105. /* careful with this; it's using static array sizing to make managing
  120106. all the modes a little less annoying. If we use a residue backend
  120107. with > 12 partition types, or a different division of iteration,
  120108. this needs to be updated. */
  120109. typedef struct {
  120110. static_codebook *books[12][3];
  120111. } static_bookblock;
  120112. typedef struct {
  120113. int res_type;
  120114. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120115. vorbis_info_residue0 *res;
  120116. static_codebook *book_aux;
  120117. static_codebook *book_aux_managed;
  120118. static_bookblock *books_base;
  120119. static_bookblock *books_base_managed;
  120120. } vorbis_residue_template;
  120121. typedef struct {
  120122. vorbis_info_mapping0 *map;
  120123. vorbis_residue_template *res;
  120124. } vorbis_mapping_template;
  120125. typedef struct vp_adjblock{
  120126. int block[P_BANDS];
  120127. } vp_adjblock;
  120128. typedef struct {
  120129. int data[NOISE_COMPAND_LEVELS];
  120130. } compandblock;
  120131. /* high level configuration information for setting things up
  120132. step-by-step with the detailed vorbis_encode_ctl interface.
  120133. There's a fair amount of redundancy such that interactive setup
  120134. does not directly deal with any vorbis_info or codec_setup_info
  120135. initialization; it's all stored (until full init) in this highlevel
  120136. setup, then flushed out to the real codec setup structs later. */
  120137. typedef struct {
  120138. int att[P_NOISECURVES];
  120139. float boost;
  120140. float decay;
  120141. } att3;
  120142. typedef struct { int data[P_NOISECURVES]; } adj3;
  120143. typedef struct {
  120144. int pre[PACKETBLOBS];
  120145. int post[PACKETBLOBS];
  120146. float kHz[PACKETBLOBS];
  120147. float lowpasskHz[PACKETBLOBS];
  120148. } adj_stereo;
  120149. typedef struct {
  120150. int lo;
  120151. int hi;
  120152. int fixed;
  120153. } noiseguard;
  120154. typedef struct {
  120155. int data[P_NOISECURVES][17];
  120156. } noise3;
  120157. typedef struct {
  120158. int mappings;
  120159. double *rate_mapping;
  120160. double *quality_mapping;
  120161. int coupling_restriction;
  120162. long samplerate_min_restriction;
  120163. long samplerate_max_restriction;
  120164. int *blocksize_short;
  120165. int *blocksize_long;
  120166. att3 *psy_tone_masteratt;
  120167. int *psy_tone_0dB;
  120168. int *psy_tone_dBsuppress;
  120169. vp_adjblock *psy_tone_adj_impulse;
  120170. vp_adjblock *psy_tone_adj_long;
  120171. vp_adjblock *psy_tone_adj_other;
  120172. noiseguard *psy_noiseguards;
  120173. noise3 *psy_noise_bias_impulse;
  120174. noise3 *psy_noise_bias_padding;
  120175. noise3 *psy_noise_bias_trans;
  120176. noise3 *psy_noise_bias_long;
  120177. int *psy_noise_dBsuppress;
  120178. compandblock *psy_noise_compand;
  120179. double *psy_noise_compand_short_mapping;
  120180. double *psy_noise_compand_long_mapping;
  120181. int *psy_noise_normal_start[2];
  120182. int *psy_noise_normal_partition[2];
  120183. double *psy_noise_normal_thresh;
  120184. int *psy_ath_float;
  120185. int *psy_ath_abs;
  120186. double *psy_lowpass;
  120187. vorbis_info_psy_global *global_params;
  120188. double *global_mapping;
  120189. adj_stereo *stereo_modes;
  120190. static_codebook ***floor_books;
  120191. vorbis_info_floor1 *floor_params;
  120192. int *floor_short_mapping;
  120193. int *floor_long_mapping;
  120194. vorbis_mapping_template *maps;
  120195. } ve_setup_data_template;
  120196. /* a few static coder conventions */
  120197. static vorbis_info_mode _mode_template[2]={
  120198. {0,0,0,0},
  120199. {1,0,0,1}
  120200. };
  120201. static vorbis_info_mapping0 _map_nominal[2]={
  120202. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120203. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120204. };
  120205. /*** Start of inlined file: setup_44.h ***/
  120206. /*** Start of inlined file: floor_all.h ***/
  120207. /*** Start of inlined file: floor_books.h ***/
  120208. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120209. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120210. };
  120211. static static_codebook _huff_book_line_256x7_0sub1 = {
  120212. 1, 9,
  120213. _huff_lengthlist_line_256x7_0sub1,
  120214. 0, 0, 0, 0, 0,
  120215. NULL,
  120216. NULL,
  120217. NULL,
  120218. NULL,
  120219. 0
  120220. };
  120221. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120223. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120224. };
  120225. static static_codebook _huff_book_line_256x7_0sub2 = {
  120226. 1, 25,
  120227. _huff_lengthlist_line_256x7_0sub2,
  120228. 0, 0, 0, 0, 0,
  120229. NULL,
  120230. NULL,
  120231. NULL,
  120232. NULL,
  120233. 0
  120234. };
  120235. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120238. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120239. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120240. };
  120241. static static_codebook _huff_book_line_256x7_0sub3 = {
  120242. 1, 64,
  120243. _huff_lengthlist_line_256x7_0sub3,
  120244. 0, 0, 0, 0, 0,
  120245. NULL,
  120246. NULL,
  120247. NULL,
  120248. NULL,
  120249. 0
  120250. };
  120251. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120252. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120253. };
  120254. static static_codebook _huff_book_line_256x7_1sub1 = {
  120255. 1, 9,
  120256. _huff_lengthlist_line_256x7_1sub1,
  120257. 0, 0, 0, 0, 0,
  120258. NULL,
  120259. NULL,
  120260. NULL,
  120261. NULL,
  120262. 0
  120263. };
  120264. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120266. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120267. };
  120268. static static_codebook _huff_book_line_256x7_1sub2 = {
  120269. 1, 25,
  120270. _huff_lengthlist_line_256x7_1sub2,
  120271. 0, 0, 0, 0, 0,
  120272. NULL,
  120273. NULL,
  120274. NULL,
  120275. NULL,
  120276. 0
  120277. };
  120278. static long _huff_lengthlist_line_256x7_1sub3[] = {
  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, 3, 2, 4, 3, 6, 3, 7,
  120281. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120282. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120283. };
  120284. static static_codebook _huff_book_line_256x7_1sub3 = {
  120285. 1, 64,
  120286. _huff_lengthlist_line_256x7_1sub3,
  120287. 0, 0, 0, 0, 0,
  120288. NULL,
  120289. NULL,
  120290. NULL,
  120291. NULL,
  120292. 0
  120293. };
  120294. static long _huff_lengthlist_line_256x7_class0[] = {
  120295. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120296. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120297. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120298. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120299. };
  120300. static static_codebook _huff_book_line_256x7_class0 = {
  120301. 1, 64,
  120302. _huff_lengthlist_line_256x7_class0,
  120303. 0, 0, 0, 0, 0,
  120304. NULL,
  120305. NULL,
  120306. NULL,
  120307. NULL,
  120308. 0
  120309. };
  120310. static long _huff_lengthlist_line_256x7_class1[] = {
  120311. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120312. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120313. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120314. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120315. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120316. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120317. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120318. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120319. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120320. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120321. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120322. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120323. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120324. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120325. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120326. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120327. };
  120328. static static_codebook _huff_book_line_256x7_class1 = {
  120329. 1, 256,
  120330. _huff_lengthlist_line_256x7_class1,
  120331. 0, 0, 0, 0, 0,
  120332. NULL,
  120333. NULL,
  120334. NULL,
  120335. NULL,
  120336. 0
  120337. };
  120338. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120339. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120340. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120341. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120342. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120343. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120344. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120345. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120346. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120347. };
  120348. static static_codebook _huff_book_line_512x17_0sub0 = {
  120349. 1, 128,
  120350. _huff_lengthlist_line_512x17_0sub0,
  120351. 0, 0, 0, 0, 0,
  120352. NULL,
  120353. NULL,
  120354. NULL,
  120355. NULL,
  120356. 0
  120357. };
  120358. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120359. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120360. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120361. };
  120362. static static_codebook _huff_book_line_512x17_1sub0 = {
  120363. 1, 32,
  120364. _huff_lengthlist_line_512x17_1sub0,
  120365. 0, 0, 0, 0, 0,
  120366. NULL,
  120367. NULL,
  120368. NULL,
  120369. NULL,
  120370. 0
  120371. };
  120372. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120375. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120376. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120377. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120378. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120379. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120380. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120381. };
  120382. static static_codebook _huff_book_line_512x17_1sub1 = {
  120383. 1, 128,
  120384. _huff_lengthlist_line_512x17_1sub1,
  120385. 0, 0, 0, 0, 0,
  120386. NULL,
  120387. NULL,
  120388. NULL,
  120389. NULL,
  120390. 0
  120391. };
  120392. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120393. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120394. 5, 3,
  120395. };
  120396. static static_codebook _huff_book_line_512x17_2sub1 = {
  120397. 1, 18,
  120398. _huff_lengthlist_line_512x17_2sub1,
  120399. 0, 0, 0, 0, 0,
  120400. NULL,
  120401. NULL,
  120402. NULL,
  120403. NULL,
  120404. 0
  120405. };
  120406. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120408. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120409. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120410. 9, 8,
  120411. };
  120412. static static_codebook _huff_book_line_512x17_2sub2 = {
  120413. 1, 50,
  120414. _huff_lengthlist_line_512x17_2sub2,
  120415. 0, 0, 0, 0, 0,
  120416. NULL,
  120417. NULL,
  120418. NULL,
  120419. NULL,
  120420. 0
  120421. };
  120422. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120426. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120427. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120428. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120429. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120430. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120431. };
  120432. static static_codebook _huff_book_line_512x17_2sub3 = {
  120433. 1, 128,
  120434. _huff_lengthlist_line_512x17_2sub3,
  120435. 0, 0, 0, 0, 0,
  120436. NULL,
  120437. NULL,
  120438. NULL,
  120439. NULL,
  120440. 0
  120441. };
  120442. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120443. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120444. 5, 5,
  120445. };
  120446. static static_codebook _huff_book_line_512x17_3sub1 = {
  120447. 1, 18,
  120448. _huff_lengthlist_line_512x17_3sub1,
  120449. 0, 0, 0, 0, 0,
  120450. NULL,
  120451. NULL,
  120452. NULL,
  120453. NULL,
  120454. 0
  120455. };
  120456. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120458. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120459. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120460. 11,14,
  120461. };
  120462. static static_codebook _huff_book_line_512x17_3sub2 = {
  120463. 1, 50,
  120464. _huff_lengthlist_line_512x17_3sub2,
  120465. 0, 0, 0, 0, 0,
  120466. NULL,
  120467. NULL,
  120468. NULL,
  120469. NULL,
  120470. 0
  120471. };
  120472. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120476. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120477. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120478. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120479. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120480. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120481. };
  120482. static static_codebook _huff_book_line_512x17_3sub3 = {
  120483. 1, 128,
  120484. _huff_lengthlist_line_512x17_3sub3,
  120485. 0, 0, 0, 0, 0,
  120486. NULL,
  120487. NULL,
  120488. NULL,
  120489. NULL,
  120490. 0
  120491. };
  120492. static long _huff_lengthlist_line_512x17_class1[] = {
  120493. 1, 2, 3, 6, 5, 4, 7, 7,
  120494. };
  120495. static static_codebook _huff_book_line_512x17_class1 = {
  120496. 1, 8,
  120497. _huff_lengthlist_line_512x17_class1,
  120498. 0, 0, 0, 0, 0,
  120499. NULL,
  120500. NULL,
  120501. NULL,
  120502. NULL,
  120503. 0
  120504. };
  120505. static long _huff_lengthlist_line_512x17_class2[] = {
  120506. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120507. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120508. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120509. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120510. };
  120511. static static_codebook _huff_book_line_512x17_class2 = {
  120512. 1, 64,
  120513. _huff_lengthlist_line_512x17_class2,
  120514. 0, 0, 0, 0, 0,
  120515. NULL,
  120516. NULL,
  120517. NULL,
  120518. NULL,
  120519. 0
  120520. };
  120521. static long _huff_lengthlist_line_512x17_class3[] = {
  120522. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120523. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120524. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120525. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120526. };
  120527. static static_codebook _huff_book_line_512x17_class3 = {
  120528. 1, 64,
  120529. _huff_lengthlist_line_512x17_class3,
  120530. 0, 0, 0, 0, 0,
  120531. NULL,
  120532. NULL,
  120533. NULL,
  120534. NULL,
  120535. 0
  120536. };
  120537. static long _huff_lengthlist_line_128x4_class0[] = {
  120538. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120539. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120540. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120541. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120542. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120543. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120544. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120545. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120546. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120547. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120548. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120549. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120550. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120551. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120552. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120553. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120554. };
  120555. static static_codebook _huff_book_line_128x4_class0 = {
  120556. 1, 256,
  120557. _huff_lengthlist_line_128x4_class0,
  120558. 0, 0, 0, 0, 0,
  120559. NULL,
  120560. NULL,
  120561. NULL,
  120562. NULL,
  120563. 0
  120564. };
  120565. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120566. 2, 2, 2, 2,
  120567. };
  120568. static static_codebook _huff_book_line_128x4_0sub0 = {
  120569. 1, 4,
  120570. _huff_lengthlist_line_128x4_0sub0,
  120571. 0, 0, 0, 0, 0,
  120572. NULL,
  120573. NULL,
  120574. NULL,
  120575. NULL,
  120576. 0
  120577. };
  120578. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120579. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120580. };
  120581. static static_codebook _huff_book_line_128x4_0sub1 = {
  120582. 1, 10,
  120583. _huff_lengthlist_line_128x4_0sub1,
  120584. 0, 0, 0, 0, 0,
  120585. NULL,
  120586. NULL,
  120587. NULL,
  120588. NULL,
  120589. 0
  120590. };
  120591. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120593. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120594. };
  120595. static static_codebook _huff_book_line_128x4_0sub2 = {
  120596. 1, 25,
  120597. _huff_lengthlist_line_128x4_0sub2,
  120598. 0, 0, 0, 0, 0,
  120599. NULL,
  120600. NULL,
  120601. NULL,
  120602. NULL,
  120603. 0
  120604. };
  120605. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120608. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120609. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120610. };
  120611. static static_codebook _huff_book_line_128x4_0sub3 = {
  120612. 1, 64,
  120613. _huff_lengthlist_line_128x4_0sub3,
  120614. 0, 0, 0, 0, 0,
  120615. NULL,
  120616. NULL,
  120617. NULL,
  120618. NULL,
  120619. 0
  120620. };
  120621. static long _huff_lengthlist_line_256x4_class0[] = {
  120622. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120623. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120624. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120625. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120626. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120627. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120628. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120629. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120630. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120631. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120632. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120633. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120634. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120635. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120636. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120637. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120638. };
  120639. static static_codebook _huff_book_line_256x4_class0 = {
  120640. 1, 256,
  120641. _huff_lengthlist_line_256x4_class0,
  120642. 0, 0, 0, 0, 0,
  120643. NULL,
  120644. NULL,
  120645. NULL,
  120646. NULL,
  120647. 0
  120648. };
  120649. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120650. 2, 2, 2, 2,
  120651. };
  120652. static static_codebook _huff_book_line_256x4_0sub0 = {
  120653. 1, 4,
  120654. _huff_lengthlist_line_256x4_0sub0,
  120655. 0, 0, 0, 0, 0,
  120656. NULL,
  120657. NULL,
  120658. NULL,
  120659. NULL,
  120660. 0
  120661. };
  120662. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120663. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120664. };
  120665. static static_codebook _huff_book_line_256x4_0sub1 = {
  120666. 1, 10,
  120667. _huff_lengthlist_line_256x4_0sub1,
  120668. 0, 0, 0, 0, 0,
  120669. NULL,
  120670. NULL,
  120671. NULL,
  120672. NULL,
  120673. 0
  120674. };
  120675. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120677. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120678. };
  120679. static static_codebook _huff_book_line_256x4_0sub2 = {
  120680. 1, 25,
  120681. _huff_lengthlist_line_256x4_0sub2,
  120682. 0, 0, 0, 0, 0,
  120683. NULL,
  120684. NULL,
  120685. NULL,
  120686. NULL,
  120687. 0
  120688. };
  120689. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120692. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120693. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120694. };
  120695. static static_codebook _huff_book_line_256x4_0sub3 = {
  120696. 1, 64,
  120697. _huff_lengthlist_line_256x4_0sub3,
  120698. 0, 0, 0, 0, 0,
  120699. NULL,
  120700. NULL,
  120701. NULL,
  120702. NULL,
  120703. 0
  120704. };
  120705. static long _huff_lengthlist_line_128x7_class0[] = {
  120706. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120707. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120708. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120709. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120710. };
  120711. static static_codebook _huff_book_line_128x7_class0 = {
  120712. 1, 64,
  120713. _huff_lengthlist_line_128x7_class0,
  120714. 0, 0, 0, 0, 0,
  120715. NULL,
  120716. NULL,
  120717. NULL,
  120718. NULL,
  120719. 0
  120720. };
  120721. static long _huff_lengthlist_line_128x7_class1[] = {
  120722. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120723. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120724. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120725. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120726. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120727. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120728. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120729. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120730. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120731. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120732. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120733. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120734. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120735. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120736. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120737. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120738. };
  120739. static static_codebook _huff_book_line_128x7_class1 = {
  120740. 1, 256,
  120741. _huff_lengthlist_line_128x7_class1,
  120742. 0, 0, 0, 0, 0,
  120743. NULL,
  120744. NULL,
  120745. NULL,
  120746. NULL,
  120747. 0
  120748. };
  120749. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120750. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120751. };
  120752. static static_codebook _huff_book_line_128x7_0sub1 = {
  120753. 1, 9,
  120754. _huff_lengthlist_line_128x7_0sub1,
  120755. 0, 0, 0, 0, 0,
  120756. NULL,
  120757. NULL,
  120758. NULL,
  120759. NULL,
  120760. 0
  120761. };
  120762. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120764. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120765. };
  120766. static static_codebook _huff_book_line_128x7_0sub2 = {
  120767. 1, 25,
  120768. _huff_lengthlist_line_128x7_0sub2,
  120769. 0, 0, 0, 0, 0,
  120770. NULL,
  120771. NULL,
  120772. NULL,
  120773. NULL,
  120774. 0
  120775. };
  120776. static long _huff_lengthlist_line_128x7_0sub3[] = {
  120777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  120779. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120780. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120781. };
  120782. static static_codebook _huff_book_line_128x7_0sub3 = {
  120783. 1, 64,
  120784. _huff_lengthlist_line_128x7_0sub3,
  120785. 0, 0, 0, 0, 0,
  120786. NULL,
  120787. NULL,
  120788. NULL,
  120789. NULL,
  120790. 0
  120791. };
  120792. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120793. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120794. };
  120795. static static_codebook _huff_book_line_128x7_1sub1 = {
  120796. 1, 9,
  120797. _huff_lengthlist_line_128x7_1sub1,
  120798. 0, 0, 0, 0, 0,
  120799. NULL,
  120800. NULL,
  120801. NULL,
  120802. NULL,
  120803. 0
  120804. };
  120805. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120807. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120808. };
  120809. static static_codebook _huff_book_line_128x7_1sub2 = {
  120810. 1, 25,
  120811. _huff_lengthlist_line_128x7_1sub2,
  120812. 0, 0, 0, 0, 0,
  120813. NULL,
  120814. NULL,
  120815. NULL,
  120816. NULL,
  120817. 0
  120818. };
  120819. static long _huff_lengthlist_line_128x7_1sub3[] = {
  120820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  120822. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  120823. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  120824. };
  120825. static static_codebook _huff_book_line_128x7_1sub3 = {
  120826. 1, 64,
  120827. _huff_lengthlist_line_128x7_1sub3,
  120828. 0, 0, 0, 0, 0,
  120829. NULL,
  120830. NULL,
  120831. NULL,
  120832. NULL,
  120833. 0
  120834. };
  120835. static long _huff_lengthlist_line_128x11_class1[] = {
  120836. 1, 6, 3, 7, 2, 4, 5, 7,
  120837. };
  120838. static static_codebook _huff_book_line_128x11_class1 = {
  120839. 1, 8,
  120840. _huff_lengthlist_line_128x11_class1,
  120841. 0, 0, 0, 0, 0,
  120842. NULL,
  120843. NULL,
  120844. NULL,
  120845. NULL,
  120846. 0
  120847. };
  120848. static long _huff_lengthlist_line_128x11_class2[] = {
  120849. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  120850. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  120851. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  120852. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  120853. };
  120854. static static_codebook _huff_book_line_128x11_class2 = {
  120855. 1, 64,
  120856. _huff_lengthlist_line_128x11_class2,
  120857. 0, 0, 0, 0, 0,
  120858. NULL,
  120859. NULL,
  120860. NULL,
  120861. NULL,
  120862. 0
  120863. };
  120864. static long _huff_lengthlist_line_128x11_class3[] = {
  120865. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  120866. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  120867. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  120868. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  120869. };
  120870. static static_codebook _huff_book_line_128x11_class3 = {
  120871. 1, 64,
  120872. _huff_lengthlist_line_128x11_class3,
  120873. 0, 0, 0, 0, 0,
  120874. NULL,
  120875. NULL,
  120876. NULL,
  120877. NULL,
  120878. 0
  120879. };
  120880. static long _huff_lengthlist_line_128x11_0sub0[] = {
  120881. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120882. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  120883. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  120884. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  120885. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  120886. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  120887. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  120888. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120889. };
  120890. static static_codebook _huff_book_line_128x11_0sub0 = {
  120891. 1, 128,
  120892. _huff_lengthlist_line_128x11_0sub0,
  120893. 0, 0, 0, 0, 0,
  120894. NULL,
  120895. NULL,
  120896. NULL,
  120897. NULL,
  120898. 0
  120899. };
  120900. static long _huff_lengthlist_line_128x11_1sub0[] = {
  120901. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120902. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  120903. };
  120904. static static_codebook _huff_book_line_128x11_1sub0 = {
  120905. 1, 32,
  120906. _huff_lengthlist_line_128x11_1sub0,
  120907. 0, 0, 0, 0, 0,
  120908. NULL,
  120909. NULL,
  120910. NULL,
  120911. NULL,
  120912. 0
  120913. };
  120914. static long _huff_lengthlist_line_128x11_1sub1[] = {
  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. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120918. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  120919. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  120920. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  120921. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  120922. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  120923. };
  120924. static static_codebook _huff_book_line_128x11_1sub1 = {
  120925. 1, 128,
  120926. _huff_lengthlist_line_128x11_1sub1,
  120927. 0, 0, 0, 0, 0,
  120928. NULL,
  120929. NULL,
  120930. NULL,
  120931. NULL,
  120932. 0
  120933. };
  120934. static long _huff_lengthlist_line_128x11_2sub1[] = {
  120935. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  120936. 5, 5,
  120937. };
  120938. static static_codebook _huff_book_line_128x11_2sub1 = {
  120939. 1, 18,
  120940. _huff_lengthlist_line_128x11_2sub1,
  120941. 0, 0, 0, 0, 0,
  120942. NULL,
  120943. NULL,
  120944. NULL,
  120945. NULL,
  120946. 0
  120947. };
  120948. static long _huff_lengthlist_line_128x11_2sub2[] = {
  120949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120950. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  120951. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  120952. 8,11,
  120953. };
  120954. static static_codebook _huff_book_line_128x11_2sub2 = {
  120955. 1, 50,
  120956. _huff_lengthlist_line_128x11_2sub2,
  120957. 0, 0, 0, 0, 0,
  120958. NULL,
  120959. NULL,
  120960. NULL,
  120961. NULL,
  120962. 0
  120963. };
  120964. static long _huff_lengthlist_line_128x11_2sub3[] = {
  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, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  120969. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120970. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120971. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120972. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120973. };
  120974. static static_codebook _huff_book_line_128x11_2sub3 = {
  120975. 1, 128,
  120976. _huff_lengthlist_line_128x11_2sub3,
  120977. 0, 0, 0, 0, 0,
  120978. NULL,
  120979. NULL,
  120980. NULL,
  120981. NULL,
  120982. 0
  120983. };
  120984. static long _huff_lengthlist_line_128x11_3sub1[] = {
  120985. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  120986. 5, 4,
  120987. };
  120988. static static_codebook _huff_book_line_128x11_3sub1 = {
  120989. 1, 18,
  120990. _huff_lengthlist_line_128x11_3sub1,
  120991. 0, 0, 0, 0, 0,
  120992. NULL,
  120993. NULL,
  120994. NULL,
  120995. NULL,
  120996. 0
  120997. };
  120998. static long _huff_lengthlist_line_128x11_3sub2[] = {
  120999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121000. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121001. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121002. 12, 6,
  121003. };
  121004. static static_codebook _huff_book_line_128x11_3sub2 = {
  121005. 1, 50,
  121006. _huff_lengthlist_line_128x11_3sub2,
  121007. 0, 0, 0, 0, 0,
  121008. NULL,
  121009. NULL,
  121010. NULL,
  121011. NULL,
  121012. 0
  121013. };
  121014. static long _huff_lengthlist_line_128x11_3sub3[] = {
  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, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121019. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121021. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121022. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121023. };
  121024. static static_codebook _huff_book_line_128x11_3sub3 = {
  121025. 1, 128,
  121026. _huff_lengthlist_line_128x11_3sub3,
  121027. 0, 0, 0, 0, 0,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. NULL,
  121032. 0
  121033. };
  121034. static long _huff_lengthlist_line_128x17_class1[] = {
  121035. 1, 3, 4, 7, 2, 5, 6, 7,
  121036. };
  121037. static static_codebook _huff_book_line_128x17_class1 = {
  121038. 1, 8,
  121039. _huff_lengthlist_line_128x17_class1,
  121040. 0, 0, 0, 0, 0,
  121041. NULL,
  121042. NULL,
  121043. NULL,
  121044. NULL,
  121045. 0
  121046. };
  121047. static long _huff_lengthlist_line_128x17_class2[] = {
  121048. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121049. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121050. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121051. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121052. };
  121053. static static_codebook _huff_book_line_128x17_class2 = {
  121054. 1, 64,
  121055. _huff_lengthlist_line_128x17_class2,
  121056. 0, 0, 0, 0, 0,
  121057. NULL,
  121058. NULL,
  121059. NULL,
  121060. NULL,
  121061. 0
  121062. };
  121063. static long _huff_lengthlist_line_128x17_class3[] = {
  121064. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121065. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121066. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121067. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121068. };
  121069. static static_codebook _huff_book_line_128x17_class3 = {
  121070. 1, 64,
  121071. _huff_lengthlist_line_128x17_class3,
  121072. 0, 0, 0, 0, 0,
  121073. NULL,
  121074. NULL,
  121075. NULL,
  121076. NULL,
  121077. 0
  121078. };
  121079. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121080. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121081. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121082. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121083. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121084. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121085. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121086. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121087. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121088. };
  121089. static static_codebook _huff_book_line_128x17_0sub0 = {
  121090. 1, 128,
  121091. _huff_lengthlist_line_128x17_0sub0,
  121092. 0, 0, 0, 0, 0,
  121093. NULL,
  121094. NULL,
  121095. NULL,
  121096. NULL,
  121097. 0
  121098. };
  121099. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121100. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121101. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121102. };
  121103. static static_codebook _huff_book_line_128x17_1sub0 = {
  121104. 1, 32,
  121105. _huff_lengthlist_line_128x17_1sub0,
  121106. 0, 0, 0, 0, 0,
  121107. NULL,
  121108. NULL,
  121109. NULL,
  121110. NULL,
  121111. 0
  121112. };
  121113. static long _huff_lengthlist_line_128x17_1sub1[] = {
  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. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121117. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121118. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121119. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121120. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121121. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121122. };
  121123. static static_codebook _huff_book_line_128x17_1sub1 = {
  121124. 1, 128,
  121125. _huff_lengthlist_line_128x17_1sub1,
  121126. 0, 0, 0, 0, 0,
  121127. NULL,
  121128. NULL,
  121129. NULL,
  121130. NULL,
  121131. 0
  121132. };
  121133. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121134. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121135. 9, 4,
  121136. };
  121137. static static_codebook _huff_book_line_128x17_2sub1 = {
  121138. 1, 18,
  121139. _huff_lengthlist_line_128x17_2sub1,
  121140. 0, 0, 0, 0, 0,
  121141. NULL,
  121142. NULL,
  121143. NULL,
  121144. NULL,
  121145. 0
  121146. };
  121147. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121149. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121150. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121151. 13,13,
  121152. };
  121153. static static_codebook _huff_book_line_128x17_2sub2 = {
  121154. 1, 50,
  121155. _huff_lengthlist_line_128x17_2sub2,
  121156. 0, 0, 0, 0, 0,
  121157. NULL,
  121158. NULL,
  121159. NULL,
  121160. NULL,
  121161. 0
  121162. };
  121163. static long _huff_lengthlist_line_128x17_2sub3[] = {
  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, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121168. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121169. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121170. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121171. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121172. };
  121173. static static_codebook _huff_book_line_128x17_2sub3 = {
  121174. 1, 128,
  121175. _huff_lengthlist_line_128x17_2sub3,
  121176. 0, 0, 0, 0, 0,
  121177. NULL,
  121178. NULL,
  121179. NULL,
  121180. NULL,
  121181. 0
  121182. };
  121183. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121184. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121185. 6, 4,
  121186. };
  121187. static static_codebook _huff_book_line_128x17_3sub1 = {
  121188. 1, 18,
  121189. _huff_lengthlist_line_128x17_3sub1,
  121190. 0, 0, 0, 0, 0,
  121191. NULL,
  121192. NULL,
  121193. NULL,
  121194. NULL,
  121195. 0
  121196. };
  121197. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121199. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121200. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121201. 10, 8,
  121202. };
  121203. static static_codebook _huff_book_line_128x17_3sub2 = {
  121204. 1, 50,
  121205. _huff_lengthlist_line_128x17_3sub2,
  121206. 0, 0, 0, 0, 0,
  121207. NULL,
  121208. NULL,
  121209. NULL,
  121210. NULL,
  121211. 0
  121212. };
  121213. static long _huff_lengthlist_line_128x17_3sub3[] = {
  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, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121218. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121219. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121221. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121222. };
  121223. static static_codebook _huff_book_line_128x17_3sub3 = {
  121224. 1, 128,
  121225. _huff_lengthlist_line_128x17_3sub3,
  121226. 0, 0, 0, 0, 0,
  121227. NULL,
  121228. NULL,
  121229. NULL,
  121230. NULL,
  121231. 0
  121232. };
  121233. static long _huff_lengthlist_line_1024x27_class1[] = {
  121234. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121235. };
  121236. static static_codebook _huff_book_line_1024x27_class1 = {
  121237. 1, 16,
  121238. _huff_lengthlist_line_1024x27_class1,
  121239. 0, 0, 0, 0, 0,
  121240. NULL,
  121241. NULL,
  121242. NULL,
  121243. NULL,
  121244. 0
  121245. };
  121246. static long _huff_lengthlist_line_1024x27_class2[] = {
  121247. 1, 4, 2, 6, 3, 7, 5, 7,
  121248. };
  121249. static static_codebook _huff_book_line_1024x27_class2 = {
  121250. 1, 8,
  121251. _huff_lengthlist_line_1024x27_class2,
  121252. 0, 0, 0, 0, 0,
  121253. NULL,
  121254. NULL,
  121255. NULL,
  121256. NULL,
  121257. 0
  121258. };
  121259. static long _huff_lengthlist_line_1024x27_class3[] = {
  121260. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121261. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121262. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121263. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121264. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121265. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121266. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121267. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121268. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121269. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121270. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121271. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121272. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121273. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121274. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121275. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121276. };
  121277. static static_codebook _huff_book_line_1024x27_class3 = {
  121278. 1, 256,
  121279. _huff_lengthlist_line_1024x27_class3,
  121280. 0, 0, 0, 0, 0,
  121281. NULL,
  121282. NULL,
  121283. NULL,
  121284. NULL,
  121285. 0
  121286. };
  121287. static long _huff_lengthlist_line_1024x27_class4[] = {
  121288. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121289. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121290. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121291. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121292. };
  121293. static static_codebook _huff_book_line_1024x27_class4 = {
  121294. 1, 64,
  121295. _huff_lengthlist_line_1024x27_class4,
  121296. 0, 0, 0, 0, 0,
  121297. NULL,
  121298. NULL,
  121299. NULL,
  121300. NULL,
  121301. 0
  121302. };
  121303. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121304. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121305. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121306. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121307. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121308. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121309. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121310. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121311. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121312. };
  121313. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121314. 1, 128,
  121315. _huff_lengthlist_line_1024x27_0sub0,
  121316. 0, 0, 0, 0, 0,
  121317. NULL,
  121318. NULL,
  121319. NULL,
  121320. NULL,
  121321. 0
  121322. };
  121323. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121324. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121325. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121326. };
  121327. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121328. 1, 32,
  121329. _huff_lengthlist_line_1024x27_1sub0,
  121330. 0, 0, 0, 0, 0,
  121331. NULL,
  121332. NULL,
  121333. NULL,
  121334. NULL,
  121335. 0
  121336. };
  121337. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121340. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121341. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121342. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121343. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121344. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121345. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121346. };
  121347. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121348. 1, 128,
  121349. _huff_lengthlist_line_1024x27_1sub1,
  121350. 0, 0, 0, 0, 0,
  121351. NULL,
  121352. NULL,
  121353. NULL,
  121354. NULL,
  121355. 0
  121356. };
  121357. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121358. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121359. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121360. };
  121361. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121362. 1, 32,
  121363. _huff_lengthlist_line_1024x27_2sub0,
  121364. 0, 0, 0, 0, 0,
  121365. NULL,
  121366. NULL,
  121367. NULL,
  121368. NULL,
  121369. 0
  121370. };
  121371. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  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. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121375. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121376. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121377. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121378. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121379. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121380. };
  121381. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121382. 1, 128,
  121383. _huff_lengthlist_line_1024x27_2sub1,
  121384. 0, 0, 0, 0, 0,
  121385. NULL,
  121386. NULL,
  121387. NULL,
  121388. NULL,
  121389. 0
  121390. };
  121391. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121392. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121393. 5, 5,
  121394. };
  121395. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121396. 1, 18,
  121397. _huff_lengthlist_line_1024x27_3sub1,
  121398. 0, 0, 0, 0, 0,
  121399. NULL,
  121400. NULL,
  121401. NULL,
  121402. NULL,
  121403. 0
  121404. };
  121405. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121407. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121408. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121409. 9,11,
  121410. };
  121411. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121412. 1, 50,
  121413. _huff_lengthlist_line_1024x27_3sub2,
  121414. 0, 0, 0, 0, 0,
  121415. NULL,
  121416. NULL,
  121417. NULL,
  121418. NULL,
  121419. 0
  121420. };
  121421. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121425. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121426. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121427. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121428. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121429. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121430. };
  121431. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121432. 1, 128,
  121433. _huff_lengthlist_line_1024x27_3sub3,
  121434. 0, 0, 0, 0, 0,
  121435. NULL,
  121436. NULL,
  121437. NULL,
  121438. NULL,
  121439. 0
  121440. };
  121441. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121442. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121443. 5, 4,
  121444. };
  121445. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121446. 1, 18,
  121447. _huff_lengthlist_line_1024x27_4sub1,
  121448. 0, 0, 0, 0, 0,
  121449. NULL,
  121450. NULL,
  121451. NULL,
  121452. NULL,
  121453. 0
  121454. };
  121455. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121457. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121458. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121459. 9,12,
  121460. };
  121461. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121462. 1, 50,
  121463. _huff_lengthlist_line_1024x27_4sub2,
  121464. 0, 0, 0, 0, 0,
  121465. NULL,
  121466. NULL,
  121467. NULL,
  121468. NULL,
  121469. 0
  121470. };
  121471. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121475. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121476. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121479. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121480. };
  121481. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121482. 1, 128,
  121483. _huff_lengthlist_line_1024x27_4sub3,
  121484. 0, 0, 0, 0, 0,
  121485. NULL,
  121486. NULL,
  121487. NULL,
  121488. NULL,
  121489. 0
  121490. };
  121491. static long _huff_lengthlist_line_2048x27_class1[] = {
  121492. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121493. };
  121494. static static_codebook _huff_book_line_2048x27_class1 = {
  121495. 1, 16,
  121496. _huff_lengthlist_line_2048x27_class1,
  121497. 0, 0, 0, 0, 0,
  121498. NULL,
  121499. NULL,
  121500. NULL,
  121501. NULL,
  121502. 0
  121503. };
  121504. static long _huff_lengthlist_line_2048x27_class2[] = {
  121505. 1, 2, 3, 6, 4, 7, 5, 7,
  121506. };
  121507. static static_codebook _huff_book_line_2048x27_class2 = {
  121508. 1, 8,
  121509. _huff_lengthlist_line_2048x27_class2,
  121510. 0, 0, 0, 0, 0,
  121511. NULL,
  121512. NULL,
  121513. NULL,
  121514. NULL,
  121515. 0
  121516. };
  121517. static long _huff_lengthlist_line_2048x27_class3[] = {
  121518. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121519. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121520. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121521. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121522. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121523. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121524. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121525. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121526. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121527. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121528. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121529. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121530. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121531. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121532. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121533. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121534. };
  121535. static static_codebook _huff_book_line_2048x27_class3 = {
  121536. 1, 256,
  121537. _huff_lengthlist_line_2048x27_class3,
  121538. 0, 0, 0, 0, 0,
  121539. NULL,
  121540. NULL,
  121541. NULL,
  121542. NULL,
  121543. 0
  121544. };
  121545. static long _huff_lengthlist_line_2048x27_class4[] = {
  121546. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121547. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121548. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121549. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121550. };
  121551. static static_codebook _huff_book_line_2048x27_class4 = {
  121552. 1, 64,
  121553. _huff_lengthlist_line_2048x27_class4,
  121554. 0, 0, 0, 0, 0,
  121555. NULL,
  121556. NULL,
  121557. NULL,
  121558. NULL,
  121559. 0
  121560. };
  121561. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121562. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121563. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121564. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121565. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121566. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121567. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121568. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121569. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121570. };
  121571. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121572. 1, 128,
  121573. _huff_lengthlist_line_2048x27_0sub0,
  121574. 0, 0, 0, 0, 0,
  121575. NULL,
  121576. NULL,
  121577. NULL,
  121578. NULL,
  121579. 0
  121580. };
  121581. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121582. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121583. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121584. };
  121585. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121586. 1, 32,
  121587. _huff_lengthlist_line_2048x27_1sub0,
  121588. 0, 0, 0, 0, 0,
  121589. NULL,
  121590. NULL,
  121591. NULL,
  121592. NULL,
  121593. 0
  121594. };
  121595. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121598. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121599. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121600. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121601. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121602. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121603. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121604. };
  121605. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121606. 1, 128,
  121607. _huff_lengthlist_line_2048x27_1sub1,
  121608. 0, 0, 0, 0, 0,
  121609. NULL,
  121610. NULL,
  121611. NULL,
  121612. NULL,
  121613. 0
  121614. };
  121615. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121616. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121617. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121618. };
  121619. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121620. 1, 32,
  121621. _huff_lengthlist_line_2048x27_2sub0,
  121622. 0, 0, 0, 0, 0,
  121623. NULL,
  121624. NULL,
  121625. NULL,
  121626. NULL,
  121627. 0
  121628. };
  121629. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121632. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121633. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121634. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121635. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121636. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121637. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121638. };
  121639. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121640. 1, 128,
  121641. _huff_lengthlist_line_2048x27_2sub1,
  121642. 0, 0, 0, 0, 0,
  121643. NULL,
  121644. NULL,
  121645. NULL,
  121646. NULL,
  121647. 0
  121648. };
  121649. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121650. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121651. 5, 5,
  121652. };
  121653. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121654. 1, 18,
  121655. _huff_lengthlist_line_2048x27_3sub1,
  121656. 0, 0, 0, 0, 0,
  121657. NULL,
  121658. NULL,
  121659. NULL,
  121660. NULL,
  121661. 0
  121662. };
  121663. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121665. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121666. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121667. 10,12,
  121668. };
  121669. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121670. 1, 50,
  121671. _huff_lengthlist_line_2048x27_3sub2,
  121672. 0, 0, 0, 0, 0,
  121673. NULL,
  121674. NULL,
  121675. NULL,
  121676. NULL,
  121677. 0
  121678. };
  121679. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121683. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121684. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121685. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121686. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121687. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121688. };
  121689. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121690. 1, 128,
  121691. _huff_lengthlist_line_2048x27_3sub3,
  121692. 0, 0, 0, 0, 0,
  121693. NULL,
  121694. NULL,
  121695. NULL,
  121696. NULL,
  121697. 0
  121698. };
  121699. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121700. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121701. 4, 5,
  121702. };
  121703. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121704. 1, 18,
  121705. _huff_lengthlist_line_2048x27_4sub1,
  121706. 0, 0, 0, 0, 0,
  121707. NULL,
  121708. NULL,
  121709. NULL,
  121710. NULL,
  121711. 0
  121712. };
  121713. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121715. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121716. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121717. 10,10,
  121718. };
  121719. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121720. 1, 50,
  121721. _huff_lengthlist_line_2048x27_4sub2,
  121722. 0, 0, 0, 0, 0,
  121723. NULL,
  121724. NULL,
  121725. NULL,
  121726. NULL,
  121727. 0
  121728. };
  121729. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121733. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121734. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121735. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121736. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121737. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121738. };
  121739. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121740. 1, 128,
  121741. _huff_lengthlist_line_2048x27_4sub3,
  121742. 0, 0, 0, 0, 0,
  121743. NULL,
  121744. NULL,
  121745. NULL,
  121746. NULL,
  121747. 0
  121748. };
  121749. static long _huff_lengthlist_line_256x4low_class0[] = {
  121750. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121751. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121752. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121753. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121754. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121755. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121756. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121757. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121758. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121759. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121760. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121761. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121762. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121763. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121764. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121765. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121766. };
  121767. static static_codebook _huff_book_line_256x4low_class0 = {
  121768. 1, 256,
  121769. _huff_lengthlist_line_256x4low_class0,
  121770. 0, 0, 0, 0, 0,
  121771. NULL,
  121772. NULL,
  121773. NULL,
  121774. NULL,
  121775. 0
  121776. };
  121777. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121778. 1, 3, 2, 3,
  121779. };
  121780. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121781. 1, 4,
  121782. _huff_lengthlist_line_256x4low_0sub0,
  121783. 0, 0, 0, 0, 0,
  121784. NULL,
  121785. NULL,
  121786. NULL,
  121787. NULL,
  121788. 0
  121789. };
  121790. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121791. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121792. };
  121793. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121794. 1, 10,
  121795. _huff_lengthlist_line_256x4low_0sub1,
  121796. 0, 0, 0, 0, 0,
  121797. NULL,
  121798. NULL,
  121799. NULL,
  121800. NULL,
  121801. 0
  121802. };
  121803. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121805. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121806. };
  121807. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121808. 1, 25,
  121809. _huff_lengthlist_line_256x4low_0sub2,
  121810. 0, 0, 0, 0, 0,
  121811. NULL,
  121812. NULL,
  121813. NULL,
  121814. NULL,
  121815. 0
  121816. };
  121817. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  121818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  121820. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  121821. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  121822. };
  121823. static static_codebook _huff_book_line_256x4low_0sub3 = {
  121824. 1, 64,
  121825. _huff_lengthlist_line_256x4low_0sub3,
  121826. 0, 0, 0, 0, 0,
  121827. NULL,
  121828. NULL,
  121829. NULL,
  121830. NULL,
  121831. 0
  121832. };
  121833. /*** End of inlined file: floor_books.h ***/
  121834. static static_codebook *_floor_128x4_books[]={
  121835. &_huff_book_line_128x4_class0,
  121836. &_huff_book_line_128x4_0sub0,
  121837. &_huff_book_line_128x4_0sub1,
  121838. &_huff_book_line_128x4_0sub2,
  121839. &_huff_book_line_128x4_0sub3,
  121840. };
  121841. static static_codebook *_floor_256x4_books[]={
  121842. &_huff_book_line_256x4_class0,
  121843. &_huff_book_line_256x4_0sub0,
  121844. &_huff_book_line_256x4_0sub1,
  121845. &_huff_book_line_256x4_0sub2,
  121846. &_huff_book_line_256x4_0sub3,
  121847. };
  121848. static static_codebook *_floor_128x7_books[]={
  121849. &_huff_book_line_128x7_class0,
  121850. &_huff_book_line_128x7_class1,
  121851. &_huff_book_line_128x7_0sub1,
  121852. &_huff_book_line_128x7_0sub2,
  121853. &_huff_book_line_128x7_0sub3,
  121854. &_huff_book_line_128x7_1sub1,
  121855. &_huff_book_line_128x7_1sub2,
  121856. &_huff_book_line_128x7_1sub3,
  121857. };
  121858. static static_codebook *_floor_256x7_books[]={
  121859. &_huff_book_line_256x7_class0,
  121860. &_huff_book_line_256x7_class1,
  121861. &_huff_book_line_256x7_0sub1,
  121862. &_huff_book_line_256x7_0sub2,
  121863. &_huff_book_line_256x7_0sub3,
  121864. &_huff_book_line_256x7_1sub1,
  121865. &_huff_book_line_256x7_1sub2,
  121866. &_huff_book_line_256x7_1sub3,
  121867. };
  121868. static static_codebook *_floor_128x11_books[]={
  121869. &_huff_book_line_128x11_class1,
  121870. &_huff_book_line_128x11_class2,
  121871. &_huff_book_line_128x11_class3,
  121872. &_huff_book_line_128x11_0sub0,
  121873. &_huff_book_line_128x11_1sub0,
  121874. &_huff_book_line_128x11_1sub1,
  121875. &_huff_book_line_128x11_2sub1,
  121876. &_huff_book_line_128x11_2sub2,
  121877. &_huff_book_line_128x11_2sub3,
  121878. &_huff_book_line_128x11_3sub1,
  121879. &_huff_book_line_128x11_3sub2,
  121880. &_huff_book_line_128x11_3sub3,
  121881. };
  121882. static static_codebook *_floor_128x17_books[]={
  121883. &_huff_book_line_128x17_class1,
  121884. &_huff_book_line_128x17_class2,
  121885. &_huff_book_line_128x17_class3,
  121886. &_huff_book_line_128x17_0sub0,
  121887. &_huff_book_line_128x17_1sub0,
  121888. &_huff_book_line_128x17_1sub1,
  121889. &_huff_book_line_128x17_2sub1,
  121890. &_huff_book_line_128x17_2sub2,
  121891. &_huff_book_line_128x17_2sub3,
  121892. &_huff_book_line_128x17_3sub1,
  121893. &_huff_book_line_128x17_3sub2,
  121894. &_huff_book_line_128x17_3sub3,
  121895. };
  121896. static static_codebook *_floor_256x4low_books[]={
  121897. &_huff_book_line_256x4low_class0,
  121898. &_huff_book_line_256x4low_0sub0,
  121899. &_huff_book_line_256x4low_0sub1,
  121900. &_huff_book_line_256x4low_0sub2,
  121901. &_huff_book_line_256x4low_0sub3,
  121902. };
  121903. static static_codebook *_floor_1024x27_books[]={
  121904. &_huff_book_line_1024x27_class1,
  121905. &_huff_book_line_1024x27_class2,
  121906. &_huff_book_line_1024x27_class3,
  121907. &_huff_book_line_1024x27_class4,
  121908. &_huff_book_line_1024x27_0sub0,
  121909. &_huff_book_line_1024x27_1sub0,
  121910. &_huff_book_line_1024x27_1sub1,
  121911. &_huff_book_line_1024x27_2sub0,
  121912. &_huff_book_line_1024x27_2sub1,
  121913. &_huff_book_line_1024x27_3sub1,
  121914. &_huff_book_line_1024x27_3sub2,
  121915. &_huff_book_line_1024x27_3sub3,
  121916. &_huff_book_line_1024x27_4sub1,
  121917. &_huff_book_line_1024x27_4sub2,
  121918. &_huff_book_line_1024x27_4sub3,
  121919. };
  121920. static static_codebook *_floor_2048x27_books[]={
  121921. &_huff_book_line_2048x27_class1,
  121922. &_huff_book_line_2048x27_class2,
  121923. &_huff_book_line_2048x27_class3,
  121924. &_huff_book_line_2048x27_class4,
  121925. &_huff_book_line_2048x27_0sub0,
  121926. &_huff_book_line_2048x27_1sub0,
  121927. &_huff_book_line_2048x27_1sub1,
  121928. &_huff_book_line_2048x27_2sub0,
  121929. &_huff_book_line_2048x27_2sub1,
  121930. &_huff_book_line_2048x27_3sub1,
  121931. &_huff_book_line_2048x27_3sub2,
  121932. &_huff_book_line_2048x27_3sub3,
  121933. &_huff_book_line_2048x27_4sub1,
  121934. &_huff_book_line_2048x27_4sub2,
  121935. &_huff_book_line_2048x27_4sub3,
  121936. };
  121937. static static_codebook *_floor_512x17_books[]={
  121938. &_huff_book_line_512x17_class1,
  121939. &_huff_book_line_512x17_class2,
  121940. &_huff_book_line_512x17_class3,
  121941. &_huff_book_line_512x17_0sub0,
  121942. &_huff_book_line_512x17_1sub0,
  121943. &_huff_book_line_512x17_1sub1,
  121944. &_huff_book_line_512x17_2sub1,
  121945. &_huff_book_line_512x17_2sub2,
  121946. &_huff_book_line_512x17_2sub3,
  121947. &_huff_book_line_512x17_3sub1,
  121948. &_huff_book_line_512x17_3sub2,
  121949. &_huff_book_line_512x17_3sub3,
  121950. };
  121951. static static_codebook **_floor_books[10]={
  121952. _floor_128x4_books,
  121953. _floor_256x4_books,
  121954. _floor_128x7_books,
  121955. _floor_256x7_books,
  121956. _floor_128x11_books,
  121957. _floor_128x17_books,
  121958. _floor_256x4low_books,
  121959. _floor_1024x27_books,
  121960. _floor_2048x27_books,
  121961. _floor_512x17_books,
  121962. };
  121963. static vorbis_info_floor1 _floor[10]={
  121964. /* 128 x 4 */
  121965. {
  121966. 1,{0},{4},{2},{0},
  121967. {{1,2,3,4}},
  121968. 4,{0,128, 33,8,16,70},
  121969. 60,30,500, 1.,18., -1
  121970. },
  121971. /* 256 x 4 */
  121972. {
  121973. 1,{0},{4},{2},{0},
  121974. {{1,2,3,4}},
  121975. 4,{0,256, 66,16,32,140},
  121976. 60,30,500, 1.,18., -1
  121977. },
  121978. /* 128 x 7 */
  121979. {
  121980. 2,{0,1},{3,4},{2,2},{0,1},
  121981. {{-1,2,3,4},{-1,5,6,7}},
  121982. 4,{0,128, 14,4,58, 2,8,28,90},
  121983. 60,30,500, 1.,18., -1
  121984. },
  121985. /* 256 x 7 */
  121986. {
  121987. 2,{0,1},{3,4},{2,2},{0,1},
  121988. {{-1,2,3,4},{-1,5,6,7}},
  121989. 4,{0,256, 28,8,116, 4,16,56,180},
  121990. 60,30,500, 1.,18., -1
  121991. },
  121992. /* 128 x 11 */
  121993. {
  121994. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121995. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121996. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  121997. 60,30,500, 1,18., -1
  121998. },
  121999. /* 128 x 17 */
  122000. {
  122001. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122002. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122003. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122004. 60,30,500, 1,18., -1
  122005. },
  122006. /* 256 x 4 (low bitrate version) */
  122007. {
  122008. 1,{0},{4},{2},{0},
  122009. {{1,2,3,4}},
  122010. 4,{0,256, 66,16,32,140},
  122011. 60,30,500, 1.,18., -1
  122012. },
  122013. /* 1024 x 27 */
  122014. {
  122015. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122016. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122017. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122018. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122019. 60,30,500, 3,18., -1 /* lowpass */
  122020. },
  122021. /* 2048 x 27 */
  122022. {
  122023. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122024. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122025. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122026. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122027. 60,30,500, 3,18., -1 /* lowpass */
  122028. },
  122029. /* 512 x 17 */
  122030. {
  122031. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122032. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122033. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122034. 7,23,39, 55,79,110, 156,232,360},
  122035. 60,30,500, 1,18., -1 /* lowpass! */
  122036. },
  122037. };
  122038. /*** End of inlined file: floor_all.h ***/
  122039. /*** Start of inlined file: residue_44.h ***/
  122040. /*** Start of inlined file: res_books_stereo.h ***/
  122041. static long _vq_quantlist__16c0_s_p1_0[] = {
  122042. 1,
  122043. 0,
  122044. 2,
  122045. };
  122046. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122047. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122048. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122053. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122057. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122058. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122093. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122098. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122103. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122139. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122144. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122149. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0,
  122458. };
  122459. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122460. -0.5, 0.5,
  122461. };
  122462. static long _vq_quantmap__16c0_s_p1_0[] = {
  122463. 1, 0, 2,
  122464. };
  122465. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122466. _vq_quantthresh__16c0_s_p1_0,
  122467. _vq_quantmap__16c0_s_p1_0,
  122468. 3,
  122469. 3
  122470. };
  122471. static static_codebook _16c0_s_p1_0 = {
  122472. 8, 6561,
  122473. _vq_lengthlist__16c0_s_p1_0,
  122474. 1, -535822336, 1611661312, 2, 0,
  122475. _vq_quantlist__16c0_s_p1_0,
  122476. NULL,
  122477. &_vq_auxt__16c0_s_p1_0,
  122478. NULL,
  122479. 0
  122480. };
  122481. static long _vq_quantlist__16c0_s_p2_0[] = {
  122482. 2,
  122483. 1,
  122484. 3,
  122485. 0,
  122486. 4,
  122487. };
  122488. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0,
  122529. };
  122530. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122531. -1.5, -0.5, 0.5, 1.5,
  122532. };
  122533. static long _vq_quantmap__16c0_s_p2_0[] = {
  122534. 3, 1, 0, 2, 4,
  122535. };
  122536. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122537. _vq_quantthresh__16c0_s_p2_0,
  122538. _vq_quantmap__16c0_s_p2_0,
  122539. 5,
  122540. 5
  122541. };
  122542. static static_codebook _16c0_s_p2_0 = {
  122543. 4, 625,
  122544. _vq_lengthlist__16c0_s_p2_0,
  122545. 1, -533725184, 1611661312, 3, 0,
  122546. _vq_quantlist__16c0_s_p2_0,
  122547. NULL,
  122548. &_vq_auxt__16c0_s_p2_0,
  122549. NULL,
  122550. 0
  122551. };
  122552. static long _vq_quantlist__16c0_s_p3_0[] = {
  122553. 2,
  122554. 1,
  122555. 3,
  122556. 0,
  122557. 4,
  122558. };
  122559. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122560. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0,
  122600. };
  122601. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122602. -1.5, -0.5, 0.5, 1.5,
  122603. };
  122604. static long _vq_quantmap__16c0_s_p3_0[] = {
  122605. 3, 1, 0, 2, 4,
  122606. };
  122607. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122608. _vq_quantthresh__16c0_s_p3_0,
  122609. _vq_quantmap__16c0_s_p3_0,
  122610. 5,
  122611. 5
  122612. };
  122613. static static_codebook _16c0_s_p3_0 = {
  122614. 4, 625,
  122615. _vq_lengthlist__16c0_s_p3_0,
  122616. 1, -533725184, 1611661312, 3, 0,
  122617. _vq_quantlist__16c0_s_p3_0,
  122618. NULL,
  122619. &_vq_auxt__16c0_s_p3_0,
  122620. NULL,
  122621. 0
  122622. };
  122623. static long _vq_quantlist__16c0_s_p4_0[] = {
  122624. 4,
  122625. 3,
  122626. 5,
  122627. 2,
  122628. 6,
  122629. 1,
  122630. 7,
  122631. 0,
  122632. 8,
  122633. };
  122634. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122635. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122636. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122637. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122638. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122639. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0,
  122641. };
  122642. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122643. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122644. };
  122645. static long _vq_quantmap__16c0_s_p4_0[] = {
  122646. 7, 5, 3, 1, 0, 2, 4, 6,
  122647. 8,
  122648. };
  122649. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122650. _vq_quantthresh__16c0_s_p4_0,
  122651. _vq_quantmap__16c0_s_p4_0,
  122652. 9,
  122653. 9
  122654. };
  122655. static static_codebook _16c0_s_p4_0 = {
  122656. 2, 81,
  122657. _vq_lengthlist__16c0_s_p4_0,
  122658. 1, -531628032, 1611661312, 4, 0,
  122659. _vq_quantlist__16c0_s_p4_0,
  122660. NULL,
  122661. &_vq_auxt__16c0_s_p4_0,
  122662. NULL,
  122663. 0
  122664. };
  122665. static long _vq_quantlist__16c0_s_p5_0[] = {
  122666. 4,
  122667. 3,
  122668. 5,
  122669. 2,
  122670. 6,
  122671. 1,
  122672. 7,
  122673. 0,
  122674. 8,
  122675. };
  122676. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122677. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122678. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122679. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122680. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122681. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122682. 10,
  122683. };
  122684. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122685. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122686. };
  122687. static long _vq_quantmap__16c0_s_p5_0[] = {
  122688. 7, 5, 3, 1, 0, 2, 4, 6,
  122689. 8,
  122690. };
  122691. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122692. _vq_quantthresh__16c0_s_p5_0,
  122693. _vq_quantmap__16c0_s_p5_0,
  122694. 9,
  122695. 9
  122696. };
  122697. static static_codebook _16c0_s_p5_0 = {
  122698. 2, 81,
  122699. _vq_lengthlist__16c0_s_p5_0,
  122700. 1, -531628032, 1611661312, 4, 0,
  122701. _vq_quantlist__16c0_s_p5_0,
  122702. NULL,
  122703. &_vq_auxt__16c0_s_p5_0,
  122704. NULL,
  122705. 0
  122706. };
  122707. static long _vq_quantlist__16c0_s_p6_0[] = {
  122708. 8,
  122709. 7,
  122710. 9,
  122711. 6,
  122712. 10,
  122713. 5,
  122714. 11,
  122715. 4,
  122716. 12,
  122717. 3,
  122718. 13,
  122719. 2,
  122720. 14,
  122721. 1,
  122722. 15,
  122723. 0,
  122724. 16,
  122725. };
  122726. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122727. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122728. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122729. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122730. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122731. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122732. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122733. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122734. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122735. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122736. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122737. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122738. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122739. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122740. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122741. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122742. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122743. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122745. 14,
  122746. };
  122747. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122748. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122749. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122750. };
  122751. static long _vq_quantmap__16c0_s_p6_0[] = {
  122752. 15, 13, 11, 9, 7, 5, 3, 1,
  122753. 0, 2, 4, 6, 8, 10, 12, 14,
  122754. 16,
  122755. };
  122756. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122757. _vq_quantthresh__16c0_s_p6_0,
  122758. _vq_quantmap__16c0_s_p6_0,
  122759. 17,
  122760. 17
  122761. };
  122762. static static_codebook _16c0_s_p6_0 = {
  122763. 2, 289,
  122764. _vq_lengthlist__16c0_s_p6_0,
  122765. 1, -529530880, 1611661312, 5, 0,
  122766. _vq_quantlist__16c0_s_p6_0,
  122767. NULL,
  122768. &_vq_auxt__16c0_s_p6_0,
  122769. NULL,
  122770. 0
  122771. };
  122772. static long _vq_quantlist__16c0_s_p7_0[] = {
  122773. 1,
  122774. 0,
  122775. 2,
  122776. };
  122777. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122778. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122779. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122780. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122781. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122782. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122783. 13,
  122784. };
  122785. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122786. -5.5, 5.5,
  122787. };
  122788. static long _vq_quantmap__16c0_s_p7_0[] = {
  122789. 1, 0, 2,
  122790. };
  122791. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122792. _vq_quantthresh__16c0_s_p7_0,
  122793. _vq_quantmap__16c0_s_p7_0,
  122794. 3,
  122795. 3
  122796. };
  122797. static static_codebook _16c0_s_p7_0 = {
  122798. 4, 81,
  122799. _vq_lengthlist__16c0_s_p7_0,
  122800. 1, -529137664, 1618345984, 2, 0,
  122801. _vq_quantlist__16c0_s_p7_0,
  122802. NULL,
  122803. &_vq_auxt__16c0_s_p7_0,
  122804. NULL,
  122805. 0
  122806. };
  122807. static long _vq_quantlist__16c0_s_p7_1[] = {
  122808. 5,
  122809. 4,
  122810. 6,
  122811. 3,
  122812. 7,
  122813. 2,
  122814. 8,
  122815. 1,
  122816. 9,
  122817. 0,
  122818. 10,
  122819. };
  122820. static long _vq_lengthlist__16c0_s_p7_1[] = {
  122821. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  122822. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  122823. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  122824. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  122825. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  122826. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  122827. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  122828. 11,11,11, 9, 9, 9, 9,10,10,
  122829. };
  122830. static float _vq_quantthresh__16c0_s_p7_1[] = {
  122831. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122832. 3.5, 4.5,
  122833. };
  122834. static long _vq_quantmap__16c0_s_p7_1[] = {
  122835. 9, 7, 5, 3, 1, 0, 2, 4,
  122836. 6, 8, 10,
  122837. };
  122838. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  122839. _vq_quantthresh__16c0_s_p7_1,
  122840. _vq_quantmap__16c0_s_p7_1,
  122841. 11,
  122842. 11
  122843. };
  122844. static static_codebook _16c0_s_p7_1 = {
  122845. 2, 121,
  122846. _vq_lengthlist__16c0_s_p7_1,
  122847. 1, -531365888, 1611661312, 4, 0,
  122848. _vq_quantlist__16c0_s_p7_1,
  122849. NULL,
  122850. &_vq_auxt__16c0_s_p7_1,
  122851. NULL,
  122852. 0
  122853. };
  122854. static long _vq_quantlist__16c0_s_p8_0[] = {
  122855. 6,
  122856. 5,
  122857. 7,
  122858. 4,
  122859. 8,
  122860. 3,
  122861. 9,
  122862. 2,
  122863. 10,
  122864. 1,
  122865. 11,
  122866. 0,
  122867. 12,
  122868. };
  122869. static long _vq_lengthlist__16c0_s_p8_0[] = {
  122870. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  122871. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  122872. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  122873. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  122874. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  122875. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  122876. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  122877. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  122878. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  122879. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  122880. 0,12,13,13,12,13,14,14,14,
  122881. };
  122882. static float _vq_quantthresh__16c0_s_p8_0[] = {
  122883. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122884. 12.5, 17.5, 22.5, 27.5,
  122885. };
  122886. static long _vq_quantmap__16c0_s_p8_0[] = {
  122887. 11, 9, 7, 5, 3, 1, 0, 2,
  122888. 4, 6, 8, 10, 12,
  122889. };
  122890. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  122891. _vq_quantthresh__16c0_s_p8_0,
  122892. _vq_quantmap__16c0_s_p8_0,
  122893. 13,
  122894. 13
  122895. };
  122896. static static_codebook _16c0_s_p8_0 = {
  122897. 2, 169,
  122898. _vq_lengthlist__16c0_s_p8_0,
  122899. 1, -526516224, 1616117760, 4, 0,
  122900. _vq_quantlist__16c0_s_p8_0,
  122901. NULL,
  122902. &_vq_auxt__16c0_s_p8_0,
  122903. NULL,
  122904. 0
  122905. };
  122906. static long _vq_quantlist__16c0_s_p8_1[] = {
  122907. 2,
  122908. 1,
  122909. 3,
  122910. 0,
  122911. 4,
  122912. };
  122913. static long _vq_lengthlist__16c0_s_p8_1[] = {
  122914. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  122915. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122916. };
  122917. static float _vq_quantthresh__16c0_s_p8_1[] = {
  122918. -1.5, -0.5, 0.5, 1.5,
  122919. };
  122920. static long _vq_quantmap__16c0_s_p8_1[] = {
  122921. 3, 1, 0, 2, 4,
  122922. };
  122923. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  122924. _vq_quantthresh__16c0_s_p8_1,
  122925. _vq_quantmap__16c0_s_p8_1,
  122926. 5,
  122927. 5
  122928. };
  122929. static static_codebook _16c0_s_p8_1 = {
  122930. 2, 25,
  122931. _vq_lengthlist__16c0_s_p8_1,
  122932. 1, -533725184, 1611661312, 3, 0,
  122933. _vq_quantlist__16c0_s_p8_1,
  122934. NULL,
  122935. &_vq_auxt__16c0_s_p8_1,
  122936. NULL,
  122937. 0
  122938. };
  122939. static long _vq_quantlist__16c0_s_p9_0[] = {
  122940. 1,
  122941. 0,
  122942. 2,
  122943. };
  122944. static long _vq_lengthlist__16c0_s_p9_0[] = {
  122945. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122946. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122947. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122948. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122949. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122950. 7,
  122951. };
  122952. static float _vq_quantthresh__16c0_s_p9_0[] = {
  122953. -157.5, 157.5,
  122954. };
  122955. static long _vq_quantmap__16c0_s_p9_0[] = {
  122956. 1, 0, 2,
  122957. };
  122958. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  122959. _vq_quantthresh__16c0_s_p9_0,
  122960. _vq_quantmap__16c0_s_p9_0,
  122961. 3,
  122962. 3
  122963. };
  122964. static static_codebook _16c0_s_p9_0 = {
  122965. 4, 81,
  122966. _vq_lengthlist__16c0_s_p9_0,
  122967. 1, -518803456, 1628680192, 2, 0,
  122968. _vq_quantlist__16c0_s_p9_0,
  122969. NULL,
  122970. &_vq_auxt__16c0_s_p9_0,
  122971. NULL,
  122972. 0
  122973. };
  122974. static long _vq_quantlist__16c0_s_p9_1[] = {
  122975. 7,
  122976. 6,
  122977. 8,
  122978. 5,
  122979. 9,
  122980. 4,
  122981. 10,
  122982. 3,
  122983. 11,
  122984. 2,
  122985. 12,
  122986. 1,
  122987. 13,
  122988. 0,
  122989. 14,
  122990. };
  122991. static long _vq_lengthlist__16c0_s_p9_1[] = {
  122992. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  122993. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  122994. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  122995. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  122996. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122997. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122998. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122999. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123000. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123001. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123002. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123003. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123004. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123005. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123006. 10,
  123007. };
  123008. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123009. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123010. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123011. };
  123012. static long _vq_quantmap__16c0_s_p9_1[] = {
  123013. 13, 11, 9, 7, 5, 3, 1, 0,
  123014. 2, 4, 6, 8, 10, 12, 14,
  123015. };
  123016. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123017. _vq_quantthresh__16c0_s_p9_1,
  123018. _vq_quantmap__16c0_s_p9_1,
  123019. 15,
  123020. 15
  123021. };
  123022. static static_codebook _16c0_s_p9_1 = {
  123023. 2, 225,
  123024. _vq_lengthlist__16c0_s_p9_1,
  123025. 1, -520986624, 1620377600, 4, 0,
  123026. _vq_quantlist__16c0_s_p9_1,
  123027. NULL,
  123028. &_vq_auxt__16c0_s_p9_1,
  123029. NULL,
  123030. 0
  123031. };
  123032. static long _vq_quantlist__16c0_s_p9_2[] = {
  123033. 10,
  123034. 9,
  123035. 11,
  123036. 8,
  123037. 12,
  123038. 7,
  123039. 13,
  123040. 6,
  123041. 14,
  123042. 5,
  123043. 15,
  123044. 4,
  123045. 16,
  123046. 3,
  123047. 17,
  123048. 2,
  123049. 18,
  123050. 1,
  123051. 19,
  123052. 0,
  123053. 20,
  123054. };
  123055. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123056. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123057. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123058. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123059. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123060. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123061. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123062. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123063. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123064. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123065. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123066. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123067. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123068. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123069. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123070. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123071. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123072. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123073. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123074. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123075. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123076. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123077. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123078. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123079. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123080. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123081. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123082. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123083. 10,11,10,10,11, 9,10,10,10,
  123084. };
  123085. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123086. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123087. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123088. 6.5, 7.5, 8.5, 9.5,
  123089. };
  123090. static long _vq_quantmap__16c0_s_p9_2[] = {
  123091. 19, 17, 15, 13, 11, 9, 7, 5,
  123092. 3, 1, 0, 2, 4, 6, 8, 10,
  123093. 12, 14, 16, 18, 20,
  123094. };
  123095. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123096. _vq_quantthresh__16c0_s_p9_2,
  123097. _vq_quantmap__16c0_s_p9_2,
  123098. 21,
  123099. 21
  123100. };
  123101. static static_codebook _16c0_s_p9_2 = {
  123102. 2, 441,
  123103. _vq_lengthlist__16c0_s_p9_2,
  123104. 1, -529268736, 1611661312, 5, 0,
  123105. _vq_quantlist__16c0_s_p9_2,
  123106. NULL,
  123107. &_vq_auxt__16c0_s_p9_2,
  123108. NULL,
  123109. 0
  123110. };
  123111. static long _huff_lengthlist__16c0_s_single[] = {
  123112. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123113. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123114. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123115. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123116. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123117. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123118. 16,16,18,18,
  123119. };
  123120. static static_codebook _huff_book__16c0_s_single = {
  123121. 2, 100,
  123122. _huff_lengthlist__16c0_s_single,
  123123. 0, 0, 0, 0, 0,
  123124. NULL,
  123125. NULL,
  123126. NULL,
  123127. NULL,
  123128. 0
  123129. };
  123130. static long _huff_lengthlist__16c1_s_long[] = {
  123131. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123132. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123133. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123134. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123135. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123136. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123137. 12,11,11,13,
  123138. };
  123139. static static_codebook _huff_book__16c1_s_long = {
  123140. 2, 100,
  123141. _huff_lengthlist__16c1_s_long,
  123142. 0, 0, 0, 0, 0,
  123143. NULL,
  123144. NULL,
  123145. NULL,
  123146. NULL,
  123147. 0
  123148. };
  123149. static long _vq_quantlist__16c1_s_p1_0[] = {
  123150. 1,
  123151. 0,
  123152. 2,
  123153. };
  123154. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123155. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123156. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123161. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123166. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123201. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123206. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123211. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123247. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123252. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123257. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0,
  123566. };
  123567. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123568. -0.5, 0.5,
  123569. };
  123570. static long _vq_quantmap__16c1_s_p1_0[] = {
  123571. 1, 0, 2,
  123572. };
  123573. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123574. _vq_quantthresh__16c1_s_p1_0,
  123575. _vq_quantmap__16c1_s_p1_0,
  123576. 3,
  123577. 3
  123578. };
  123579. static static_codebook _16c1_s_p1_0 = {
  123580. 8, 6561,
  123581. _vq_lengthlist__16c1_s_p1_0,
  123582. 1, -535822336, 1611661312, 2, 0,
  123583. _vq_quantlist__16c1_s_p1_0,
  123584. NULL,
  123585. &_vq_auxt__16c1_s_p1_0,
  123586. NULL,
  123587. 0
  123588. };
  123589. static long _vq_quantlist__16c1_s_p2_0[] = {
  123590. 2,
  123591. 1,
  123592. 3,
  123593. 0,
  123594. 4,
  123595. };
  123596. static long _vq_lengthlist__16c1_s_p2_0[] = {
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0,
  123637. };
  123638. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123639. -1.5, -0.5, 0.5, 1.5,
  123640. };
  123641. static long _vq_quantmap__16c1_s_p2_0[] = {
  123642. 3, 1, 0, 2, 4,
  123643. };
  123644. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123645. _vq_quantthresh__16c1_s_p2_0,
  123646. _vq_quantmap__16c1_s_p2_0,
  123647. 5,
  123648. 5
  123649. };
  123650. static static_codebook _16c1_s_p2_0 = {
  123651. 4, 625,
  123652. _vq_lengthlist__16c1_s_p2_0,
  123653. 1, -533725184, 1611661312, 3, 0,
  123654. _vq_quantlist__16c1_s_p2_0,
  123655. NULL,
  123656. &_vq_auxt__16c1_s_p2_0,
  123657. NULL,
  123658. 0
  123659. };
  123660. static long _vq_quantlist__16c1_s_p3_0[] = {
  123661. 2,
  123662. 1,
  123663. 3,
  123664. 0,
  123665. 4,
  123666. };
  123667. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123668. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0,
  123708. };
  123709. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123710. -1.5, -0.5, 0.5, 1.5,
  123711. };
  123712. static long _vq_quantmap__16c1_s_p3_0[] = {
  123713. 3, 1, 0, 2, 4,
  123714. };
  123715. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123716. _vq_quantthresh__16c1_s_p3_0,
  123717. _vq_quantmap__16c1_s_p3_0,
  123718. 5,
  123719. 5
  123720. };
  123721. static static_codebook _16c1_s_p3_0 = {
  123722. 4, 625,
  123723. _vq_lengthlist__16c1_s_p3_0,
  123724. 1, -533725184, 1611661312, 3, 0,
  123725. _vq_quantlist__16c1_s_p3_0,
  123726. NULL,
  123727. &_vq_auxt__16c1_s_p3_0,
  123728. NULL,
  123729. 0
  123730. };
  123731. static long _vq_quantlist__16c1_s_p4_0[] = {
  123732. 4,
  123733. 3,
  123734. 5,
  123735. 2,
  123736. 6,
  123737. 1,
  123738. 7,
  123739. 0,
  123740. 8,
  123741. };
  123742. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123743. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123744. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123745. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123746. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123747. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0,
  123749. };
  123750. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123751. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123752. };
  123753. static long _vq_quantmap__16c1_s_p4_0[] = {
  123754. 7, 5, 3, 1, 0, 2, 4, 6,
  123755. 8,
  123756. };
  123757. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123758. _vq_quantthresh__16c1_s_p4_0,
  123759. _vq_quantmap__16c1_s_p4_0,
  123760. 9,
  123761. 9
  123762. };
  123763. static static_codebook _16c1_s_p4_0 = {
  123764. 2, 81,
  123765. _vq_lengthlist__16c1_s_p4_0,
  123766. 1, -531628032, 1611661312, 4, 0,
  123767. _vq_quantlist__16c1_s_p4_0,
  123768. NULL,
  123769. &_vq_auxt__16c1_s_p4_0,
  123770. NULL,
  123771. 0
  123772. };
  123773. static long _vq_quantlist__16c1_s_p5_0[] = {
  123774. 4,
  123775. 3,
  123776. 5,
  123777. 2,
  123778. 6,
  123779. 1,
  123780. 7,
  123781. 0,
  123782. 8,
  123783. };
  123784. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123785. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123786. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123787. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123788. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123789. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123790. 10,
  123791. };
  123792. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123793. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123794. };
  123795. static long _vq_quantmap__16c1_s_p5_0[] = {
  123796. 7, 5, 3, 1, 0, 2, 4, 6,
  123797. 8,
  123798. };
  123799. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123800. _vq_quantthresh__16c1_s_p5_0,
  123801. _vq_quantmap__16c1_s_p5_0,
  123802. 9,
  123803. 9
  123804. };
  123805. static static_codebook _16c1_s_p5_0 = {
  123806. 2, 81,
  123807. _vq_lengthlist__16c1_s_p5_0,
  123808. 1, -531628032, 1611661312, 4, 0,
  123809. _vq_quantlist__16c1_s_p5_0,
  123810. NULL,
  123811. &_vq_auxt__16c1_s_p5_0,
  123812. NULL,
  123813. 0
  123814. };
  123815. static long _vq_quantlist__16c1_s_p6_0[] = {
  123816. 8,
  123817. 7,
  123818. 9,
  123819. 6,
  123820. 10,
  123821. 5,
  123822. 11,
  123823. 4,
  123824. 12,
  123825. 3,
  123826. 13,
  123827. 2,
  123828. 14,
  123829. 1,
  123830. 15,
  123831. 0,
  123832. 16,
  123833. };
  123834. static long _vq_lengthlist__16c1_s_p6_0[] = {
  123835. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  123836. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123837. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123838. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  123839. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  123840. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123841. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123842. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123843. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123844. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123845. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123846. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  123847. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  123848. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123849. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  123850. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  123851. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123853. 14,
  123854. };
  123855. static float _vq_quantthresh__16c1_s_p6_0[] = {
  123856. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123857. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123858. };
  123859. static long _vq_quantmap__16c1_s_p6_0[] = {
  123860. 15, 13, 11, 9, 7, 5, 3, 1,
  123861. 0, 2, 4, 6, 8, 10, 12, 14,
  123862. 16,
  123863. };
  123864. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  123865. _vq_quantthresh__16c1_s_p6_0,
  123866. _vq_quantmap__16c1_s_p6_0,
  123867. 17,
  123868. 17
  123869. };
  123870. static static_codebook _16c1_s_p6_0 = {
  123871. 2, 289,
  123872. _vq_lengthlist__16c1_s_p6_0,
  123873. 1, -529530880, 1611661312, 5, 0,
  123874. _vq_quantlist__16c1_s_p6_0,
  123875. NULL,
  123876. &_vq_auxt__16c1_s_p6_0,
  123877. NULL,
  123878. 0
  123879. };
  123880. static long _vq_quantlist__16c1_s_p7_0[] = {
  123881. 1,
  123882. 0,
  123883. 2,
  123884. };
  123885. static long _vq_lengthlist__16c1_s_p7_0[] = {
  123886. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  123887. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123888. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  123889. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  123890. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  123891. 11,
  123892. };
  123893. static float _vq_quantthresh__16c1_s_p7_0[] = {
  123894. -5.5, 5.5,
  123895. };
  123896. static long _vq_quantmap__16c1_s_p7_0[] = {
  123897. 1, 0, 2,
  123898. };
  123899. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  123900. _vq_quantthresh__16c1_s_p7_0,
  123901. _vq_quantmap__16c1_s_p7_0,
  123902. 3,
  123903. 3
  123904. };
  123905. static static_codebook _16c1_s_p7_0 = {
  123906. 4, 81,
  123907. _vq_lengthlist__16c1_s_p7_0,
  123908. 1, -529137664, 1618345984, 2, 0,
  123909. _vq_quantlist__16c1_s_p7_0,
  123910. NULL,
  123911. &_vq_auxt__16c1_s_p7_0,
  123912. NULL,
  123913. 0
  123914. };
  123915. static long _vq_quantlist__16c1_s_p7_1[] = {
  123916. 5,
  123917. 4,
  123918. 6,
  123919. 3,
  123920. 7,
  123921. 2,
  123922. 8,
  123923. 1,
  123924. 9,
  123925. 0,
  123926. 10,
  123927. };
  123928. static long _vq_lengthlist__16c1_s_p7_1[] = {
  123929. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  123930. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  123931. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123932. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123933. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  123934. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  123935. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  123936. 10,10,10, 8, 8, 8, 8, 9, 9,
  123937. };
  123938. static float _vq_quantthresh__16c1_s_p7_1[] = {
  123939. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123940. 3.5, 4.5,
  123941. };
  123942. static long _vq_quantmap__16c1_s_p7_1[] = {
  123943. 9, 7, 5, 3, 1, 0, 2, 4,
  123944. 6, 8, 10,
  123945. };
  123946. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  123947. _vq_quantthresh__16c1_s_p7_1,
  123948. _vq_quantmap__16c1_s_p7_1,
  123949. 11,
  123950. 11
  123951. };
  123952. static static_codebook _16c1_s_p7_1 = {
  123953. 2, 121,
  123954. _vq_lengthlist__16c1_s_p7_1,
  123955. 1, -531365888, 1611661312, 4, 0,
  123956. _vq_quantlist__16c1_s_p7_1,
  123957. NULL,
  123958. &_vq_auxt__16c1_s_p7_1,
  123959. NULL,
  123960. 0
  123961. };
  123962. static long _vq_quantlist__16c1_s_p8_0[] = {
  123963. 6,
  123964. 5,
  123965. 7,
  123966. 4,
  123967. 8,
  123968. 3,
  123969. 9,
  123970. 2,
  123971. 10,
  123972. 1,
  123973. 11,
  123974. 0,
  123975. 12,
  123976. };
  123977. static long _vq_lengthlist__16c1_s_p8_0[] = {
  123978. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123979. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  123980. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  123981. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  123982. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  123983. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123984. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  123985. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  123986. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  123987. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  123988. 0,12,12,12,12,13,13,14,15,
  123989. };
  123990. static float _vq_quantthresh__16c1_s_p8_0[] = {
  123991. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123992. 12.5, 17.5, 22.5, 27.5,
  123993. };
  123994. static long _vq_quantmap__16c1_s_p8_0[] = {
  123995. 11, 9, 7, 5, 3, 1, 0, 2,
  123996. 4, 6, 8, 10, 12,
  123997. };
  123998. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  123999. _vq_quantthresh__16c1_s_p8_0,
  124000. _vq_quantmap__16c1_s_p8_0,
  124001. 13,
  124002. 13
  124003. };
  124004. static static_codebook _16c1_s_p8_0 = {
  124005. 2, 169,
  124006. _vq_lengthlist__16c1_s_p8_0,
  124007. 1, -526516224, 1616117760, 4, 0,
  124008. _vq_quantlist__16c1_s_p8_0,
  124009. NULL,
  124010. &_vq_auxt__16c1_s_p8_0,
  124011. NULL,
  124012. 0
  124013. };
  124014. static long _vq_quantlist__16c1_s_p8_1[] = {
  124015. 2,
  124016. 1,
  124017. 3,
  124018. 0,
  124019. 4,
  124020. };
  124021. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124022. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124023. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124024. };
  124025. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124026. -1.5, -0.5, 0.5, 1.5,
  124027. };
  124028. static long _vq_quantmap__16c1_s_p8_1[] = {
  124029. 3, 1, 0, 2, 4,
  124030. };
  124031. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124032. _vq_quantthresh__16c1_s_p8_1,
  124033. _vq_quantmap__16c1_s_p8_1,
  124034. 5,
  124035. 5
  124036. };
  124037. static static_codebook _16c1_s_p8_1 = {
  124038. 2, 25,
  124039. _vq_lengthlist__16c1_s_p8_1,
  124040. 1, -533725184, 1611661312, 3, 0,
  124041. _vq_quantlist__16c1_s_p8_1,
  124042. NULL,
  124043. &_vq_auxt__16c1_s_p8_1,
  124044. NULL,
  124045. 0
  124046. };
  124047. static long _vq_quantlist__16c1_s_p9_0[] = {
  124048. 6,
  124049. 5,
  124050. 7,
  124051. 4,
  124052. 8,
  124053. 3,
  124054. 9,
  124055. 2,
  124056. 10,
  124057. 1,
  124058. 11,
  124059. 0,
  124060. 12,
  124061. };
  124062. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124063. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124064. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124065. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124066. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124067. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124068. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124069. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124070. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124071. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124072. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124073. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124074. };
  124075. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124076. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124077. 787.5, 1102.5, 1417.5, 1732.5,
  124078. };
  124079. static long _vq_quantmap__16c1_s_p9_0[] = {
  124080. 11, 9, 7, 5, 3, 1, 0, 2,
  124081. 4, 6, 8, 10, 12,
  124082. };
  124083. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124084. _vq_quantthresh__16c1_s_p9_0,
  124085. _vq_quantmap__16c1_s_p9_0,
  124086. 13,
  124087. 13
  124088. };
  124089. static static_codebook _16c1_s_p9_0 = {
  124090. 2, 169,
  124091. _vq_lengthlist__16c1_s_p9_0,
  124092. 1, -513964032, 1628680192, 4, 0,
  124093. _vq_quantlist__16c1_s_p9_0,
  124094. NULL,
  124095. &_vq_auxt__16c1_s_p9_0,
  124096. NULL,
  124097. 0
  124098. };
  124099. static long _vq_quantlist__16c1_s_p9_1[] = {
  124100. 7,
  124101. 6,
  124102. 8,
  124103. 5,
  124104. 9,
  124105. 4,
  124106. 10,
  124107. 3,
  124108. 11,
  124109. 2,
  124110. 12,
  124111. 1,
  124112. 13,
  124113. 0,
  124114. 14,
  124115. };
  124116. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124117. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124118. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124119. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124120. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124121. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124122. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124123. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124124. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124125. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124126. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124127. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124128. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124129. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124130. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124131. 13,
  124132. };
  124133. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124134. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124135. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124136. };
  124137. static long _vq_quantmap__16c1_s_p9_1[] = {
  124138. 13, 11, 9, 7, 5, 3, 1, 0,
  124139. 2, 4, 6, 8, 10, 12, 14,
  124140. };
  124141. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124142. _vq_quantthresh__16c1_s_p9_1,
  124143. _vq_quantmap__16c1_s_p9_1,
  124144. 15,
  124145. 15
  124146. };
  124147. static static_codebook _16c1_s_p9_1 = {
  124148. 2, 225,
  124149. _vq_lengthlist__16c1_s_p9_1,
  124150. 1, -520986624, 1620377600, 4, 0,
  124151. _vq_quantlist__16c1_s_p9_1,
  124152. NULL,
  124153. &_vq_auxt__16c1_s_p9_1,
  124154. NULL,
  124155. 0
  124156. };
  124157. static long _vq_quantlist__16c1_s_p9_2[] = {
  124158. 10,
  124159. 9,
  124160. 11,
  124161. 8,
  124162. 12,
  124163. 7,
  124164. 13,
  124165. 6,
  124166. 14,
  124167. 5,
  124168. 15,
  124169. 4,
  124170. 16,
  124171. 3,
  124172. 17,
  124173. 2,
  124174. 18,
  124175. 1,
  124176. 19,
  124177. 0,
  124178. 20,
  124179. };
  124180. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124181. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124182. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124183. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124184. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124185. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124186. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124187. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124188. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124189. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124190. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124191. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124192. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124193. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124194. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124195. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124196. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124197. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124198. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124199. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124200. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124201. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124202. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124203. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124204. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124205. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124206. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124207. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124208. 11,11,11,11,12,11,11,12,11,
  124209. };
  124210. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124211. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124212. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124213. 6.5, 7.5, 8.5, 9.5,
  124214. };
  124215. static long _vq_quantmap__16c1_s_p9_2[] = {
  124216. 19, 17, 15, 13, 11, 9, 7, 5,
  124217. 3, 1, 0, 2, 4, 6, 8, 10,
  124218. 12, 14, 16, 18, 20,
  124219. };
  124220. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124221. _vq_quantthresh__16c1_s_p9_2,
  124222. _vq_quantmap__16c1_s_p9_2,
  124223. 21,
  124224. 21
  124225. };
  124226. static static_codebook _16c1_s_p9_2 = {
  124227. 2, 441,
  124228. _vq_lengthlist__16c1_s_p9_2,
  124229. 1, -529268736, 1611661312, 5, 0,
  124230. _vq_quantlist__16c1_s_p9_2,
  124231. NULL,
  124232. &_vq_auxt__16c1_s_p9_2,
  124233. NULL,
  124234. 0
  124235. };
  124236. static long _huff_lengthlist__16c1_s_short[] = {
  124237. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124238. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124239. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124240. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124241. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124242. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124243. 9, 9,10,13,
  124244. };
  124245. static static_codebook _huff_book__16c1_s_short = {
  124246. 2, 100,
  124247. _huff_lengthlist__16c1_s_short,
  124248. 0, 0, 0, 0, 0,
  124249. NULL,
  124250. NULL,
  124251. NULL,
  124252. NULL,
  124253. 0
  124254. };
  124255. static long _huff_lengthlist__16c2_s_long[] = {
  124256. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124257. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124258. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124259. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124260. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124261. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124262. 14,14,16,18,
  124263. };
  124264. static static_codebook _huff_book__16c2_s_long = {
  124265. 2, 100,
  124266. _huff_lengthlist__16c2_s_long,
  124267. 0, 0, 0, 0, 0,
  124268. NULL,
  124269. NULL,
  124270. NULL,
  124271. NULL,
  124272. 0
  124273. };
  124274. static long _vq_quantlist__16c2_s_p1_0[] = {
  124275. 1,
  124276. 0,
  124277. 2,
  124278. };
  124279. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124280. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124281. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0,
  124286. };
  124287. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124288. -0.5, 0.5,
  124289. };
  124290. static long _vq_quantmap__16c2_s_p1_0[] = {
  124291. 1, 0, 2,
  124292. };
  124293. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124294. _vq_quantthresh__16c2_s_p1_0,
  124295. _vq_quantmap__16c2_s_p1_0,
  124296. 3,
  124297. 3
  124298. };
  124299. static static_codebook _16c2_s_p1_0 = {
  124300. 4, 81,
  124301. _vq_lengthlist__16c2_s_p1_0,
  124302. 1, -535822336, 1611661312, 2, 0,
  124303. _vq_quantlist__16c2_s_p1_0,
  124304. NULL,
  124305. &_vq_auxt__16c2_s_p1_0,
  124306. NULL,
  124307. 0
  124308. };
  124309. static long _vq_quantlist__16c2_s_p2_0[] = {
  124310. 2,
  124311. 1,
  124312. 3,
  124313. 0,
  124314. 4,
  124315. };
  124316. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124317. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124318. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124319. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124320. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124321. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124322. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124323. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124324. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 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, 8, 8, 8,11,11, 0, 0, 0,
  124330. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124331. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124332. 0, 0, 0,12,13, 0, 0, 0,13,13, 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, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124338. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124339. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124340. 13,13, 0, 0, 0,12,13, 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, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124346. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124347. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124348. 0, 0,13,13, 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, 8,
  124353. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124354. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124355. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124356. 13,
  124357. };
  124358. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124359. -1.5, -0.5, 0.5, 1.5,
  124360. };
  124361. static long _vq_quantmap__16c2_s_p2_0[] = {
  124362. 3, 1, 0, 2, 4,
  124363. };
  124364. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124365. _vq_quantthresh__16c2_s_p2_0,
  124366. _vq_quantmap__16c2_s_p2_0,
  124367. 5,
  124368. 5
  124369. };
  124370. static static_codebook _16c2_s_p2_0 = {
  124371. 4, 625,
  124372. _vq_lengthlist__16c2_s_p2_0,
  124373. 1, -533725184, 1611661312, 3, 0,
  124374. _vq_quantlist__16c2_s_p2_0,
  124375. NULL,
  124376. &_vq_auxt__16c2_s_p2_0,
  124377. NULL,
  124378. 0
  124379. };
  124380. static long _vq_quantlist__16c2_s_p3_0[] = {
  124381. 4,
  124382. 3,
  124383. 5,
  124384. 2,
  124385. 6,
  124386. 1,
  124387. 7,
  124388. 0,
  124389. 8,
  124390. };
  124391. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124392. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124393. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124394. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124395. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0,
  124398. };
  124399. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124400. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124401. };
  124402. static long _vq_quantmap__16c2_s_p3_0[] = {
  124403. 7, 5, 3, 1, 0, 2, 4, 6,
  124404. 8,
  124405. };
  124406. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124407. _vq_quantthresh__16c2_s_p3_0,
  124408. _vq_quantmap__16c2_s_p3_0,
  124409. 9,
  124410. 9
  124411. };
  124412. static static_codebook _16c2_s_p3_0 = {
  124413. 2, 81,
  124414. _vq_lengthlist__16c2_s_p3_0,
  124415. 1, -531628032, 1611661312, 4, 0,
  124416. _vq_quantlist__16c2_s_p3_0,
  124417. NULL,
  124418. &_vq_auxt__16c2_s_p3_0,
  124419. NULL,
  124420. 0
  124421. };
  124422. static long _vq_quantlist__16c2_s_p4_0[] = {
  124423. 8,
  124424. 7,
  124425. 9,
  124426. 6,
  124427. 10,
  124428. 5,
  124429. 11,
  124430. 4,
  124431. 12,
  124432. 3,
  124433. 13,
  124434. 2,
  124435. 14,
  124436. 1,
  124437. 15,
  124438. 0,
  124439. 16,
  124440. };
  124441. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124442. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124443. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124444. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124445. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124446. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124447. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124448. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124449. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124450. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124451. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124460. 0,
  124461. };
  124462. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124463. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124464. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124465. };
  124466. static long _vq_quantmap__16c2_s_p4_0[] = {
  124467. 15, 13, 11, 9, 7, 5, 3, 1,
  124468. 0, 2, 4, 6, 8, 10, 12, 14,
  124469. 16,
  124470. };
  124471. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124472. _vq_quantthresh__16c2_s_p4_0,
  124473. _vq_quantmap__16c2_s_p4_0,
  124474. 17,
  124475. 17
  124476. };
  124477. static static_codebook _16c2_s_p4_0 = {
  124478. 2, 289,
  124479. _vq_lengthlist__16c2_s_p4_0,
  124480. 1, -529530880, 1611661312, 5, 0,
  124481. _vq_quantlist__16c2_s_p4_0,
  124482. NULL,
  124483. &_vq_auxt__16c2_s_p4_0,
  124484. NULL,
  124485. 0
  124486. };
  124487. static long _vq_quantlist__16c2_s_p5_0[] = {
  124488. 1,
  124489. 0,
  124490. 2,
  124491. };
  124492. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124493. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124494. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124495. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124496. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124497. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124498. 12,
  124499. };
  124500. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124501. -5.5, 5.5,
  124502. };
  124503. static long _vq_quantmap__16c2_s_p5_0[] = {
  124504. 1, 0, 2,
  124505. };
  124506. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124507. _vq_quantthresh__16c2_s_p5_0,
  124508. _vq_quantmap__16c2_s_p5_0,
  124509. 3,
  124510. 3
  124511. };
  124512. static static_codebook _16c2_s_p5_0 = {
  124513. 4, 81,
  124514. _vq_lengthlist__16c2_s_p5_0,
  124515. 1, -529137664, 1618345984, 2, 0,
  124516. _vq_quantlist__16c2_s_p5_0,
  124517. NULL,
  124518. &_vq_auxt__16c2_s_p5_0,
  124519. NULL,
  124520. 0
  124521. };
  124522. static long _vq_quantlist__16c2_s_p5_1[] = {
  124523. 5,
  124524. 4,
  124525. 6,
  124526. 3,
  124527. 7,
  124528. 2,
  124529. 8,
  124530. 1,
  124531. 9,
  124532. 0,
  124533. 10,
  124534. };
  124535. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124536. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124537. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124538. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124539. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124540. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124541. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124542. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124543. 11,11,11, 7, 7, 8, 8, 8, 8,
  124544. };
  124545. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124546. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124547. 3.5, 4.5,
  124548. };
  124549. static long _vq_quantmap__16c2_s_p5_1[] = {
  124550. 9, 7, 5, 3, 1, 0, 2, 4,
  124551. 6, 8, 10,
  124552. };
  124553. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124554. _vq_quantthresh__16c2_s_p5_1,
  124555. _vq_quantmap__16c2_s_p5_1,
  124556. 11,
  124557. 11
  124558. };
  124559. static static_codebook _16c2_s_p5_1 = {
  124560. 2, 121,
  124561. _vq_lengthlist__16c2_s_p5_1,
  124562. 1, -531365888, 1611661312, 4, 0,
  124563. _vq_quantlist__16c2_s_p5_1,
  124564. NULL,
  124565. &_vq_auxt__16c2_s_p5_1,
  124566. NULL,
  124567. 0
  124568. };
  124569. static long _vq_quantlist__16c2_s_p6_0[] = {
  124570. 6,
  124571. 5,
  124572. 7,
  124573. 4,
  124574. 8,
  124575. 3,
  124576. 9,
  124577. 2,
  124578. 10,
  124579. 1,
  124580. 11,
  124581. 0,
  124582. 12,
  124583. };
  124584. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124585. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124586. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124587. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124588. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124589. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124590. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124595. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124596. };
  124597. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124598. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124599. 12.5, 17.5, 22.5, 27.5,
  124600. };
  124601. static long _vq_quantmap__16c2_s_p6_0[] = {
  124602. 11, 9, 7, 5, 3, 1, 0, 2,
  124603. 4, 6, 8, 10, 12,
  124604. };
  124605. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124606. _vq_quantthresh__16c2_s_p6_0,
  124607. _vq_quantmap__16c2_s_p6_0,
  124608. 13,
  124609. 13
  124610. };
  124611. static static_codebook _16c2_s_p6_0 = {
  124612. 2, 169,
  124613. _vq_lengthlist__16c2_s_p6_0,
  124614. 1, -526516224, 1616117760, 4, 0,
  124615. _vq_quantlist__16c2_s_p6_0,
  124616. NULL,
  124617. &_vq_auxt__16c2_s_p6_0,
  124618. NULL,
  124619. 0
  124620. };
  124621. static long _vq_quantlist__16c2_s_p6_1[] = {
  124622. 2,
  124623. 1,
  124624. 3,
  124625. 0,
  124626. 4,
  124627. };
  124628. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124629. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124630. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124631. };
  124632. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124633. -1.5, -0.5, 0.5, 1.5,
  124634. };
  124635. static long _vq_quantmap__16c2_s_p6_1[] = {
  124636. 3, 1, 0, 2, 4,
  124637. };
  124638. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124639. _vq_quantthresh__16c2_s_p6_1,
  124640. _vq_quantmap__16c2_s_p6_1,
  124641. 5,
  124642. 5
  124643. };
  124644. static static_codebook _16c2_s_p6_1 = {
  124645. 2, 25,
  124646. _vq_lengthlist__16c2_s_p6_1,
  124647. 1, -533725184, 1611661312, 3, 0,
  124648. _vq_quantlist__16c2_s_p6_1,
  124649. NULL,
  124650. &_vq_auxt__16c2_s_p6_1,
  124651. NULL,
  124652. 0
  124653. };
  124654. static long _vq_quantlist__16c2_s_p7_0[] = {
  124655. 6,
  124656. 5,
  124657. 7,
  124658. 4,
  124659. 8,
  124660. 3,
  124661. 9,
  124662. 2,
  124663. 10,
  124664. 1,
  124665. 11,
  124666. 0,
  124667. 12,
  124668. };
  124669. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124670. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124671. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124672. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124673. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124674. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124675. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124676. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124677. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124678. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124679. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124680. 18,13,14,13,13,14,13,15,14,
  124681. };
  124682. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124683. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124684. 27.5, 38.5, 49.5, 60.5,
  124685. };
  124686. static long _vq_quantmap__16c2_s_p7_0[] = {
  124687. 11, 9, 7, 5, 3, 1, 0, 2,
  124688. 4, 6, 8, 10, 12,
  124689. };
  124690. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124691. _vq_quantthresh__16c2_s_p7_0,
  124692. _vq_quantmap__16c2_s_p7_0,
  124693. 13,
  124694. 13
  124695. };
  124696. static static_codebook _16c2_s_p7_0 = {
  124697. 2, 169,
  124698. _vq_lengthlist__16c2_s_p7_0,
  124699. 1, -523206656, 1618345984, 4, 0,
  124700. _vq_quantlist__16c2_s_p7_0,
  124701. NULL,
  124702. &_vq_auxt__16c2_s_p7_0,
  124703. NULL,
  124704. 0
  124705. };
  124706. static long _vq_quantlist__16c2_s_p7_1[] = {
  124707. 5,
  124708. 4,
  124709. 6,
  124710. 3,
  124711. 7,
  124712. 2,
  124713. 8,
  124714. 1,
  124715. 9,
  124716. 0,
  124717. 10,
  124718. };
  124719. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124720. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124721. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124722. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124723. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124724. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124725. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124726. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124727. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124728. };
  124729. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124730. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124731. 3.5, 4.5,
  124732. };
  124733. static long _vq_quantmap__16c2_s_p7_1[] = {
  124734. 9, 7, 5, 3, 1, 0, 2, 4,
  124735. 6, 8, 10,
  124736. };
  124737. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124738. _vq_quantthresh__16c2_s_p7_1,
  124739. _vq_quantmap__16c2_s_p7_1,
  124740. 11,
  124741. 11
  124742. };
  124743. static static_codebook _16c2_s_p7_1 = {
  124744. 2, 121,
  124745. _vq_lengthlist__16c2_s_p7_1,
  124746. 1, -531365888, 1611661312, 4, 0,
  124747. _vq_quantlist__16c2_s_p7_1,
  124748. NULL,
  124749. &_vq_auxt__16c2_s_p7_1,
  124750. NULL,
  124751. 0
  124752. };
  124753. static long _vq_quantlist__16c2_s_p8_0[] = {
  124754. 7,
  124755. 6,
  124756. 8,
  124757. 5,
  124758. 9,
  124759. 4,
  124760. 10,
  124761. 3,
  124762. 11,
  124763. 2,
  124764. 12,
  124765. 1,
  124766. 13,
  124767. 0,
  124768. 14,
  124769. };
  124770. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124771. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124772. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124773. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124774. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124775. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124776. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124777. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124778. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124779. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124780. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124781. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124782. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124783. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124784. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124785. 13,
  124786. };
  124787. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124788. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124789. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124790. };
  124791. static long _vq_quantmap__16c2_s_p8_0[] = {
  124792. 13, 11, 9, 7, 5, 3, 1, 0,
  124793. 2, 4, 6, 8, 10, 12, 14,
  124794. };
  124795. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124796. _vq_quantthresh__16c2_s_p8_0,
  124797. _vq_quantmap__16c2_s_p8_0,
  124798. 15,
  124799. 15
  124800. };
  124801. static static_codebook _16c2_s_p8_0 = {
  124802. 2, 225,
  124803. _vq_lengthlist__16c2_s_p8_0,
  124804. 1, -520986624, 1620377600, 4, 0,
  124805. _vq_quantlist__16c2_s_p8_0,
  124806. NULL,
  124807. &_vq_auxt__16c2_s_p8_0,
  124808. NULL,
  124809. 0
  124810. };
  124811. static long _vq_quantlist__16c2_s_p8_1[] = {
  124812. 10,
  124813. 9,
  124814. 11,
  124815. 8,
  124816. 12,
  124817. 7,
  124818. 13,
  124819. 6,
  124820. 14,
  124821. 5,
  124822. 15,
  124823. 4,
  124824. 16,
  124825. 3,
  124826. 17,
  124827. 2,
  124828. 18,
  124829. 1,
  124830. 19,
  124831. 0,
  124832. 20,
  124833. };
  124834. static long _vq_lengthlist__16c2_s_p8_1[] = {
  124835. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  124836. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  124837. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  124838. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  124839. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  124840. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  124841. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  124842. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124843. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  124844. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  124845. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  124846. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  124847. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  124848. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  124849. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  124850. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  124851. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  124852. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  124853. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  124854. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  124855. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  124856. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  124857. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  124858. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  124859. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  124860. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  124861. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  124862. 10,11,10,10,10,10,10,10,10,
  124863. };
  124864. static float _vq_quantthresh__16c2_s_p8_1[] = {
  124865. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124866. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124867. 6.5, 7.5, 8.5, 9.5,
  124868. };
  124869. static long _vq_quantmap__16c2_s_p8_1[] = {
  124870. 19, 17, 15, 13, 11, 9, 7, 5,
  124871. 3, 1, 0, 2, 4, 6, 8, 10,
  124872. 12, 14, 16, 18, 20,
  124873. };
  124874. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  124875. _vq_quantthresh__16c2_s_p8_1,
  124876. _vq_quantmap__16c2_s_p8_1,
  124877. 21,
  124878. 21
  124879. };
  124880. static static_codebook _16c2_s_p8_1 = {
  124881. 2, 441,
  124882. _vq_lengthlist__16c2_s_p8_1,
  124883. 1, -529268736, 1611661312, 5, 0,
  124884. _vq_quantlist__16c2_s_p8_1,
  124885. NULL,
  124886. &_vq_auxt__16c2_s_p8_1,
  124887. NULL,
  124888. 0
  124889. };
  124890. static long _vq_quantlist__16c2_s_p9_0[] = {
  124891. 6,
  124892. 5,
  124893. 7,
  124894. 4,
  124895. 8,
  124896. 3,
  124897. 9,
  124898. 2,
  124899. 10,
  124900. 1,
  124901. 11,
  124902. 0,
  124903. 12,
  124904. };
  124905. static long _vq_lengthlist__16c2_s_p9_0[] = {
  124906. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124907. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124908. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124909. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124910. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124911. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124912. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124913. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124914. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124915. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124916. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124917. };
  124918. static float _vq_quantthresh__16c2_s_p9_0[] = {
  124919. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  124920. 2327.5, 3258.5, 4189.5, 5120.5,
  124921. };
  124922. static long _vq_quantmap__16c2_s_p9_0[] = {
  124923. 11, 9, 7, 5, 3, 1, 0, 2,
  124924. 4, 6, 8, 10, 12,
  124925. };
  124926. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  124927. _vq_quantthresh__16c2_s_p9_0,
  124928. _vq_quantmap__16c2_s_p9_0,
  124929. 13,
  124930. 13
  124931. };
  124932. static static_codebook _16c2_s_p9_0 = {
  124933. 2, 169,
  124934. _vq_lengthlist__16c2_s_p9_0,
  124935. 1, -510275072, 1631393792, 4, 0,
  124936. _vq_quantlist__16c2_s_p9_0,
  124937. NULL,
  124938. &_vq_auxt__16c2_s_p9_0,
  124939. NULL,
  124940. 0
  124941. };
  124942. static long _vq_quantlist__16c2_s_p9_1[] = {
  124943. 8,
  124944. 7,
  124945. 9,
  124946. 6,
  124947. 10,
  124948. 5,
  124949. 11,
  124950. 4,
  124951. 12,
  124952. 3,
  124953. 13,
  124954. 2,
  124955. 14,
  124956. 1,
  124957. 15,
  124958. 0,
  124959. 16,
  124960. };
  124961. static long _vq_lengthlist__16c2_s_p9_1[] = {
  124962. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  124963. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  124964. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  124965. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  124966. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  124967. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  124968. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  124969. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  124970. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  124971. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  124972. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124973. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124974. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124975. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124976. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124977. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  124978. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  124979. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124980. 10,
  124981. };
  124982. static float _vq_quantthresh__16c2_s_p9_1[] = {
  124983. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  124984. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  124985. };
  124986. static long _vq_quantmap__16c2_s_p9_1[] = {
  124987. 15, 13, 11, 9, 7, 5, 3, 1,
  124988. 0, 2, 4, 6, 8, 10, 12, 14,
  124989. 16,
  124990. };
  124991. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  124992. _vq_quantthresh__16c2_s_p9_1,
  124993. _vq_quantmap__16c2_s_p9_1,
  124994. 17,
  124995. 17
  124996. };
  124997. static static_codebook _16c2_s_p9_1 = {
  124998. 2, 289,
  124999. _vq_lengthlist__16c2_s_p9_1,
  125000. 1, -518488064, 1622704128, 5, 0,
  125001. _vq_quantlist__16c2_s_p9_1,
  125002. NULL,
  125003. &_vq_auxt__16c2_s_p9_1,
  125004. NULL,
  125005. 0
  125006. };
  125007. static long _vq_quantlist__16c2_s_p9_2[] = {
  125008. 13,
  125009. 12,
  125010. 14,
  125011. 11,
  125012. 15,
  125013. 10,
  125014. 16,
  125015. 9,
  125016. 17,
  125017. 8,
  125018. 18,
  125019. 7,
  125020. 19,
  125021. 6,
  125022. 20,
  125023. 5,
  125024. 21,
  125025. 4,
  125026. 22,
  125027. 3,
  125028. 23,
  125029. 2,
  125030. 24,
  125031. 1,
  125032. 25,
  125033. 0,
  125034. 26,
  125035. };
  125036. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125037. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125038. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125039. };
  125040. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125041. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125042. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125043. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125044. 11.5, 12.5,
  125045. };
  125046. static long _vq_quantmap__16c2_s_p9_2[] = {
  125047. 25, 23, 21, 19, 17, 15, 13, 11,
  125048. 9, 7, 5, 3, 1, 0, 2, 4,
  125049. 6, 8, 10, 12, 14, 16, 18, 20,
  125050. 22, 24, 26,
  125051. };
  125052. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125053. _vq_quantthresh__16c2_s_p9_2,
  125054. _vq_quantmap__16c2_s_p9_2,
  125055. 27,
  125056. 27
  125057. };
  125058. static static_codebook _16c2_s_p9_2 = {
  125059. 1, 27,
  125060. _vq_lengthlist__16c2_s_p9_2,
  125061. 1, -528875520, 1611661312, 5, 0,
  125062. _vq_quantlist__16c2_s_p9_2,
  125063. NULL,
  125064. &_vq_auxt__16c2_s_p9_2,
  125065. NULL,
  125066. 0
  125067. };
  125068. static long _huff_lengthlist__16c2_s_short[] = {
  125069. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125070. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125071. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125072. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125073. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125074. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125075. 15,12,14,14,
  125076. };
  125077. static static_codebook _huff_book__16c2_s_short = {
  125078. 2, 100,
  125079. _huff_lengthlist__16c2_s_short,
  125080. 0, 0, 0, 0, 0,
  125081. NULL,
  125082. NULL,
  125083. NULL,
  125084. NULL,
  125085. 0
  125086. };
  125087. static long _vq_quantlist__8c0_s_p1_0[] = {
  125088. 1,
  125089. 0,
  125090. 2,
  125091. };
  125092. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125093. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125094. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125099. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125104. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  125139. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125144. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125149. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125185. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125190. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125195. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0,
  125504. };
  125505. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125506. -0.5, 0.5,
  125507. };
  125508. static long _vq_quantmap__8c0_s_p1_0[] = {
  125509. 1, 0, 2,
  125510. };
  125511. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125512. _vq_quantthresh__8c0_s_p1_0,
  125513. _vq_quantmap__8c0_s_p1_0,
  125514. 3,
  125515. 3
  125516. };
  125517. static static_codebook _8c0_s_p1_0 = {
  125518. 8, 6561,
  125519. _vq_lengthlist__8c0_s_p1_0,
  125520. 1, -535822336, 1611661312, 2, 0,
  125521. _vq_quantlist__8c0_s_p1_0,
  125522. NULL,
  125523. &_vq_auxt__8c0_s_p1_0,
  125524. NULL,
  125525. 0
  125526. };
  125527. static long _vq_quantlist__8c0_s_p2_0[] = {
  125528. 2,
  125529. 1,
  125530. 3,
  125531. 0,
  125532. 4,
  125533. };
  125534. static long _vq_lengthlist__8c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125574. 0,
  125575. };
  125576. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125577. -1.5, -0.5, 0.5, 1.5,
  125578. };
  125579. static long _vq_quantmap__8c0_s_p2_0[] = {
  125580. 3, 1, 0, 2, 4,
  125581. };
  125582. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125583. _vq_quantthresh__8c0_s_p2_0,
  125584. _vq_quantmap__8c0_s_p2_0,
  125585. 5,
  125586. 5
  125587. };
  125588. static static_codebook _8c0_s_p2_0 = {
  125589. 4, 625,
  125590. _vq_lengthlist__8c0_s_p2_0,
  125591. 1, -533725184, 1611661312, 3, 0,
  125592. _vq_quantlist__8c0_s_p2_0,
  125593. NULL,
  125594. &_vq_auxt__8c0_s_p2_0,
  125595. NULL,
  125596. 0
  125597. };
  125598. static long _vq_quantlist__8c0_s_p3_0[] = {
  125599. 2,
  125600. 1,
  125601. 3,
  125602. 0,
  125603. 4,
  125604. };
  125605. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125606. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0,
  125646. };
  125647. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125648. -1.5, -0.5, 0.5, 1.5,
  125649. };
  125650. static long _vq_quantmap__8c0_s_p3_0[] = {
  125651. 3, 1, 0, 2, 4,
  125652. };
  125653. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125654. _vq_quantthresh__8c0_s_p3_0,
  125655. _vq_quantmap__8c0_s_p3_0,
  125656. 5,
  125657. 5
  125658. };
  125659. static static_codebook _8c0_s_p3_0 = {
  125660. 4, 625,
  125661. _vq_lengthlist__8c0_s_p3_0,
  125662. 1, -533725184, 1611661312, 3, 0,
  125663. _vq_quantlist__8c0_s_p3_0,
  125664. NULL,
  125665. &_vq_auxt__8c0_s_p3_0,
  125666. NULL,
  125667. 0
  125668. };
  125669. static long _vq_quantlist__8c0_s_p4_0[] = {
  125670. 4,
  125671. 3,
  125672. 5,
  125673. 2,
  125674. 6,
  125675. 1,
  125676. 7,
  125677. 0,
  125678. 8,
  125679. };
  125680. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125681. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125682. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125683. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125684. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125685. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0,
  125687. };
  125688. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125689. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125690. };
  125691. static long _vq_quantmap__8c0_s_p4_0[] = {
  125692. 7, 5, 3, 1, 0, 2, 4, 6,
  125693. 8,
  125694. };
  125695. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125696. _vq_quantthresh__8c0_s_p4_0,
  125697. _vq_quantmap__8c0_s_p4_0,
  125698. 9,
  125699. 9
  125700. };
  125701. static static_codebook _8c0_s_p4_0 = {
  125702. 2, 81,
  125703. _vq_lengthlist__8c0_s_p4_0,
  125704. 1, -531628032, 1611661312, 4, 0,
  125705. _vq_quantlist__8c0_s_p4_0,
  125706. NULL,
  125707. &_vq_auxt__8c0_s_p4_0,
  125708. NULL,
  125709. 0
  125710. };
  125711. static long _vq_quantlist__8c0_s_p5_0[] = {
  125712. 4,
  125713. 3,
  125714. 5,
  125715. 2,
  125716. 6,
  125717. 1,
  125718. 7,
  125719. 0,
  125720. 8,
  125721. };
  125722. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125723. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125724. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125725. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125726. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125727. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125728. 10,
  125729. };
  125730. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125731. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125732. };
  125733. static long _vq_quantmap__8c0_s_p5_0[] = {
  125734. 7, 5, 3, 1, 0, 2, 4, 6,
  125735. 8,
  125736. };
  125737. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125738. _vq_quantthresh__8c0_s_p5_0,
  125739. _vq_quantmap__8c0_s_p5_0,
  125740. 9,
  125741. 9
  125742. };
  125743. static static_codebook _8c0_s_p5_0 = {
  125744. 2, 81,
  125745. _vq_lengthlist__8c0_s_p5_0,
  125746. 1, -531628032, 1611661312, 4, 0,
  125747. _vq_quantlist__8c0_s_p5_0,
  125748. NULL,
  125749. &_vq_auxt__8c0_s_p5_0,
  125750. NULL,
  125751. 0
  125752. };
  125753. static long _vq_quantlist__8c0_s_p6_0[] = {
  125754. 8,
  125755. 7,
  125756. 9,
  125757. 6,
  125758. 10,
  125759. 5,
  125760. 11,
  125761. 4,
  125762. 12,
  125763. 3,
  125764. 13,
  125765. 2,
  125766. 14,
  125767. 1,
  125768. 15,
  125769. 0,
  125770. 16,
  125771. };
  125772. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125773. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125774. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125775. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125776. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125777. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125778. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125779. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125780. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125781. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125782. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125783. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125784. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125785. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125786. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125787. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125788. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125789. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125791. 14,
  125792. };
  125793. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125794. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125795. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125796. };
  125797. static long _vq_quantmap__8c0_s_p6_0[] = {
  125798. 15, 13, 11, 9, 7, 5, 3, 1,
  125799. 0, 2, 4, 6, 8, 10, 12, 14,
  125800. 16,
  125801. };
  125802. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125803. _vq_quantthresh__8c0_s_p6_0,
  125804. _vq_quantmap__8c0_s_p6_0,
  125805. 17,
  125806. 17
  125807. };
  125808. static static_codebook _8c0_s_p6_0 = {
  125809. 2, 289,
  125810. _vq_lengthlist__8c0_s_p6_0,
  125811. 1, -529530880, 1611661312, 5, 0,
  125812. _vq_quantlist__8c0_s_p6_0,
  125813. NULL,
  125814. &_vq_auxt__8c0_s_p6_0,
  125815. NULL,
  125816. 0
  125817. };
  125818. static long _vq_quantlist__8c0_s_p7_0[] = {
  125819. 1,
  125820. 0,
  125821. 2,
  125822. };
  125823. static long _vq_lengthlist__8c0_s_p7_0[] = {
  125824. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  125825. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  125826. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  125827. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  125828. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  125829. 10,
  125830. };
  125831. static float _vq_quantthresh__8c0_s_p7_0[] = {
  125832. -5.5, 5.5,
  125833. };
  125834. static long _vq_quantmap__8c0_s_p7_0[] = {
  125835. 1, 0, 2,
  125836. };
  125837. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  125838. _vq_quantthresh__8c0_s_p7_0,
  125839. _vq_quantmap__8c0_s_p7_0,
  125840. 3,
  125841. 3
  125842. };
  125843. static static_codebook _8c0_s_p7_0 = {
  125844. 4, 81,
  125845. _vq_lengthlist__8c0_s_p7_0,
  125846. 1, -529137664, 1618345984, 2, 0,
  125847. _vq_quantlist__8c0_s_p7_0,
  125848. NULL,
  125849. &_vq_auxt__8c0_s_p7_0,
  125850. NULL,
  125851. 0
  125852. };
  125853. static long _vq_quantlist__8c0_s_p7_1[] = {
  125854. 5,
  125855. 4,
  125856. 6,
  125857. 3,
  125858. 7,
  125859. 2,
  125860. 8,
  125861. 1,
  125862. 9,
  125863. 0,
  125864. 10,
  125865. };
  125866. static long _vq_lengthlist__8c0_s_p7_1[] = {
  125867. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  125868. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  125869. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  125870. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  125871. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  125872. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  125873. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  125874. 10,10,10, 9, 9, 9,10,10,10,
  125875. };
  125876. static float _vq_quantthresh__8c0_s_p7_1[] = {
  125877. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125878. 3.5, 4.5,
  125879. };
  125880. static long _vq_quantmap__8c0_s_p7_1[] = {
  125881. 9, 7, 5, 3, 1, 0, 2, 4,
  125882. 6, 8, 10,
  125883. };
  125884. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  125885. _vq_quantthresh__8c0_s_p7_1,
  125886. _vq_quantmap__8c0_s_p7_1,
  125887. 11,
  125888. 11
  125889. };
  125890. static static_codebook _8c0_s_p7_1 = {
  125891. 2, 121,
  125892. _vq_lengthlist__8c0_s_p7_1,
  125893. 1, -531365888, 1611661312, 4, 0,
  125894. _vq_quantlist__8c0_s_p7_1,
  125895. NULL,
  125896. &_vq_auxt__8c0_s_p7_1,
  125897. NULL,
  125898. 0
  125899. };
  125900. static long _vq_quantlist__8c0_s_p8_0[] = {
  125901. 6,
  125902. 5,
  125903. 7,
  125904. 4,
  125905. 8,
  125906. 3,
  125907. 9,
  125908. 2,
  125909. 10,
  125910. 1,
  125911. 11,
  125912. 0,
  125913. 12,
  125914. };
  125915. static long _vq_lengthlist__8c0_s_p8_0[] = {
  125916. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  125917. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  125918. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  125919. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  125920. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  125921. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  125922. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  125923. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  125924. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  125925. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  125926. 0, 0,13,13,11,13,13,11,12,
  125927. };
  125928. static float _vq_quantthresh__8c0_s_p8_0[] = {
  125929. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125930. 12.5, 17.5, 22.5, 27.5,
  125931. };
  125932. static long _vq_quantmap__8c0_s_p8_0[] = {
  125933. 11, 9, 7, 5, 3, 1, 0, 2,
  125934. 4, 6, 8, 10, 12,
  125935. };
  125936. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  125937. _vq_quantthresh__8c0_s_p8_0,
  125938. _vq_quantmap__8c0_s_p8_0,
  125939. 13,
  125940. 13
  125941. };
  125942. static static_codebook _8c0_s_p8_0 = {
  125943. 2, 169,
  125944. _vq_lengthlist__8c0_s_p8_0,
  125945. 1, -526516224, 1616117760, 4, 0,
  125946. _vq_quantlist__8c0_s_p8_0,
  125947. NULL,
  125948. &_vq_auxt__8c0_s_p8_0,
  125949. NULL,
  125950. 0
  125951. };
  125952. static long _vq_quantlist__8c0_s_p8_1[] = {
  125953. 2,
  125954. 1,
  125955. 3,
  125956. 0,
  125957. 4,
  125958. };
  125959. static long _vq_lengthlist__8c0_s_p8_1[] = {
  125960. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  125961. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  125962. };
  125963. static float _vq_quantthresh__8c0_s_p8_1[] = {
  125964. -1.5, -0.5, 0.5, 1.5,
  125965. };
  125966. static long _vq_quantmap__8c0_s_p8_1[] = {
  125967. 3, 1, 0, 2, 4,
  125968. };
  125969. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  125970. _vq_quantthresh__8c0_s_p8_1,
  125971. _vq_quantmap__8c0_s_p8_1,
  125972. 5,
  125973. 5
  125974. };
  125975. static static_codebook _8c0_s_p8_1 = {
  125976. 2, 25,
  125977. _vq_lengthlist__8c0_s_p8_1,
  125978. 1, -533725184, 1611661312, 3, 0,
  125979. _vq_quantlist__8c0_s_p8_1,
  125980. NULL,
  125981. &_vq_auxt__8c0_s_p8_1,
  125982. NULL,
  125983. 0
  125984. };
  125985. static long _vq_quantlist__8c0_s_p9_0[] = {
  125986. 1,
  125987. 0,
  125988. 2,
  125989. };
  125990. static long _vq_lengthlist__8c0_s_p9_0[] = {
  125991. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125992. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125993. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125994. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125995. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125996. 7,
  125997. };
  125998. static float _vq_quantthresh__8c0_s_p9_0[] = {
  125999. -157.5, 157.5,
  126000. };
  126001. static long _vq_quantmap__8c0_s_p9_0[] = {
  126002. 1, 0, 2,
  126003. };
  126004. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126005. _vq_quantthresh__8c0_s_p9_0,
  126006. _vq_quantmap__8c0_s_p9_0,
  126007. 3,
  126008. 3
  126009. };
  126010. static static_codebook _8c0_s_p9_0 = {
  126011. 4, 81,
  126012. _vq_lengthlist__8c0_s_p9_0,
  126013. 1, -518803456, 1628680192, 2, 0,
  126014. _vq_quantlist__8c0_s_p9_0,
  126015. NULL,
  126016. &_vq_auxt__8c0_s_p9_0,
  126017. NULL,
  126018. 0
  126019. };
  126020. static long _vq_quantlist__8c0_s_p9_1[] = {
  126021. 7,
  126022. 6,
  126023. 8,
  126024. 5,
  126025. 9,
  126026. 4,
  126027. 10,
  126028. 3,
  126029. 11,
  126030. 2,
  126031. 12,
  126032. 1,
  126033. 13,
  126034. 0,
  126035. 14,
  126036. };
  126037. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126038. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126039. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126040. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126041. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126042. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126043. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126052. 11,
  126053. };
  126054. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126055. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126056. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126057. };
  126058. static long _vq_quantmap__8c0_s_p9_1[] = {
  126059. 13, 11, 9, 7, 5, 3, 1, 0,
  126060. 2, 4, 6, 8, 10, 12, 14,
  126061. };
  126062. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126063. _vq_quantthresh__8c0_s_p9_1,
  126064. _vq_quantmap__8c0_s_p9_1,
  126065. 15,
  126066. 15
  126067. };
  126068. static static_codebook _8c0_s_p9_1 = {
  126069. 2, 225,
  126070. _vq_lengthlist__8c0_s_p9_1,
  126071. 1, -520986624, 1620377600, 4, 0,
  126072. _vq_quantlist__8c0_s_p9_1,
  126073. NULL,
  126074. &_vq_auxt__8c0_s_p9_1,
  126075. NULL,
  126076. 0
  126077. };
  126078. static long _vq_quantlist__8c0_s_p9_2[] = {
  126079. 10,
  126080. 9,
  126081. 11,
  126082. 8,
  126083. 12,
  126084. 7,
  126085. 13,
  126086. 6,
  126087. 14,
  126088. 5,
  126089. 15,
  126090. 4,
  126091. 16,
  126092. 3,
  126093. 17,
  126094. 2,
  126095. 18,
  126096. 1,
  126097. 19,
  126098. 0,
  126099. 20,
  126100. };
  126101. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126102. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126103. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126104. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126105. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126106. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126107. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126108. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126109. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126110. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126111. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126112. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126113. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126114. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126115. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126116. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126117. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126118. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126119. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126120. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126121. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126122. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126123. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126124. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126125. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126126. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126127. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126128. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126129. 10,11, 9,11,10, 9,10, 9,10,
  126130. };
  126131. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126132. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126133. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126134. 6.5, 7.5, 8.5, 9.5,
  126135. };
  126136. static long _vq_quantmap__8c0_s_p9_2[] = {
  126137. 19, 17, 15, 13, 11, 9, 7, 5,
  126138. 3, 1, 0, 2, 4, 6, 8, 10,
  126139. 12, 14, 16, 18, 20,
  126140. };
  126141. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126142. _vq_quantthresh__8c0_s_p9_2,
  126143. _vq_quantmap__8c0_s_p9_2,
  126144. 21,
  126145. 21
  126146. };
  126147. static static_codebook _8c0_s_p9_2 = {
  126148. 2, 441,
  126149. _vq_lengthlist__8c0_s_p9_2,
  126150. 1, -529268736, 1611661312, 5, 0,
  126151. _vq_quantlist__8c0_s_p9_2,
  126152. NULL,
  126153. &_vq_auxt__8c0_s_p9_2,
  126154. NULL,
  126155. 0
  126156. };
  126157. static long _huff_lengthlist__8c0_s_single[] = {
  126158. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126159. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126160. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126161. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126162. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126163. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126164. 17,16,17,17,
  126165. };
  126166. static static_codebook _huff_book__8c0_s_single = {
  126167. 2, 100,
  126168. _huff_lengthlist__8c0_s_single,
  126169. 0, 0, 0, 0, 0,
  126170. NULL,
  126171. NULL,
  126172. NULL,
  126173. NULL,
  126174. 0
  126175. };
  126176. static long _vq_quantlist__8c1_s_p1_0[] = {
  126177. 1,
  126178. 0,
  126179. 2,
  126180. };
  126181. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126182. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126183. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126188. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126193. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  126228. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126233. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126238. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126274. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126279. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126284. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0,
  126593. };
  126594. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126595. -0.5, 0.5,
  126596. };
  126597. static long _vq_quantmap__8c1_s_p1_0[] = {
  126598. 1, 0, 2,
  126599. };
  126600. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126601. _vq_quantthresh__8c1_s_p1_0,
  126602. _vq_quantmap__8c1_s_p1_0,
  126603. 3,
  126604. 3
  126605. };
  126606. static static_codebook _8c1_s_p1_0 = {
  126607. 8, 6561,
  126608. _vq_lengthlist__8c1_s_p1_0,
  126609. 1, -535822336, 1611661312, 2, 0,
  126610. _vq_quantlist__8c1_s_p1_0,
  126611. NULL,
  126612. &_vq_auxt__8c1_s_p1_0,
  126613. NULL,
  126614. 0
  126615. };
  126616. static long _vq_quantlist__8c1_s_p2_0[] = {
  126617. 2,
  126618. 1,
  126619. 3,
  126620. 0,
  126621. 4,
  126622. };
  126623. static long _vq_lengthlist__8c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0,
  126664. };
  126665. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126666. -1.5, -0.5, 0.5, 1.5,
  126667. };
  126668. static long _vq_quantmap__8c1_s_p2_0[] = {
  126669. 3, 1, 0, 2, 4,
  126670. };
  126671. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126672. _vq_quantthresh__8c1_s_p2_0,
  126673. _vq_quantmap__8c1_s_p2_0,
  126674. 5,
  126675. 5
  126676. };
  126677. static static_codebook _8c1_s_p2_0 = {
  126678. 4, 625,
  126679. _vq_lengthlist__8c1_s_p2_0,
  126680. 1, -533725184, 1611661312, 3, 0,
  126681. _vq_quantlist__8c1_s_p2_0,
  126682. NULL,
  126683. &_vq_auxt__8c1_s_p2_0,
  126684. NULL,
  126685. 0
  126686. };
  126687. static long _vq_quantlist__8c1_s_p3_0[] = {
  126688. 2,
  126689. 1,
  126690. 3,
  126691. 0,
  126692. 4,
  126693. };
  126694. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126695. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0,
  126735. };
  126736. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126737. -1.5, -0.5, 0.5, 1.5,
  126738. };
  126739. static long _vq_quantmap__8c1_s_p3_0[] = {
  126740. 3, 1, 0, 2, 4,
  126741. };
  126742. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126743. _vq_quantthresh__8c1_s_p3_0,
  126744. _vq_quantmap__8c1_s_p3_0,
  126745. 5,
  126746. 5
  126747. };
  126748. static static_codebook _8c1_s_p3_0 = {
  126749. 4, 625,
  126750. _vq_lengthlist__8c1_s_p3_0,
  126751. 1, -533725184, 1611661312, 3, 0,
  126752. _vq_quantlist__8c1_s_p3_0,
  126753. NULL,
  126754. &_vq_auxt__8c1_s_p3_0,
  126755. NULL,
  126756. 0
  126757. };
  126758. static long _vq_quantlist__8c1_s_p4_0[] = {
  126759. 4,
  126760. 3,
  126761. 5,
  126762. 2,
  126763. 6,
  126764. 1,
  126765. 7,
  126766. 0,
  126767. 8,
  126768. };
  126769. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126770. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126771. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126772. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126773. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126774. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0,
  126776. };
  126777. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126778. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126779. };
  126780. static long _vq_quantmap__8c1_s_p4_0[] = {
  126781. 7, 5, 3, 1, 0, 2, 4, 6,
  126782. 8,
  126783. };
  126784. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126785. _vq_quantthresh__8c1_s_p4_0,
  126786. _vq_quantmap__8c1_s_p4_0,
  126787. 9,
  126788. 9
  126789. };
  126790. static static_codebook _8c1_s_p4_0 = {
  126791. 2, 81,
  126792. _vq_lengthlist__8c1_s_p4_0,
  126793. 1, -531628032, 1611661312, 4, 0,
  126794. _vq_quantlist__8c1_s_p4_0,
  126795. NULL,
  126796. &_vq_auxt__8c1_s_p4_0,
  126797. NULL,
  126798. 0
  126799. };
  126800. static long _vq_quantlist__8c1_s_p5_0[] = {
  126801. 4,
  126802. 3,
  126803. 5,
  126804. 2,
  126805. 6,
  126806. 1,
  126807. 7,
  126808. 0,
  126809. 8,
  126810. };
  126811. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126812. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126813. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  126814. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  126815. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  126816. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126817. 10,
  126818. };
  126819. static float _vq_quantthresh__8c1_s_p5_0[] = {
  126820. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126821. };
  126822. static long _vq_quantmap__8c1_s_p5_0[] = {
  126823. 7, 5, 3, 1, 0, 2, 4, 6,
  126824. 8,
  126825. };
  126826. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  126827. _vq_quantthresh__8c1_s_p5_0,
  126828. _vq_quantmap__8c1_s_p5_0,
  126829. 9,
  126830. 9
  126831. };
  126832. static static_codebook _8c1_s_p5_0 = {
  126833. 2, 81,
  126834. _vq_lengthlist__8c1_s_p5_0,
  126835. 1, -531628032, 1611661312, 4, 0,
  126836. _vq_quantlist__8c1_s_p5_0,
  126837. NULL,
  126838. &_vq_auxt__8c1_s_p5_0,
  126839. NULL,
  126840. 0
  126841. };
  126842. static long _vq_quantlist__8c1_s_p6_0[] = {
  126843. 8,
  126844. 7,
  126845. 9,
  126846. 6,
  126847. 10,
  126848. 5,
  126849. 11,
  126850. 4,
  126851. 12,
  126852. 3,
  126853. 13,
  126854. 2,
  126855. 14,
  126856. 1,
  126857. 15,
  126858. 0,
  126859. 16,
  126860. };
  126861. static long _vq_lengthlist__8c1_s_p6_0[] = {
  126862. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  126863. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126864. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126865. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  126866. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  126867. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  126868. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  126869. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  126870. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  126871. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126872. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  126873. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  126874. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  126875. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  126876. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  126877. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  126878. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  126880. 14,
  126881. };
  126882. static float _vq_quantthresh__8c1_s_p6_0[] = {
  126883. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126884. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126885. };
  126886. static long _vq_quantmap__8c1_s_p6_0[] = {
  126887. 15, 13, 11, 9, 7, 5, 3, 1,
  126888. 0, 2, 4, 6, 8, 10, 12, 14,
  126889. 16,
  126890. };
  126891. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  126892. _vq_quantthresh__8c1_s_p6_0,
  126893. _vq_quantmap__8c1_s_p6_0,
  126894. 17,
  126895. 17
  126896. };
  126897. static static_codebook _8c1_s_p6_0 = {
  126898. 2, 289,
  126899. _vq_lengthlist__8c1_s_p6_0,
  126900. 1, -529530880, 1611661312, 5, 0,
  126901. _vq_quantlist__8c1_s_p6_0,
  126902. NULL,
  126903. &_vq_auxt__8c1_s_p6_0,
  126904. NULL,
  126905. 0
  126906. };
  126907. static long _vq_quantlist__8c1_s_p7_0[] = {
  126908. 1,
  126909. 0,
  126910. 2,
  126911. };
  126912. static long _vq_lengthlist__8c1_s_p7_0[] = {
  126913. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  126914. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  126915. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  126916. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  126917. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  126918. 9,
  126919. };
  126920. static float _vq_quantthresh__8c1_s_p7_0[] = {
  126921. -5.5, 5.5,
  126922. };
  126923. static long _vq_quantmap__8c1_s_p7_0[] = {
  126924. 1, 0, 2,
  126925. };
  126926. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  126927. _vq_quantthresh__8c1_s_p7_0,
  126928. _vq_quantmap__8c1_s_p7_0,
  126929. 3,
  126930. 3
  126931. };
  126932. static static_codebook _8c1_s_p7_0 = {
  126933. 4, 81,
  126934. _vq_lengthlist__8c1_s_p7_0,
  126935. 1, -529137664, 1618345984, 2, 0,
  126936. _vq_quantlist__8c1_s_p7_0,
  126937. NULL,
  126938. &_vq_auxt__8c1_s_p7_0,
  126939. NULL,
  126940. 0
  126941. };
  126942. static long _vq_quantlist__8c1_s_p7_1[] = {
  126943. 5,
  126944. 4,
  126945. 6,
  126946. 3,
  126947. 7,
  126948. 2,
  126949. 8,
  126950. 1,
  126951. 9,
  126952. 0,
  126953. 10,
  126954. };
  126955. static long _vq_lengthlist__8c1_s_p7_1[] = {
  126956. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  126957. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  126958. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  126959. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126960. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126961. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126962. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  126963. 10,10,10, 8, 8, 8, 8, 8, 8,
  126964. };
  126965. static float _vq_quantthresh__8c1_s_p7_1[] = {
  126966. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126967. 3.5, 4.5,
  126968. };
  126969. static long _vq_quantmap__8c1_s_p7_1[] = {
  126970. 9, 7, 5, 3, 1, 0, 2, 4,
  126971. 6, 8, 10,
  126972. };
  126973. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  126974. _vq_quantthresh__8c1_s_p7_1,
  126975. _vq_quantmap__8c1_s_p7_1,
  126976. 11,
  126977. 11
  126978. };
  126979. static static_codebook _8c1_s_p7_1 = {
  126980. 2, 121,
  126981. _vq_lengthlist__8c1_s_p7_1,
  126982. 1, -531365888, 1611661312, 4, 0,
  126983. _vq_quantlist__8c1_s_p7_1,
  126984. NULL,
  126985. &_vq_auxt__8c1_s_p7_1,
  126986. NULL,
  126987. 0
  126988. };
  126989. static long _vq_quantlist__8c1_s_p8_0[] = {
  126990. 6,
  126991. 5,
  126992. 7,
  126993. 4,
  126994. 8,
  126995. 3,
  126996. 9,
  126997. 2,
  126998. 10,
  126999. 1,
  127000. 11,
  127001. 0,
  127002. 12,
  127003. };
  127004. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127005. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127006. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127007. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127008. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127009. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127010. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127011. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127012. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127013. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127014. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127015. 0,12,12,11,10,12,11,13,12,
  127016. };
  127017. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127018. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127019. 12.5, 17.5, 22.5, 27.5,
  127020. };
  127021. static long _vq_quantmap__8c1_s_p8_0[] = {
  127022. 11, 9, 7, 5, 3, 1, 0, 2,
  127023. 4, 6, 8, 10, 12,
  127024. };
  127025. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127026. _vq_quantthresh__8c1_s_p8_0,
  127027. _vq_quantmap__8c1_s_p8_0,
  127028. 13,
  127029. 13
  127030. };
  127031. static static_codebook _8c1_s_p8_0 = {
  127032. 2, 169,
  127033. _vq_lengthlist__8c1_s_p8_0,
  127034. 1, -526516224, 1616117760, 4, 0,
  127035. _vq_quantlist__8c1_s_p8_0,
  127036. NULL,
  127037. &_vq_auxt__8c1_s_p8_0,
  127038. NULL,
  127039. 0
  127040. };
  127041. static long _vq_quantlist__8c1_s_p8_1[] = {
  127042. 2,
  127043. 1,
  127044. 3,
  127045. 0,
  127046. 4,
  127047. };
  127048. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127049. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127050. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127051. };
  127052. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127053. -1.5, -0.5, 0.5, 1.5,
  127054. };
  127055. static long _vq_quantmap__8c1_s_p8_1[] = {
  127056. 3, 1, 0, 2, 4,
  127057. };
  127058. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127059. _vq_quantthresh__8c1_s_p8_1,
  127060. _vq_quantmap__8c1_s_p8_1,
  127061. 5,
  127062. 5
  127063. };
  127064. static static_codebook _8c1_s_p8_1 = {
  127065. 2, 25,
  127066. _vq_lengthlist__8c1_s_p8_1,
  127067. 1, -533725184, 1611661312, 3, 0,
  127068. _vq_quantlist__8c1_s_p8_1,
  127069. NULL,
  127070. &_vq_auxt__8c1_s_p8_1,
  127071. NULL,
  127072. 0
  127073. };
  127074. static long _vq_quantlist__8c1_s_p9_0[] = {
  127075. 6,
  127076. 5,
  127077. 7,
  127078. 4,
  127079. 8,
  127080. 3,
  127081. 9,
  127082. 2,
  127083. 10,
  127084. 1,
  127085. 11,
  127086. 0,
  127087. 12,
  127088. };
  127089. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127090. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127091. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127092. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127093. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127094. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127095. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127096. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127097. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127098. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127099. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127100. 10,10,10,10,10, 9, 9, 9, 9,
  127101. };
  127102. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127103. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127104. 787.5, 1102.5, 1417.5, 1732.5,
  127105. };
  127106. static long _vq_quantmap__8c1_s_p9_0[] = {
  127107. 11, 9, 7, 5, 3, 1, 0, 2,
  127108. 4, 6, 8, 10, 12,
  127109. };
  127110. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127111. _vq_quantthresh__8c1_s_p9_0,
  127112. _vq_quantmap__8c1_s_p9_0,
  127113. 13,
  127114. 13
  127115. };
  127116. static static_codebook _8c1_s_p9_0 = {
  127117. 2, 169,
  127118. _vq_lengthlist__8c1_s_p9_0,
  127119. 1, -513964032, 1628680192, 4, 0,
  127120. _vq_quantlist__8c1_s_p9_0,
  127121. NULL,
  127122. &_vq_auxt__8c1_s_p9_0,
  127123. NULL,
  127124. 0
  127125. };
  127126. static long _vq_quantlist__8c1_s_p9_1[] = {
  127127. 7,
  127128. 6,
  127129. 8,
  127130. 5,
  127131. 9,
  127132. 4,
  127133. 10,
  127134. 3,
  127135. 11,
  127136. 2,
  127137. 12,
  127138. 1,
  127139. 13,
  127140. 0,
  127141. 14,
  127142. };
  127143. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127144. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127145. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127146. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127147. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127148. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127149. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127150. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127151. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127152. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127153. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127154. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127155. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127156. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127157. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127158. 15,
  127159. };
  127160. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127161. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127162. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127163. };
  127164. static long _vq_quantmap__8c1_s_p9_1[] = {
  127165. 13, 11, 9, 7, 5, 3, 1, 0,
  127166. 2, 4, 6, 8, 10, 12, 14,
  127167. };
  127168. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127169. _vq_quantthresh__8c1_s_p9_1,
  127170. _vq_quantmap__8c1_s_p9_1,
  127171. 15,
  127172. 15
  127173. };
  127174. static static_codebook _8c1_s_p9_1 = {
  127175. 2, 225,
  127176. _vq_lengthlist__8c1_s_p9_1,
  127177. 1, -520986624, 1620377600, 4, 0,
  127178. _vq_quantlist__8c1_s_p9_1,
  127179. NULL,
  127180. &_vq_auxt__8c1_s_p9_1,
  127181. NULL,
  127182. 0
  127183. };
  127184. static long _vq_quantlist__8c1_s_p9_2[] = {
  127185. 10,
  127186. 9,
  127187. 11,
  127188. 8,
  127189. 12,
  127190. 7,
  127191. 13,
  127192. 6,
  127193. 14,
  127194. 5,
  127195. 15,
  127196. 4,
  127197. 16,
  127198. 3,
  127199. 17,
  127200. 2,
  127201. 18,
  127202. 1,
  127203. 19,
  127204. 0,
  127205. 20,
  127206. };
  127207. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127208. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127209. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127210. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127211. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127212. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127213. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127214. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127215. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127216. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127217. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127218. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127219. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127220. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127221. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127222. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127223. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127224. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127225. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127226. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127227. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127228. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127229. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127230. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127231. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127232. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127233. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127234. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127235. 10,10,10,10,10,10,10,10,10,
  127236. };
  127237. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127238. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127239. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127240. 6.5, 7.5, 8.5, 9.5,
  127241. };
  127242. static long _vq_quantmap__8c1_s_p9_2[] = {
  127243. 19, 17, 15, 13, 11, 9, 7, 5,
  127244. 3, 1, 0, 2, 4, 6, 8, 10,
  127245. 12, 14, 16, 18, 20,
  127246. };
  127247. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127248. _vq_quantthresh__8c1_s_p9_2,
  127249. _vq_quantmap__8c1_s_p9_2,
  127250. 21,
  127251. 21
  127252. };
  127253. static static_codebook _8c1_s_p9_2 = {
  127254. 2, 441,
  127255. _vq_lengthlist__8c1_s_p9_2,
  127256. 1, -529268736, 1611661312, 5, 0,
  127257. _vq_quantlist__8c1_s_p9_2,
  127258. NULL,
  127259. &_vq_auxt__8c1_s_p9_2,
  127260. NULL,
  127261. 0
  127262. };
  127263. static long _huff_lengthlist__8c1_s_single[] = {
  127264. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127265. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127266. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127267. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127268. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127269. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127270. 9, 7, 7, 8,
  127271. };
  127272. static static_codebook _huff_book__8c1_s_single = {
  127273. 2, 100,
  127274. _huff_lengthlist__8c1_s_single,
  127275. 0, 0, 0, 0, 0,
  127276. NULL,
  127277. NULL,
  127278. NULL,
  127279. NULL,
  127280. 0
  127281. };
  127282. static long _huff_lengthlist__44c2_s_long[] = {
  127283. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127284. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127285. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127286. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127287. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127288. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127289. 10, 8, 8, 9,
  127290. };
  127291. static static_codebook _huff_book__44c2_s_long = {
  127292. 2, 100,
  127293. _huff_lengthlist__44c2_s_long,
  127294. 0, 0, 0, 0, 0,
  127295. NULL,
  127296. NULL,
  127297. NULL,
  127298. NULL,
  127299. 0
  127300. };
  127301. static long _vq_quantlist__44c2_s_p1_0[] = {
  127302. 1,
  127303. 0,
  127304. 2,
  127305. };
  127306. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127307. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127308. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127313. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127318. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  127353. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  127358. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  127363. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127399. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127404. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127409. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0,
  127718. };
  127719. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127720. -0.5, 0.5,
  127721. };
  127722. static long _vq_quantmap__44c2_s_p1_0[] = {
  127723. 1, 0, 2,
  127724. };
  127725. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127726. _vq_quantthresh__44c2_s_p1_0,
  127727. _vq_quantmap__44c2_s_p1_0,
  127728. 3,
  127729. 3
  127730. };
  127731. static static_codebook _44c2_s_p1_0 = {
  127732. 8, 6561,
  127733. _vq_lengthlist__44c2_s_p1_0,
  127734. 1, -535822336, 1611661312, 2, 0,
  127735. _vq_quantlist__44c2_s_p1_0,
  127736. NULL,
  127737. &_vq_auxt__44c2_s_p1_0,
  127738. NULL,
  127739. 0
  127740. };
  127741. static long _vq_quantlist__44c2_s_p2_0[] = {
  127742. 2,
  127743. 1,
  127744. 3,
  127745. 0,
  127746. 4,
  127747. };
  127748. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127749. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127750. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127751. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127752. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127753. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127759. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127760. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127761. 12, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127766. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127767. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127768. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  127769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127774. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127775. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127776. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  127777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127788. 0,
  127789. };
  127790. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127791. -1.5, -0.5, 0.5, 1.5,
  127792. };
  127793. static long _vq_quantmap__44c2_s_p2_0[] = {
  127794. 3, 1, 0, 2, 4,
  127795. };
  127796. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127797. _vq_quantthresh__44c2_s_p2_0,
  127798. _vq_quantmap__44c2_s_p2_0,
  127799. 5,
  127800. 5
  127801. };
  127802. static static_codebook _44c2_s_p2_0 = {
  127803. 4, 625,
  127804. _vq_lengthlist__44c2_s_p2_0,
  127805. 1, -533725184, 1611661312, 3, 0,
  127806. _vq_quantlist__44c2_s_p2_0,
  127807. NULL,
  127808. &_vq_auxt__44c2_s_p2_0,
  127809. NULL,
  127810. 0
  127811. };
  127812. static long _vq_quantlist__44c2_s_p3_0[] = {
  127813. 2,
  127814. 1,
  127815. 3,
  127816. 0,
  127817. 4,
  127818. };
  127819. static long _vq_lengthlist__44c2_s_p3_0[] = {
  127820. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0,
  127860. };
  127861. static float _vq_quantthresh__44c2_s_p3_0[] = {
  127862. -1.5, -0.5, 0.5, 1.5,
  127863. };
  127864. static long _vq_quantmap__44c2_s_p3_0[] = {
  127865. 3, 1, 0, 2, 4,
  127866. };
  127867. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  127868. _vq_quantthresh__44c2_s_p3_0,
  127869. _vq_quantmap__44c2_s_p3_0,
  127870. 5,
  127871. 5
  127872. };
  127873. static static_codebook _44c2_s_p3_0 = {
  127874. 4, 625,
  127875. _vq_lengthlist__44c2_s_p3_0,
  127876. 1, -533725184, 1611661312, 3, 0,
  127877. _vq_quantlist__44c2_s_p3_0,
  127878. NULL,
  127879. &_vq_auxt__44c2_s_p3_0,
  127880. NULL,
  127881. 0
  127882. };
  127883. static long _vq_quantlist__44c2_s_p4_0[] = {
  127884. 4,
  127885. 3,
  127886. 5,
  127887. 2,
  127888. 6,
  127889. 1,
  127890. 7,
  127891. 0,
  127892. 8,
  127893. };
  127894. static long _vq_lengthlist__44c2_s_p4_0[] = {
  127895. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  127896. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  127897. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  127898. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  127899. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0,
  127901. };
  127902. static float _vq_quantthresh__44c2_s_p4_0[] = {
  127903. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127904. };
  127905. static long _vq_quantmap__44c2_s_p4_0[] = {
  127906. 7, 5, 3, 1, 0, 2, 4, 6,
  127907. 8,
  127908. };
  127909. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  127910. _vq_quantthresh__44c2_s_p4_0,
  127911. _vq_quantmap__44c2_s_p4_0,
  127912. 9,
  127913. 9
  127914. };
  127915. static static_codebook _44c2_s_p4_0 = {
  127916. 2, 81,
  127917. _vq_lengthlist__44c2_s_p4_0,
  127918. 1, -531628032, 1611661312, 4, 0,
  127919. _vq_quantlist__44c2_s_p4_0,
  127920. NULL,
  127921. &_vq_auxt__44c2_s_p4_0,
  127922. NULL,
  127923. 0
  127924. };
  127925. static long _vq_quantlist__44c2_s_p5_0[] = {
  127926. 4,
  127927. 3,
  127928. 5,
  127929. 2,
  127930. 6,
  127931. 1,
  127932. 7,
  127933. 0,
  127934. 8,
  127935. };
  127936. static long _vq_lengthlist__44c2_s_p5_0[] = {
  127937. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  127938. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  127939. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  127940. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  127941. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  127942. 11,
  127943. };
  127944. static float _vq_quantthresh__44c2_s_p5_0[] = {
  127945. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127946. };
  127947. static long _vq_quantmap__44c2_s_p5_0[] = {
  127948. 7, 5, 3, 1, 0, 2, 4, 6,
  127949. 8,
  127950. };
  127951. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  127952. _vq_quantthresh__44c2_s_p5_0,
  127953. _vq_quantmap__44c2_s_p5_0,
  127954. 9,
  127955. 9
  127956. };
  127957. static static_codebook _44c2_s_p5_0 = {
  127958. 2, 81,
  127959. _vq_lengthlist__44c2_s_p5_0,
  127960. 1, -531628032, 1611661312, 4, 0,
  127961. _vq_quantlist__44c2_s_p5_0,
  127962. NULL,
  127963. &_vq_auxt__44c2_s_p5_0,
  127964. NULL,
  127965. 0
  127966. };
  127967. static long _vq_quantlist__44c2_s_p6_0[] = {
  127968. 8,
  127969. 7,
  127970. 9,
  127971. 6,
  127972. 10,
  127973. 5,
  127974. 11,
  127975. 4,
  127976. 12,
  127977. 3,
  127978. 13,
  127979. 2,
  127980. 14,
  127981. 1,
  127982. 15,
  127983. 0,
  127984. 16,
  127985. };
  127986. static long _vq_lengthlist__44c2_s_p6_0[] = {
  127987. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  127988. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127989. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  127990. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  127991. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  127992. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  127993. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  127994. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127995. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127996. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127997. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127998. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  127999. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128000. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128001. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128002. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128003. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128005. 14,
  128006. };
  128007. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128008. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128009. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128010. };
  128011. static long _vq_quantmap__44c2_s_p6_0[] = {
  128012. 15, 13, 11, 9, 7, 5, 3, 1,
  128013. 0, 2, 4, 6, 8, 10, 12, 14,
  128014. 16,
  128015. };
  128016. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128017. _vq_quantthresh__44c2_s_p6_0,
  128018. _vq_quantmap__44c2_s_p6_0,
  128019. 17,
  128020. 17
  128021. };
  128022. static static_codebook _44c2_s_p6_0 = {
  128023. 2, 289,
  128024. _vq_lengthlist__44c2_s_p6_0,
  128025. 1, -529530880, 1611661312, 5, 0,
  128026. _vq_quantlist__44c2_s_p6_0,
  128027. NULL,
  128028. &_vq_auxt__44c2_s_p6_0,
  128029. NULL,
  128030. 0
  128031. };
  128032. static long _vq_quantlist__44c2_s_p7_0[] = {
  128033. 1,
  128034. 0,
  128035. 2,
  128036. };
  128037. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128038. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128039. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128040. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128041. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128042. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128043. 11,
  128044. };
  128045. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128046. -5.5, 5.5,
  128047. };
  128048. static long _vq_quantmap__44c2_s_p7_0[] = {
  128049. 1, 0, 2,
  128050. };
  128051. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128052. _vq_quantthresh__44c2_s_p7_0,
  128053. _vq_quantmap__44c2_s_p7_0,
  128054. 3,
  128055. 3
  128056. };
  128057. static static_codebook _44c2_s_p7_0 = {
  128058. 4, 81,
  128059. _vq_lengthlist__44c2_s_p7_0,
  128060. 1, -529137664, 1618345984, 2, 0,
  128061. _vq_quantlist__44c2_s_p7_0,
  128062. NULL,
  128063. &_vq_auxt__44c2_s_p7_0,
  128064. NULL,
  128065. 0
  128066. };
  128067. static long _vq_quantlist__44c2_s_p7_1[] = {
  128068. 5,
  128069. 4,
  128070. 6,
  128071. 3,
  128072. 7,
  128073. 2,
  128074. 8,
  128075. 1,
  128076. 9,
  128077. 0,
  128078. 10,
  128079. };
  128080. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128081. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128082. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128083. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128084. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128085. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128086. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128087. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128088. 10,10,10, 8, 8, 8, 8, 8, 8,
  128089. };
  128090. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128091. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128092. 3.5, 4.5,
  128093. };
  128094. static long _vq_quantmap__44c2_s_p7_1[] = {
  128095. 9, 7, 5, 3, 1, 0, 2, 4,
  128096. 6, 8, 10,
  128097. };
  128098. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128099. _vq_quantthresh__44c2_s_p7_1,
  128100. _vq_quantmap__44c2_s_p7_1,
  128101. 11,
  128102. 11
  128103. };
  128104. static static_codebook _44c2_s_p7_1 = {
  128105. 2, 121,
  128106. _vq_lengthlist__44c2_s_p7_1,
  128107. 1, -531365888, 1611661312, 4, 0,
  128108. _vq_quantlist__44c2_s_p7_1,
  128109. NULL,
  128110. &_vq_auxt__44c2_s_p7_1,
  128111. NULL,
  128112. 0
  128113. };
  128114. static long _vq_quantlist__44c2_s_p8_0[] = {
  128115. 6,
  128116. 5,
  128117. 7,
  128118. 4,
  128119. 8,
  128120. 3,
  128121. 9,
  128122. 2,
  128123. 10,
  128124. 1,
  128125. 11,
  128126. 0,
  128127. 12,
  128128. };
  128129. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128130. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128131. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128132. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128133. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128134. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128135. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128136. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128137. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128138. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128139. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128140. 0,12,12,12,12,13,12,14,14,
  128141. };
  128142. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128143. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128144. 12.5, 17.5, 22.5, 27.5,
  128145. };
  128146. static long _vq_quantmap__44c2_s_p8_0[] = {
  128147. 11, 9, 7, 5, 3, 1, 0, 2,
  128148. 4, 6, 8, 10, 12,
  128149. };
  128150. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128151. _vq_quantthresh__44c2_s_p8_0,
  128152. _vq_quantmap__44c2_s_p8_0,
  128153. 13,
  128154. 13
  128155. };
  128156. static static_codebook _44c2_s_p8_0 = {
  128157. 2, 169,
  128158. _vq_lengthlist__44c2_s_p8_0,
  128159. 1, -526516224, 1616117760, 4, 0,
  128160. _vq_quantlist__44c2_s_p8_0,
  128161. NULL,
  128162. &_vq_auxt__44c2_s_p8_0,
  128163. NULL,
  128164. 0
  128165. };
  128166. static long _vq_quantlist__44c2_s_p8_1[] = {
  128167. 2,
  128168. 1,
  128169. 3,
  128170. 0,
  128171. 4,
  128172. };
  128173. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128174. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128175. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128176. };
  128177. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128178. -1.5, -0.5, 0.5, 1.5,
  128179. };
  128180. static long _vq_quantmap__44c2_s_p8_1[] = {
  128181. 3, 1, 0, 2, 4,
  128182. };
  128183. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128184. _vq_quantthresh__44c2_s_p8_1,
  128185. _vq_quantmap__44c2_s_p8_1,
  128186. 5,
  128187. 5
  128188. };
  128189. static static_codebook _44c2_s_p8_1 = {
  128190. 2, 25,
  128191. _vq_lengthlist__44c2_s_p8_1,
  128192. 1, -533725184, 1611661312, 3, 0,
  128193. _vq_quantlist__44c2_s_p8_1,
  128194. NULL,
  128195. &_vq_auxt__44c2_s_p8_1,
  128196. NULL,
  128197. 0
  128198. };
  128199. static long _vq_quantlist__44c2_s_p9_0[] = {
  128200. 6,
  128201. 5,
  128202. 7,
  128203. 4,
  128204. 8,
  128205. 3,
  128206. 9,
  128207. 2,
  128208. 10,
  128209. 1,
  128210. 11,
  128211. 0,
  128212. 12,
  128213. };
  128214. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128215. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128216. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128217. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128218. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128219. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128221. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128222. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128223. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128224. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128225. 11,11,11,11,11,11,11,11,11,
  128226. };
  128227. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128228. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128229. 552.5, 773.5, 994.5, 1215.5,
  128230. };
  128231. static long _vq_quantmap__44c2_s_p9_0[] = {
  128232. 11, 9, 7, 5, 3, 1, 0, 2,
  128233. 4, 6, 8, 10, 12,
  128234. };
  128235. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128236. _vq_quantthresh__44c2_s_p9_0,
  128237. _vq_quantmap__44c2_s_p9_0,
  128238. 13,
  128239. 13
  128240. };
  128241. static static_codebook _44c2_s_p9_0 = {
  128242. 2, 169,
  128243. _vq_lengthlist__44c2_s_p9_0,
  128244. 1, -514541568, 1627103232, 4, 0,
  128245. _vq_quantlist__44c2_s_p9_0,
  128246. NULL,
  128247. &_vq_auxt__44c2_s_p9_0,
  128248. NULL,
  128249. 0
  128250. };
  128251. static long _vq_quantlist__44c2_s_p9_1[] = {
  128252. 6,
  128253. 5,
  128254. 7,
  128255. 4,
  128256. 8,
  128257. 3,
  128258. 9,
  128259. 2,
  128260. 10,
  128261. 1,
  128262. 11,
  128263. 0,
  128264. 12,
  128265. };
  128266. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128267. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128268. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128269. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128270. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128271. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128272. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128273. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128274. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128275. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128276. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128277. 17,13,12,12,10,13,11,14,14,
  128278. };
  128279. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128280. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128281. 42.5, 59.5, 76.5, 93.5,
  128282. };
  128283. static long _vq_quantmap__44c2_s_p9_1[] = {
  128284. 11, 9, 7, 5, 3, 1, 0, 2,
  128285. 4, 6, 8, 10, 12,
  128286. };
  128287. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128288. _vq_quantthresh__44c2_s_p9_1,
  128289. _vq_quantmap__44c2_s_p9_1,
  128290. 13,
  128291. 13
  128292. };
  128293. static static_codebook _44c2_s_p9_1 = {
  128294. 2, 169,
  128295. _vq_lengthlist__44c2_s_p9_1,
  128296. 1, -522616832, 1620115456, 4, 0,
  128297. _vq_quantlist__44c2_s_p9_1,
  128298. NULL,
  128299. &_vq_auxt__44c2_s_p9_1,
  128300. NULL,
  128301. 0
  128302. };
  128303. static long _vq_quantlist__44c2_s_p9_2[] = {
  128304. 8,
  128305. 7,
  128306. 9,
  128307. 6,
  128308. 10,
  128309. 5,
  128310. 11,
  128311. 4,
  128312. 12,
  128313. 3,
  128314. 13,
  128315. 2,
  128316. 14,
  128317. 1,
  128318. 15,
  128319. 0,
  128320. 16,
  128321. };
  128322. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128323. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128324. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128325. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128326. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128327. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128328. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128329. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128330. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128331. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128332. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128333. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128334. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128335. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128336. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128337. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128338. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128339. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128340. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128341. 10,
  128342. };
  128343. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128344. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128345. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128346. };
  128347. static long _vq_quantmap__44c2_s_p9_2[] = {
  128348. 15, 13, 11, 9, 7, 5, 3, 1,
  128349. 0, 2, 4, 6, 8, 10, 12, 14,
  128350. 16,
  128351. };
  128352. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128353. _vq_quantthresh__44c2_s_p9_2,
  128354. _vq_quantmap__44c2_s_p9_2,
  128355. 17,
  128356. 17
  128357. };
  128358. static static_codebook _44c2_s_p9_2 = {
  128359. 2, 289,
  128360. _vq_lengthlist__44c2_s_p9_2,
  128361. 1, -529530880, 1611661312, 5, 0,
  128362. _vq_quantlist__44c2_s_p9_2,
  128363. NULL,
  128364. &_vq_auxt__44c2_s_p9_2,
  128365. NULL,
  128366. 0
  128367. };
  128368. static long _huff_lengthlist__44c2_s_short[] = {
  128369. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128370. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128371. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128372. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128373. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128374. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128375. 6, 8, 9,12,
  128376. };
  128377. static static_codebook _huff_book__44c2_s_short = {
  128378. 2, 100,
  128379. _huff_lengthlist__44c2_s_short,
  128380. 0, 0, 0, 0, 0,
  128381. NULL,
  128382. NULL,
  128383. NULL,
  128384. NULL,
  128385. 0
  128386. };
  128387. static long _huff_lengthlist__44c3_s_long[] = {
  128388. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128389. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128390. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128391. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128392. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128393. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128394. 9, 8, 8, 8,
  128395. };
  128396. static static_codebook _huff_book__44c3_s_long = {
  128397. 2, 100,
  128398. _huff_lengthlist__44c3_s_long,
  128399. 0, 0, 0, 0, 0,
  128400. NULL,
  128401. NULL,
  128402. NULL,
  128403. NULL,
  128404. 0
  128405. };
  128406. static long _vq_quantlist__44c3_s_p1_0[] = {
  128407. 1,
  128408. 0,
  128409. 2,
  128410. };
  128411. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128412. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128413. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128418. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128423. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  128458. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128463. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128468. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128504. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128509. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128514. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128822. 0,
  128823. };
  128824. static float _vq_quantthresh__44c3_s_p1_0[] = {
  128825. -0.5, 0.5,
  128826. };
  128827. static long _vq_quantmap__44c3_s_p1_0[] = {
  128828. 1, 0, 2,
  128829. };
  128830. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  128831. _vq_quantthresh__44c3_s_p1_0,
  128832. _vq_quantmap__44c3_s_p1_0,
  128833. 3,
  128834. 3
  128835. };
  128836. static static_codebook _44c3_s_p1_0 = {
  128837. 8, 6561,
  128838. _vq_lengthlist__44c3_s_p1_0,
  128839. 1, -535822336, 1611661312, 2, 0,
  128840. _vq_quantlist__44c3_s_p1_0,
  128841. NULL,
  128842. &_vq_auxt__44c3_s_p1_0,
  128843. NULL,
  128844. 0
  128845. };
  128846. static long _vq_quantlist__44c3_s_p2_0[] = {
  128847. 2,
  128848. 1,
  128849. 3,
  128850. 0,
  128851. 4,
  128852. };
  128853. static long _vq_lengthlist__44c3_s_p2_0[] = {
  128854. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128855. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  128856. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128857. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  128858. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  128864. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  128865. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  128866. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  128872. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  128873. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  128880. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  128881. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128893. 0,
  128894. };
  128895. static float _vq_quantthresh__44c3_s_p2_0[] = {
  128896. -1.5, -0.5, 0.5, 1.5,
  128897. };
  128898. static long _vq_quantmap__44c3_s_p2_0[] = {
  128899. 3, 1, 0, 2, 4,
  128900. };
  128901. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  128902. _vq_quantthresh__44c3_s_p2_0,
  128903. _vq_quantmap__44c3_s_p2_0,
  128904. 5,
  128905. 5
  128906. };
  128907. static static_codebook _44c3_s_p2_0 = {
  128908. 4, 625,
  128909. _vq_lengthlist__44c3_s_p2_0,
  128910. 1, -533725184, 1611661312, 3, 0,
  128911. _vq_quantlist__44c3_s_p2_0,
  128912. NULL,
  128913. &_vq_auxt__44c3_s_p2_0,
  128914. NULL,
  128915. 0
  128916. };
  128917. static long _vq_quantlist__44c3_s_p3_0[] = {
  128918. 2,
  128919. 1,
  128920. 3,
  128921. 0,
  128922. 4,
  128923. };
  128924. static long _vq_lengthlist__44c3_s_p3_0[] = {
  128925. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128928. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0,
  128965. };
  128966. static float _vq_quantthresh__44c3_s_p3_0[] = {
  128967. -1.5, -0.5, 0.5, 1.5,
  128968. };
  128969. static long _vq_quantmap__44c3_s_p3_0[] = {
  128970. 3, 1, 0, 2, 4,
  128971. };
  128972. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  128973. _vq_quantthresh__44c3_s_p3_0,
  128974. _vq_quantmap__44c3_s_p3_0,
  128975. 5,
  128976. 5
  128977. };
  128978. static static_codebook _44c3_s_p3_0 = {
  128979. 4, 625,
  128980. _vq_lengthlist__44c3_s_p3_0,
  128981. 1, -533725184, 1611661312, 3, 0,
  128982. _vq_quantlist__44c3_s_p3_0,
  128983. NULL,
  128984. &_vq_auxt__44c3_s_p3_0,
  128985. NULL,
  128986. 0
  128987. };
  128988. static long _vq_quantlist__44c3_s_p4_0[] = {
  128989. 4,
  128990. 3,
  128991. 5,
  128992. 2,
  128993. 6,
  128994. 1,
  128995. 7,
  128996. 0,
  128997. 8,
  128998. };
  128999. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129000. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129001. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129002. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129003. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129004. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0,
  129006. };
  129007. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129008. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129009. };
  129010. static long _vq_quantmap__44c3_s_p4_0[] = {
  129011. 7, 5, 3, 1, 0, 2, 4, 6,
  129012. 8,
  129013. };
  129014. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129015. _vq_quantthresh__44c3_s_p4_0,
  129016. _vq_quantmap__44c3_s_p4_0,
  129017. 9,
  129018. 9
  129019. };
  129020. static static_codebook _44c3_s_p4_0 = {
  129021. 2, 81,
  129022. _vq_lengthlist__44c3_s_p4_0,
  129023. 1, -531628032, 1611661312, 4, 0,
  129024. _vq_quantlist__44c3_s_p4_0,
  129025. NULL,
  129026. &_vq_auxt__44c3_s_p4_0,
  129027. NULL,
  129028. 0
  129029. };
  129030. static long _vq_quantlist__44c3_s_p5_0[] = {
  129031. 4,
  129032. 3,
  129033. 5,
  129034. 2,
  129035. 6,
  129036. 1,
  129037. 7,
  129038. 0,
  129039. 8,
  129040. };
  129041. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129042. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129043. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129044. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129045. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129046. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129047. 11,
  129048. };
  129049. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129050. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129051. };
  129052. static long _vq_quantmap__44c3_s_p5_0[] = {
  129053. 7, 5, 3, 1, 0, 2, 4, 6,
  129054. 8,
  129055. };
  129056. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129057. _vq_quantthresh__44c3_s_p5_0,
  129058. _vq_quantmap__44c3_s_p5_0,
  129059. 9,
  129060. 9
  129061. };
  129062. static static_codebook _44c3_s_p5_0 = {
  129063. 2, 81,
  129064. _vq_lengthlist__44c3_s_p5_0,
  129065. 1, -531628032, 1611661312, 4, 0,
  129066. _vq_quantlist__44c3_s_p5_0,
  129067. NULL,
  129068. &_vq_auxt__44c3_s_p5_0,
  129069. NULL,
  129070. 0
  129071. };
  129072. static long _vq_quantlist__44c3_s_p6_0[] = {
  129073. 8,
  129074. 7,
  129075. 9,
  129076. 6,
  129077. 10,
  129078. 5,
  129079. 11,
  129080. 4,
  129081. 12,
  129082. 3,
  129083. 13,
  129084. 2,
  129085. 14,
  129086. 1,
  129087. 15,
  129088. 0,
  129089. 16,
  129090. };
  129091. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129092. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129093. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129094. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129095. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129096. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129097. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129098. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129099. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129100. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129101. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129102. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129103. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129104. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129105. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129106. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129107. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129108. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129110. 13,
  129111. };
  129112. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129113. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129114. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129115. };
  129116. static long _vq_quantmap__44c3_s_p6_0[] = {
  129117. 15, 13, 11, 9, 7, 5, 3, 1,
  129118. 0, 2, 4, 6, 8, 10, 12, 14,
  129119. 16,
  129120. };
  129121. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129122. _vq_quantthresh__44c3_s_p6_0,
  129123. _vq_quantmap__44c3_s_p6_0,
  129124. 17,
  129125. 17
  129126. };
  129127. static static_codebook _44c3_s_p6_0 = {
  129128. 2, 289,
  129129. _vq_lengthlist__44c3_s_p6_0,
  129130. 1, -529530880, 1611661312, 5, 0,
  129131. _vq_quantlist__44c3_s_p6_0,
  129132. NULL,
  129133. &_vq_auxt__44c3_s_p6_0,
  129134. NULL,
  129135. 0
  129136. };
  129137. static long _vq_quantlist__44c3_s_p7_0[] = {
  129138. 1,
  129139. 0,
  129140. 2,
  129141. };
  129142. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129143. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129144. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129145. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129146. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129147. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129148. 10,
  129149. };
  129150. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129151. -5.5, 5.5,
  129152. };
  129153. static long _vq_quantmap__44c3_s_p7_0[] = {
  129154. 1, 0, 2,
  129155. };
  129156. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129157. _vq_quantthresh__44c3_s_p7_0,
  129158. _vq_quantmap__44c3_s_p7_0,
  129159. 3,
  129160. 3
  129161. };
  129162. static static_codebook _44c3_s_p7_0 = {
  129163. 4, 81,
  129164. _vq_lengthlist__44c3_s_p7_0,
  129165. 1, -529137664, 1618345984, 2, 0,
  129166. _vq_quantlist__44c3_s_p7_0,
  129167. NULL,
  129168. &_vq_auxt__44c3_s_p7_0,
  129169. NULL,
  129170. 0
  129171. };
  129172. static long _vq_quantlist__44c3_s_p7_1[] = {
  129173. 5,
  129174. 4,
  129175. 6,
  129176. 3,
  129177. 7,
  129178. 2,
  129179. 8,
  129180. 1,
  129181. 9,
  129182. 0,
  129183. 10,
  129184. };
  129185. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129186. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129187. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129188. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129189. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129190. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129191. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129192. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129193. 10,10,10, 8, 8, 8, 8, 8, 8,
  129194. };
  129195. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129196. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129197. 3.5, 4.5,
  129198. };
  129199. static long _vq_quantmap__44c3_s_p7_1[] = {
  129200. 9, 7, 5, 3, 1, 0, 2, 4,
  129201. 6, 8, 10,
  129202. };
  129203. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129204. _vq_quantthresh__44c3_s_p7_1,
  129205. _vq_quantmap__44c3_s_p7_1,
  129206. 11,
  129207. 11
  129208. };
  129209. static static_codebook _44c3_s_p7_1 = {
  129210. 2, 121,
  129211. _vq_lengthlist__44c3_s_p7_1,
  129212. 1, -531365888, 1611661312, 4, 0,
  129213. _vq_quantlist__44c3_s_p7_1,
  129214. NULL,
  129215. &_vq_auxt__44c3_s_p7_1,
  129216. NULL,
  129217. 0
  129218. };
  129219. static long _vq_quantlist__44c3_s_p8_0[] = {
  129220. 6,
  129221. 5,
  129222. 7,
  129223. 4,
  129224. 8,
  129225. 3,
  129226. 9,
  129227. 2,
  129228. 10,
  129229. 1,
  129230. 11,
  129231. 0,
  129232. 12,
  129233. };
  129234. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129235. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129236. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129237. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129238. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129239. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129240. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129241. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129242. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129243. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129244. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129245. 0,13,13,12,12,13,12,14,13,
  129246. };
  129247. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129248. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129249. 12.5, 17.5, 22.5, 27.5,
  129250. };
  129251. static long _vq_quantmap__44c3_s_p8_0[] = {
  129252. 11, 9, 7, 5, 3, 1, 0, 2,
  129253. 4, 6, 8, 10, 12,
  129254. };
  129255. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129256. _vq_quantthresh__44c3_s_p8_0,
  129257. _vq_quantmap__44c3_s_p8_0,
  129258. 13,
  129259. 13
  129260. };
  129261. static static_codebook _44c3_s_p8_0 = {
  129262. 2, 169,
  129263. _vq_lengthlist__44c3_s_p8_0,
  129264. 1, -526516224, 1616117760, 4, 0,
  129265. _vq_quantlist__44c3_s_p8_0,
  129266. NULL,
  129267. &_vq_auxt__44c3_s_p8_0,
  129268. NULL,
  129269. 0
  129270. };
  129271. static long _vq_quantlist__44c3_s_p8_1[] = {
  129272. 2,
  129273. 1,
  129274. 3,
  129275. 0,
  129276. 4,
  129277. };
  129278. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129279. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129280. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129281. };
  129282. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129283. -1.5, -0.5, 0.5, 1.5,
  129284. };
  129285. static long _vq_quantmap__44c3_s_p8_1[] = {
  129286. 3, 1, 0, 2, 4,
  129287. };
  129288. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129289. _vq_quantthresh__44c3_s_p8_1,
  129290. _vq_quantmap__44c3_s_p8_1,
  129291. 5,
  129292. 5
  129293. };
  129294. static static_codebook _44c3_s_p8_1 = {
  129295. 2, 25,
  129296. _vq_lengthlist__44c3_s_p8_1,
  129297. 1, -533725184, 1611661312, 3, 0,
  129298. _vq_quantlist__44c3_s_p8_1,
  129299. NULL,
  129300. &_vq_auxt__44c3_s_p8_1,
  129301. NULL,
  129302. 0
  129303. };
  129304. static long _vq_quantlist__44c3_s_p9_0[] = {
  129305. 6,
  129306. 5,
  129307. 7,
  129308. 4,
  129309. 8,
  129310. 3,
  129311. 9,
  129312. 2,
  129313. 10,
  129314. 1,
  129315. 11,
  129316. 0,
  129317. 12,
  129318. };
  129319. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129320. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129321. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129322. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129323. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129324. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129325. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129326. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129327. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129328. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129329. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129330. 11,11,11,11,11,11,11,11,11,
  129331. };
  129332. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129333. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129334. 637.5, 892.5, 1147.5, 1402.5,
  129335. };
  129336. static long _vq_quantmap__44c3_s_p9_0[] = {
  129337. 11, 9, 7, 5, 3, 1, 0, 2,
  129338. 4, 6, 8, 10, 12,
  129339. };
  129340. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129341. _vq_quantthresh__44c3_s_p9_0,
  129342. _vq_quantmap__44c3_s_p9_0,
  129343. 13,
  129344. 13
  129345. };
  129346. static static_codebook _44c3_s_p9_0 = {
  129347. 2, 169,
  129348. _vq_lengthlist__44c3_s_p9_0,
  129349. 1, -514332672, 1627381760, 4, 0,
  129350. _vq_quantlist__44c3_s_p9_0,
  129351. NULL,
  129352. &_vq_auxt__44c3_s_p9_0,
  129353. NULL,
  129354. 0
  129355. };
  129356. static long _vq_quantlist__44c3_s_p9_1[] = {
  129357. 7,
  129358. 6,
  129359. 8,
  129360. 5,
  129361. 9,
  129362. 4,
  129363. 10,
  129364. 3,
  129365. 11,
  129366. 2,
  129367. 12,
  129368. 1,
  129369. 13,
  129370. 0,
  129371. 14,
  129372. };
  129373. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129374. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129375. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129376. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129377. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129378. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129379. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129380. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129381. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129382. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129383. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129384. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129385. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129386. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129387. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129388. 15,
  129389. };
  129390. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129391. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129392. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129393. };
  129394. static long _vq_quantmap__44c3_s_p9_1[] = {
  129395. 13, 11, 9, 7, 5, 3, 1, 0,
  129396. 2, 4, 6, 8, 10, 12, 14,
  129397. };
  129398. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129399. _vq_quantthresh__44c3_s_p9_1,
  129400. _vq_quantmap__44c3_s_p9_1,
  129401. 15,
  129402. 15
  129403. };
  129404. static static_codebook _44c3_s_p9_1 = {
  129405. 2, 225,
  129406. _vq_lengthlist__44c3_s_p9_1,
  129407. 1, -522338304, 1620115456, 4, 0,
  129408. _vq_quantlist__44c3_s_p9_1,
  129409. NULL,
  129410. &_vq_auxt__44c3_s_p9_1,
  129411. NULL,
  129412. 0
  129413. };
  129414. static long _vq_quantlist__44c3_s_p9_2[] = {
  129415. 8,
  129416. 7,
  129417. 9,
  129418. 6,
  129419. 10,
  129420. 5,
  129421. 11,
  129422. 4,
  129423. 12,
  129424. 3,
  129425. 13,
  129426. 2,
  129427. 14,
  129428. 1,
  129429. 15,
  129430. 0,
  129431. 16,
  129432. };
  129433. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129434. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129435. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129436. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129437. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129438. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129439. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129440. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129441. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129442. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129443. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129444. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129445. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129446. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129447. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129448. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129449. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129450. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129451. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129452. 10,
  129453. };
  129454. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129455. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129456. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129457. };
  129458. static long _vq_quantmap__44c3_s_p9_2[] = {
  129459. 15, 13, 11, 9, 7, 5, 3, 1,
  129460. 0, 2, 4, 6, 8, 10, 12, 14,
  129461. 16,
  129462. };
  129463. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129464. _vq_quantthresh__44c3_s_p9_2,
  129465. _vq_quantmap__44c3_s_p9_2,
  129466. 17,
  129467. 17
  129468. };
  129469. static static_codebook _44c3_s_p9_2 = {
  129470. 2, 289,
  129471. _vq_lengthlist__44c3_s_p9_2,
  129472. 1, -529530880, 1611661312, 5, 0,
  129473. _vq_quantlist__44c3_s_p9_2,
  129474. NULL,
  129475. &_vq_auxt__44c3_s_p9_2,
  129476. NULL,
  129477. 0
  129478. };
  129479. static long _huff_lengthlist__44c3_s_short[] = {
  129480. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129481. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129482. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129483. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129484. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129485. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129486. 6, 8, 9,11,
  129487. };
  129488. static static_codebook _huff_book__44c3_s_short = {
  129489. 2, 100,
  129490. _huff_lengthlist__44c3_s_short,
  129491. 0, 0, 0, 0, 0,
  129492. NULL,
  129493. NULL,
  129494. NULL,
  129495. NULL,
  129496. 0
  129497. };
  129498. static long _huff_lengthlist__44c4_s_long[] = {
  129499. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129500. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129501. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129502. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129503. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129504. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129505. 9, 8, 7, 7,
  129506. };
  129507. static static_codebook _huff_book__44c4_s_long = {
  129508. 2, 100,
  129509. _huff_lengthlist__44c4_s_long,
  129510. 0, 0, 0, 0, 0,
  129511. NULL,
  129512. NULL,
  129513. NULL,
  129514. NULL,
  129515. 0
  129516. };
  129517. static long _vq_quantlist__44c4_s_p1_0[] = {
  129518. 1,
  129519. 0,
  129520. 2,
  129521. };
  129522. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129523. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129524. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129529. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129534. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 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, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129569. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129574. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129579. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129615. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129620. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129625. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0,
  129934. };
  129935. static float _vq_quantthresh__44c4_s_p1_0[] = {
  129936. -0.5, 0.5,
  129937. };
  129938. static long _vq_quantmap__44c4_s_p1_0[] = {
  129939. 1, 0, 2,
  129940. };
  129941. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  129942. _vq_quantthresh__44c4_s_p1_0,
  129943. _vq_quantmap__44c4_s_p1_0,
  129944. 3,
  129945. 3
  129946. };
  129947. static static_codebook _44c4_s_p1_0 = {
  129948. 8, 6561,
  129949. _vq_lengthlist__44c4_s_p1_0,
  129950. 1, -535822336, 1611661312, 2, 0,
  129951. _vq_quantlist__44c4_s_p1_0,
  129952. NULL,
  129953. &_vq_auxt__44c4_s_p1_0,
  129954. NULL,
  129955. 0
  129956. };
  129957. static long _vq_quantlist__44c4_s_p2_0[] = {
  129958. 2,
  129959. 1,
  129960. 3,
  129961. 0,
  129962. 4,
  129963. };
  129964. static long _vq_lengthlist__44c4_s_p2_0[] = {
  129965. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129966. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129967. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129968. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129969. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129974. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  129975. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129976. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129977. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129982. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129983. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129984. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129990. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129991. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129992. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0,
  130005. };
  130006. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130007. -1.5, -0.5, 0.5, 1.5,
  130008. };
  130009. static long _vq_quantmap__44c4_s_p2_0[] = {
  130010. 3, 1, 0, 2, 4,
  130011. };
  130012. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130013. _vq_quantthresh__44c4_s_p2_0,
  130014. _vq_quantmap__44c4_s_p2_0,
  130015. 5,
  130016. 5
  130017. };
  130018. static static_codebook _44c4_s_p2_0 = {
  130019. 4, 625,
  130020. _vq_lengthlist__44c4_s_p2_0,
  130021. 1, -533725184, 1611661312, 3, 0,
  130022. _vq_quantlist__44c4_s_p2_0,
  130023. NULL,
  130024. &_vq_auxt__44c4_s_p2_0,
  130025. NULL,
  130026. 0
  130027. };
  130028. static long _vq_quantlist__44c4_s_p3_0[] = {
  130029. 2,
  130030. 1,
  130031. 3,
  130032. 0,
  130033. 4,
  130034. };
  130035. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130036. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0,
  130076. };
  130077. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130078. -1.5, -0.5, 0.5, 1.5,
  130079. };
  130080. static long _vq_quantmap__44c4_s_p3_0[] = {
  130081. 3, 1, 0, 2, 4,
  130082. };
  130083. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130084. _vq_quantthresh__44c4_s_p3_0,
  130085. _vq_quantmap__44c4_s_p3_0,
  130086. 5,
  130087. 5
  130088. };
  130089. static static_codebook _44c4_s_p3_0 = {
  130090. 4, 625,
  130091. _vq_lengthlist__44c4_s_p3_0,
  130092. 1, -533725184, 1611661312, 3, 0,
  130093. _vq_quantlist__44c4_s_p3_0,
  130094. NULL,
  130095. &_vq_auxt__44c4_s_p3_0,
  130096. NULL,
  130097. 0
  130098. };
  130099. static long _vq_quantlist__44c4_s_p4_0[] = {
  130100. 4,
  130101. 3,
  130102. 5,
  130103. 2,
  130104. 6,
  130105. 1,
  130106. 7,
  130107. 0,
  130108. 8,
  130109. };
  130110. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130111. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130112. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130113. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130114. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130115. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0,
  130117. };
  130118. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130119. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130120. };
  130121. static long _vq_quantmap__44c4_s_p4_0[] = {
  130122. 7, 5, 3, 1, 0, 2, 4, 6,
  130123. 8,
  130124. };
  130125. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130126. _vq_quantthresh__44c4_s_p4_0,
  130127. _vq_quantmap__44c4_s_p4_0,
  130128. 9,
  130129. 9
  130130. };
  130131. static static_codebook _44c4_s_p4_0 = {
  130132. 2, 81,
  130133. _vq_lengthlist__44c4_s_p4_0,
  130134. 1, -531628032, 1611661312, 4, 0,
  130135. _vq_quantlist__44c4_s_p4_0,
  130136. NULL,
  130137. &_vq_auxt__44c4_s_p4_0,
  130138. NULL,
  130139. 0
  130140. };
  130141. static long _vq_quantlist__44c4_s_p5_0[] = {
  130142. 4,
  130143. 3,
  130144. 5,
  130145. 2,
  130146. 6,
  130147. 1,
  130148. 7,
  130149. 0,
  130150. 8,
  130151. };
  130152. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130153. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130154. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130155. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130156. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130157. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130158. 10,
  130159. };
  130160. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130161. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130162. };
  130163. static long _vq_quantmap__44c4_s_p5_0[] = {
  130164. 7, 5, 3, 1, 0, 2, 4, 6,
  130165. 8,
  130166. };
  130167. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130168. _vq_quantthresh__44c4_s_p5_0,
  130169. _vq_quantmap__44c4_s_p5_0,
  130170. 9,
  130171. 9
  130172. };
  130173. static static_codebook _44c4_s_p5_0 = {
  130174. 2, 81,
  130175. _vq_lengthlist__44c4_s_p5_0,
  130176. 1, -531628032, 1611661312, 4, 0,
  130177. _vq_quantlist__44c4_s_p5_0,
  130178. NULL,
  130179. &_vq_auxt__44c4_s_p5_0,
  130180. NULL,
  130181. 0
  130182. };
  130183. static long _vq_quantlist__44c4_s_p6_0[] = {
  130184. 8,
  130185. 7,
  130186. 9,
  130187. 6,
  130188. 10,
  130189. 5,
  130190. 11,
  130191. 4,
  130192. 12,
  130193. 3,
  130194. 13,
  130195. 2,
  130196. 14,
  130197. 1,
  130198. 15,
  130199. 0,
  130200. 16,
  130201. };
  130202. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130203. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130204. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130205. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130206. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130207. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130208. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130209. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130210. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130211. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130212. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130213. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130214. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130215. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130216. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130217. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130218. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130219. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130221. 13,
  130222. };
  130223. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130224. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130225. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130226. };
  130227. static long _vq_quantmap__44c4_s_p6_0[] = {
  130228. 15, 13, 11, 9, 7, 5, 3, 1,
  130229. 0, 2, 4, 6, 8, 10, 12, 14,
  130230. 16,
  130231. };
  130232. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130233. _vq_quantthresh__44c4_s_p6_0,
  130234. _vq_quantmap__44c4_s_p6_0,
  130235. 17,
  130236. 17
  130237. };
  130238. static static_codebook _44c4_s_p6_0 = {
  130239. 2, 289,
  130240. _vq_lengthlist__44c4_s_p6_0,
  130241. 1, -529530880, 1611661312, 5, 0,
  130242. _vq_quantlist__44c4_s_p6_0,
  130243. NULL,
  130244. &_vq_auxt__44c4_s_p6_0,
  130245. NULL,
  130246. 0
  130247. };
  130248. static long _vq_quantlist__44c4_s_p7_0[] = {
  130249. 1,
  130250. 0,
  130251. 2,
  130252. };
  130253. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130254. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130255. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130256. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130257. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130258. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130259. 10,
  130260. };
  130261. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130262. -5.5, 5.5,
  130263. };
  130264. static long _vq_quantmap__44c4_s_p7_0[] = {
  130265. 1, 0, 2,
  130266. };
  130267. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130268. _vq_quantthresh__44c4_s_p7_0,
  130269. _vq_quantmap__44c4_s_p7_0,
  130270. 3,
  130271. 3
  130272. };
  130273. static static_codebook _44c4_s_p7_0 = {
  130274. 4, 81,
  130275. _vq_lengthlist__44c4_s_p7_0,
  130276. 1, -529137664, 1618345984, 2, 0,
  130277. _vq_quantlist__44c4_s_p7_0,
  130278. NULL,
  130279. &_vq_auxt__44c4_s_p7_0,
  130280. NULL,
  130281. 0
  130282. };
  130283. static long _vq_quantlist__44c4_s_p7_1[] = {
  130284. 5,
  130285. 4,
  130286. 6,
  130287. 3,
  130288. 7,
  130289. 2,
  130290. 8,
  130291. 1,
  130292. 9,
  130293. 0,
  130294. 10,
  130295. };
  130296. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130297. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130298. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130299. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130300. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130301. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130302. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130303. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130304. 10,10,10, 8, 8, 8, 8, 9, 9,
  130305. };
  130306. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130307. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130308. 3.5, 4.5,
  130309. };
  130310. static long _vq_quantmap__44c4_s_p7_1[] = {
  130311. 9, 7, 5, 3, 1, 0, 2, 4,
  130312. 6, 8, 10,
  130313. };
  130314. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130315. _vq_quantthresh__44c4_s_p7_1,
  130316. _vq_quantmap__44c4_s_p7_1,
  130317. 11,
  130318. 11
  130319. };
  130320. static static_codebook _44c4_s_p7_1 = {
  130321. 2, 121,
  130322. _vq_lengthlist__44c4_s_p7_1,
  130323. 1, -531365888, 1611661312, 4, 0,
  130324. _vq_quantlist__44c4_s_p7_1,
  130325. NULL,
  130326. &_vq_auxt__44c4_s_p7_1,
  130327. NULL,
  130328. 0
  130329. };
  130330. static long _vq_quantlist__44c4_s_p8_0[] = {
  130331. 6,
  130332. 5,
  130333. 7,
  130334. 4,
  130335. 8,
  130336. 3,
  130337. 9,
  130338. 2,
  130339. 10,
  130340. 1,
  130341. 11,
  130342. 0,
  130343. 12,
  130344. };
  130345. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130346. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130347. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130348. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130349. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130350. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130351. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130352. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130353. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130354. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130355. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130356. 0,13,12,12,12,12,12,13,13,
  130357. };
  130358. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130359. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130360. 12.5, 17.5, 22.5, 27.5,
  130361. };
  130362. static long _vq_quantmap__44c4_s_p8_0[] = {
  130363. 11, 9, 7, 5, 3, 1, 0, 2,
  130364. 4, 6, 8, 10, 12,
  130365. };
  130366. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130367. _vq_quantthresh__44c4_s_p8_0,
  130368. _vq_quantmap__44c4_s_p8_0,
  130369. 13,
  130370. 13
  130371. };
  130372. static static_codebook _44c4_s_p8_0 = {
  130373. 2, 169,
  130374. _vq_lengthlist__44c4_s_p8_0,
  130375. 1, -526516224, 1616117760, 4, 0,
  130376. _vq_quantlist__44c4_s_p8_0,
  130377. NULL,
  130378. &_vq_auxt__44c4_s_p8_0,
  130379. NULL,
  130380. 0
  130381. };
  130382. static long _vq_quantlist__44c4_s_p8_1[] = {
  130383. 2,
  130384. 1,
  130385. 3,
  130386. 0,
  130387. 4,
  130388. };
  130389. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130390. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130391. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130392. };
  130393. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130394. -1.5, -0.5, 0.5, 1.5,
  130395. };
  130396. static long _vq_quantmap__44c4_s_p8_1[] = {
  130397. 3, 1, 0, 2, 4,
  130398. };
  130399. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130400. _vq_quantthresh__44c4_s_p8_1,
  130401. _vq_quantmap__44c4_s_p8_1,
  130402. 5,
  130403. 5
  130404. };
  130405. static static_codebook _44c4_s_p8_1 = {
  130406. 2, 25,
  130407. _vq_lengthlist__44c4_s_p8_1,
  130408. 1, -533725184, 1611661312, 3, 0,
  130409. _vq_quantlist__44c4_s_p8_1,
  130410. NULL,
  130411. &_vq_auxt__44c4_s_p8_1,
  130412. NULL,
  130413. 0
  130414. };
  130415. static long _vq_quantlist__44c4_s_p9_0[] = {
  130416. 6,
  130417. 5,
  130418. 7,
  130419. 4,
  130420. 8,
  130421. 3,
  130422. 9,
  130423. 2,
  130424. 10,
  130425. 1,
  130426. 11,
  130427. 0,
  130428. 12,
  130429. };
  130430. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130431. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130432. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130433. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130434. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130435. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130436. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130437. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130438. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130439. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130440. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130441. 12,12,12,12,12,12,12,12,12,
  130442. };
  130443. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130444. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130445. 787.5, 1102.5, 1417.5, 1732.5,
  130446. };
  130447. static long _vq_quantmap__44c4_s_p9_0[] = {
  130448. 11, 9, 7, 5, 3, 1, 0, 2,
  130449. 4, 6, 8, 10, 12,
  130450. };
  130451. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130452. _vq_quantthresh__44c4_s_p9_0,
  130453. _vq_quantmap__44c4_s_p9_0,
  130454. 13,
  130455. 13
  130456. };
  130457. static static_codebook _44c4_s_p9_0 = {
  130458. 2, 169,
  130459. _vq_lengthlist__44c4_s_p9_0,
  130460. 1, -513964032, 1628680192, 4, 0,
  130461. _vq_quantlist__44c4_s_p9_0,
  130462. NULL,
  130463. &_vq_auxt__44c4_s_p9_0,
  130464. NULL,
  130465. 0
  130466. };
  130467. static long _vq_quantlist__44c4_s_p9_1[] = {
  130468. 7,
  130469. 6,
  130470. 8,
  130471. 5,
  130472. 9,
  130473. 4,
  130474. 10,
  130475. 3,
  130476. 11,
  130477. 2,
  130478. 12,
  130479. 1,
  130480. 13,
  130481. 0,
  130482. 14,
  130483. };
  130484. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130485. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130486. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130487. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130488. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130489. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130490. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130491. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130492. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130493. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130494. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130495. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130496. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130497. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130498. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130499. 15,
  130500. };
  130501. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130502. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130503. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130504. };
  130505. static long _vq_quantmap__44c4_s_p9_1[] = {
  130506. 13, 11, 9, 7, 5, 3, 1, 0,
  130507. 2, 4, 6, 8, 10, 12, 14,
  130508. };
  130509. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130510. _vq_quantthresh__44c4_s_p9_1,
  130511. _vq_quantmap__44c4_s_p9_1,
  130512. 15,
  130513. 15
  130514. };
  130515. static static_codebook _44c4_s_p9_1 = {
  130516. 2, 225,
  130517. _vq_lengthlist__44c4_s_p9_1,
  130518. 1, -520986624, 1620377600, 4, 0,
  130519. _vq_quantlist__44c4_s_p9_1,
  130520. NULL,
  130521. &_vq_auxt__44c4_s_p9_1,
  130522. NULL,
  130523. 0
  130524. };
  130525. static long _vq_quantlist__44c4_s_p9_2[] = {
  130526. 10,
  130527. 9,
  130528. 11,
  130529. 8,
  130530. 12,
  130531. 7,
  130532. 13,
  130533. 6,
  130534. 14,
  130535. 5,
  130536. 15,
  130537. 4,
  130538. 16,
  130539. 3,
  130540. 17,
  130541. 2,
  130542. 18,
  130543. 1,
  130544. 19,
  130545. 0,
  130546. 20,
  130547. };
  130548. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130549. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130550. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130551. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130552. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130553. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130554. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130555. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130556. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130557. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130558. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130559. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130560. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130561. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130562. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130563. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130564. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130565. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130566. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130567. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130568. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130569. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130570. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130571. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130572. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130573. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130574. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130575. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130576. 10,10,10,10,10,10,10,10,10,
  130577. };
  130578. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130579. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130580. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130581. 6.5, 7.5, 8.5, 9.5,
  130582. };
  130583. static long _vq_quantmap__44c4_s_p9_2[] = {
  130584. 19, 17, 15, 13, 11, 9, 7, 5,
  130585. 3, 1, 0, 2, 4, 6, 8, 10,
  130586. 12, 14, 16, 18, 20,
  130587. };
  130588. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130589. _vq_quantthresh__44c4_s_p9_2,
  130590. _vq_quantmap__44c4_s_p9_2,
  130591. 21,
  130592. 21
  130593. };
  130594. static static_codebook _44c4_s_p9_2 = {
  130595. 2, 441,
  130596. _vq_lengthlist__44c4_s_p9_2,
  130597. 1, -529268736, 1611661312, 5, 0,
  130598. _vq_quantlist__44c4_s_p9_2,
  130599. NULL,
  130600. &_vq_auxt__44c4_s_p9_2,
  130601. NULL,
  130602. 0
  130603. };
  130604. static long _huff_lengthlist__44c4_s_short[] = {
  130605. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130606. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130607. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130608. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130609. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130610. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130611. 7, 9,12,17,
  130612. };
  130613. static static_codebook _huff_book__44c4_s_short = {
  130614. 2, 100,
  130615. _huff_lengthlist__44c4_s_short,
  130616. 0, 0, 0, 0, 0,
  130617. NULL,
  130618. NULL,
  130619. NULL,
  130620. NULL,
  130621. 0
  130622. };
  130623. static long _huff_lengthlist__44c5_s_long[] = {
  130624. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130625. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130626. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130627. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130628. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130629. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130630. 9, 8, 7, 7,
  130631. };
  130632. static static_codebook _huff_book__44c5_s_long = {
  130633. 2, 100,
  130634. _huff_lengthlist__44c5_s_long,
  130635. 0, 0, 0, 0, 0,
  130636. NULL,
  130637. NULL,
  130638. NULL,
  130639. NULL,
  130640. 0
  130641. };
  130642. static long _vq_quantlist__44c5_s_p1_0[] = {
  130643. 1,
  130644. 0,
  130645. 2,
  130646. };
  130647. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130648. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130649. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130654. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130659. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130694. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130699. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130704. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130740. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130744. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130745. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130750. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0,
  131059. };
  131060. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131061. -0.5, 0.5,
  131062. };
  131063. static long _vq_quantmap__44c5_s_p1_0[] = {
  131064. 1, 0, 2,
  131065. };
  131066. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131067. _vq_quantthresh__44c5_s_p1_0,
  131068. _vq_quantmap__44c5_s_p1_0,
  131069. 3,
  131070. 3
  131071. };
  131072. static static_codebook _44c5_s_p1_0 = {
  131073. 8, 6561,
  131074. _vq_lengthlist__44c5_s_p1_0,
  131075. 1, -535822336, 1611661312, 2, 0,
  131076. _vq_quantlist__44c5_s_p1_0,
  131077. NULL,
  131078. &_vq_auxt__44c5_s_p1_0,
  131079. NULL,
  131080. 0
  131081. };
  131082. static long _vq_quantlist__44c5_s_p2_0[] = {
  131083. 2,
  131084. 1,
  131085. 3,
  131086. 0,
  131087. 4,
  131088. };
  131089. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131090. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131091. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131092. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131093. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131094. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131100. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131101. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131102. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131108. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131109. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131116. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131117. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0,
  131130. };
  131131. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131132. -1.5, -0.5, 0.5, 1.5,
  131133. };
  131134. static long _vq_quantmap__44c5_s_p2_0[] = {
  131135. 3, 1, 0, 2, 4,
  131136. };
  131137. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131138. _vq_quantthresh__44c5_s_p2_0,
  131139. _vq_quantmap__44c5_s_p2_0,
  131140. 5,
  131141. 5
  131142. };
  131143. static static_codebook _44c5_s_p2_0 = {
  131144. 4, 625,
  131145. _vq_lengthlist__44c5_s_p2_0,
  131146. 1, -533725184, 1611661312, 3, 0,
  131147. _vq_quantlist__44c5_s_p2_0,
  131148. NULL,
  131149. &_vq_auxt__44c5_s_p2_0,
  131150. NULL,
  131151. 0
  131152. };
  131153. static long _vq_quantlist__44c5_s_p3_0[] = {
  131154. 2,
  131155. 1,
  131156. 3,
  131157. 0,
  131158. 4,
  131159. };
  131160. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131161. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0,
  131201. };
  131202. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131203. -1.5, -0.5, 0.5, 1.5,
  131204. };
  131205. static long _vq_quantmap__44c5_s_p3_0[] = {
  131206. 3, 1, 0, 2, 4,
  131207. };
  131208. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131209. _vq_quantthresh__44c5_s_p3_0,
  131210. _vq_quantmap__44c5_s_p3_0,
  131211. 5,
  131212. 5
  131213. };
  131214. static static_codebook _44c5_s_p3_0 = {
  131215. 4, 625,
  131216. _vq_lengthlist__44c5_s_p3_0,
  131217. 1, -533725184, 1611661312, 3, 0,
  131218. _vq_quantlist__44c5_s_p3_0,
  131219. NULL,
  131220. &_vq_auxt__44c5_s_p3_0,
  131221. NULL,
  131222. 0
  131223. };
  131224. static long _vq_quantlist__44c5_s_p4_0[] = {
  131225. 4,
  131226. 3,
  131227. 5,
  131228. 2,
  131229. 6,
  131230. 1,
  131231. 7,
  131232. 0,
  131233. 8,
  131234. };
  131235. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131236. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131237. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131238. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131239. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131240. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0,
  131242. };
  131243. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131244. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131245. };
  131246. static long _vq_quantmap__44c5_s_p4_0[] = {
  131247. 7, 5, 3, 1, 0, 2, 4, 6,
  131248. 8,
  131249. };
  131250. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131251. _vq_quantthresh__44c5_s_p4_0,
  131252. _vq_quantmap__44c5_s_p4_0,
  131253. 9,
  131254. 9
  131255. };
  131256. static static_codebook _44c5_s_p4_0 = {
  131257. 2, 81,
  131258. _vq_lengthlist__44c5_s_p4_0,
  131259. 1, -531628032, 1611661312, 4, 0,
  131260. _vq_quantlist__44c5_s_p4_0,
  131261. NULL,
  131262. &_vq_auxt__44c5_s_p4_0,
  131263. NULL,
  131264. 0
  131265. };
  131266. static long _vq_quantlist__44c5_s_p5_0[] = {
  131267. 4,
  131268. 3,
  131269. 5,
  131270. 2,
  131271. 6,
  131272. 1,
  131273. 7,
  131274. 0,
  131275. 8,
  131276. };
  131277. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131278. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131279. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131280. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131281. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131282. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131283. 10,
  131284. };
  131285. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131286. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131287. };
  131288. static long _vq_quantmap__44c5_s_p5_0[] = {
  131289. 7, 5, 3, 1, 0, 2, 4, 6,
  131290. 8,
  131291. };
  131292. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131293. _vq_quantthresh__44c5_s_p5_0,
  131294. _vq_quantmap__44c5_s_p5_0,
  131295. 9,
  131296. 9
  131297. };
  131298. static static_codebook _44c5_s_p5_0 = {
  131299. 2, 81,
  131300. _vq_lengthlist__44c5_s_p5_0,
  131301. 1, -531628032, 1611661312, 4, 0,
  131302. _vq_quantlist__44c5_s_p5_0,
  131303. NULL,
  131304. &_vq_auxt__44c5_s_p5_0,
  131305. NULL,
  131306. 0
  131307. };
  131308. static long _vq_quantlist__44c5_s_p6_0[] = {
  131309. 8,
  131310. 7,
  131311. 9,
  131312. 6,
  131313. 10,
  131314. 5,
  131315. 11,
  131316. 4,
  131317. 12,
  131318. 3,
  131319. 13,
  131320. 2,
  131321. 14,
  131322. 1,
  131323. 15,
  131324. 0,
  131325. 16,
  131326. };
  131327. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131328. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131329. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131330. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131331. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131332. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131333. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131334. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131335. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131336. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131337. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131338. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131339. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131340. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131341. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131342. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131343. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131344. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131346. 13,
  131347. };
  131348. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131349. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131350. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131351. };
  131352. static long _vq_quantmap__44c5_s_p6_0[] = {
  131353. 15, 13, 11, 9, 7, 5, 3, 1,
  131354. 0, 2, 4, 6, 8, 10, 12, 14,
  131355. 16,
  131356. };
  131357. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131358. _vq_quantthresh__44c5_s_p6_0,
  131359. _vq_quantmap__44c5_s_p6_0,
  131360. 17,
  131361. 17
  131362. };
  131363. static static_codebook _44c5_s_p6_0 = {
  131364. 2, 289,
  131365. _vq_lengthlist__44c5_s_p6_0,
  131366. 1, -529530880, 1611661312, 5, 0,
  131367. _vq_quantlist__44c5_s_p6_0,
  131368. NULL,
  131369. &_vq_auxt__44c5_s_p6_0,
  131370. NULL,
  131371. 0
  131372. };
  131373. static long _vq_quantlist__44c5_s_p7_0[] = {
  131374. 1,
  131375. 0,
  131376. 2,
  131377. };
  131378. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131379. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131380. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131381. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131382. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131383. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131384. 10,
  131385. };
  131386. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131387. -5.5, 5.5,
  131388. };
  131389. static long _vq_quantmap__44c5_s_p7_0[] = {
  131390. 1, 0, 2,
  131391. };
  131392. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131393. _vq_quantthresh__44c5_s_p7_0,
  131394. _vq_quantmap__44c5_s_p7_0,
  131395. 3,
  131396. 3
  131397. };
  131398. static static_codebook _44c5_s_p7_0 = {
  131399. 4, 81,
  131400. _vq_lengthlist__44c5_s_p7_0,
  131401. 1, -529137664, 1618345984, 2, 0,
  131402. _vq_quantlist__44c5_s_p7_0,
  131403. NULL,
  131404. &_vq_auxt__44c5_s_p7_0,
  131405. NULL,
  131406. 0
  131407. };
  131408. static long _vq_quantlist__44c5_s_p7_1[] = {
  131409. 5,
  131410. 4,
  131411. 6,
  131412. 3,
  131413. 7,
  131414. 2,
  131415. 8,
  131416. 1,
  131417. 9,
  131418. 0,
  131419. 10,
  131420. };
  131421. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131422. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131423. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131424. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131425. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131426. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131427. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131428. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131429. 10,10,10, 8, 8, 8, 8, 8, 8,
  131430. };
  131431. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131432. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131433. 3.5, 4.5,
  131434. };
  131435. static long _vq_quantmap__44c5_s_p7_1[] = {
  131436. 9, 7, 5, 3, 1, 0, 2, 4,
  131437. 6, 8, 10,
  131438. };
  131439. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131440. _vq_quantthresh__44c5_s_p7_1,
  131441. _vq_quantmap__44c5_s_p7_1,
  131442. 11,
  131443. 11
  131444. };
  131445. static static_codebook _44c5_s_p7_1 = {
  131446. 2, 121,
  131447. _vq_lengthlist__44c5_s_p7_1,
  131448. 1, -531365888, 1611661312, 4, 0,
  131449. _vq_quantlist__44c5_s_p7_1,
  131450. NULL,
  131451. &_vq_auxt__44c5_s_p7_1,
  131452. NULL,
  131453. 0
  131454. };
  131455. static long _vq_quantlist__44c5_s_p8_0[] = {
  131456. 6,
  131457. 5,
  131458. 7,
  131459. 4,
  131460. 8,
  131461. 3,
  131462. 9,
  131463. 2,
  131464. 10,
  131465. 1,
  131466. 11,
  131467. 0,
  131468. 12,
  131469. };
  131470. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131471. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131472. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131473. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131474. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131475. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131476. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131477. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131478. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131479. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131480. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131481. 0,12,12,12,12,12,12,13,13,
  131482. };
  131483. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131484. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131485. 12.5, 17.5, 22.5, 27.5,
  131486. };
  131487. static long _vq_quantmap__44c5_s_p8_0[] = {
  131488. 11, 9, 7, 5, 3, 1, 0, 2,
  131489. 4, 6, 8, 10, 12,
  131490. };
  131491. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131492. _vq_quantthresh__44c5_s_p8_0,
  131493. _vq_quantmap__44c5_s_p8_0,
  131494. 13,
  131495. 13
  131496. };
  131497. static static_codebook _44c5_s_p8_0 = {
  131498. 2, 169,
  131499. _vq_lengthlist__44c5_s_p8_0,
  131500. 1, -526516224, 1616117760, 4, 0,
  131501. _vq_quantlist__44c5_s_p8_0,
  131502. NULL,
  131503. &_vq_auxt__44c5_s_p8_0,
  131504. NULL,
  131505. 0
  131506. };
  131507. static long _vq_quantlist__44c5_s_p8_1[] = {
  131508. 2,
  131509. 1,
  131510. 3,
  131511. 0,
  131512. 4,
  131513. };
  131514. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131515. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131516. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131517. };
  131518. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131519. -1.5, -0.5, 0.5, 1.5,
  131520. };
  131521. static long _vq_quantmap__44c5_s_p8_1[] = {
  131522. 3, 1, 0, 2, 4,
  131523. };
  131524. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131525. _vq_quantthresh__44c5_s_p8_1,
  131526. _vq_quantmap__44c5_s_p8_1,
  131527. 5,
  131528. 5
  131529. };
  131530. static static_codebook _44c5_s_p8_1 = {
  131531. 2, 25,
  131532. _vq_lengthlist__44c5_s_p8_1,
  131533. 1, -533725184, 1611661312, 3, 0,
  131534. _vq_quantlist__44c5_s_p8_1,
  131535. NULL,
  131536. &_vq_auxt__44c5_s_p8_1,
  131537. NULL,
  131538. 0
  131539. };
  131540. static long _vq_quantlist__44c5_s_p9_0[] = {
  131541. 7,
  131542. 6,
  131543. 8,
  131544. 5,
  131545. 9,
  131546. 4,
  131547. 10,
  131548. 3,
  131549. 11,
  131550. 2,
  131551. 12,
  131552. 1,
  131553. 13,
  131554. 0,
  131555. 14,
  131556. };
  131557. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131558. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131559. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131560. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131561. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131562. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131563. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131564. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131565. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131566. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131567. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131568. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131569. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131570. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131571. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131572. 12,
  131573. };
  131574. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131575. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131576. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131577. };
  131578. static long _vq_quantmap__44c5_s_p9_0[] = {
  131579. 13, 11, 9, 7, 5, 3, 1, 0,
  131580. 2, 4, 6, 8, 10, 12, 14,
  131581. };
  131582. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131583. _vq_quantthresh__44c5_s_p9_0,
  131584. _vq_quantmap__44c5_s_p9_0,
  131585. 15,
  131586. 15
  131587. };
  131588. static static_codebook _44c5_s_p9_0 = {
  131589. 2, 225,
  131590. _vq_lengthlist__44c5_s_p9_0,
  131591. 1, -512522752, 1628852224, 4, 0,
  131592. _vq_quantlist__44c5_s_p9_0,
  131593. NULL,
  131594. &_vq_auxt__44c5_s_p9_0,
  131595. NULL,
  131596. 0
  131597. };
  131598. static long _vq_quantlist__44c5_s_p9_1[] = {
  131599. 8,
  131600. 7,
  131601. 9,
  131602. 6,
  131603. 10,
  131604. 5,
  131605. 11,
  131606. 4,
  131607. 12,
  131608. 3,
  131609. 13,
  131610. 2,
  131611. 14,
  131612. 1,
  131613. 15,
  131614. 0,
  131615. 16,
  131616. };
  131617. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131618. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131619. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131620. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131621. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131622. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131623. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131624. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131625. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131626. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131627. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131628. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131629. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131630. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131631. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131632. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131633. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131634. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131635. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131636. 15,
  131637. };
  131638. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131639. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131640. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131641. };
  131642. static long _vq_quantmap__44c5_s_p9_1[] = {
  131643. 15, 13, 11, 9, 7, 5, 3, 1,
  131644. 0, 2, 4, 6, 8, 10, 12, 14,
  131645. 16,
  131646. };
  131647. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131648. _vq_quantthresh__44c5_s_p9_1,
  131649. _vq_quantmap__44c5_s_p9_1,
  131650. 17,
  131651. 17
  131652. };
  131653. static static_codebook _44c5_s_p9_1 = {
  131654. 2, 289,
  131655. _vq_lengthlist__44c5_s_p9_1,
  131656. 1, -520814592, 1620377600, 5, 0,
  131657. _vq_quantlist__44c5_s_p9_1,
  131658. NULL,
  131659. &_vq_auxt__44c5_s_p9_1,
  131660. NULL,
  131661. 0
  131662. };
  131663. static long _vq_quantlist__44c5_s_p9_2[] = {
  131664. 10,
  131665. 9,
  131666. 11,
  131667. 8,
  131668. 12,
  131669. 7,
  131670. 13,
  131671. 6,
  131672. 14,
  131673. 5,
  131674. 15,
  131675. 4,
  131676. 16,
  131677. 3,
  131678. 17,
  131679. 2,
  131680. 18,
  131681. 1,
  131682. 19,
  131683. 0,
  131684. 20,
  131685. };
  131686. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131687. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131688. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131689. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131690. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131691. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131692. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131693. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131694. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131695. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131696. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131697. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131698. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131699. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131700. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131701. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131702. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131703. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131704. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131705. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131706. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131707. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131708. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131709. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131710. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131711. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131712. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131713. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131714. 10,10,10,10,10,10,10,10,10,
  131715. };
  131716. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131717. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131718. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131719. 6.5, 7.5, 8.5, 9.5,
  131720. };
  131721. static long _vq_quantmap__44c5_s_p9_2[] = {
  131722. 19, 17, 15, 13, 11, 9, 7, 5,
  131723. 3, 1, 0, 2, 4, 6, 8, 10,
  131724. 12, 14, 16, 18, 20,
  131725. };
  131726. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131727. _vq_quantthresh__44c5_s_p9_2,
  131728. _vq_quantmap__44c5_s_p9_2,
  131729. 21,
  131730. 21
  131731. };
  131732. static static_codebook _44c5_s_p9_2 = {
  131733. 2, 441,
  131734. _vq_lengthlist__44c5_s_p9_2,
  131735. 1, -529268736, 1611661312, 5, 0,
  131736. _vq_quantlist__44c5_s_p9_2,
  131737. NULL,
  131738. &_vq_auxt__44c5_s_p9_2,
  131739. NULL,
  131740. 0
  131741. };
  131742. static long _huff_lengthlist__44c5_s_short[] = {
  131743. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131744. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131745. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131746. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131747. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131748. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131749. 6, 8,11,16,
  131750. };
  131751. static static_codebook _huff_book__44c5_s_short = {
  131752. 2, 100,
  131753. _huff_lengthlist__44c5_s_short,
  131754. 0, 0, 0, 0, 0,
  131755. NULL,
  131756. NULL,
  131757. NULL,
  131758. NULL,
  131759. 0
  131760. };
  131761. static long _huff_lengthlist__44c6_s_long[] = {
  131762. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131763. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131764. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131765. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131766. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131767. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131768. 11,10,10,12,
  131769. };
  131770. static static_codebook _huff_book__44c6_s_long = {
  131771. 2, 100,
  131772. _huff_lengthlist__44c6_s_long,
  131773. 0, 0, 0, 0, 0,
  131774. NULL,
  131775. NULL,
  131776. NULL,
  131777. NULL,
  131778. 0
  131779. };
  131780. static long _vq_quantlist__44c6_s_p1_0[] = {
  131781. 1,
  131782. 0,
  131783. 2,
  131784. };
  131785. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131786. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131787. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131789. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131790. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131791. 8,
  131792. };
  131793. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131794. -0.5, 0.5,
  131795. };
  131796. static long _vq_quantmap__44c6_s_p1_0[] = {
  131797. 1, 0, 2,
  131798. };
  131799. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131800. _vq_quantthresh__44c6_s_p1_0,
  131801. _vq_quantmap__44c6_s_p1_0,
  131802. 3,
  131803. 3
  131804. };
  131805. static static_codebook _44c6_s_p1_0 = {
  131806. 4, 81,
  131807. _vq_lengthlist__44c6_s_p1_0,
  131808. 1, -535822336, 1611661312, 2, 0,
  131809. _vq_quantlist__44c6_s_p1_0,
  131810. NULL,
  131811. &_vq_auxt__44c6_s_p1_0,
  131812. NULL,
  131813. 0
  131814. };
  131815. static long _vq_quantlist__44c6_s_p2_0[] = {
  131816. 2,
  131817. 1,
  131818. 3,
  131819. 0,
  131820. 4,
  131821. };
  131822. static long _vq_lengthlist__44c6_s_p2_0[] = {
  131823. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131824. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131825. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131826. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  131827. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  131828. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  131829. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  131830. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131833. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  131834. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131835. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  131836. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  131837. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  131838. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  131839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131840. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  131841. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  131842. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  131843. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  131844. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  131845. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  131846. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131848. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  131849. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  131850. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131851. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  131852. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  131853. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  131854. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131859. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  131860. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  131861. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  131862. 13,
  131863. };
  131864. static float _vq_quantthresh__44c6_s_p2_0[] = {
  131865. -1.5, -0.5, 0.5, 1.5,
  131866. };
  131867. static long _vq_quantmap__44c6_s_p2_0[] = {
  131868. 3, 1, 0, 2, 4,
  131869. };
  131870. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  131871. _vq_quantthresh__44c6_s_p2_0,
  131872. _vq_quantmap__44c6_s_p2_0,
  131873. 5,
  131874. 5
  131875. };
  131876. static static_codebook _44c6_s_p2_0 = {
  131877. 4, 625,
  131878. _vq_lengthlist__44c6_s_p2_0,
  131879. 1, -533725184, 1611661312, 3, 0,
  131880. _vq_quantlist__44c6_s_p2_0,
  131881. NULL,
  131882. &_vq_auxt__44c6_s_p2_0,
  131883. NULL,
  131884. 0
  131885. };
  131886. static long _vq_quantlist__44c6_s_p3_0[] = {
  131887. 4,
  131888. 3,
  131889. 5,
  131890. 2,
  131891. 6,
  131892. 1,
  131893. 7,
  131894. 0,
  131895. 8,
  131896. };
  131897. static long _vq_lengthlist__44c6_s_p3_0[] = {
  131898. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131899. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  131900. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  131901. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  131902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131903. 0,
  131904. };
  131905. static float _vq_quantthresh__44c6_s_p3_0[] = {
  131906. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131907. };
  131908. static long _vq_quantmap__44c6_s_p3_0[] = {
  131909. 7, 5, 3, 1, 0, 2, 4, 6,
  131910. 8,
  131911. };
  131912. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  131913. _vq_quantthresh__44c6_s_p3_0,
  131914. _vq_quantmap__44c6_s_p3_0,
  131915. 9,
  131916. 9
  131917. };
  131918. static static_codebook _44c6_s_p3_0 = {
  131919. 2, 81,
  131920. _vq_lengthlist__44c6_s_p3_0,
  131921. 1, -531628032, 1611661312, 4, 0,
  131922. _vq_quantlist__44c6_s_p3_0,
  131923. NULL,
  131924. &_vq_auxt__44c6_s_p3_0,
  131925. NULL,
  131926. 0
  131927. };
  131928. static long _vq_quantlist__44c6_s_p4_0[] = {
  131929. 8,
  131930. 7,
  131931. 9,
  131932. 6,
  131933. 10,
  131934. 5,
  131935. 11,
  131936. 4,
  131937. 12,
  131938. 3,
  131939. 13,
  131940. 2,
  131941. 14,
  131942. 1,
  131943. 15,
  131944. 0,
  131945. 16,
  131946. };
  131947. static long _vq_lengthlist__44c6_s_p4_0[] = {
  131948. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  131949. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131950. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  131951. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131952. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131953. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131954. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  131955. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131956. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  131957. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0,
  131967. };
  131968. static float _vq_quantthresh__44c6_s_p4_0[] = {
  131969. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131970. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131971. };
  131972. static long _vq_quantmap__44c6_s_p4_0[] = {
  131973. 15, 13, 11, 9, 7, 5, 3, 1,
  131974. 0, 2, 4, 6, 8, 10, 12, 14,
  131975. 16,
  131976. };
  131977. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  131978. _vq_quantthresh__44c6_s_p4_0,
  131979. _vq_quantmap__44c6_s_p4_0,
  131980. 17,
  131981. 17
  131982. };
  131983. static static_codebook _44c6_s_p4_0 = {
  131984. 2, 289,
  131985. _vq_lengthlist__44c6_s_p4_0,
  131986. 1, -529530880, 1611661312, 5, 0,
  131987. _vq_quantlist__44c6_s_p4_0,
  131988. NULL,
  131989. &_vq_auxt__44c6_s_p4_0,
  131990. NULL,
  131991. 0
  131992. };
  131993. static long _vq_quantlist__44c6_s_p5_0[] = {
  131994. 1,
  131995. 0,
  131996. 2,
  131997. };
  131998. static long _vq_lengthlist__44c6_s_p5_0[] = {
  131999. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132000. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132001. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132002. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132003. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132004. 12,
  132005. };
  132006. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132007. -5.5, 5.5,
  132008. };
  132009. static long _vq_quantmap__44c6_s_p5_0[] = {
  132010. 1, 0, 2,
  132011. };
  132012. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132013. _vq_quantthresh__44c6_s_p5_0,
  132014. _vq_quantmap__44c6_s_p5_0,
  132015. 3,
  132016. 3
  132017. };
  132018. static static_codebook _44c6_s_p5_0 = {
  132019. 4, 81,
  132020. _vq_lengthlist__44c6_s_p5_0,
  132021. 1, -529137664, 1618345984, 2, 0,
  132022. _vq_quantlist__44c6_s_p5_0,
  132023. NULL,
  132024. &_vq_auxt__44c6_s_p5_0,
  132025. NULL,
  132026. 0
  132027. };
  132028. static long _vq_quantlist__44c6_s_p5_1[] = {
  132029. 5,
  132030. 4,
  132031. 6,
  132032. 3,
  132033. 7,
  132034. 2,
  132035. 8,
  132036. 1,
  132037. 9,
  132038. 0,
  132039. 10,
  132040. };
  132041. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132042. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132043. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132044. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132045. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132046. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132047. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132048. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132049. 11,10,10, 7, 7, 8, 8, 8, 8,
  132050. };
  132051. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132052. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132053. 3.5, 4.5,
  132054. };
  132055. static long _vq_quantmap__44c6_s_p5_1[] = {
  132056. 9, 7, 5, 3, 1, 0, 2, 4,
  132057. 6, 8, 10,
  132058. };
  132059. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132060. _vq_quantthresh__44c6_s_p5_1,
  132061. _vq_quantmap__44c6_s_p5_1,
  132062. 11,
  132063. 11
  132064. };
  132065. static static_codebook _44c6_s_p5_1 = {
  132066. 2, 121,
  132067. _vq_lengthlist__44c6_s_p5_1,
  132068. 1, -531365888, 1611661312, 4, 0,
  132069. _vq_quantlist__44c6_s_p5_1,
  132070. NULL,
  132071. &_vq_auxt__44c6_s_p5_1,
  132072. NULL,
  132073. 0
  132074. };
  132075. static long _vq_quantlist__44c6_s_p6_0[] = {
  132076. 6,
  132077. 5,
  132078. 7,
  132079. 4,
  132080. 8,
  132081. 3,
  132082. 9,
  132083. 2,
  132084. 10,
  132085. 1,
  132086. 11,
  132087. 0,
  132088. 12,
  132089. };
  132090. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132091. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132092. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132093. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132094. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132095. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132096. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132101. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132102. };
  132103. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132104. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132105. 12.5, 17.5, 22.5, 27.5,
  132106. };
  132107. static long _vq_quantmap__44c6_s_p6_0[] = {
  132108. 11, 9, 7, 5, 3, 1, 0, 2,
  132109. 4, 6, 8, 10, 12,
  132110. };
  132111. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132112. _vq_quantthresh__44c6_s_p6_0,
  132113. _vq_quantmap__44c6_s_p6_0,
  132114. 13,
  132115. 13
  132116. };
  132117. static static_codebook _44c6_s_p6_0 = {
  132118. 2, 169,
  132119. _vq_lengthlist__44c6_s_p6_0,
  132120. 1, -526516224, 1616117760, 4, 0,
  132121. _vq_quantlist__44c6_s_p6_0,
  132122. NULL,
  132123. &_vq_auxt__44c6_s_p6_0,
  132124. NULL,
  132125. 0
  132126. };
  132127. static long _vq_quantlist__44c6_s_p6_1[] = {
  132128. 2,
  132129. 1,
  132130. 3,
  132131. 0,
  132132. 4,
  132133. };
  132134. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132135. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132136. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132137. };
  132138. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132139. -1.5, -0.5, 0.5, 1.5,
  132140. };
  132141. static long _vq_quantmap__44c6_s_p6_1[] = {
  132142. 3, 1, 0, 2, 4,
  132143. };
  132144. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132145. _vq_quantthresh__44c6_s_p6_1,
  132146. _vq_quantmap__44c6_s_p6_1,
  132147. 5,
  132148. 5
  132149. };
  132150. static static_codebook _44c6_s_p6_1 = {
  132151. 2, 25,
  132152. _vq_lengthlist__44c6_s_p6_1,
  132153. 1, -533725184, 1611661312, 3, 0,
  132154. _vq_quantlist__44c6_s_p6_1,
  132155. NULL,
  132156. &_vq_auxt__44c6_s_p6_1,
  132157. NULL,
  132158. 0
  132159. };
  132160. static long _vq_quantlist__44c6_s_p7_0[] = {
  132161. 6,
  132162. 5,
  132163. 7,
  132164. 4,
  132165. 8,
  132166. 3,
  132167. 9,
  132168. 2,
  132169. 10,
  132170. 1,
  132171. 11,
  132172. 0,
  132173. 12,
  132174. };
  132175. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132176. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132177. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132178. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132179. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132180. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132181. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132182. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132183. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132184. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132185. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132186. 20,13,13,13,13,13,13,14,14,
  132187. };
  132188. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132189. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132190. 27.5, 38.5, 49.5, 60.5,
  132191. };
  132192. static long _vq_quantmap__44c6_s_p7_0[] = {
  132193. 11, 9, 7, 5, 3, 1, 0, 2,
  132194. 4, 6, 8, 10, 12,
  132195. };
  132196. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132197. _vq_quantthresh__44c6_s_p7_0,
  132198. _vq_quantmap__44c6_s_p7_0,
  132199. 13,
  132200. 13
  132201. };
  132202. static static_codebook _44c6_s_p7_0 = {
  132203. 2, 169,
  132204. _vq_lengthlist__44c6_s_p7_0,
  132205. 1, -523206656, 1618345984, 4, 0,
  132206. _vq_quantlist__44c6_s_p7_0,
  132207. NULL,
  132208. &_vq_auxt__44c6_s_p7_0,
  132209. NULL,
  132210. 0
  132211. };
  132212. static long _vq_quantlist__44c6_s_p7_1[] = {
  132213. 5,
  132214. 4,
  132215. 6,
  132216. 3,
  132217. 7,
  132218. 2,
  132219. 8,
  132220. 1,
  132221. 9,
  132222. 0,
  132223. 10,
  132224. };
  132225. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132226. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132227. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132228. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132229. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132230. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132231. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132232. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132233. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132234. };
  132235. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132236. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132237. 3.5, 4.5,
  132238. };
  132239. static long _vq_quantmap__44c6_s_p7_1[] = {
  132240. 9, 7, 5, 3, 1, 0, 2, 4,
  132241. 6, 8, 10,
  132242. };
  132243. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132244. _vq_quantthresh__44c6_s_p7_1,
  132245. _vq_quantmap__44c6_s_p7_1,
  132246. 11,
  132247. 11
  132248. };
  132249. static static_codebook _44c6_s_p7_1 = {
  132250. 2, 121,
  132251. _vq_lengthlist__44c6_s_p7_1,
  132252. 1, -531365888, 1611661312, 4, 0,
  132253. _vq_quantlist__44c6_s_p7_1,
  132254. NULL,
  132255. &_vq_auxt__44c6_s_p7_1,
  132256. NULL,
  132257. 0
  132258. };
  132259. static long _vq_quantlist__44c6_s_p8_0[] = {
  132260. 7,
  132261. 6,
  132262. 8,
  132263. 5,
  132264. 9,
  132265. 4,
  132266. 10,
  132267. 3,
  132268. 11,
  132269. 2,
  132270. 12,
  132271. 1,
  132272. 13,
  132273. 0,
  132274. 14,
  132275. };
  132276. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132277. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132278. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132279. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132280. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132281. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132282. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132283. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132284. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132285. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132286. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132287. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132288. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132289. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132290. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132291. 14,
  132292. };
  132293. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132294. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132295. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132296. };
  132297. static long _vq_quantmap__44c6_s_p8_0[] = {
  132298. 13, 11, 9, 7, 5, 3, 1, 0,
  132299. 2, 4, 6, 8, 10, 12, 14,
  132300. };
  132301. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132302. _vq_quantthresh__44c6_s_p8_0,
  132303. _vq_quantmap__44c6_s_p8_0,
  132304. 15,
  132305. 15
  132306. };
  132307. static static_codebook _44c6_s_p8_0 = {
  132308. 2, 225,
  132309. _vq_lengthlist__44c6_s_p8_0,
  132310. 1, -520986624, 1620377600, 4, 0,
  132311. _vq_quantlist__44c6_s_p8_0,
  132312. NULL,
  132313. &_vq_auxt__44c6_s_p8_0,
  132314. NULL,
  132315. 0
  132316. };
  132317. static long _vq_quantlist__44c6_s_p8_1[] = {
  132318. 10,
  132319. 9,
  132320. 11,
  132321. 8,
  132322. 12,
  132323. 7,
  132324. 13,
  132325. 6,
  132326. 14,
  132327. 5,
  132328. 15,
  132329. 4,
  132330. 16,
  132331. 3,
  132332. 17,
  132333. 2,
  132334. 18,
  132335. 1,
  132336. 19,
  132337. 0,
  132338. 20,
  132339. };
  132340. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132341. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132342. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132343. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132344. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132345. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132346. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132347. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132348. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132349. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132350. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132351. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132352. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132353. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132354. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132355. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132356. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132357. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132358. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132359. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132360. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132361. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132362. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132363. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132364. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132365. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132366. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132367. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132368. 10,10,10,10,10,10,10,10,10,
  132369. };
  132370. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132371. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132372. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132373. 6.5, 7.5, 8.5, 9.5,
  132374. };
  132375. static long _vq_quantmap__44c6_s_p8_1[] = {
  132376. 19, 17, 15, 13, 11, 9, 7, 5,
  132377. 3, 1, 0, 2, 4, 6, 8, 10,
  132378. 12, 14, 16, 18, 20,
  132379. };
  132380. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132381. _vq_quantthresh__44c6_s_p8_1,
  132382. _vq_quantmap__44c6_s_p8_1,
  132383. 21,
  132384. 21
  132385. };
  132386. static static_codebook _44c6_s_p8_1 = {
  132387. 2, 441,
  132388. _vq_lengthlist__44c6_s_p8_1,
  132389. 1, -529268736, 1611661312, 5, 0,
  132390. _vq_quantlist__44c6_s_p8_1,
  132391. NULL,
  132392. &_vq_auxt__44c6_s_p8_1,
  132393. NULL,
  132394. 0
  132395. };
  132396. static long _vq_quantlist__44c6_s_p9_0[] = {
  132397. 6,
  132398. 5,
  132399. 7,
  132400. 4,
  132401. 8,
  132402. 3,
  132403. 9,
  132404. 2,
  132405. 10,
  132406. 1,
  132407. 11,
  132408. 0,
  132409. 12,
  132410. };
  132411. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132412. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132413. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132414. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132415. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132417. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132418. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132419. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132420. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132421. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132422. 10,10,10,10,10,10,10,10,10,
  132423. };
  132424. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132425. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132426. 1592.5, 2229.5, 2866.5, 3503.5,
  132427. };
  132428. static long _vq_quantmap__44c6_s_p9_0[] = {
  132429. 11, 9, 7, 5, 3, 1, 0, 2,
  132430. 4, 6, 8, 10, 12,
  132431. };
  132432. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132433. _vq_quantthresh__44c6_s_p9_0,
  132434. _vq_quantmap__44c6_s_p9_0,
  132435. 13,
  132436. 13
  132437. };
  132438. static static_codebook _44c6_s_p9_0 = {
  132439. 2, 169,
  132440. _vq_lengthlist__44c6_s_p9_0,
  132441. 1, -511845376, 1630791680, 4, 0,
  132442. _vq_quantlist__44c6_s_p9_0,
  132443. NULL,
  132444. &_vq_auxt__44c6_s_p9_0,
  132445. NULL,
  132446. 0
  132447. };
  132448. static long _vq_quantlist__44c6_s_p9_1[] = {
  132449. 6,
  132450. 5,
  132451. 7,
  132452. 4,
  132453. 8,
  132454. 3,
  132455. 9,
  132456. 2,
  132457. 10,
  132458. 1,
  132459. 11,
  132460. 0,
  132461. 12,
  132462. };
  132463. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132464. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132465. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132466. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132467. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132468. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132469. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132470. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132471. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132472. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132473. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132474. 15,12,10,11,11,13,11,12,13,
  132475. };
  132476. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132477. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132478. 122.5, 171.5, 220.5, 269.5,
  132479. };
  132480. static long _vq_quantmap__44c6_s_p9_1[] = {
  132481. 11, 9, 7, 5, 3, 1, 0, 2,
  132482. 4, 6, 8, 10, 12,
  132483. };
  132484. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132485. _vq_quantthresh__44c6_s_p9_1,
  132486. _vq_quantmap__44c6_s_p9_1,
  132487. 13,
  132488. 13
  132489. };
  132490. static static_codebook _44c6_s_p9_1 = {
  132491. 2, 169,
  132492. _vq_lengthlist__44c6_s_p9_1,
  132493. 1, -518889472, 1622704128, 4, 0,
  132494. _vq_quantlist__44c6_s_p9_1,
  132495. NULL,
  132496. &_vq_auxt__44c6_s_p9_1,
  132497. NULL,
  132498. 0
  132499. };
  132500. static long _vq_quantlist__44c6_s_p9_2[] = {
  132501. 24,
  132502. 23,
  132503. 25,
  132504. 22,
  132505. 26,
  132506. 21,
  132507. 27,
  132508. 20,
  132509. 28,
  132510. 19,
  132511. 29,
  132512. 18,
  132513. 30,
  132514. 17,
  132515. 31,
  132516. 16,
  132517. 32,
  132518. 15,
  132519. 33,
  132520. 14,
  132521. 34,
  132522. 13,
  132523. 35,
  132524. 12,
  132525. 36,
  132526. 11,
  132527. 37,
  132528. 10,
  132529. 38,
  132530. 9,
  132531. 39,
  132532. 8,
  132533. 40,
  132534. 7,
  132535. 41,
  132536. 6,
  132537. 42,
  132538. 5,
  132539. 43,
  132540. 4,
  132541. 44,
  132542. 3,
  132543. 45,
  132544. 2,
  132545. 46,
  132546. 1,
  132547. 47,
  132548. 0,
  132549. 48,
  132550. };
  132551. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132552. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132553. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132554. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132555. 7,
  132556. };
  132557. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132558. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132559. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132560. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132561. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132562. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132563. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132564. };
  132565. static long _vq_quantmap__44c6_s_p9_2[] = {
  132566. 47, 45, 43, 41, 39, 37, 35, 33,
  132567. 31, 29, 27, 25, 23, 21, 19, 17,
  132568. 15, 13, 11, 9, 7, 5, 3, 1,
  132569. 0, 2, 4, 6, 8, 10, 12, 14,
  132570. 16, 18, 20, 22, 24, 26, 28, 30,
  132571. 32, 34, 36, 38, 40, 42, 44, 46,
  132572. 48,
  132573. };
  132574. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132575. _vq_quantthresh__44c6_s_p9_2,
  132576. _vq_quantmap__44c6_s_p9_2,
  132577. 49,
  132578. 49
  132579. };
  132580. static static_codebook _44c6_s_p9_2 = {
  132581. 1, 49,
  132582. _vq_lengthlist__44c6_s_p9_2,
  132583. 1, -526909440, 1611661312, 6, 0,
  132584. _vq_quantlist__44c6_s_p9_2,
  132585. NULL,
  132586. &_vq_auxt__44c6_s_p9_2,
  132587. NULL,
  132588. 0
  132589. };
  132590. static long _huff_lengthlist__44c6_s_short[] = {
  132591. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132592. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132593. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132594. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132595. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132596. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132597. 9,10,17,18,
  132598. };
  132599. static static_codebook _huff_book__44c6_s_short = {
  132600. 2, 100,
  132601. _huff_lengthlist__44c6_s_short,
  132602. 0, 0, 0, 0, 0,
  132603. NULL,
  132604. NULL,
  132605. NULL,
  132606. NULL,
  132607. 0
  132608. };
  132609. static long _huff_lengthlist__44c7_s_long[] = {
  132610. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132611. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132612. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132613. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132614. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132615. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132616. 11,10,10,12,
  132617. };
  132618. static static_codebook _huff_book__44c7_s_long = {
  132619. 2, 100,
  132620. _huff_lengthlist__44c7_s_long,
  132621. 0, 0, 0, 0, 0,
  132622. NULL,
  132623. NULL,
  132624. NULL,
  132625. NULL,
  132626. 0
  132627. };
  132628. static long _vq_quantlist__44c7_s_p1_0[] = {
  132629. 1,
  132630. 0,
  132631. 2,
  132632. };
  132633. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132634. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132635. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132636. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132637. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132638. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132639. 8,
  132640. };
  132641. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132642. -0.5, 0.5,
  132643. };
  132644. static long _vq_quantmap__44c7_s_p1_0[] = {
  132645. 1, 0, 2,
  132646. };
  132647. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132648. _vq_quantthresh__44c7_s_p1_0,
  132649. _vq_quantmap__44c7_s_p1_0,
  132650. 3,
  132651. 3
  132652. };
  132653. static static_codebook _44c7_s_p1_0 = {
  132654. 4, 81,
  132655. _vq_lengthlist__44c7_s_p1_0,
  132656. 1, -535822336, 1611661312, 2, 0,
  132657. _vq_quantlist__44c7_s_p1_0,
  132658. NULL,
  132659. &_vq_auxt__44c7_s_p1_0,
  132660. NULL,
  132661. 0
  132662. };
  132663. static long _vq_quantlist__44c7_s_p2_0[] = {
  132664. 2,
  132665. 1,
  132666. 3,
  132667. 0,
  132668. 4,
  132669. };
  132670. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132671. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132672. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132673. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132674. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132675. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132676. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132677. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132678. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132680. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132681. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132682. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132683. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132684. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132685. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132686. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132688. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132689. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132690. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132691. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132692. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132693. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132694. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132696. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132697. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132698. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132699. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132700. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132701. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132702. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132707. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132708. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132709. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132710. 13,
  132711. };
  132712. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132713. -1.5, -0.5, 0.5, 1.5,
  132714. };
  132715. static long _vq_quantmap__44c7_s_p2_0[] = {
  132716. 3, 1, 0, 2, 4,
  132717. };
  132718. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132719. _vq_quantthresh__44c7_s_p2_0,
  132720. _vq_quantmap__44c7_s_p2_0,
  132721. 5,
  132722. 5
  132723. };
  132724. static static_codebook _44c7_s_p2_0 = {
  132725. 4, 625,
  132726. _vq_lengthlist__44c7_s_p2_0,
  132727. 1, -533725184, 1611661312, 3, 0,
  132728. _vq_quantlist__44c7_s_p2_0,
  132729. NULL,
  132730. &_vq_auxt__44c7_s_p2_0,
  132731. NULL,
  132732. 0
  132733. };
  132734. static long _vq_quantlist__44c7_s_p3_0[] = {
  132735. 4,
  132736. 3,
  132737. 5,
  132738. 2,
  132739. 6,
  132740. 1,
  132741. 7,
  132742. 0,
  132743. 8,
  132744. };
  132745. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132746. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132747. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132748. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132749. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132751. 0,
  132752. };
  132753. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132754. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132755. };
  132756. static long _vq_quantmap__44c7_s_p3_0[] = {
  132757. 7, 5, 3, 1, 0, 2, 4, 6,
  132758. 8,
  132759. };
  132760. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132761. _vq_quantthresh__44c7_s_p3_0,
  132762. _vq_quantmap__44c7_s_p3_0,
  132763. 9,
  132764. 9
  132765. };
  132766. static static_codebook _44c7_s_p3_0 = {
  132767. 2, 81,
  132768. _vq_lengthlist__44c7_s_p3_0,
  132769. 1, -531628032, 1611661312, 4, 0,
  132770. _vq_quantlist__44c7_s_p3_0,
  132771. NULL,
  132772. &_vq_auxt__44c7_s_p3_0,
  132773. NULL,
  132774. 0
  132775. };
  132776. static long _vq_quantlist__44c7_s_p4_0[] = {
  132777. 8,
  132778. 7,
  132779. 9,
  132780. 6,
  132781. 10,
  132782. 5,
  132783. 11,
  132784. 4,
  132785. 12,
  132786. 3,
  132787. 13,
  132788. 2,
  132789. 14,
  132790. 1,
  132791. 15,
  132792. 0,
  132793. 16,
  132794. };
  132795. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132796. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132797. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132798. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132799. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132800. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132801. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132802. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132803. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132804. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132805. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  132806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132814. 0,
  132815. };
  132816. static float _vq_quantthresh__44c7_s_p4_0[] = {
  132817. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132818. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132819. };
  132820. static long _vq_quantmap__44c7_s_p4_0[] = {
  132821. 15, 13, 11, 9, 7, 5, 3, 1,
  132822. 0, 2, 4, 6, 8, 10, 12, 14,
  132823. 16,
  132824. };
  132825. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  132826. _vq_quantthresh__44c7_s_p4_0,
  132827. _vq_quantmap__44c7_s_p4_0,
  132828. 17,
  132829. 17
  132830. };
  132831. static static_codebook _44c7_s_p4_0 = {
  132832. 2, 289,
  132833. _vq_lengthlist__44c7_s_p4_0,
  132834. 1, -529530880, 1611661312, 5, 0,
  132835. _vq_quantlist__44c7_s_p4_0,
  132836. NULL,
  132837. &_vq_auxt__44c7_s_p4_0,
  132838. NULL,
  132839. 0
  132840. };
  132841. static long _vq_quantlist__44c7_s_p5_0[] = {
  132842. 1,
  132843. 0,
  132844. 2,
  132845. };
  132846. static long _vq_lengthlist__44c7_s_p5_0[] = {
  132847. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  132848. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  132849. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  132850. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132851. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  132852. 12,
  132853. };
  132854. static float _vq_quantthresh__44c7_s_p5_0[] = {
  132855. -5.5, 5.5,
  132856. };
  132857. static long _vq_quantmap__44c7_s_p5_0[] = {
  132858. 1, 0, 2,
  132859. };
  132860. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  132861. _vq_quantthresh__44c7_s_p5_0,
  132862. _vq_quantmap__44c7_s_p5_0,
  132863. 3,
  132864. 3
  132865. };
  132866. static static_codebook _44c7_s_p5_0 = {
  132867. 4, 81,
  132868. _vq_lengthlist__44c7_s_p5_0,
  132869. 1, -529137664, 1618345984, 2, 0,
  132870. _vq_quantlist__44c7_s_p5_0,
  132871. NULL,
  132872. &_vq_auxt__44c7_s_p5_0,
  132873. NULL,
  132874. 0
  132875. };
  132876. static long _vq_quantlist__44c7_s_p5_1[] = {
  132877. 5,
  132878. 4,
  132879. 6,
  132880. 3,
  132881. 7,
  132882. 2,
  132883. 8,
  132884. 1,
  132885. 9,
  132886. 0,
  132887. 10,
  132888. };
  132889. static long _vq_lengthlist__44c7_s_p5_1[] = {
  132890. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132891. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  132892. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  132893. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  132894. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  132895. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  132896. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  132897. 11,11,11, 7, 7, 8, 8, 8, 8,
  132898. };
  132899. static float _vq_quantthresh__44c7_s_p5_1[] = {
  132900. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132901. 3.5, 4.5,
  132902. };
  132903. static long _vq_quantmap__44c7_s_p5_1[] = {
  132904. 9, 7, 5, 3, 1, 0, 2, 4,
  132905. 6, 8, 10,
  132906. };
  132907. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  132908. _vq_quantthresh__44c7_s_p5_1,
  132909. _vq_quantmap__44c7_s_p5_1,
  132910. 11,
  132911. 11
  132912. };
  132913. static static_codebook _44c7_s_p5_1 = {
  132914. 2, 121,
  132915. _vq_lengthlist__44c7_s_p5_1,
  132916. 1, -531365888, 1611661312, 4, 0,
  132917. _vq_quantlist__44c7_s_p5_1,
  132918. NULL,
  132919. &_vq_auxt__44c7_s_p5_1,
  132920. NULL,
  132921. 0
  132922. };
  132923. static long _vq_quantlist__44c7_s_p6_0[] = {
  132924. 6,
  132925. 5,
  132926. 7,
  132927. 4,
  132928. 8,
  132929. 3,
  132930. 9,
  132931. 2,
  132932. 10,
  132933. 1,
  132934. 11,
  132935. 0,
  132936. 12,
  132937. };
  132938. static long _vq_lengthlist__44c7_s_p6_0[] = {
  132939. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  132940. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  132941. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  132942. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  132943. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  132944. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  132945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132946. 0, 0, 0, 0, 0, 0, 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,
  132950. };
  132951. static float _vq_quantthresh__44c7_s_p6_0[] = {
  132952. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132953. 12.5, 17.5, 22.5, 27.5,
  132954. };
  132955. static long _vq_quantmap__44c7_s_p6_0[] = {
  132956. 11, 9, 7, 5, 3, 1, 0, 2,
  132957. 4, 6, 8, 10, 12,
  132958. };
  132959. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  132960. _vq_quantthresh__44c7_s_p6_0,
  132961. _vq_quantmap__44c7_s_p6_0,
  132962. 13,
  132963. 13
  132964. };
  132965. static static_codebook _44c7_s_p6_0 = {
  132966. 2, 169,
  132967. _vq_lengthlist__44c7_s_p6_0,
  132968. 1, -526516224, 1616117760, 4, 0,
  132969. _vq_quantlist__44c7_s_p6_0,
  132970. NULL,
  132971. &_vq_auxt__44c7_s_p6_0,
  132972. NULL,
  132973. 0
  132974. };
  132975. static long _vq_quantlist__44c7_s_p6_1[] = {
  132976. 2,
  132977. 1,
  132978. 3,
  132979. 0,
  132980. 4,
  132981. };
  132982. static long _vq_lengthlist__44c7_s_p6_1[] = {
  132983. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132984. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132985. };
  132986. static float _vq_quantthresh__44c7_s_p6_1[] = {
  132987. -1.5, -0.5, 0.5, 1.5,
  132988. };
  132989. static long _vq_quantmap__44c7_s_p6_1[] = {
  132990. 3, 1, 0, 2, 4,
  132991. };
  132992. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  132993. _vq_quantthresh__44c7_s_p6_1,
  132994. _vq_quantmap__44c7_s_p6_1,
  132995. 5,
  132996. 5
  132997. };
  132998. static static_codebook _44c7_s_p6_1 = {
  132999. 2, 25,
  133000. _vq_lengthlist__44c7_s_p6_1,
  133001. 1, -533725184, 1611661312, 3, 0,
  133002. _vq_quantlist__44c7_s_p6_1,
  133003. NULL,
  133004. &_vq_auxt__44c7_s_p6_1,
  133005. NULL,
  133006. 0
  133007. };
  133008. static long _vq_quantlist__44c7_s_p7_0[] = {
  133009. 6,
  133010. 5,
  133011. 7,
  133012. 4,
  133013. 8,
  133014. 3,
  133015. 9,
  133016. 2,
  133017. 10,
  133018. 1,
  133019. 11,
  133020. 0,
  133021. 12,
  133022. };
  133023. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133024. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133025. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133026. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133027. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133028. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133029. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133030. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133031. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133032. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133033. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133034. 19,13,13,13,13,14,14,15,15,
  133035. };
  133036. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133037. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133038. 27.5, 38.5, 49.5, 60.5,
  133039. };
  133040. static long _vq_quantmap__44c7_s_p7_0[] = {
  133041. 11, 9, 7, 5, 3, 1, 0, 2,
  133042. 4, 6, 8, 10, 12,
  133043. };
  133044. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133045. _vq_quantthresh__44c7_s_p7_0,
  133046. _vq_quantmap__44c7_s_p7_0,
  133047. 13,
  133048. 13
  133049. };
  133050. static static_codebook _44c7_s_p7_0 = {
  133051. 2, 169,
  133052. _vq_lengthlist__44c7_s_p7_0,
  133053. 1, -523206656, 1618345984, 4, 0,
  133054. _vq_quantlist__44c7_s_p7_0,
  133055. NULL,
  133056. &_vq_auxt__44c7_s_p7_0,
  133057. NULL,
  133058. 0
  133059. };
  133060. static long _vq_quantlist__44c7_s_p7_1[] = {
  133061. 5,
  133062. 4,
  133063. 6,
  133064. 3,
  133065. 7,
  133066. 2,
  133067. 8,
  133068. 1,
  133069. 9,
  133070. 0,
  133071. 10,
  133072. };
  133073. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133074. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133075. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133076. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133077. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133078. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133079. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133080. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133081. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133082. };
  133083. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133084. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133085. 3.5, 4.5,
  133086. };
  133087. static long _vq_quantmap__44c7_s_p7_1[] = {
  133088. 9, 7, 5, 3, 1, 0, 2, 4,
  133089. 6, 8, 10,
  133090. };
  133091. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133092. _vq_quantthresh__44c7_s_p7_1,
  133093. _vq_quantmap__44c7_s_p7_1,
  133094. 11,
  133095. 11
  133096. };
  133097. static static_codebook _44c7_s_p7_1 = {
  133098. 2, 121,
  133099. _vq_lengthlist__44c7_s_p7_1,
  133100. 1, -531365888, 1611661312, 4, 0,
  133101. _vq_quantlist__44c7_s_p7_1,
  133102. NULL,
  133103. &_vq_auxt__44c7_s_p7_1,
  133104. NULL,
  133105. 0
  133106. };
  133107. static long _vq_quantlist__44c7_s_p8_0[] = {
  133108. 7,
  133109. 6,
  133110. 8,
  133111. 5,
  133112. 9,
  133113. 4,
  133114. 10,
  133115. 3,
  133116. 11,
  133117. 2,
  133118. 12,
  133119. 1,
  133120. 13,
  133121. 0,
  133122. 14,
  133123. };
  133124. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133125. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133126. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133127. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133128. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133129. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133130. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133131. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133132. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133133. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133134. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133135. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133136. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133137. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133138. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133139. 14,
  133140. };
  133141. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133142. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133143. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133144. };
  133145. static long _vq_quantmap__44c7_s_p8_0[] = {
  133146. 13, 11, 9, 7, 5, 3, 1, 0,
  133147. 2, 4, 6, 8, 10, 12, 14,
  133148. };
  133149. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133150. _vq_quantthresh__44c7_s_p8_0,
  133151. _vq_quantmap__44c7_s_p8_0,
  133152. 15,
  133153. 15
  133154. };
  133155. static static_codebook _44c7_s_p8_0 = {
  133156. 2, 225,
  133157. _vq_lengthlist__44c7_s_p8_0,
  133158. 1, -520986624, 1620377600, 4, 0,
  133159. _vq_quantlist__44c7_s_p8_0,
  133160. NULL,
  133161. &_vq_auxt__44c7_s_p8_0,
  133162. NULL,
  133163. 0
  133164. };
  133165. static long _vq_quantlist__44c7_s_p8_1[] = {
  133166. 10,
  133167. 9,
  133168. 11,
  133169. 8,
  133170. 12,
  133171. 7,
  133172. 13,
  133173. 6,
  133174. 14,
  133175. 5,
  133176. 15,
  133177. 4,
  133178. 16,
  133179. 3,
  133180. 17,
  133181. 2,
  133182. 18,
  133183. 1,
  133184. 19,
  133185. 0,
  133186. 20,
  133187. };
  133188. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133189. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133190. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133191. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133192. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133193. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133194. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133195. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133196. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133197. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133198. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133199. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133200. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133201. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133202. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133203. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133204. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133205. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133206. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133207. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133208. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133209. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133210. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133211. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133212. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133213. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133214. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133215. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133216. 10,10,10,10,10,10,10,10,10,
  133217. };
  133218. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133219. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133220. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133221. 6.5, 7.5, 8.5, 9.5,
  133222. };
  133223. static long _vq_quantmap__44c7_s_p8_1[] = {
  133224. 19, 17, 15, 13, 11, 9, 7, 5,
  133225. 3, 1, 0, 2, 4, 6, 8, 10,
  133226. 12, 14, 16, 18, 20,
  133227. };
  133228. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133229. _vq_quantthresh__44c7_s_p8_1,
  133230. _vq_quantmap__44c7_s_p8_1,
  133231. 21,
  133232. 21
  133233. };
  133234. static static_codebook _44c7_s_p8_1 = {
  133235. 2, 441,
  133236. _vq_lengthlist__44c7_s_p8_1,
  133237. 1, -529268736, 1611661312, 5, 0,
  133238. _vq_quantlist__44c7_s_p8_1,
  133239. NULL,
  133240. &_vq_auxt__44c7_s_p8_1,
  133241. NULL,
  133242. 0
  133243. };
  133244. static long _vq_quantlist__44c7_s_p9_0[] = {
  133245. 6,
  133246. 5,
  133247. 7,
  133248. 4,
  133249. 8,
  133250. 3,
  133251. 9,
  133252. 2,
  133253. 10,
  133254. 1,
  133255. 11,
  133256. 0,
  133257. 12,
  133258. };
  133259. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133260. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133261. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133270. 11,11,11,11,11,11,11,11,11,
  133271. };
  133272. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133273. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133274. 1592.5, 2229.5, 2866.5, 3503.5,
  133275. };
  133276. static long _vq_quantmap__44c7_s_p9_0[] = {
  133277. 11, 9, 7, 5, 3, 1, 0, 2,
  133278. 4, 6, 8, 10, 12,
  133279. };
  133280. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133281. _vq_quantthresh__44c7_s_p9_0,
  133282. _vq_quantmap__44c7_s_p9_0,
  133283. 13,
  133284. 13
  133285. };
  133286. static static_codebook _44c7_s_p9_0 = {
  133287. 2, 169,
  133288. _vq_lengthlist__44c7_s_p9_0,
  133289. 1, -511845376, 1630791680, 4, 0,
  133290. _vq_quantlist__44c7_s_p9_0,
  133291. NULL,
  133292. &_vq_auxt__44c7_s_p9_0,
  133293. NULL,
  133294. 0
  133295. };
  133296. static long _vq_quantlist__44c7_s_p9_1[] = {
  133297. 6,
  133298. 5,
  133299. 7,
  133300. 4,
  133301. 8,
  133302. 3,
  133303. 9,
  133304. 2,
  133305. 10,
  133306. 1,
  133307. 11,
  133308. 0,
  133309. 12,
  133310. };
  133311. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133312. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133313. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133314. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133315. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133316. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133317. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133318. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133319. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133320. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133321. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133322. 15,11,11,10,10,12,12,12,12,
  133323. };
  133324. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133325. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133326. 122.5, 171.5, 220.5, 269.5,
  133327. };
  133328. static long _vq_quantmap__44c7_s_p9_1[] = {
  133329. 11, 9, 7, 5, 3, 1, 0, 2,
  133330. 4, 6, 8, 10, 12,
  133331. };
  133332. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133333. _vq_quantthresh__44c7_s_p9_1,
  133334. _vq_quantmap__44c7_s_p9_1,
  133335. 13,
  133336. 13
  133337. };
  133338. static static_codebook _44c7_s_p9_1 = {
  133339. 2, 169,
  133340. _vq_lengthlist__44c7_s_p9_1,
  133341. 1, -518889472, 1622704128, 4, 0,
  133342. _vq_quantlist__44c7_s_p9_1,
  133343. NULL,
  133344. &_vq_auxt__44c7_s_p9_1,
  133345. NULL,
  133346. 0
  133347. };
  133348. static long _vq_quantlist__44c7_s_p9_2[] = {
  133349. 24,
  133350. 23,
  133351. 25,
  133352. 22,
  133353. 26,
  133354. 21,
  133355. 27,
  133356. 20,
  133357. 28,
  133358. 19,
  133359. 29,
  133360. 18,
  133361. 30,
  133362. 17,
  133363. 31,
  133364. 16,
  133365. 32,
  133366. 15,
  133367. 33,
  133368. 14,
  133369. 34,
  133370. 13,
  133371. 35,
  133372. 12,
  133373. 36,
  133374. 11,
  133375. 37,
  133376. 10,
  133377. 38,
  133378. 9,
  133379. 39,
  133380. 8,
  133381. 40,
  133382. 7,
  133383. 41,
  133384. 6,
  133385. 42,
  133386. 5,
  133387. 43,
  133388. 4,
  133389. 44,
  133390. 3,
  133391. 45,
  133392. 2,
  133393. 46,
  133394. 1,
  133395. 47,
  133396. 0,
  133397. 48,
  133398. };
  133399. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133400. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133401. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133402. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133403. 7,
  133404. };
  133405. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133406. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133407. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133408. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133409. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133410. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133411. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133412. };
  133413. static long _vq_quantmap__44c7_s_p9_2[] = {
  133414. 47, 45, 43, 41, 39, 37, 35, 33,
  133415. 31, 29, 27, 25, 23, 21, 19, 17,
  133416. 15, 13, 11, 9, 7, 5, 3, 1,
  133417. 0, 2, 4, 6, 8, 10, 12, 14,
  133418. 16, 18, 20, 22, 24, 26, 28, 30,
  133419. 32, 34, 36, 38, 40, 42, 44, 46,
  133420. 48,
  133421. };
  133422. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133423. _vq_quantthresh__44c7_s_p9_2,
  133424. _vq_quantmap__44c7_s_p9_2,
  133425. 49,
  133426. 49
  133427. };
  133428. static static_codebook _44c7_s_p9_2 = {
  133429. 1, 49,
  133430. _vq_lengthlist__44c7_s_p9_2,
  133431. 1, -526909440, 1611661312, 6, 0,
  133432. _vq_quantlist__44c7_s_p9_2,
  133433. NULL,
  133434. &_vq_auxt__44c7_s_p9_2,
  133435. NULL,
  133436. 0
  133437. };
  133438. static long _huff_lengthlist__44c7_s_short[] = {
  133439. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133440. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133441. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133442. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133443. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133444. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133445. 10, 9,11,14,
  133446. };
  133447. static static_codebook _huff_book__44c7_s_short = {
  133448. 2, 100,
  133449. _huff_lengthlist__44c7_s_short,
  133450. 0, 0, 0, 0, 0,
  133451. NULL,
  133452. NULL,
  133453. NULL,
  133454. NULL,
  133455. 0
  133456. };
  133457. static long _huff_lengthlist__44c8_s_long[] = {
  133458. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133459. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133460. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133461. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133462. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133463. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133464. 11, 9, 9,10,
  133465. };
  133466. static static_codebook _huff_book__44c8_s_long = {
  133467. 2, 100,
  133468. _huff_lengthlist__44c8_s_long,
  133469. 0, 0, 0, 0, 0,
  133470. NULL,
  133471. NULL,
  133472. NULL,
  133473. NULL,
  133474. 0
  133475. };
  133476. static long _vq_quantlist__44c8_s_p1_0[] = {
  133477. 1,
  133478. 0,
  133479. 2,
  133480. };
  133481. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133482. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133483. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133484. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133485. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133486. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133487. 8,
  133488. };
  133489. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133490. -0.5, 0.5,
  133491. };
  133492. static long _vq_quantmap__44c8_s_p1_0[] = {
  133493. 1, 0, 2,
  133494. };
  133495. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133496. _vq_quantthresh__44c8_s_p1_0,
  133497. _vq_quantmap__44c8_s_p1_0,
  133498. 3,
  133499. 3
  133500. };
  133501. static static_codebook _44c8_s_p1_0 = {
  133502. 4, 81,
  133503. _vq_lengthlist__44c8_s_p1_0,
  133504. 1, -535822336, 1611661312, 2, 0,
  133505. _vq_quantlist__44c8_s_p1_0,
  133506. NULL,
  133507. &_vq_auxt__44c8_s_p1_0,
  133508. NULL,
  133509. 0
  133510. };
  133511. static long _vq_quantlist__44c8_s_p2_0[] = {
  133512. 2,
  133513. 1,
  133514. 3,
  133515. 0,
  133516. 4,
  133517. };
  133518. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133519. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133520. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133521. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133522. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133523. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133524. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133525. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133526. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133528. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133529. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133530. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133531. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133532. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133533. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133534. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133536. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133537. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133538. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133539. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133540. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133541. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133542. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133544. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133545. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133546. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133547. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133548. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133549. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133550. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133555. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133556. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133557. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133558. 13,
  133559. };
  133560. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133561. -1.5, -0.5, 0.5, 1.5,
  133562. };
  133563. static long _vq_quantmap__44c8_s_p2_0[] = {
  133564. 3, 1, 0, 2, 4,
  133565. };
  133566. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133567. _vq_quantthresh__44c8_s_p2_0,
  133568. _vq_quantmap__44c8_s_p2_0,
  133569. 5,
  133570. 5
  133571. };
  133572. static static_codebook _44c8_s_p2_0 = {
  133573. 4, 625,
  133574. _vq_lengthlist__44c8_s_p2_0,
  133575. 1, -533725184, 1611661312, 3, 0,
  133576. _vq_quantlist__44c8_s_p2_0,
  133577. NULL,
  133578. &_vq_auxt__44c8_s_p2_0,
  133579. NULL,
  133580. 0
  133581. };
  133582. static long _vq_quantlist__44c8_s_p3_0[] = {
  133583. 4,
  133584. 3,
  133585. 5,
  133586. 2,
  133587. 6,
  133588. 1,
  133589. 7,
  133590. 0,
  133591. 8,
  133592. };
  133593. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133594. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133595. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133596. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133597. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133599. 0,
  133600. };
  133601. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133602. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133603. };
  133604. static long _vq_quantmap__44c8_s_p3_0[] = {
  133605. 7, 5, 3, 1, 0, 2, 4, 6,
  133606. 8,
  133607. };
  133608. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133609. _vq_quantthresh__44c8_s_p3_0,
  133610. _vq_quantmap__44c8_s_p3_0,
  133611. 9,
  133612. 9
  133613. };
  133614. static static_codebook _44c8_s_p3_0 = {
  133615. 2, 81,
  133616. _vq_lengthlist__44c8_s_p3_0,
  133617. 1, -531628032, 1611661312, 4, 0,
  133618. _vq_quantlist__44c8_s_p3_0,
  133619. NULL,
  133620. &_vq_auxt__44c8_s_p3_0,
  133621. NULL,
  133622. 0
  133623. };
  133624. static long _vq_quantlist__44c8_s_p4_0[] = {
  133625. 8,
  133626. 7,
  133627. 9,
  133628. 6,
  133629. 10,
  133630. 5,
  133631. 11,
  133632. 4,
  133633. 12,
  133634. 3,
  133635. 13,
  133636. 2,
  133637. 14,
  133638. 1,
  133639. 15,
  133640. 0,
  133641. 16,
  133642. };
  133643. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133644. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133645. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133646. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133647. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133648. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133649. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133650. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133651. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133652. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133653. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133662. 0,
  133663. };
  133664. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133665. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133666. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133667. };
  133668. static long _vq_quantmap__44c8_s_p4_0[] = {
  133669. 15, 13, 11, 9, 7, 5, 3, 1,
  133670. 0, 2, 4, 6, 8, 10, 12, 14,
  133671. 16,
  133672. };
  133673. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133674. _vq_quantthresh__44c8_s_p4_0,
  133675. _vq_quantmap__44c8_s_p4_0,
  133676. 17,
  133677. 17
  133678. };
  133679. static static_codebook _44c8_s_p4_0 = {
  133680. 2, 289,
  133681. _vq_lengthlist__44c8_s_p4_0,
  133682. 1, -529530880, 1611661312, 5, 0,
  133683. _vq_quantlist__44c8_s_p4_0,
  133684. NULL,
  133685. &_vq_auxt__44c8_s_p4_0,
  133686. NULL,
  133687. 0
  133688. };
  133689. static long _vq_quantlist__44c8_s_p5_0[] = {
  133690. 1,
  133691. 0,
  133692. 2,
  133693. };
  133694. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133695. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133696. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133697. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133698. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133699. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133700. 12,
  133701. };
  133702. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133703. -5.5, 5.5,
  133704. };
  133705. static long _vq_quantmap__44c8_s_p5_0[] = {
  133706. 1, 0, 2,
  133707. };
  133708. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133709. _vq_quantthresh__44c8_s_p5_0,
  133710. _vq_quantmap__44c8_s_p5_0,
  133711. 3,
  133712. 3
  133713. };
  133714. static static_codebook _44c8_s_p5_0 = {
  133715. 4, 81,
  133716. _vq_lengthlist__44c8_s_p5_0,
  133717. 1, -529137664, 1618345984, 2, 0,
  133718. _vq_quantlist__44c8_s_p5_0,
  133719. NULL,
  133720. &_vq_auxt__44c8_s_p5_0,
  133721. NULL,
  133722. 0
  133723. };
  133724. static long _vq_quantlist__44c8_s_p5_1[] = {
  133725. 5,
  133726. 4,
  133727. 6,
  133728. 3,
  133729. 7,
  133730. 2,
  133731. 8,
  133732. 1,
  133733. 9,
  133734. 0,
  133735. 10,
  133736. };
  133737. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133738. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133739. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133740. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133741. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133742. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133743. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133744. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133745. 11,11,11, 7, 7, 7, 7, 8, 8,
  133746. };
  133747. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133748. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133749. 3.5, 4.5,
  133750. };
  133751. static long _vq_quantmap__44c8_s_p5_1[] = {
  133752. 9, 7, 5, 3, 1, 0, 2, 4,
  133753. 6, 8, 10,
  133754. };
  133755. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133756. _vq_quantthresh__44c8_s_p5_1,
  133757. _vq_quantmap__44c8_s_p5_1,
  133758. 11,
  133759. 11
  133760. };
  133761. static static_codebook _44c8_s_p5_1 = {
  133762. 2, 121,
  133763. _vq_lengthlist__44c8_s_p5_1,
  133764. 1, -531365888, 1611661312, 4, 0,
  133765. _vq_quantlist__44c8_s_p5_1,
  133766. NULL,
  133767. &_vq_auxt__44c8_s_p5_1,
  133768. NULL,
  133769. 0
  133770. };
  133771. static long _vq_quantlist__44c8_s_p6_0[] = {
  133772. 6,
  133773. 5,
  133774. 7,
  133775. 4,
  133776. 8,
  133777. 3,
  133778. 9,
  133779. 2,
  133780. 10,
  133781. 1,
  133782. 11,
  133783. 0,
  133784. 12,
  133785. };
  133786. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133787. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133788. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133789. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133790. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133791. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133792. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  133793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133797. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133798. };
  133799. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133800. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133801. 12.5, 17.5, 22.5, 27.5,
  133802. };
  133803. static long _vq_quantmap__44c8_s_p6_0[] = {
  133804. 11, 9, 7, 5, 3, 1, 0, 2,
  133805. 4, 6, 8, 10, 12,
  133806. };
  133807. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133808. _vq_quantthresh__44c8_s_p6_0,
  133809. _vq_quantmap__44c8_s_p6_0,
  133810. 13,
  133811. 13
  133812. };
  133813. static static_codebook _44c8_s_p6_0 = {
  133814. 2, 169,
  133815. _vq_lengthlist__44c8_s_p6_0,
  133816. 1, -526516224, 1616117760, 4, 0,
  133817. _vq_quantlist__44c8_s_p6_0,
  133818. NULL,
  133819. &_vq_auxt__44c8_s_p6_0,
  133820. NULL,
  133821. 0
  133822. };
  133823. static long _vq_quantlist__44c8_s_p6_1[] = {
  133824. 2,
  133825. 1,
  133826. 3,
  133827. 0,
  133828. 4,
  133829. };
  133830. static long _vq_lengthlist__44c8_s_p6_1[] = {
  133831. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133832. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133833. };
  133834. static float _vq_quantthresh__44c8_s_p6_1[] = {
  133835. -1.5, -0.5, 0.5, 1.5,
  133836. };
  133837. static long _vq_quantmap__44c8_s_p6_1[] = {
  133838. 3, 1, 0, 2, 4,
  133839. };
  133840. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  133841. _vq_quantthresh__44c8_s_p6_1,
  133842. _vq_quantmap__44c8_s_p6_1,
  133843. 5,
  133844. 5
  133845. };
  133846. static static_codebook _44c8_s_p6_1 = {
  133847. 2, 25,
  133848. _vq_lengthlist__44c8_s_p6_1,
  133849. 1, -533725184, 1611661312, 3, 0,
  133850. _vq_quantlist__44c8_s_p6_1,
  133851. NULL,
  133852. &_vq_auxt__44c8_s_p6_1,
  133853. NULL,
  133854. 0
  133855. };
  133856. static long _vq_quantlist__44c8_s_p7_0[] = {
  133857. 6,
  133858. 5,
  133859. 7,
  133860. 4,
  133861. 8,
  133862. 3,
  133863. 9,
  133864. 2,
  133865. 10,
  133866. 1,
  133867. 11,
  133868. 0,
  133869. 12,
  133870. };
  133871. static long _vq_lengthlist__44c8_s_p7_0[] = {
  133872. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133873. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133874. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  133875. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  133876. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  133877. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  133878. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  133879. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  133880. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  133881. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  133882. 20,13,13,13,13,14,13,15,15,
  133883. };
  133884. static float _vq_quantthresh__44c8_s_p7_0[] = {
  133885. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133886. 27.5, 38.5, 49.5, 60.5,
  133887. };
  133888. static long _vq_quantmap__44c8_s_p7_0[] = {
  133889. 11, 9, 7, 5, 3, 1, 0, 2,
  133890. 4, 6, 8, 10, 12,
  133891. };
  133892. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  133893. _vq_quantthresh__44c8_s_p7_0,
  133894. _vq_quantmap__44c8_s_p7_0,
  133895. 13,
  133896. 13
  133897. };
  133898. static static_codebook _44c8_s_p7_0 = {
  133899. 2, 169,
  133900. _vq_lengthlist__44c8_s_p7_0,
  133901. 1, -523206656, 1618345984, 4, 0,
  133902. _vq_quantlist__44c8_s_p7_0,
  133903. NULL,
  133904. &_vq_auxt__44c8_s_p7_0,
  133905. NULL,
  133906. 0
  133907. };
  133908. static long _vq_quantlist__44c8_s_p7_1[] = {
  133909. 5,
  133910. 4,
  133911. 6,
  133912. 3,
  133913. 7,
  133914. 2,
  133915. 8,
  133916. 1,
  133917. 9,
  133918. 0,
  133919. 10,
  133920. };
  133921. static long _vq_lengthlist__44c8_s_p7_1[] = {
  133922. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  133923. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  133924. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133925. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133926. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133927. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133928. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133929. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133930. };
  133931. static float _vq_quantthresh__44c8_s_p7_1[] = {
  133932. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133933. 3.5, 4.5,
  133934. };
  133935. static long _vq_quantmap__44c8_s_p7_1[] = {
  133936. 9, 7, 5, 3, 1, 0, 2, 4,
  133937. 6, 8, 10,
  133938. };
  133939. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  133940. _vq_quantthresh__44c8_s_p7_1,
  133941. _vq_quantmap__44c8_s_p7_1,
  133942. 11,
  133943. 11
  133944. };
  133945. static static_codebook _44c8_s_p7_1 = {
  133946. 2, 121,
  133947. _vq_lengthlist__44c8_s_p7_1,
  133948. 1, -531365888, 1611661312, 4, 0,
  133949. _vq_quantlist__44c8_s_p7_1,
  133950. NULL,
  133951. &_vq_auxt__44c8_s_p7_1,
  133952. NULL,
  133953. 0
  133954. };
  133955. static long _vq_quantlist__44c8_s_p8_0[] = {
  133956. 7,
  133957. 6,
  133958. 8,
  133959. 5,
  133960. 9,
  133961. 4,
  133962. 10,
  133963. 3,
  133964. 11,
  133965. 2,
  133966. 12,
  133967. 1,
  133968. 13,
  133969. 0,
  133970. 14,
  133971. };
  133972. static long _vq_lengthlist__44c8_s_p8_0[] = {
  133973. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  133974. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  133975. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  133976. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  133977. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  133978. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  133979. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  133980. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  133981. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  133982. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  133983. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  133984. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133985. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  133986. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  133987. 15,
  133988. };
  133989. static float _vq_quantthresh__44c8_s_p8_0[] = {
  133990. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133991. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133992. };
  133993. static long _vq_quantmap__44c8_s_p8_0[] = {
  133994. 13, 11, 9, 7, 5, 3, 1, 0,
  133995. 2, 4, 6, 8, 10, 12, 14,
  133996. };
  133997. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  133998. _vq_quantthresh__44c8_s_p8_0,
  133999. _vq_quantmap__44c8_s_p8_0,
  134000. 15,
  134001. 15
  134002. };
  134003. static static_codebook _44c8_s_p8_0 = {
  134004. 2, 225,
  134005. _vq_lengthlist__44c8_s_p8_0,
  134006. 1, -520986624, 1620377600, 4, 0,
  134007. _vq_quantlist__44c8_s_p8_0,
  134008. NULL,
  134009. &_vq_auxt__44c8_s_p8_0,
  134010. NULL,
  134011. 0
  134012. };
  134013. static long _vq_quantlist__44c8_s_p8_1[] = {
  134014. 10,
  134015. 9,
  134016. 11,
  134017. 8,
  134018. 12,
  134019. 7,
  134020. 13,
  134021. 6,
  134022. 14,
  134023. 5,
  134024. 15,
  134025. 4,
  134026. 16,
  134027. 3,
  134028. 17,
  134029. 2,
  134030. 18,
  134031. 1,
  134032. 19,
  134033. 0,
  134034. 20,
  134035. };
  134036. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134037. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134038. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134039. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134040. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134041. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134042. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134043. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134044. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134045. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134046. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134047. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134048. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134049. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134050. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134051. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134052. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134053. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134054. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134055. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134056. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134057. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134058. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134059. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134060. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134061. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134062. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134063. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134064. 10, 9, 9,10,10, 9,10, 9, 9,
  134065. };
  134066. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134067. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134068. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134069. 6.5, 7.5, 8.5, 9.5,
  134070. };
  134071. static long _vq_quantmap__44c8_s_p8_1[] = {
  134072. 19, 17, 15, 13, 11, 9, 7, 5,
  134073. 3, 1, 0, 2, 4, 6, 8, 10,
  134074. 12, 14, 16, 18, 20,
  134075. };
  134076. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134077. _vq_quantthresh__44c8_s_p8_1,
  134078. _vq_quantmap__44c8_s_p8_1,
  134079. 21,
  134080. 21
  134081. };
  134082. static static_codebook _44c8_s_p8_1 = {
  134083. 2, 441,
  134084. _vq_lengthlist__44c8_s_p8_1,
  134085. 1, -529268736, 1611661312, 5, 0,
  134086. _vq_quantlist__44c8_s_p8_1,
  134087. NULL,
  134088. &_vq_auxt__44c8_s_p8_1,
  134089. NULL,
  134090. 0
  134091. };
  134092. static long _vq_quantlist__44c8_s_p9_0[] = {
  134093. 8,
  134094. 7,
  134095. 9,
  134096. 6,
  134097. 10,
  134098. 5,
  134099. 11,
  134100. 4,
  134101. 12,
  134102. 3,
  134103. 13,
  134104. 2,
  134105. 14,
  134106. 1,
  134107. 15,
  134108. 0,
  134109. 16,
  134110. };
  134111. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134112. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134113. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134114. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134117. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134118. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134119. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134120. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134121. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134122. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134123. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134124. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134125. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134126. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134127. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134128. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134129. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134130. 10,
  134131. };
  134132. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134133. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134134. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134135. };
  134136. static long _vq_quantmap__44c8_s_p9_0[] = {
  134137. 15, 13, 11, 9, 7, 5, 3, 1,
  134138. 0, 2, 4, 6, 8, 10, 12, 14,
  134139. 16,
  134140. };
  134141. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134142. _vq_quantthresh__44c8_s_p9_0,
  134143. _vq_quantmap__44c8_s_p9_0,
  134144. 17,
  134145. 17
  134146. };
  134147. static static_codebook _44c8_s_p9_0 = {
  134148. 2, 289,
  134149. _vq_lengthlist__44c8_s_p9_0,
  134150. 1, -509798400, 1631393792, 5, 0,
  134151. _vq_quantlist__44c8_s_p9_0,
  134152. NULL,
  134153. &_vq_auxt__44c8_s_p9_0,
  134154. NULL,
  134155. 0
  134156. };
  134157. static long _vq_quantlist__44c8_s_p9_1[] = {
  134158. 9,
  134159. 8,
  134160. 10,
  134161. 7,
  134162. 11,
  134163. 6,
  134164. 12,
  134165. 5,
  134166. 13,
  134167. 4,
  134168. 14,
  134169. 3,
  134170. 15,
  134171. 2,
  134172. 16,
  134173. 1,
  134174. 17,
  134175. 0,
  134176. 18,
  134177. };
  134178. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134179. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134180. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134181. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134182. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134183. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134184. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134185. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134186. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134187. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134188. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134189. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134190. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134191. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134192. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134193. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134194. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134195. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134196. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134197. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134198. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134199. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134200. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134201. 14,13,13,14,14,15,14,15,14,
  134202. };
  134203. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134204. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134205. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134206. 367.5, 416.5,
  134207. };
  134208. static long _vq_quantmap__44c8_s_p9_1[] = {
  134209. 17, 15, 13, 11, 9, 7, 5, 3,
  134210. 1, 0, 2, 4, 6, 8, 10, 12,
  134211. 14, 16, 18,
  134212. };
  134213. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134214. _vq_quantthresh__44c8_s_p9_1,
  134215. _vq_quantmap__44c8_s_p9_1,
  134216. 19,
  134217. 19
  134218. };
  134219. static static_codebook _44c8_s_p9_1 = {
  134220. 2, 361,
  134221. _vq_lengthlist__44c8_s_p9_1,
  134222. 1, -518287360, 1622704128, 5, 0,
  134223. _vq_quantlist__44c8_s_p9_1,
  134224. NULL,
  134225. &_vq_auxt__44c8_s_p9_1,
  134226. NULL,
  134227. 0
  134228. };
  134229. static long _vq_quantlist__44c8_s_p9_2[] = {
  134230. 24,
  134231. 23,
  134232. 25,
  134233. 22,
  134234. 26,
  134235. 21,
  134236. 27,
  134237. 20,
  134238. 28,
  134239. 19,
  134240. 29,
  134241. 18,
  134242. 30,
  134243. 17,
  134244. 31,
  134245. 16,
  134246. 32,
  134247. 15,
  134248. 33,
  134249. 14,
  134250. 34,
  134251. 13,
  134252. 35,
  134253. 12,
  134254. 36,
  134255. 11,
  134256. 37,
  134257. 10,
  134258. 38,
  134259. 9,
  134260. 39,
  134261. 8,
  134262. 40,
  134263. 7,
  134264. 41,
  134265. 6,
  134266. 42,
  134267. 5,
  134268. 43,
  134269. 4,
  134270. 44,
  134271. 3,
  134272. 45,
  134273. 2,
  134274. 46,
  134275. 1,
  134276. 47,
  134277. 0,
  134278. 48,
  134279. };
  134280. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134281. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134282. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134283. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134284. 7,
  134285. };
  134286. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134287. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134288. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134289. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134290. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134291. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134292. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134293. };
  134294. static long _vq_quantmap__44c8_s_p9_2[] = {
  134295. 47, 45, 43, 41, 39, 37, 35, 33,
  134296. 31, 29, 27, 25, 23, 21, 19, 17,
  134297. 15, 13, 11, 9, 7, 5, 3, 1,
  134298. 0, 2, 4, 6, 8, 10, 12, 14,
  134299. 16, 18, 20, 22, 24, 26, 28, 30,
  134300. 32, 34, 36, 38, 40, 42, 44, 46,
  134301. 48,
  134302. };
  134303. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134304. _vq_quantthresh__44c8_s_p9_2,
  134305. _vq_quantmap__44c8_s_p9_2,
  134306. 49,
  134307. 49
  134308. };
  134309. static static_codebook _44c8_s_p9_2 = {
  134310. 1, 49,
  134311. _vq_lengthlist__44c8_s_p9_2,
  134312. 1, -526909440, 1611661312, 6, 0,
  134313. _vq_quantlist__44c8_s_p9_2,
  134314. NULL,
  134315. &_vq_auxt__44c8_s_p9_2,
  134316. NULL,
  134317. 0
  134318. };
  134319. static long _huff_lengthlist__44c8_s_short[] = {
  134320. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134321. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134322. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134323. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134324. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134325. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134326. 10, 9,11,14,
  134327. };
  134328. static static_codebook _huff_book__44c8_s_short = {
  134329. 2, 100,
  134330. _huff_lengthlist__44c8_s_short,
  134331. 0, 0, 0, 0, 0,
  134332. NULL,
  134333. NULL,
  134334. NULL,
  134335. NULL,
  134336. 0
  134337. };
  134338. static long _huff_lengthlist__44c9_s_long[] = {
  134339. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134340. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134341. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134342. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134343. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134344. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134345. 10, 9, 8, 9,
  134346. };
  134347. static static_codebook _huff_book__44c9_s_long = {
  134348. 2, 100,
  134349. _huff_lengthlist__44c9_s_long,
  134350. 0, 0, 0, 0, 0,
  134351. NULL,
  134352. NULL,
  134353. NULL,
  134354. NULL,
  134355. 0
  134356. };
  134357. static long _vq_quantlist__44c9_s_p1_0[] = {
  134358. 1,
  134359. 0,
  134360. 2,
  134361. };
  134362. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134363. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134364. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134366. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134367. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134368. 7,
  134369. };
  134370. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134371. -0.5, 0.5,
  134372. };
  134373. static long _vq_quantmap__44c9_s_p1_0[] = {
  134374. 1, 0, 2,
  134375. };
  134376. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134377. _vq_quantthresh__44c9_s_p1_0,
  134378. _vq_quantmap__44c9_s_p1_0,
  134379. 3,
  134380. 3
  134381. };
  134382. static static_codebook _44c9_s_p1_0 = {
  134383. 4, 81,
  134384. _vq_lengthlist__44c9_s_p1_0,
  134385. 1, -535822336, 1611661312, 2, 0,
  134386. _vq_quantlist__44c9_s_p1_0,
  134387. NULL,
  134388. &_vq_auxt__44c9_s_p1_0,
  134389. NULL,
  134390. 0
  134391. };
  134392. static long _vq_quantlist__44c9_s_p2_0[] = {
  134393. 2,
  134394. 1,
  134395. 3,
  134396. 0,
  134397. 4,
  134398. };
  134399. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134400. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134401. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134402. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134403. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134404. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134405. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134406. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134407. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134409. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134410. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134411. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134412. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134413. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134414. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134415. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134417. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134418. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134419. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134420. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134421. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134422. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134423. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134425. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134426. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134427. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134428. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134429. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134430. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134431. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134436. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134437. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134438. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134439. 12,
  134440. };
  134441. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134442. -1.5, -0.5, 0.5, 1.5,
  134443. };
  134444. static long _vq_quantmap__44c9_s_p2_0[] = {
  134445. 3, 1, 0, 2, 4,
  134446. };
  134447. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134448. _vq_quantthresh__44c9_s_p2_0,
  134449. _vq_quantmap__44c9_s_p2_0,
  134450. 5,
  134451. 5
  134452. };
  134453. static static_codebook _44c9_s_p2_0 = {
  134454. 4, 625,
  134455. _vq_lengthlist__44c9_s_p2_0,
  134456. 1, -533725184, 1611661312, 3, 0,
  134457. _vq_quantlist__44c9_s_p2_0,
  134458. NULL,
  134459. &_vq_auxt__44c9_s_p2_0,
  134460. NULL,
  134461. 0
  134462. };
  134463. static long _vq_quantlist__44c9_s_p3_0[] = {
  134464. 4,
  134465. 3,
  134466. 5,
  134467. 2,
  134468. 6,
  134469. 1,
  134470. 7,
  134471. 0,
  134472. 8,
  134473. };
  134474. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134475. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134476. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134477. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134478. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134480. 0,
  134481. };
  134482. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134483. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134484. };
  134485. static long _vq_quantmap__44c9_s_p3_0[] = {
  134486. 7, 5, 3, 1, 0, 2, 4, 6,
  134487. 8,
  134488. };
  134489. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134490. _vq_quantthresh__44c9_s_p3_0,
  134491. _vq_quantmap__44c9_s_p3_0,
  134492. 9,
  134493. 9
  134494. };
  134495. static static_codebook _44c9_s_p3_0 = {
  134496. 2, 81,
  134497. _vq_lengthlist__44c9_s_p3_0,
  134498. 1, -531628032, 1611661312, 4, 0,
  134499. _vq_quantlist__44c9_s_p3_0,
  134500. NULL,
  134501. &_vq_auxt__44c9_s_p3_0,
  134502. NULL,
  134503. 0
  134504. };
  134505. static long _vq_quantlist__44c9_s_p4_0[] = {
  134506. 8,
  134507. 7,
  134508. 9,
  134509. 6,
  134510. 10,
  134511. 5,
  134512. 11,
  134513. 4,
  134514. 12,
  134515. 3,
  134516. 13,
  134517. 2,
  134518. 14,
  134519. 1,
  134520. 15,
  134521. 0,
  134522. 16,
  134523. };
  134524. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134525. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134526. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134527. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134528. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134529. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134530. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134531. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134532. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134533. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134534. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134543. 0,
  134544. };
  134545. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134546. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134547. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134548. };
  134549. static long _vq_quantmap__44c9_s_p4_0[] = {
  134550. 15, 13, 11, 9, 7, 5, 3, 1,
  134551. 0, 2, 4, 6, 8, 10, 12, 14,
  134552. 16,
  134553. };
  134554. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134555. _vq_quantthresh__44c9_s_p4_0,
  134556. _vq_quantmap__44c9_s_p4_0,
  134557. 17,
  134558. 17
  134559. };
  134560. static static_codebook _44c9_s_p4_0 = {
  134561. 2, 289,
  134562. _vq_lengthlist__44c9_s_p4_0,
  134563. 1, -529530880, 1611661312, 5, 0,
  134564. _vq_quantlist__44c9_s_p4_0,
  134565. NULL,
  134566. &_vq_auxt__44c9_s_p4_0,
  134567. NULL,
  134568. 0
  134569. };
  134570. static long _vq_quantlist__44c9_s_p5_0[] = {
  134571. 1,
  134572. 0,
  134573. 2,
  134574. };
  134575. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134576. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134577. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134578. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134579. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134580. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134581. 12,
  134582. };
  134583. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134584. -5.5, 5.5,
  134585. };
  134586. static long _vq_quantmap__44c9_s_p5_0[] = {
  134587. 1, 0, 2,
  134588. };
  134589. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134590. _vq_quantthresh__44c9_s_p5_0,
  134591. _vq_quantmap__44c9_s_p5_0,
  134592. 3,
  134593. 3
  134594. };
  134595. static static_codebook _44c9_s_p5_0 = {
  134596. 4, 81,
  134597. _vq_lengthlist__44c9_s_p5_0,
  134598. 1, -529137664, 1618345984, 2, 0,
  134599. _vq_quantlist__44c9_s_p5_0,
  134600. NULL,
  134601. &_vq_auxt__44c9_s_p5_0,
  134602. NULL,
  134603. 0
  134604. };
  134605. static long _vq_quantlist__44c9_s_p5_1[] = {
  134606. 5,
  134607. 4,
  134608. 6,
  134609. 3,
  134610. 7,
  134611. 2,
  134612. 8,
  134613. 1,
  134614. 9,
  134615. 0,
  134616. 10,
  134617. };
  134618. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134619. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134620. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134621. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134622. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134623. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134624. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134625. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134626. 11,11,11, 7, 7, 7, 7, 7, 7,
  134627. };
  134628. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134629. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134630. 3.5, 4.5,
  134631. };
  134632. static long _vq_quantmap__44c9_s_p5_1[] = {
  134633. 9, 7, 5, 3, 1, 0, 2, 4,
  134634. 6, 8, 10,
  134635. };
  134636. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134637. _vq_quantthresh__44c9_s_p5_1,
  134638. _vq_quantmap__44c9_s_p5_1,
  134639. 11,
  134640. 11
  134641. };
  134642. static static_codebook _44c9_s_p5_1 = {
  134643. 2, 121,
  134644. _vq_lengthlist__44c9_s_p5_1,
  134645. 1, -531365888, 1611661312, 4, 0,
  134646. _vq_quantlist__44c9_s_p5_1,
  134647. NULL,
  134648. &_vq_auxt__44c9_s_p5_1,
  134649. NULL,
  134650. 0
  134651. };
  134652. static long _vq_quantlist__44c9_s_p6_0[] = {
  134653. 6,
  134654. 5,
  134655. 7,
  134656. 4,
  134657. 8,
  134658. 3,
  134659. 9,
  134660. 2,
  134661. 10,
  134662. 1,
  134663. 11,
  134664. 0,
  134665. 12,
  134666. };
  134667. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134668. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134669. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134670. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134671. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134672. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134673. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134678. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134679. };
  134680. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134681. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134682. 12.5, 17.5, 22.5, 27.5,
  134683. };
  134684. static long _vq_quantmap__44c9_s_p6_0[] = {
  134685. 11, 9, 7, 5, 3, 1, 0, 2,
  134686. 4, 6, 8, 10, 12,
  134687. };
  134688. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134689. _vq_quantthresh__44c9_s_p6_0,
  134690. _vq_quantmap__44c9_s_p6_0,
  134691. 13,
  134692. 13
  134693. };
  134694. static static_codebook _44c9_s_p6_0 = {
  134695. 2, 169,
  134696. _vq_lengthlist__44c9_s_p6_0,
  134697. 1, -526516224, 1616117760, 4, 0,
  134698. _vq_quantlist__44c9_s_p6_0,
  134699. NULL,
  134700. &_vq_auxt__44c9_s_p6_0,
  134701. NULL,
  134702. 0
  134703. };
  134704. static long _vq_quantlist__44c9_s_p6_1[] = {
  134705. 2,
  134706. 1,
  134707. 3,
  134708. 0,
  134709. 4,
  134710. };
  134711. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134712. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134713. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134714. };
  134715. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134716. -1.5, -0.5, 0.5, 1.5,
  134717. };
  134718. static long _vq_quantmap__44c9_s_p6_1[] = {
  134719. 3, 1, 0, 2, 4,
  134720. };
  134721. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134722. _vq_quantthresh__44c9_s_p6_1,
  134723. _vq_quantmap__44c9_s_p6_1,
  134724. 5,
  134725. 5
  134726. };
  134727. static static_codebook _44c9_s_p6_1 = {
  134728. 2, 25,
  134729. _vq_lengthlist__44c9_s_p6_1,
  134730. 1, -533725184, 1611661312, 3, 0,
  134731. _vq_quantlist__44c9_s_p6_1,
  134732. NULL,
  134733. &_vq_auxt__44c9_s_p6_1,
  134734. NULL,
  134735. 0
  134736. };
  134737. static long _vq_quantlist__44c9_s_p7_0[] = {
  134738. 6,
  134739. 5,
  134740. 7,
  134741. 4,
  134742. 8,
  134743. 3,
  134744. 9,
  134745. 2,
  134746. 10,
  134747. 1,
  134748. 11,
  134749. 0,
  134750. 12,
  134751. };
  134752. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134753. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134754. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134755. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134756. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134757. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134758. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134759. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134760. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134761. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134762. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134763. 19,12,12,12,12,13,13,14,14,
  134764. };
  134765. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134766. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134767. 27.5, 38.5, 49.5, 60.5,
  134768. };
  134769. static long _vq_quantmap__44c9_s_p7_0[] = {
  134770. 11, 9, 7, 5, 3, 1, 0, 2,
  134771. 4, 6, 8, 10, 12,
  134772. };
  134773. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134774. _vq_quantthresh__44c9_s_p7_0,
  134775. _vq_quantmap__44c9_s_p7_0,
  134776. 13,
  134777. 13
  134778. };
  134779. static static_codebook _44c9_s_p7_0 = {
  134780. 2, 169,
  134781. _vq_lengthlist__44c9_s_p7_0,
  134782. 1, -523206656, 1618345984, 4, 0,
  134783. _vq_quantlist__44c9_s_p7_0,
  134784. NULL,
  134785. &_vq_auxt__44c9_s_p7_0,
  134786. NULL,
  134787. 0
  134788. };
  134789. static long _vq_quantlist__44c9_s_p7_1[] = {
  134790. 5,
  134791. 4,
  134792. 6,
  134793. 3,
  134794. 7,
  134795. 2,
  134796. 8,
  134797. 1,
  134798. 9,
  134799. 0,
  134800. 10,
  134801. };
  134802. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134803. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134804. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134805. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134806. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134807. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134808. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134809. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134810. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134811. };
  134812. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134813. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134814. 3.5, 4.5,
  134815. };
  134816. static long _vq_quantmap__44c9_s_p7_1[] = {
  134817. 9, 7, 5, 3, 1, 0, 2, 4,
  134818. 6, 8, 10,
  134819. };
  134820. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  134821. _vq_quantthresh__44c9_s_p7_1,
  134822. _vq_quantmap__44c9_s_p7_1,
  134823. 11,
  134824. 11
  134825. };
  134826. static static_codebook _44c9_s_p7_1 = {
  134827. 2, 121,
  134828. _vq_lengthlist__44c9_s_p7_1,
  134829. 1, -531365888, 1611661312, 4, 0,
  134830. _vq_quantlist__44c9_s_p7_1,
  134831. NULL,
  134832. &_vq_auxt__44c9_s_p7_1,
  134833. NULL,
  134834. 0
  134835. };
  134836. static long _vq_quantlist__44c9_s_p8_0[] = {
  134837. 7,
  134838. 6,
  134839. 8,
  134840. 5,
  134841. 9,
  134842. 4,
  134843. 10,
  134844. 3,
  134845. 11,
  134846. 2,
  134847. 12,
  134848. 1,
  134849. 13,
  134850. 0,
  134851. 14,
  134852. };
  134853. static long _vq_lengthlist__44c9_s_p8_0[] = {
  134854. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  134855. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  134856. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  134857. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  134858. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  134859. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  134860. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  134861. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  134862. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  134863. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  134864. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  134865. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  134866. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  134867. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  134868. 14,
  134869. };
  134870. static float _vq_quantthresh__44c9_s_p8_0[] = {
  134871. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134872. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134873. };
  134874. static long _vq_quantmap__44c9_s_p8_0[] = {
  134875. 13, 11, 9, 7, 5, 3, 1, 0,
  134876. 2, 4, 6, 8, 10, 12, 14,
  134877. };
  134878. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  134879. _vq_quantthresh__44c9_s_p8_0,
  134880. _vq_quantmap__44c9_s_p8_0,
  134881. 15,
  134882. 15
  134883. };
  134884. static static_codebook _44c9_s_p8_0 = {
  134885. 2, 225,
  134886. _vq_lengthlist__44c9_s_p8_0,
  134887. 1, -520986624, 1620377600, 4, 0,
  134888. _vq_quantlist__44c9_s_p8_0,
  134889. NULL,
  134890. &_vq_auxt__44c9_s_p8_0,
  134891. NULL,
  134892. 0
  134893. };
  134894. static long _vq_quantlist__44c9_s_p8_1[] = {
  134895. 10,
  134896. 9,
  134897. 11,
  134898. 8,
  134899. 12,
  134900. 7,
  134901. 13,
  134902. 6,
  134903. 14,
  134904. 5,
  134905. 15,
  134906. 4,
  134907. 16,
  134908. 3,
  134909. 17,
  134910. 2,
  134911. 18,
  134912. 1,
  134913. 19,
  134914. 0,
  134915. 20,
  134916. };
  134917. static long _vq_lengthlist__44c9_s_p8_1[] = {
  134918. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134919. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134920. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134921. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134922. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134923. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134924. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  134925. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134926. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134927. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134928. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134929. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134930. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134931. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134932. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134933. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  134934. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  134935. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  134936. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  134937. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134938. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134939. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  134940. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  134941. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134942. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  134943. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  134944. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  134945. 9, 9, 9,10, 9, 9, 9, 9, 9,
  134946. };
  134947. static float _vq_quantthresh__44c9_s_p8_1[] = {
  134948. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134949. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134950. 6.5, 7.5, 8.5, 9.5,
  134951. };
  134952. static long _vq_quantmap__44c9_s_p8_1[] = {
  134953. 19, 17, 15, 13, 11, 9, 7, 5,
  134954. 3, 1, 0, 2, 4, 6, 8, 10,
  134955. 12, 14, 16, 18, 20,
  134956. };
  134957. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  134958. _vq_quantthresh__44c9_s_p8_1,
  134959. _vq_quantmap__44c9_s_p8_1,
  134960. 21,
  134961. 21
  134962. };
  134963. static static_codebook _44c9_s_p8_1 = {
  134964. 2, 441,
  134965. _vq_lengthlist__44c9_s_p8_1,
  134966. 1, -529268736, 1611661312, 5, 0,
  134967. _vq_quantlist__44c9_s_p8_1,
  134968. NULL,
  134969. &_vq_auxt__44c9_s_p8_1,
  134970. NULL,
  134971. 0
  134972. };
  134973. static long _vq_quantlist__44c9_s_p9_0[] = {
  134974. 9,
  134975. 8,
  134976. 10,
  134977. 7,
  134978. 11,
  134979. 6,
  134980. 12,
  134981. 5,
  134982. 13,
  134983. 4,
  134984. 14,
  134985. 3,
  134986. 15,
  134987. 2,
  134988. 16,
  134989. 1,
  134990. 17,
  134991. 0,
  134992. 18,
  134993. };
  134994. static long _vq_lengthlist__44c9_s_p9_0[] = {
  134995. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134996. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  134997. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  134998. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  134999. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135000. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135001. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135002. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135003. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135004. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135005. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135006. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135007. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135008. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135009. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135010. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135011. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135017. 11,11,11,11,11,11,11,11,11,
  135018. };
  135019. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135020. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135021. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135022. 6982.5, 7913.5,
  135023. };
  135024. static long _vq_quantmap__44c9_s_p9_0[] = {
  135025. 17, 15, 13, 11, 9, 7, 5, 3,
  135026. 1, 0, 2, 4, 6, 8, 10, 12,
  135027. 14, 16, 18,
  135028. };
  135029. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135030. _vq_quantthresh__44c9_s_p9_0,
  135031. _vq_quantmap__44c9_s_p9_0,
  135032. 19,
  135033. 19
  135034. };
  135035. static static_codebook _44c9_s_p9_0 = {
  135036. 2, 361,
  135037. _vq_lengthlist__44c9_s_p9_0,
  135038. 1, -508535424, 1631393792, 5, 0,
  135039. _vq_quantlist__44c9_s_p9_0,
  135040. NULL,
  135041. &_vq_auxt__44c9_s_p9_0,
  135042. NULL,
  135043. 0
  135044. };
  135045. static long _vq_quantlist__44c9_s_p9_1[] = {
  135046. 9,
  135047. 8,
  135048. 10,
  135049. 7,
  135050. 11,
  135051. 6,
  135052. 12,
  135053. 5,
  135054. 13,
  135055. 4,
  135056. 14,
  135057. 3,
  135058. 15,
  135059. 2,
  135060. 16,
  135061. 1,
  135062. 17,
  135063. 0,
  135064. 18,
  135065. };
  135066. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135067. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135068. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135069. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135070. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135071. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135072. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135073. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135074. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135075. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135076. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135077. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135078. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135079. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135080. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135081. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135082. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135083. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135084. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135085. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135086. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135087. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135088. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135089. 13,13,13,14,13,14,15,15,15,
  135090. };
  135091. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135092. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135093. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135094. 367.5, 416.5,
  135095. };
  135096. static long _vq_quantmap__44c9_s_p9_1[] = {
  135097. 17, 15, 13, 11, 9, 7, 5, 3,
  135098. 1, 0, 2, 4, 6, 8, 10, 12,
  135099. 14, 16, 18,
  135100. };
  135101. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135102. _vq_quantthresh__44c9_s_p9_1,
  135103. _vq_quantmap__44c9_s_p9_1,
  135104. 19,
  135105. 19
  135106. };
  135107. static static_codebook _44c9_s_p9_1 = {
  135108. 2, 361,
  135109. _vq_lengthlist__44c9_s_p9_1,
  135110. 1, -518287360, 1622704128, 5, 0,
  135111. _vq_quantlist__44c9_s_p9_1,
  135112. NULL,
  135113. &_vq_auxt__44c9_s_p9_1,
  135114. NULL,
  135115. 0
  135116. };
  135117. static long _vq_quantlist__44c9_s_p9_2[] = {
  135118. 24,
  135119. 23,
  135120. 25,
  135121. 22,
  135122. 26,
  135123. 21,
  135124. 27,
  135125. 20,
  135126. 28,
  135127. 19,
  135128. 29,
  135129. 18,
  135130. 30,
  135131. 17,
  135132. 31,
  135133. 16,
  135134. 32,
  135135. 15,
  135136. 33,
  135137. 14,
  135138. 34,
  135139. 13,
  135140. 35,
  135141. 12,
  135142. 36,
  135143. 11,
  135144. 37,
  135145. 10,
  135146. 38,
  135147. 9,
  135148. 39,
  135149. 8,
  135150. 40,
  135151. 7,
  135152. 41,
  135153. 6,
  135154. 42,
  135155. 5,
  135156. 43,
  135157. 4,
  135158. 44,
  135159. 3,
  135160. 45,
  135161. 2,
  135162. 46,
  135163. 1,
  135164. 47,
  135165. 0,
  135166. 48,
  135167. };
  135168. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135169. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135170. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135171. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135172. 7,
  135173. };
  135174. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135175. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135176. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135177. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135178. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135179. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135180. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135181. };
  135182. static long _vq_quantmap__44c9_s_p9_2[] = {
  135183. 47, 45, 43, 41, 39, 37, 35, 33,
  135184. 31, 29, 27, 25, 23, 21, 19, 17,
  135185. 15, 13, 11, 9, 7, 5, 3, 1,
  135186. 0, 2, 4, 6, 8, 10, 12, 14,
  135187. 16, 18, 20, 22, 24, 26, 28, 30,
  135188. 32, 34, 36, 38, 40, 42, 44, 46,
  135189. 48,
  135190. };
  135191. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135192. _vq_quantthresh__44c9_s_p9_2,
  135193. _vq_quantmap__44c9_s_p9_2,
  135194. 49,
  135195. 49
  135196. };
  135197. static static_codebook _44c9_s_p9_2 = {
  135198. 1, 49,
  135199. _vq_lengthlist__44c9_s_p9_2,
  135200. 1, -526909440, 1611661312, 6, 0,
  135201. _vq_quantlist__44c9_s_p9_2,
  135202. NULL,
  135203. &_vq_auxt__44c9_s_p9_2,
  135204. NULL,
  135205. 0
  135206. };
  135207. static long _huff_lengthlist__44c9_s_short[] = {
  135208. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135209. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135210. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135211. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135212. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135213. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135214. 9, 8,10,13,
  135215. };
  135216. static static_codebook _huff_book__44c9_s_short = {
  135217. 2, 100,
  135218. _huff_lengthlist__44c9_s_short,
  135219. 0, 0, 0, 0, 0,
  135220. NULL,
  135221. NULL,
  135222. NULL,
  135223. NULL,
  135224. 0
  135225. };
  135226. static long _huff_lengthlist__44c0_s_long[] = {
  135227. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135228. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135229. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135230. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135231. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135232. 12,
  135233. };
  135234. static static_codebook _huff_book__44c0_s_long = {
  135235. 2, 81,
  135236. _huff_lengthlist__44c0_s_long,
  135237. 0, 0, 0, 0, 0,
  135238. NULL,
  135239. NULL,
  135240. NULL,
  135241. NULL,
  135242. 0
  135243. };
  135244. static long _vq_quantlist__44c0_s_p1_0[] = {
  135245. 1,
  135246. 0,
  135247. 2,
  135248. };
  135249. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135250. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135251. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135256. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135261. 0, 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0,
  135296. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  135301. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  135306. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135342. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135347. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135352. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135660. 0,
  135661. };
  135662. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135663. -0.5, 0.5,
  135664. };
  135665. static long _vq_quantmap__44c0_s_p1_0[] = {
  135666. 1, 0, 2,
  135667. };
  135668. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135669. _vq_quantthresh__44c0_s_p1_0,
  135670. _vq_quantmap__44c0_s_p1_0,
  135671. 3,
  135672. 3
  135673. };
  135674. static static_codebook _44c0_s_p1_0 = {
  135675. 8, 6561,
  135676. _vq_lengthlist__44c0_s_p1_0,
  135677. 1, -535822336, 1611661312, 2, 0,
  135678. _vq_quantlist__44c0_s_p1_0,
  135679. NULL,
  135680. &_vq_auxt__44c0_s_p1_0,
  135681. NULL,
  135682. 0
  135683. };
  135684. static long _vq_quantlist__44c0_s_p2_0[] = {
  135685. 2,
  135686. 1,
  135687. 3,
  135688. 0,
  135689. 4,
  135690. };
  135691. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135692. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135731. 0,
  135732. };
  135733. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135734. -1.5, -0.5, 0.5, 1.5,
  135735. };
  135736. static long _vq_quantmap__44c0_s_p2_0[] = {
  135737. 3, 1, 0, 2, 4,
  135738. };
  135739. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135740. _vq_quantthresh__44c0_s_p2_0,
  135741. _vq_quantmap__44c0_s_p2_0,
  135742. 5,
  135743. 5
  135744. };
  135745. static static_codebook _44c0_s_p2_0 = {
  135746. 4, 625,
  135747. _vq_lengthlist__44c0_s_p2_0,
  135748. 1, -533725184, 1611661312, 3, 0,
  135749. _vq_quantlist__44c0_s_p2_0,
  135750. NULL,
  135751. &_vq_auxt__44c0_s_p2_0,
  135752. NULL,
  135753. 0
  135754. };
  135755. static long _vq_quantlist__44c0_s_p3_0[] = {
  135756. 4,
  135757. 3,
  135758. 5,
  135759. 2,
  135760. 6,
  135761. 1,
  135762. 7,
  135763. 0,
  135764. 8,
  135765. };
  135766. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135767. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135768. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135769. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135770. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135771. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0,
  135773. };
  135774. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135775. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135776. };
  135777. static long _vq_quantmap__44c0_s_p3_0[] = {
  135778. 7, 5, 3, 1, 0, 2, 4, 6,
  135779. 8,
  135780. };
  135781. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135782. _vq_quantthresh__44c0_s_p3_0,
  135783. _vq_quantmap__44c0_s_p3_0,
  135784. 9,
  135785. 9
  135786. };
  135787. static static_codebook _44c0_s_p3_0 = {
  135788. 2, 81,
  135789. _vq_lengthlist__44c0_s_p3_0,
  135790. 1, -531628032, 1611661312, 4, 0,
  135791. _vq_quantlist__44c0_s_p3_0,
  135792. NULL,
  135793. &_vq_auxt__44c0_s_p3_0,
  135794. NULL,
  135795. 0
  135796. };
  135797. static long _vq_quantlist__44c0_s_p4_0[] = {
  135798. 4,
  135799. 3,
  135800. 5,
  135801. 2,
  135802. 6,
  135803. 1,
  135804. 7,
  135805. 0,
  135806. 8,
  135807. };
  135808. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135809. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135810. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135811. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135812. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135813. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  135814. 10,
  135815. };
  135816. static float _vq_quantthresh__44c0_s_p4_0[] = {
  135817. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135818. };
  135819. static long _vq_quantmap__44c0_s_p4_0[] = {
  135820. 7, 5, 3, 1, 0, 2, 4, 6,
  135821. 8,
  135822. };
  135823. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  135824. _vq_quantthresh__44c0_s_p4_0,
  135825. _vq_quantmap__44c0_s_p4_0,
  135826. 9,
  135827. 9
  135828. };
  135829. static static_codebook _44c0_s_p4_0 = {
  135830. 2, 81,
  135831. _vq_lengthlist__44c0_s_p4_0,
  135832. 1, -531628032, 1611661312, 4, 0,
  135833. _vq_quantlist__44c0_s_p4_0,
  135834. NULL,
  135835. &_vq_auxt__44c0_s_p4_0,
  135836. NULL,
  135837. 0
  135838. };
  135839. static long _vq_quantlist__44c0_s_p5_0[] = {
  135840. 8,
  135841. 7,
  135842. 9,
  135843. 6,
  135844. 10,
  135845. 5,
  135846. 11,
  135847. 4,
  135848. 12,
  135849. 3,
  135850. 13,
  135851. 2,
  135852. 14,
  135853. 1,
  135854. 15,
  135855. 0,
  135856. 16,
  135857. };
  135858. static long _vq_lengthlist__44c0_s_p5_0[] = {
  135859. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135860. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  135861. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135862. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135863. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135864. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135865. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135866. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135867. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135868. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  135869. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135870. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135871. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  135872. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  135873. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  135874. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  135875. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135877. 14,
  135878. };
  135879. static float _vq_quantthresh__44c0_s_p5_0[] = {
  135880. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135881. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135882. };
  135883. static long _vq_quantmap__44c0_s_p5_0[] = {
  135884. 15, 13, 11, 9, 7, 5, 3, 1,
  135885. 0, 2, 4, 6, 8, 10, 12, 14,
  135886. 16,
  135887. };
  135888. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  135889. _vq_quantthresh__44c0_s_p5_0,
  135890. _vq_quantmap__44c0_s_p5_0,
  135891. 17,
  135892. 17
  135893. };
  135894. static static_codebook _44c0_s_p5_0 = {
  135895. 2, 289,
  135896. _vq_lengthlist__44c0_s_p5_0,
  135897. 1, -529530880, 1611661312, 5, 0,
  135898. _vq_quantlist__44c0_s_p5_0,
  135899. NULL,
  135900. &_vq_auxt__44c0_s_p5_0,
  135901. NULL,
  135902. 0
  135903. };
  135904. static long _vq_quantlist__44c0_s_p6_0[] = {
  135905. 1,
  135906. 0,
  135907. 2,
  135908. };
  135909. static long _vq_lengthlist__44c0_s_p6_0[] = {
  135910. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  135911. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  135912. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  135913. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  135914. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  135915. 10,
  135916. };
  135917. static float _vq_quantthresh__44c0_s_p6_0[] = {
  135918. -5.5, 5.5,
  135919. };
  135920. static long _vq_quantmap__44c0_s_p6_0[] = {
  135921. 1, 0, 2,
  135922. };
  135923. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  135924. _vq_quantthresh__44c0_s_p6_0,
  135925. _vq_quantmap__44c0_s_p6_0,
  135926. 3,
  135927. 3
  135928. };
  135929. static static_codebook _44c0_s_p6_0 = {
  135930. 4, 81,
  135931. _vq_lengthlist__44c0_s_p6_0,
  135932. 1, -529137664, 1618345984, 2, 0,
  135933. _vq_quantlist__44c0_s_p6_0,
  135934. NULL,
  135935. &_vq_auxt__44c0_s_p6_0,
  135936. NULL,
  135937. 0
  135938. };
  135939. static long _vq_quantlist__44c0_s_p6_1[] = {
  135940. 5,
  135941. 4,
  135942. 6,
  135943. 3,
  135944. 7,
  135945. 2,
  135946. 8,
  135947. 1,
  135948. 9,
  135949. 0,
  135950. 10,
  135951. };
  135952. static long _vq_lengthlist__44c0_s_p6_1[] = {
  135953. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  135954. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135955. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135956. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  135957. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135958. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135959. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135960. 10,10,10, 8, 8, 8, 8, 8, 8,
  135961. };
  135962. static float _vq_quantthresh__44c0_s_p6_1[] = {
  135963. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135964. 3.5, 4.5,
  135965. };
  135966. static long _vq_quantmap__44c0_s_p6_1[] = {
  135967. 9, 7, 5, 3, 1, 0, 2, 4,
  135968. 6, 8, 10,
  135969. };
  135970. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  135971. _vq_quantthresh__44c0_s_p6_1,
  135972. _vq_quantmap__44c0_s_p6_1,
  135973. 11,
  135974. 11
  135975. };
  135976. static static_codebook _44c0_s_p6_1 = {
  135977. 2, 121,
  135978. _vq_lengthlist__44c0_s_p6_1,
  135979. 1, -531365888, 1611661312, 4, 0,
  135980. _vq_quantlist__44c0_s_p6_1,
  135981. NULL,
  135982. &_vq_auxt__44c0_s_p6_1,
  135983. NULL,
  135984. 0
  135985. };
  135986. static long _vq_quantlist__44c0_s_p7_0[] = {
  135987. 6,
  135988. 5,
  135989. 7,
  135990. 4,
  135991. 8,
  135992. 3,
  135993. 9,
  135994. 2,
  135995. 10,
  135996. 1,
  135997. 11,
  135998. 0,
  135999. 12,
  136000. };
  136001. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136002. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136003. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136004. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136005. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136006. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136007. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136008. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136009. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136010. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136011. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136012. 0,12,12,11,11,12,12,13,13,
  136013. };
  136014. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136015. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136016. 12.5, 17.5, 22.5, 27.5,
  136017. };
  136018. static long _vq_quantmap__44c0_s_p7_0[] = {
  136019. 11, 9, 7, 5, 3, 1, 0, 2,
  136020. 4, 6, 8, 10, 12,
  136021. };
  136022. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136023. _vq_quantthresh__44c0_s_p7_0,
  136024. _vq_quantmap__44c0_s_p7_0,
  136025. 13,
  136026. 13
  136027. };
  136028. static static_codebook _44c0_s_p7_0 = {
  136029. 2, 169,
  136030. _vq_lengthlist__44c0_s_p7_0,
  136031. 1, -526516224, 1616117760, 4, 0,
  136032. _vq_quantlist__44c0_s_p7_0,
  136033. NULL,
  136034. &_vq_auxt__44c0_s_p7_0,
  136035. NULL,
  136036. 0
  136037. };
  136038. static long _vq_quantlist__44c0_s_p7_1[] = {
  136039. 2,
  136040. 1,
  136041. 3,
  136042. 0,
  136043. 4,
  136044. };
  136045. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136046. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136047. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136048. };
  136049. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136050. -1.5, -0.5, 0.5, 1.5,
  136051. };
  136052. static long _vq_quantmap__44c0_s_p7_1[] = {
  136053. 3, 1, 0, 2, 4,
  136054. };
  136055. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136056. _vq_quantthresh__44c0_s_p7_1,
  136057. _vq_quantmap__44c0_s_p7_1,
  136058. 5,
  136059. 5
  136060. };
  136061. static static_codebook _44c0_s_p7_1 = {
  136062. 2, 25,
  136063. _vq_lengthlist__44c0_s_p7_1,
  136064. 1, -533725184, 1611661312, 3, 0,
  136065. _vq_quantlist__44c0_s_p7_1,
  136066. NULL,
  136067. &_vq_auxt__44c0_s_p7_1,
  136068. NULL,
  136069. 0
  136070. };
  136071. static long _vq_quantlist__44c0_s_p8_0[] = {
  136072. 2,
  136073. 1,
  136074. 3,
  136075. 0,
  136076. 4,
  136077. };
  136078. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136079. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136080. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136081. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136082. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136083. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136084. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136085. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136086. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136087. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136088. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136089. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136090. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136091. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136094. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136101. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136103. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136106. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136108. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136109. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136110. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136111. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136117. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136118. 11,
  136119. };
  136120. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136121. -331.5, -110.5, 110.5, 331.5,
  136122. };
  136123. static long _vq_quantmap__44c0_s_p8_0[] = {
  136124. 3, 1, 0, 2, 4,
  136125. };
  136126. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136127. _vq_quantthresh__44c0_s_p8_0,
  136128. _vq_quantmap__44c0_s_p8_0,
  136129. 5,
  136130. 5
  136131. };
  136132. static static_codebook _44c0_s_p8_0 = {
  136133. 4, 625,
  136134. _vq_lengthlist__44c0_s_p8_0,
  136135. 1, -518283264, 1627103232, 3, 0,
  136136. _vq_quantlist__44c0_s_p8_0,
  136137. NULL,
  136138. &_vq_auxt__44c0_s_p8_0,
  136139. NULL,
  136140. 0
  136141. };
  136142. static long _vq_quantlist__44c0_s_p8_1[] = {
  136143. 6,
  136144. 5,
  136145. 7,
  136146. 4,
  136147. 8,
  136148. 3,
  136149. 9,
  136150. 2,
  136151. 10,
  136152. 1,
  136153. 11,
  136154. 0,
  136155. 12,
  136156. };
  136157. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136158. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136159. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136160. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136161. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136162. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136163. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136164. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136165. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136166. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136167. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136168. 16,13,13,12,12,14,14,15,13,
  136169. };
  136170. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136171. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136172. 42.5, 59.5, 76.5, 93.5,
  136173. };
  136174. static long _vq_quantmap__44c0_s_p8_1[] = {
  136175. 11, 9, 7, 5, 3, 1, 0, 2,
  136176. 4, 6, 8, 10, 12,
  136177. };
  136178. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136179. _vq_quantthresh__44c0_s_p8_1,
  136180. _vq_quantmap__44c0_s_p8_1,
  136181. 13,
  136182. 13
  136183. };
  136184. static static_codebook _44c0_s_p8_1 = {
  136185. 2, 169,
  136186. _vq_lengthlist__44c0_s_p8_1,
  136187. 1, -522616832, 1620115456, 4, 0,
  136188. _vq_quantlist__44c0_s_p8_1,
  136189. NULL,
  136190. &_vq_auxt__44c0_s_p8_1,
  136191. NULL,
  136192. 0
  136193. };
  136194. static long _vq_quantlist__44c0_s_p8_2[] = {
  136195. 8,
  136196. 7,
  136197. 9,
  136198. 6,
  136199. 10,
  136200. 5,
  136201. 11,
  136202. 4,
  136203. 12,
  136204. 3,
  136205. 13,
  136206. 2,
  136207. 14,
  136208. 1,
  136209. 15,
  136210. 0,
  136211. 16,
  136212. };
  136213. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136214. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136215. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136216. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136217. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136218. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136219. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136220. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136221. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136222. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136223. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136224. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136225. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136226. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136227. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136228. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136229. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136230. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136231. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136232. 10,
  136233. };
  136234. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136235. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136236. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136237. };
  136238. static long _vq_quantmap__44c0_s_p8_2[] = {
  136239. 15, 13, 11, 9, 7, 5, 3, 1,
  136240. 0, 2, 4, 6, 8, 10, 12, 14,
  136241. 16,
  136242. };
  136243. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136244. _vq_quantthresh__44c0_s_p8_2,
  136245. _vq_quantmap__44c0_s_p8_2,
  136246. 17,
  136247. 17
  136248. };
  136249. static static_codebook _44c0_s_p8_2 = {
  136250. 2, 289,
  136251. _vq_lengthlist__44c0_s_p8_2,
  136252. 1, -529530880, 1611661312, 5, 0,
  136253. _vq_quantlist__44c0_s_p8_2,
  136254. NULL,
  136255. &_vq_auxt__44c0_s_p8_2,
  136256. NULL,
  136257. 0
  136258. };
  136259. static long _huff_lengthlist__44c0_s_short[] = {
  136260. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136261. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136262. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136263. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136264. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136265. 12,
  136266. };
  136267. static static_codebook _huff_book__44c0_s_short = {
  136268. 2, 81,
  136269. _huff_lengthlist__44c0_s_short,
  136270. 0, 0, 0, 0, 0,
  136271. NULL,
  136272. NULL,
  136273. NULL,
  136274. NULL,
  136275. 0
  136276. };
  136277. static long _huff_lengthlist__44c0_sm_long[] = {
  136278. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136279. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136280. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136281. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136282. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136283. 13,
  136284. };
  136285. static static_codebook _huff_book__44c0_sm_long = {
  136286. 2, 81,
  136287. _huff_lengthlist__44c0_sm_long,
  136288. 0, 0, 0, 0, 0,
  136289. NULL,
  136290. NULL,
  136291. NULL,
  136292. NULL,
  136293. 0
  136294. };
  136295. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136296. 1,
  136297. 0,
  136298. 2,
  136299. };
  136300. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136301. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136302. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136307. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136312. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  136347. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136352. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  136357. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136393. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136398. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136403. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0,
  136712. };
  136713. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136714. -0.5, 0.5,
  136715. };
  136716. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136717. 1, 0, 2,
  136718. };
  136719. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136720. _vq_quantthresh__44c0_sm_p1_0,
  136721. _vq_quantmap__44c0_sm_p1_0,
  136722. 3,
  136723. 3
  136724. };
  136725. static static_codebook _44c0_sm_p1_0 = {
  136726. 8, 6561,
  136727. _vq_lengthlist__44c0_sm_p1_0,
  136728. 1, -535822336, 1611661312, 2, 0,
  136729. _vq_quantlist__44c0_sm_p1_0,
  136730. NULL,
  136731. &_vq_auxt__44c0_sm_p1_0,
  136732. NULL,
  136733. 0
  136734. };
  136735. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136736. 2,
  136737. 1,
  136738. 3,
  136739. 0,
  136740. 4,
  136741. };
  136742. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136743. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0,
  136783. };
  136784. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136785. -1.5, -0.5, 0.5, 1.5,
  136786. };
  136787. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136788. 3, 1, 0, 2, 4,
  136789. };
  136790. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136791. _vq_quantthresh__44c0_sm_p2_0,
  136792. _vq_quantmap__44c0_sm_p2_0,
  136793. 5,
  136794. 5
  136795. };
  136796. static static_codebook _44c0_sm_p2_0 = {
  136797. 4, 625,
  136798. _vq_lengthlist__44c0_sm_p2_0,
  136799. 1, -533725184, 1611661312, 3, 0,
  136800. _vq_quantlist__44c0_sm_p2_0,
  136801. NULL,
  136802. &_vq_auxt__44c0_sm_p2_0,
  136803. NULL,
  136804. 0
  136805. };
  136806. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136807. 4,
  136808. 3,
  136809. 5,
  136810. 2,
  136811. 6,
  136812. 1,
  136813. 7,
  136814. 0,
  136815. 8,
  136816. };
  136817. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  136818. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  136819. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136820. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136821. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  136822. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0,
  136824. };
  136825. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  136826. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136827. };
  136828. static long _vq_quantmap__44c0_sm_p3_0[] = {
  136829. 7, 5, 3, 1, 0, 2, 4, 6,
  136830. 8,
  136831. };
  136832. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  136833. _vq_quantthresh__44c0_sm_p3_0,
  136834. _vq_quantmap__44c0_sm_p3_0,
  136835. 9,
  136836. 9
  136837. };
  136838. static static_codebook _44c0_sm_p3_0 = {
  136839. 2, 81,
  136840. _vq_lengthlist__44c0_sm_p3_0,
  136841. 1, -531628032, 1611661312, 4, 0,
  136842. _vq_quantlist__44c0_sm_p3_0,
  136843. NULL,
  136844. &_vq_auxt__44c0_sm_p3_0,
  136845. NULL,
  136846. 0
  136847. };
  136848. static long _vq_quantlist__44c0_sm_p4_0[] = {
  136849. 4,
  136850. 3,
  136851. 5,
  136852. 2,
  136853. 6,
  136854. 1,
  136855. 7,
  136856. 0,
  136857. 8,
  136858. };
  136859. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  136860. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136861. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136862. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136863. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136864. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136865. 11,
  136866. };
  136867. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  136868. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136869. };
  136870. static long _vq_quantmap__44c0_sm_p4_0[] = {
  136871. 7, 5, 3, 1, 0, 2, 4, 6,
  136872. 8,
  136873. };
  136874. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  136875. _vq_quantthresh__44c0_sm_p4_0,
  136876. _vq_quantmap__44c0_sm_p4_0,
  136877. 9,
  136878. 9
  136879. };
  136880. static static_codebook _44c0_sm_p4_0 = {
  136881. 2, 81,
  136882. _vq_lengthlist__44c0_sm_p4_0,
  136883. 1, -531628032, 1611661312, 4, 0,
  136884. _vq_quantlist__44c0_sm_p4_0,
  136885. NULL,
  136886. &_vq_auxt__44c0_sm_p4_0,
  136887. NULL,
  136888. 0
  136889. };
  136890. static long _vq_quantlist__44c0_sm_p5_0[] = {
  136891. 8,
  136892. 7,
  136893. 9,
  136894. 6,
  136895. 10,
  136896. 5,
  136897. 11,
  136898. 4,
  136899. 12,
  136900. 3,
  136901. 13,
  136902. 2,
  136903. 14,
  136904. 1,
  136905. 15,
  136906. 0,
  136907. 16,
  136908. };
  136909. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  136910. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  136911. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  136912. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136913. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  136914. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  136915. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136916. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136917. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136918. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  136919. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136920. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136921. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136922. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  136923. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  136924. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  136925. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  136926. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136928. 14,
  136929. };
  136930. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  136931. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136932. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136933. };
  136934. static long _vq_quantmap__44c0_sm_p5_0[] = {
  136935. 15, 13, 11, 9, 7, 5, 3, 1,
  136936. 0, 2, 4, 6, 8, 10, 12, 14,
  136937. 16,
  136938. };
  136939. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  136940. _vq_quantthresh__44c0_sm_p5_0,
  136941. _vq_quantmap__44c0_sm_p5_0,
  136942. 17,
  136943. 17
  136944. };
  136945. static static_codebook _44c0_sm_p5_0 = {
  136946. 2, 289,
  136947. _vq_lengthlist__44c0_sm_p5_0,
  136948. 1, -529530880, 1611661312, 5, 0,
  136949. _vq_quantlist__44c0_sm_p5_0,
  136950. NULL,
  136951. &_vq_auxt__44c0_sm_p5_0,
  136952. NULL,
  136953. 0
  136954. };
  136955. static long _vq_quantlist__44c0_sm_p6_0[] = {
  136956. 1,
  136957. 0,
  136958. 2,
  136959. };
  136960. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  136961. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136962. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136963. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136964. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  136965. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136966. 11,
  136967. };
  136968. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  136969. -5.5, 5.5,
  136970. };
  136971. static long _vq_quantmap__44c0_sm_p6_0[] = {
  136972. 1, 0, 2,
  136973. };
  136974. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  136975. _vq_quantthresh__44c0_sm_p6_0,
  136976. _vq_quantmap__44c0_sm_p6_0,
  136977. 3,
  136978. 3
  136979. };
  136980. static static_codebook _44c0_sm_p6_0 = {
  136981. 4, 81,
  136982. _vq_lengthlist__44c0_sm_p6_0,
  136983. 1, -529137664, 1618345984, 2, 0,
  136984. _vq_quantlist__44c0_sm_p6_0,
  136985. NULL,
  136986. &_vq_auxt__44c0_sm_p6_0,
  136987. NULL,
  136988. 0
  136989. };
  136990. static long _vq_quantlist__44c0_sm_p6_1[] = {
  136991. 5,
  136992. 4,
  136993. 6,
  136994. 3,
  136995. 7,
  136996. 2,
  136997. 8,
  136998. 1,
  136999. 9,
  137000. 0,
  137001. 10,
  137002. };
  137003. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137004. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137005. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137006. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137007. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137008. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137009. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137010. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137011. 10,10,10, 8, 8, 8, 8, 8, 8,
  137012. };
  137013. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137014. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137015. 3.5, 4.5,
  137016. };
  137017. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137018. 9, 7, 5, 3, 1, 0, 2, 4,
  137019. 6, 8, 10,
  137020. };
  137021. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137022. _vq_quantthresh__44c0_sm_p6_1,
  137023. _vq_quantmap__44c0_sm_p6_1,
  137024. 11,
  137025. 11
  137026. };
  137027. static static_codebook _44c0_sm_p6_1 = {
  137028. 2, 121,
  137029. _vq_lengthlist__44c0_sm_p6_1,
  137030. 1, -531365888, 1611661312, 4, 0,
  137031. _vq_quantlist__44c0_sm_p6_1,
  137032. NULL,
  137033. &_vq_auxt__44c0_sm_p6_1,
  137034. NULL,
  137035. 0
  137036. };
  137037. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137038. 6,
  137039. 5,
  137040. 7,
  137041. 4,
  137042. 8,
  137043. 3,
  137044. 9,
  137045. 2,
  137046. 10,
  137047. 1,
  137048. 11,
  137049. 0,
  137050. 12,
  137051. };
  137052. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137053. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137054. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137055. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137056. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137057. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137058. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137059. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137060. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137061. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137062. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137063. 0,12,12,11,11,13,12,14,14,
  137064. };
  137065. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137066. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137067. 12.5, 17.5, 22.5, 27.5,
  137068. };
  137069. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137070. 11, 9, 7, 5, 3, 1, 0, 2,
  137071. 4, 6, 8, 10, 12,
  137072. };
  137073. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137074. _vq_quantthresh__44c0_sm_p7_0,
  137075. _vq_quantmap__44c0_sm_p7_0,
  137076. 13,
  137077. 13
  137078. };
  137079. static static_codebook _44c0_sm_p7_0 = {
  137080. 2, 169,
  137081. _vq_lengthlist__44c0_sm_p7_0,
  137082. 1, -526516224, 1616117760, 4, 0,
  137083. _vq_quantlist__44c0_sm_p7_0,
  137084. NULL,
  137085. &_vq_auxt__44c0_sm_p7_0,
  137086. NULL,
  137087. 0
  137088. };
  137089. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137090. 2,
  137091. 1,
  137092. 3,
  137093. 0,
  137094. 4,
  137095. };
  137096. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137097. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137098. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137099. };
  137100. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137101. -1.5, -0.5, 0.5, 1.5,
  137102. };
  137103. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137104. 3, 1, 0, 2, 4,
  137105. };
  137106. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137107. _vq_quantthresh__44c0_sm_p7_1,
  137108. _vq_quantmap__44c0_sm_p7_1,
  137109. 5,
  137110. 5
  137111. };
  137112. static static_codebook _44c0_sm_p7_1 = {
  137113. 2, 25,
  137114. _vq_lengthlist__44c0_sm_p7_1,
  137115. 1, -533725184, 1611661312, 3, 0,
  137116. _vq_quantlist__44c0_sm_p7_1,
  137117. NULL,
  137118. &_vq_auxt__44c0_sm_p7_1,
  137119. NULL,
  137120. 0
  137121. };
  137122. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137123. 4,
  137124. 3,
  137125. 5,
  137126. 2,
  137127. 6,
  137128. 1,
  137129. 7,
  137130. 0,
  137131. 8,
  137132. };
  137133. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137134. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137135. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137137. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137138. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137139. 12,
  137140. };
  137141. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137142. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137143. };
  137144. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137145. 7, 5, 3, 1, 0, 2, 4, 6,
  137146. 8,
  137147. };
  137148. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137149. _vq_quantthresh__44c0_sm_p8_0,
  137150. _vq_quantmap__44c0_sm_p8_0,
  137151. 9,
  137152. 9
  137153. };
  137154. static static_codebook _44c0_sm_p8_0 = {
  137155. 2, 81,
  137156. _vq_lengthlist__44c0_sm_p8_0,
  137157. 1, -516186112, 1627103232, 4, 0,
  137158. _vq_quantlist__44c0_sm_p8_0,
  137159. NULL,
  137160. &_vq_auxt__44c0_sm_p8_0,
  137161. NULL,
  137162. 0
  137163. };
  137164. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137165. 6,
  137166. 5,
  137167. 7,
  137168. 4,
  137169. 8,
  137170. 3,
  137171. 9,
  137172. 2,
  137173. 10,
  137174. 1,
  137175. 11,
  137176. 0,
  137177. 12,
  137178. };
  137179. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137180. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137181. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137182. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137183. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137184. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137185. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137186. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137187. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137188. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137189. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137190. 20,13,13,12,12,16,13,15,13,
  137191. };
  137192. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137193. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137194. 42.5, 59.5, 76.5, 93.5,
  137195. };
  137196. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137197. 11, 9, 7, 5, 3, 1, 0, 2,
  137198. 4, 6, 8, 10, 12,
  137199. };
  137200. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137201. _vq_quantthresh__44c0_sm_p8_1,
  137202. _vq_quantmap__44c0_sm_p8_1,
  137203. 13,
  137204. 13
  137205. };
  137206. static static_codebook _44c0_sm_p8_1 = {
  137207. 2, 169,
  137208. _vq_lengthlist__44c0_sm_p8_1,
  137209. 1, -522616832, 1620115456, 4, 0,
  137210. _vq_quantlist__44c0_sm_p8_1,
  137211. NULL,
  137212. &_vq_auxt__44c0_sm_p8_1,
  137213. NULL,
  137214. 0
  137215. };
  137216. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137217. 8,
  137218. 7,
  137219. 9,
  137220. 6,
  137221. 10,
  137222. 5,
  137223. 11,
  137224. 4,
  137225. 12,
  137226. 3,
  137227. 13,
  137228. 2,
  137229. 14,
  137230. 1,
  137231. 15,
  137232. 0,
  137233. 16,
  137234. };
  137235. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137236. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137237. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137238. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137239. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137240. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137241. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137242. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137243. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137244. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137245. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137246. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137247. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137248. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137249. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137250. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137251. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137252. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137253. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137254. 9,
  137255. };
  137256. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137257. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137258. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137259. };
  137260. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137261. 15, 13, 11, 9, 7, 5, 3, 1,
  137262. 0, 2, 4, 6, 8, 10, 12, 14,
  137263. 16,
  137264. };
  137265. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137266. _vq_quantthresh__44c0_sm_p8_2,
  137267. _vq_quantmap__44c0_sm_p8_2,
  137268. 17,
  137269. 17
  137270. };
  137271. static static_codebook _44c0_sm_p8_2 = {
  137272. 2, 289,
  137273. _vq_lengthlist__44c0_sm_p8_2,
  137274. 1, -529530880, 1611661312, 5, 0,
  137275. _vq_quantlist__44c0_sm_p8_2,
  137276. NULL,
  137277. &_vq_auxt__44c0_sm_p8_2,
  137278. NULL,
  137279. 0
  137280. };
  137281. static long _huff_lengthlist__44c0_sm_short[] = {
  137282. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137283. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137284. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137285. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137286. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137287. 12,
  137288. };
  137289. static static_codebook _huff_book__44c0_sm_short = {
  137290. 2, 81,
  137291. _huff_lengthlist__44c0_sm_short,
  137292. 0, 0, 0, 0, 0,
  137293. NULL,
  137294. NULL,
  137295. NULL,
  137296. NULL,
  137297. 0
  137298. };
  137299. static long _huff_lengthlist__44c1_s_long[] = {
  137300. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137301. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137302. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137303. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137304. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137305. 11,
  137306. };
  137307. static static_codebook _huff_book__44c1_s_long = {
  137308. 2, 81,
  137309. _huff_lengthlist__44c1_s_long,
  137310. 0, 0, 0, 0, 0,
  137311. NULL,
  137312. NULL,
  137313. NULL,
  137314. NULL,
  137315. 0
  137316. };
  137317. static long _vq_quantlist__44c1_s_p1_0[] = {
  137318. 1,
  137319. 0,
  137320. 2,
  137321. };
  137322. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137323. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137324. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137329. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137334. 0, 0, 0, 0, 7, 8, 8, 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, 4, 7, 7, 0, 0, 0, 0,
  137369. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  137374. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  137379. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137415. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137420. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137425. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137733. 0,
  137734. };
  137735. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137736. -0.5, 0.5,
  137737. };
  137738. static long _vq_quantmap__44c1_s_p1_0[] = {
  137739. 1, 0, 2,
  137740. };
  137741. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137742. _vq_quantthresh__44c1_s_p1_0,
  137743. _vq_quantmap__44c1_s_p1_0,
  137744. 3,
  137745. 3
  137746. };
  137747. static static_codebook _44c1_s_p1_0 = {
  137748. 8, 6561,
  137749. _vq_lengthlist__44c1_s_p1_0,
  137750. 1, -535822336, 1611661312, 2, 0,
  137751. _vq_quantlist__44c1_s_p1_0,
  137752. NULL,
  137753. &_vq_auxt__44c1_s_p1_0,
  137754. NULL,
  137755. 0
  137756. };
  137757. static long _vq_quantlist__44c1_s_p2_0[] = {
  137758. 2,
  137759. 1,
  137760. 3,
  137761. 0,
  137762. 4,
  137763. };
  137764. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137765. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137768. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137804. 0,
  137805. };
  137806. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137807. -1.5, -0.5, 0.5, 1.5,
  137808. };
  137809. static long _vq_quantmap__44c1_s_p2_0[] = {
  137810. 3, 1, 0, 2, 4,
  137811. };
  137812. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137813. _vq_quantthresh__44c1_s_p2_0,
  137814. _vq_quantmap__44c1_s_p2_0,
  137815. 5,
  137816. 5
  137817. };
  137818. static static_codebook _44c1_s_p2_0 = {
  137819. 4, 625,
  137820. _vq_lengthlist__44c1_s_p2_0,
  137821. 1, -533725184, 1611661312, 3, 0,
  137822. _vq_quantlist__44c1_s_p2_0,
  137823. NULL,
  137824. &_vq_auxt__44c1_s_p2_0,
  137825. NULL,
  137826. 0
  137827. };
  137828. static long _vq_quantlist__44c1_s_p3_0[] = {
  137829. 4,
  137830. 3,
  137831. 5,
  137832. 2,
  137833. 6,
  137834. 1,
  137835. 7,
  137836. 0,
  137837. 8,
  137838. };
  137839. static long _vq_lengthlist__44c1_s_p3_0[] = {
  137840. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  137841. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137842. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137843. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137844. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0,
  137846. };
  137847. static float _vq_quantthresh__44c1_s_p3_0[] = {
  137848. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137849. };
  137850. static long _vq_quantmap__44c1_s_p3_0[] = {
  137851. 7, 5, 3, 1, 0, 2, 4, 6,
  137852. 8,
  137853. };
  137854. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  137855. _vq_quantthresh__44c1_s_p3_0,
  137856. _vq_quantmap__44c1_s_p3_0,
  137857. 9,
  137858. 9
  137859. };
  137860. static static_codebook _44c1_s_p3_0 = {
  137861. 2, 81,
  137862. _vq_lengthlist__44c1_s_p3_0,
  137863. 1, -531628032, 1611661312, 4, 0,
  137864. _vq_quantlist__44c1_s_p3_0,
  137865. NULL,
  137866. &_vq_auxt__44c1_s_p3_0,
  137867. NULL,
  137868. 0
  137869. };
  137870. static long _vq_quantlist__44c1_s_p4_0[] = {
  137871. 4,
  137872. 3,
  137873. 5,
  137874. 2,
  137875. 6,
  137876. 1,
  137877. 7,
  137878. 0,
  137879. 8,
  137880. };
  137881. static long _vq_lengthlist__44c1_s_p4_0[] = {
  137882. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137883. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137884. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137885. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  137886. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137887. 11,
  137888. };
  137889. static float _vq_quantthresh__44c1_s_p4_0[] = {
  137890. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137891. };
  137892. static long _vq_quantmap__44c1_s_p4_0[] = {
  137893. 7, 5, 3, 1, 0, 2, 4, 6,
  137894. 8,
  137895. };
  137896. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  137897. _vq_quantthresh__44c1_s_p4_0,
  137898. _vq_quantmap__44c1_s_p4_0,
  137899. 9,
  137900. 9
  137901. };
  137902. static static_codebook _44c1_s_p4_0 = {
  137903. 2, 81,
  137904. _vq_lengthlist__44c1_s_p4_0,
  137905. 1, -531628032, 1611661312, 4, 0,
  137906. _vq_quantlist__44c1_s_p4_0,
  137907. NULL,
  137908. &_vq_auxt__44c1_s_p4_0,
  137909. NULL,
  137910. 0
  137911. };
  137912. static long _vq_quantlist__44c1_s_p5_0[] = {
  137913. 8,
  137914. 7,
  137915. 9,
  137916. 6,
  137917. 10,
  137918. 5,
  137919. 11,
  137920. 4,
  137921. 12,
  137922. 3,
  137923. 13,
  137924. 2,
  137925. 14,
  137926. 1,
  137927. 15,
  137928. 0,
  137929. 16,
  137930. };
  137931. static long _vq_lengthlist__44c1_s_p5_0[] = {
  137932. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137933. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137934. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137935. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137936. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137937. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  137938. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  137939. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137940. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137941. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137942. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137943. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137944. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  137945. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137946. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  137947. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  137948. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137950. 14,
  137951. };
  137952. static float _vq_quantthresh__44c1_s_p5_0[] = {
  137953. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137954. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137955. };
  137956. static long _vq_quantmap__44c1_s_p5_0[] = {
  137957. 15, 13, 11, 9, 7, 5, 3, 1,
  137958. 0, 2, 4, 6, 8, 10, 12, 14,
  137959. 16,
  137960. };
  137961. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  137962. _vq_quantthresh__44c1_s_p5_0,
  137963. _vq_quantmap__44c1_s_p5_0,
  137964. 17,
  137965. 17
  137966. };
  137967. static static_codebook _44c1_s_p5_0 = {
  137968. 2, 289,
  137969. _vq_lengthlist__44c1_s_p5_0,
  137970. 1, -529530880, 1611661312, 5, 0,
  137971. _vq_quantlist__44c1_s_p5_0,
  137972. NULL,
  137973. &_vq_auxt__44c1_s_p5_0,
  137974. NULL,
  137975. 0
  137976. };
  137977. static long _vq_quantlist__44c1_s_p6_0[] = {
  137978. 1,
  137979. 0,
  137980. 2,
  137981. };
  137982. static long _vq_lengthlist__44c1_s_p6_0[] = {
  137983. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137984. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  137985. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137986. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  137987. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  137988. 11,
  137989. };
  137990. static float _vq_quantthresh__44c1_s_p6_0[] = {
  137991. -5.5, 5.5,
  137992. };
  137993. static long _vq_quantmap__44c1_s_p6_0[] = {
  137994. 1, 0, 2,
  137995. };
  137996. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  137997. _vq_quantthresh__44c1_s_p6_0,
  137998. _vq_quantmap__44c1_s_p6_0,
  137999. 3,
  138000. 3
  138001. };
  138002. static static_codebook _44c1_s_p6_0 = {
  138003. 4, 81,
  138004. _vq_lengthlist__44c1_s_p6_0,
  138005. 1, -529137664, 1618345984, 2, 0,
  138006. _vq_quantlist__44c1_s_p6_0,
  138007. NULL,
  138008. &_vq_auxt__44c1_s_p6_0,
  138009. NULL,
  138010. 0
  138011. };
  138012. static long _vq_quantlist__44c1_s_p6_1[] = {
  138013. 5,
  138014. 4,
  138015. 6,
  138016. 3,
  138017. 7,
  138018. 2,
  138019. 8,
  138020. 1,
  138021. 9,
  138022. 0,
  138023. 10,
  138024. };
  138025. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138026. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138027. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138028. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138029. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138030. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138031. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138032. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138033. 10,10,10, 8, 8, 8, 8, 8, 8,
  138034. };
  138035. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138036. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138037. 3.5, 4.5,
  138038. };
  138039. static long _vq_quantmap__44c1_s_p6_1[] = {
  138040. 9, 7, 5, 3, 1, 0, 2, 4,
  138041. 6, 8, 10,
  138042. };
  138043. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138044. _vq_quantthresh__44c1_s_p6_1,
  138045. _vq_quantmap__44c1_s_p6_1,
  138046. 11,
  138047. 11
  138048. };
  138049. static static_codebook _44c1_s_p6_1 = {
  138050. 2, 121,
  138051. _vq_lengthlist__44c1_s_p6_1,
  138052. 1, -531365888, 1611661312, 4, 0,
  138053. _vq_quantlist__44c1_s_p6_1,
  138054. NULL,
  138055. &_vq_auxt__44c1_s_p6_1,
  138056. NULL,
  138057. 0
  138058. };
  138059. static long _vq_quantlist__44c1_s_p7_0[] = {
  138060. 6,
  138061. 5,
  138062. 7,
  138063. 4,
  138064. 8,
  138065. 3,
  138066. 9,
  138067. 2,
  138068. 10,
  138069. 1,
  138070. 11,
  138071. 0,
  138072. 12,
  138073. };
  138074. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138075. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138076. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138077. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138078. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138079. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138080. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138081. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138082. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138083. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138084. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138085. 0,12,11,11,11,13,10,14,13,
  138086. };
  138087. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138088. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138089. 12.5, 17.5, 22.5, 27.5,
  138090. };
  138091. static long _vq_quantmap__44c1_s_p7_0[] = {
  138092. 11, 9, 7, 5, 3, 1, 0, 2,
  138093. 4, 6, 8, 10, 12,
  138094. };
  138095. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138096. _vq_quantthresh__44c1_s_p7_0,
  138097. _vq_quantmap__44c1_s_p7_0,
  138098. 13,
  138099. 13
  138100. };
  138101. static static_codebook _44c1_s_p7_0 = {
  138102. 2, 169,
  138103. _vq_lengthlist__44c1_s_p7_0,
  138104. 1, -526516224, 1616117760, 4, 0,
  138105. _vq_quantlist__44c1_s_p7_0,
  138106. NULL,
  138107. &_vq_auxt__44c1_s_p7_0,
  138108. NULL,
  138109. 0
  138110. };
  138111. static long _vq_quantlist__44c1_s_p7_1[] = {
  138112. 2,
  138113. 1,
  138114. 3,
  138115. 0,
  138116. 4,
  138117. };
  138118. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138119. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138120. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138121. };
  138122. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138123. -1.5, -0.5, 0.5, 1.5,
  138124. };
  138125. static long _vq_quantmap__44c1_s_p7_1[] = {
  138126. 3, 1, 0, 2, 4,
  138127. };
  138128. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138129. _vq_quantthresh__44c1_s_p7_1,
  138130. _vq_quantmap__44c1_s_p7_1,
  138131. 5,
  138132. 5
  138133. };
  138134. static static_codebook _44c1_s_p7_1 = {
  138135. 2, 25,
  138136. _vq_lengthlist__44c1_s_p7_1,
  138137. 1, -533725184, 1611661312, 3, 0,
  138138. _vq_quantlist__44c1_s_p7_1,
  138139. NULL,
  138140. &_vq_auxt__44c1_s_p7_1,
  138141. NULL,
  138142. 0
  138143. };
  138144. static long _vq_quantlist__44c1_s_p8_0[] = {
  138145. 6,
  138146. 5,
  138147. 7,
  138148. 4,
  138149. 8,
  138150. 3,
  138151. 9,
  138152. 2,
  138153. 10,
  138154. 1,
  138155. 11,
  138156. 0,
  138157. 12,
  138158. };
  138159. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138160. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138161. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138162. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138163. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138164. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138165. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138166. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138167. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138168. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138169. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138170. 10,10,10,10,10,10,10,10,10,
  138171. };
  138172. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138173. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138174. 552.5, 773.5, 994.5, 1215.5,
  138175. };
  138176. static long _vq_quantmap__44c1_s_p8_0[] = {
  138177. 11, 9, 7, 5, 3, 1, 0, 2,
  138178. 4, 6, 8, 10, 12,
  138179. };
  138180. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138181. _vq_quantthresh__44c1_s_p8_0,
  138182. _vq_quantmap__44c1_s_p8_0,
  138183. 13,
  138184. 13
  138185. };
  138186. static static_codebook _44c1_s_p8_0 = {
  138187. 2, 169,
  138188. _vq_lengthlist__44c1_s_p8_0,
  138189. 1, -514541568, 1627103232, 4, 0,
  138190. _vq_quantlist__44c1_s_p8_0,
  138191. NULL,
  138192. &_vq_auxt__44c1_s_p8_0,
  138193. NULL,
  138194. 0
  138195. };
  138196. static long _vq_quantlist__44c1_s_p8_1[] = {
  138197. 6,
  138198. 5,
  138199. 7,
  138200. 4,
  138201. 8,
  138202. 3,
  138203. 9,
  138204. 2,
  138205. 10,
  138206. 1,
  138207. 11,
  138208. 0,
  138209. 12,
  138210. };
  138211. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138212. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138213. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138214. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138215. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138216. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138217. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138218. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138219. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138220. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138221. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138222. 16,13,12,12,11,14,12,15,13,
  138223. };
  138224. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138225. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138226. 42.5, 59.5, 76.5, 93.5,
  138227. };
  138228. static long _vq_quantmap__44c1_s_p8_1[] = {
  138229. 11, 9, 7, 5, 3, 1, 0, 2,
  138230. 4, 6, 8, 10, 12,
  138231. };
  138232. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138233. _vq_quantthresh__44c1_s_p8_1,
  138234. _vq_quantmap__44c1_s_p8_1,
  138235. 13,
  138236. 13
  138237. };
  138238. static static_codebook _44c1_s_p8_1 = {
  138239. 2, 169,
  138240. _vq_lengthlist__44c1_s_p8_1,
  138241. 1, -522616832, 1620115456, 4, 0,
  138242. _vq_quantlist__44c1_s_p8_1,
  138243. NULL,
  138244. &_vq_auxt__44c1_s_p8_1,
  138245. NULL,
  138246. 0
  138247. };
  138248. static long _vq_quantlist__44c1_s_p8_2[] = {
  138249. 8,
  138250. 7,
  138251. 9,
  138252. 6,
  138253. 10,
  138254. 5,
  138255. 11,
  138256. 4,
  138257. 12,
  138258. 3,
  138259. 13,
  138260. 2,
  138261. 14,
  138262. 1,
  138263. 15,
  138264. 0,
  138265. 16,
  138266. };
  138267. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138268. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138269. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138270. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138271. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138272. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138273. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138274. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138275. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138276. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138277. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138278. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138279. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138280. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138281. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138282. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138283. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138284. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138285. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138286. 9,
  138287. };
  138288. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138289. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138290. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138291. };
  138292. static long _vq_quantmap__44c1_s_p8_2[] = {
  138293. 15, 13, 11, 9, 7, 5, 3, 1,
  138294. 0, 2, 4, 6, 8, 10, 12, 14,
  138295. 16,
  138296. };
  138297. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138298. _vq_quantthresh__44c1_s_p8_2,
  138299. _vq_quantmap__44c1_s_p8_2,
  138300. 17,
  138301. 17
  138302. };
  138303. static static_codebook _44c1_s_p8_2 = {
  138304. 2, 289,
  138305. _vq_lengthlist__44c1_s_p8_2,
  138306. 1, -529530880, 1611661312, 5, 0,
  138307. _vq_quantlist__44c1_s_p8_2,
  138308. NULL,
  138309. &_vq_auxt__44c1_s_p8_2,
  138310. NULL,
  138311. 0
  138312. };
  138313. static long _huff_lengthlist__44c1_s_short[] = {
  138314. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138315. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138316. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138317. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138318. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138319. 11,
  138320. };
  138321. static static_codebook _huff_book__44c1_s_short = {
  138322. 2, 81,
  138323. _huff_lengthlist__44c1_s_short,
  138324. 0, 0, 0, 0, 0,
  138325. NULL,
  138326. NULL,
  138327. NULL,
  138328. NULL,
  138329. 0
  138330. };
  138331. static long _huff_lengthlist__44c1_sm_long[] = {
  138332. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138333. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138334. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138335. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138336. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138337. 11,
  138338. };
  138339. static static_codebook _huff_book__44c1_sm_long = {
  138340. 2, 81,
  138341. _huff_lengthlist__44c1_sm_long,
  138342. 0, 0, 0, 0, 0,
  138343. NULL,
  138344. NULL,
  138345. NULL,
  138346. NULL,
  138347. 0
  138348. };
  138349. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138350. 1,
  138351. 0,
  138352. 2,
  138353. };
  138354. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138355. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138356. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138361. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138366. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  138401. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  138406. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  138411. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138447. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138452. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138457. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138765. 0,
  138766. };
  138767. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138768. -0.5, 0.5,
  138769. };
  138770. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138771. 1, 0, 2,
  138772. };
  138773. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138774. _vq_quantthresh__44c1_sm_p1_0,
  138775. _vq_quantmap__44c1_sm_p1_0,
  138776. 3,
  138777. 3
  138778. };
  138779. static static_codebook _44c1_sm_p1_0 = {
  138780. 8, 6561,
  138781. _vq_lengthlist__44c1_sm_p1_0,
  138782. 1, -535822336, 1611661312, 2, 0,
  138783. _vq_quantlist__44c1_sm_p1_0,
  138784. NULL,
  138785. &_vq_auxt__44c1_sm_p1_0,
  138786. NULL,
  138787. 0
  138788. };
  138789. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138790. 2,
  138791. 1,
  138792. 3,
  138793. 0,
  138794. 4,
  138795. };
  138796. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138797. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138800. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138803. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138836. 0,
  138837. };
  138838. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  138839. -1.5, -0.5, 0.5, 1.5,
  138840. };
  138841. static long _vq_quantmap__44c1_sm_p2_0[] = {
  138842. 3, 1, 0, 2, 4,
  138843. };
  138844. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  138845. _vq_quantthresh__44c1_sm_p2_0,
  138846. _vq_quantmap__44c1_sm_p2_0,
  138847. 5,
  138848. 5
  138849. };
  138850. static static_codebook _44c1_sm_p2_0 = {
  138851. 4, 625,
  138852. _vq_lengthlist__44c1_sm_p2_0,
  138853. 1, -533725184, 1611661312, 3, 0,
  138854. _vq_quantlist__44c1_sm_p2_0,
  138855. NULL,
  138856. &_vq_auxt__44c1_sm_p2_0,
  138857. NULL,
  138858. 0
  138859. };
  138860. static long _vq_quantlist__44c1_sm_p3_0[] = {
  138861. 4,
  138862. 3,
  138863. 5,
  138864. 2,
  138865. 6,
  138866. 1,
  138867. 7,
  138868. 0,
  138869. 8,
  138870. };
  138871. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  138872. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  138873. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  138874. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138875. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138876. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138877. 0,
  138878. };
  138879. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  138880. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138881. };
  138882. static long _vq_quantmap__44c1_sm_p3_0[] = {
  138883. 7, 5, 3, 1, 0, 2, 4, 6,
  138884. 8,
  138885. };
  138886. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  138887. _vq_quantthresh__44c1_sm_p3_0,
  138888. _vq_quantmap__44c1_sm_p3_0,
  138889. 9,
  138890. 9
  138891. };
  138892. static static_codebook _44c1_sm_p3_0 = {
  138893. 2, 81,
  138894. _vq_lengthlist__44c1_sm_p3_0,
  138895. 1, -531628032, 1611661312, 4, 0,
  138896. _vq_quantlist__44c1_sm_p3_0,
  138897. NULL,
  138898. &_vq_auxt__44c1_sm_p3_0,
  138899. NULL,
  138900. 0
  138901. };
  138902. static long _vq_quantlist__44c1_sm_p4_0[] = {
  138903. 4,
  138904. 3,
  138905. 5,
  138906. 2,
  138907. 6,
  138908. 1,
  138909. 7,
  138910. 0,
  138911. 8,
  138912. };
  138913. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  138914. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  138915. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138916. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138917. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138918. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138919. 11,
  138920. };
  138921. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  138922. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138923. };
  138924. static long _vq_quantmap__44c1_sm_p4_0[] = {
  138925. 7, 5, 3, 1, 0, 2, 4, 6,
  138926. 8,
  138927. };
  138928. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  138929. _vq_quantthresh__44c1_sm_p4_0,
  138930. _vq_quantmap__44c1_sm_p4_0,
  138931. 9,
  138932. 9
  138933. };
  138934. static static_codebook _44c1_sm_p4_0 = {
  138935. 2, 81,
  138936. _vq_lengthlist__44c1_sm_p4_0,
  138937. 1, -531628032, 1611661312, 4, 0,
  138938. _vq_quantlist__44c1_sm_p4_0,
  138939. NULL,
  138940. &_vq_auxt__44c1_sm_p4_0,
  138941. NULL,
  138942. 0
  138943. };
  138944. static long _vq_quantlist__44c1_sm_p5_0[] = {
  138945. 8,
  138946. 7,
  138947. 9,
  138948. 6,
  138949. 10,
  138950. 5,
  138951. 11,
  138952. 4,
  138953. 12,
  138954. 3,
  138955. 13,
  138956. 2,
  138957. 14,
  138958. 1,
  138959. 15,
  138960. 0,
  138961. 16,
  138962. };
  138963. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  138964. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138965. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138966. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  138967. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138968. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138969. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  138970. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  138971. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138972. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138973. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138974. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138975. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138976. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138977. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138978. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  138979. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138980. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138982. 14,
  138983. };
  138984. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  138985. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138986. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138987. };
  138988. static long _vq_quantmap__44c1_sm_p5_0[] = {
  138989. 15, 13, 11, 9, 7, 5, 3, 1,
  138990. 0, 2, 4, 6, 8, 10, 12, 14,
  138991. 16,
  138992. };
  138993. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  138994. _vq_quantthresh__44c1_sm_p5_0,
  138995. _vq_quantmap__44c1_sm_p5_0,
  138996. 17,
  138997. 17
  138998. };
  138999. static static_codebook _44c1_sm_p5_0 = {
  139000. 2, 289,
  139001. _vq_lengthlist__44c1_sm_p5_0,
  139002. 1, -529530880, 1611661312, 5, 0,
  139003. _vq_quantlist__44c1_sm_p5_0,
  139004. NULL,
  139005. &_vq_auxt__44c1_sm_p5_0,
  139006. NULL,
  139007. 0
  139008. };
  139009. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139010. 1,
  139011. 0,
  139012. 2,
  139013. };
  139014. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139015. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139016. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139017. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139018. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139019. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139020. 11,
  139021. };
  139022. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139023. -5.5, 5.5,
  139024. };
  139025. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139026. 1, 0, 2,
  139027. };
  139028. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139029. _vq_quantthresh__44c1_sm_p6_0,
  139030. _vq_quantmap__44c1_sm_p6_0,
  139031. 3,
  139032. 3
  139033. };
  139034. static static_codebook _44c1_sm_p6_0 = {
  139035. 4, 81,
  139036. _vq_lengthlist__44c1_sm_p6_0,
  139037. 1, -529137664, 1618345984, 2, 0,
  139038. _vq_quantlist__44c1_sm_p6_0,
  139039. NULL,
  139040. &_vq_auxt__44c1_sm_p6_0,
  139041. NULL,
  139042. 0
  139043. };
  139044. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139045. 5,
  139046. 4,
  139047. 6,
  139048. 3,
  139049. 7,
  139050. 2,
  139051. 8,
  139052. 1,
  139053. 9,
  139054. 0,
  139055. 10,
  139056. };
  139057. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139058. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139059. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139060. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139061. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139062. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139063. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139064. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139065. 10,10,10, 8, 8, 8, 8, 8, 8,
  139066. };
  139067. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139068. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139069. 3.5, 4.5,
  139070. };
  139071. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139072. 9, 7, 5, 3, 1, 0, 2, 4,
  139073. 6, 8, 10,
  139074. };
  139075. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139076. _vq_quantthresh__44c1_sm_p6_1,
  139077. _vq_quantmap__44c1_sm_p6_1,
  139078. 11,
  139079. 11
  139080. };
  139081. static static_codebook _44c1_sm_p6_1 = {
  139082. 2, 121,
  139083. _vq_lengthlist__44c1_sm_p6_1,
  139084. 1, -531365888, 1611661312, 4, 0,
  139085. _vq_quantlist__44c1_sm_p6_1,
  139086. NULL,
  139087. &_vq_auxt__44c1_sm_p6_1,
  139088. NULL,
  139089. 0
  139090. };
  139091. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139092. 6,
  139093. 5,
  139094. 7,
  139095. 4,
  139096. 8,
  139097. 3,
  139098. 9,
  139099. 2,
  139100. 10,
  139101. 1,
  139102. 11,
  139103. 0,
  139104. 12,
  139105. };
  139106. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139107. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139108. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139109. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139110. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139111. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139112. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139113. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139114. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139115. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139116. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139117. 0,12,12,11,11,13,12,14,13,
  139118. };
  139119. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139120. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139121. 12.5, 17.5, 22.5, 27.5,
  139122. };
  139123. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139124. 11, 9, 7, 5, 3, 1, 0, 2,
  139125. 4, 6, 8, 10, 12,
  139126. };
  139127. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139128. _vq_quantthresh__44c1_sm_p7_0,
  139129. _vq_quantmap__44c1_sm_p7_0,
  139130. 13,
  139131. 13
  139132. };
  139133. static static_codebook _44c1_sm_p7_0 = {
  139134. 2, 169,
  139135. _vq_lengthlist__44c1_sm_p7_0,
  139136. 1, -526516224, 1616117760, 4, 0,
  139137. _vq_quantlist__44c1_sm_p7_0,
  139138. NULL,
  139139. &_vq_auxt__44c1_sm_p7_0,
  139140. NULL,
  139141. 0
  139142. };
  139143. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139144. 2,
  139145. 1,
  139146. 3,
  139147. 0,
  139148. 4,
  139149. };
  139150. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139151. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139152. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139153. };
  139154. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139155. -1.5, -0.5, 0.5, 1.5,
  139156. };
  139157. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139158. 3, 1, 0, 2, 4,
  139159. };
  139160. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139161. _vq_quantthresh__44c1_sm_p7_1,
  139162. _vq_quantmap__44c1_sm_p7_1,
  139163. 5,
  139164. 5
  139165. };
  139166. static static_codebook _44c1_sm_p7_1 = {
  139167. 2, 25,
  139168. _vq_lengthlist__44c1_sm_p7_1,
  139169. 1, -533725184, 1611661312, 3, 0,
  139170. _vq_quantlist__44c1_sm_p7_1,
  139171. NULL,
  139172. &_vq_auxt__44c1_sm_p7_1,
  139173. NULL,
  139174. 0
  139175. };
  139176. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139177. 6,
  139178. 5,
  139179. 7,
  139180. 4,
  139181. 8,
  139182. 3,
  139183. 9,
  139184. 2,
  139185. 10,
  139186. 1,
  139187. 11,
  139188. 0,
  139189. 12,
  139190. };
  139191. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139192. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139193. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139194. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139195. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139196. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139197. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139198. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139199. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139200. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139201. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139202. 13,13,13,13,13,13,13,13,13,
  139203. };
  139204. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139205. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139206. 552.5, 773.5, 994.5, 1215.5,
  139207. };
  139208. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139209. 11, 9, 7, 5, 3, 1, 0, 2,
  139210. 4, 6, 8, 10, 12,
  139211. };
  139212. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139213. _vq_quantthresh__44c1_sm_p8_0,
  139214. _vq_quantmap__44c1_sm_p8_0,
  139215. 13,
  139216. 13
  139217. };
  139218. static static_codebook _44c1_sm_p8_0 = {
  139219. 2, 169,
  139220. _vq_lengthlist__44c1_sm_p8_0,
  139221. 1, -514541568, 1627103232, 4, 0,
  139222. _vq_quantlist__44c1_sm_p8_0,
  139223. NULL,
  139224. &_vq_auxt__44c1_sm_p8_0,
  139225. NULL,
  139226. 0
  139227. };
  139228. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139229. 6,
  139230. 5,
  139231. 7,
  139232. 4,
  139233. 8,
  139234. 3,
  139235. 9,
  139236. 2,
  139237. 10,
  139238. 1,
  139239. 11,
  139240. 0,
  139241. 12,
  139242. };
  139243. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139244. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139245. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139246. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139247. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139248. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139249. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139250. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139251. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139252. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139253. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139254. 20,13,12,12,12,14,12,14,13,
  139255. };
  139256. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139257. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139258. 42.5, 59.5, 76.5, 93.5,
  139259. };
  139260. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139261. 11, 9, 7, 5, 3, 1, 0, 2,
  139262. 4, 6, 8, 10, 12,
  139263. };
  139264. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139265. _vq_quantthresh__44c1_sm_p8_1,
  139266. _vq_quantmap__44c1_sm_p8_1,
  139267. 13,
  139268. 13
  139269. };
  139270. static static_codebook _44c1_sm_p8_1 = {
  139271. 2, 169,
  139272. _vq_lengthlist__44c1_sm_p8_1,
  139273. 1, -522616832, 1620115456, 4, 0,
  139274. _vq_quantlist__44c1_sm_p8_1,
  139275. NULL,
  139276. &_vq_auxt__44c1_sm_p8_1,
  139277. NULL,
  139278. 0
  139279. };
  139280. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139281. 8,
  139282. 7,
  139283. 9,
  139284. 6,
  139285. 10,
  139286. 5,
  139287. 11,
  139288. 4,
  139289. 12,
  139290. 3,
  139291. 13,
  139292. 2,
  139293. 14,
  139294. 1,
  139295. 15,
  139296. 0,
  139297. 16,
  139298. };
  139299. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139300. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139301. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139302. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139303. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139304. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139305. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139306. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139307. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139308. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139309. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139310. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139311. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139312. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139313. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139314. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139315. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139316. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139317. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139318. 9,
  139319. };
  139320. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139321. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139322. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139323. };
  139324. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139325. 15, 13, 11, 9, 7, 5, 3, 1,
  139326. 0, 2, 4, 6, 8, 10, 12, 14,
  139327. 16,
  139328. };
  139329. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139330. _vq_quantthresh__44c1_sm_p8_2,
  139331. _vq_quantmap__44c1_sm_p8_2,
  139332. 17,
  139333. 17
  139334. };
  139335. static static_codebook _44c1_sm_p8_2 = {
  139336. 2, 289,
  139337. _vq_lengthlist__44c1_sm_p8_2,
  139338. 1, -529530880, 1611661312, 5, 0,
  139339. _vq_quantlist__44c1_sm_p8_2,
  139340. NULL,
  139341. &_vq_auxt__44c1_sm_p8_2,
  139342. NULL,
  139343. 0
  139344. };
  139345. static long _huff_lengthlist__44c1_sm_short[] = {
  139346. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139347. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139348. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139349. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139350. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139351. 11,
  139352. };
  139353. static static_codebook _huff_book__44c1_sm_short = {
  139354. 2, 81,
  139355. _huff_lengthlist__44c1_sm_short,
  139356. 0, 0, 0, 0, 0,
  139357. NULL,
  139358. NULL,
  139359. NULL,
  139360. NULL,
  139361. 0
  139362. };
  139363. static long _huff_lengthlist__44cn1_s_long[] = {
  139364. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139365. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139366. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139367. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139368. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139369. 20,
  139370. };
  139371. static static_codebook _huff_book__44cn1_s_long = {
  139372. 2, 81,
  139373. _huff_lengthlist__44cn1_s_long,
  139374. 0, 0, 0, 0, 0,
  139375. NULL,
  139376. NULL,
  139377. NULL,
  139378. NULL,
  139379. 0
  139380. };
  139381. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139382. 1,
  139383. 0,
  139384. 2,
  139385. };
  139386. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139387. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139388. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139393. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139398. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139433. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139438. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139443. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139479. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139484. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139489. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139797. 0,
  139798. };
  139799. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139800. -0.5, 0.5,
  139801. };
  139802. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139803. 1, 0, 2,
  139804. };
  139805. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139806. _vq_quantthresh__44cn1_s_p1_0,
  139807. _vq_quantmap__44cn1_s_p1_0,
  139808. 3,
  139809. 3
  139810. };
  139811. static static_codebook _44cn1_s_p1_0 = {
  139812. 8, 6561,
  139813. _vq_lengthlist__44cn1_s_p1_0,
  139814. 1, -535822336, 1611661312, 2, 0,
  139815. _vq_quantlist__44cn1_s_p1_0,
  139816. NULL,
  139817. &_vq_auxt__44cn1_s_p1_0,
  139818. NULL,
  139819. 0
  139820. };
  139821. static long _vq_quantlist__44cn1_s_p2_0[] = {
  139822. 2,
  139823. 1,
  139824. 3,
  139825. 0,
  139826. 4,
  139827. };
  139828. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  139829. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  139831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139832. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  139834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139835. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139868. 0,
  139869. };
  139870. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  139871. -1.5, -0.5, 0.5, 1.5,
  139872. };
  139873. static long _vq_quantmap__44cn1_s_p2_0[] = {
  139874. 3, 1, 0, 2, 4,
  139875. };
  139876. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  139877. _vq_quantthresh__44cn1_s_p2_0,
  139878. _vq_quantmap__44cn1_s_p2_0,
  139879. 5,
  139880. 5
  139881. };
  139882. static static_codebook _44cn1_s_p2_0 = {
  139883. 4, 625,
  139884. _vq_lengthlist__44cn1_s_p2_0,
  139885. 1, -533725184, 1611661312, 3, 0,
  139886. _vq_quantlist__44cn1_s_p2_0,
  139887. NULL,
  139888. &_vq_auxt__44cn1_s_p2_0,
  139889. NULL,
  139890. 0
  139891. };
  139892. static long _vq_quantlist__44cn1_s_p3_0[] = {
  139893. 4,
  139894. 3,
  139895. 5,
  139896. 2,
  139897. 6,
  139898. 1,
  139899. 7,
  139900. 0,
  139901. 8,
  139902. };
  139903. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  139904. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  139905. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139906. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139907. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139908. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139909. 0,
  139910. };
  139911. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  139912. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139913. };
  139914. static long _vq_quantmap__44cn1_s_p3_0[] = {
  139915. 7, 5, 3, 1, 0, 2, 4, 6,
  139916. 8,
  139917. };
  139918. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  139919. _vq_quantthresh__44cn1_s_p3_0,
  139920. _vq_quantmap__44cn1_s_p3_0,
  139921. 9,
  139922. 9
  139923. };
  139924. static static_codebook _44cn1_s_p3_0 = {
  139925. 2, 81,
  139926. _vq_lengthlist__44cn1_s_p3_0,
  139927. 1, -531628032, 1611661312, 4, 0,
  139928. _vq_quantlist__44cn1_s_p3_0,
  139929. NULL,
  139930. &_vq_auxt__44cn1_s_p3_0,
  139931. NULL,
  139932. 0
  139933. };
  139934. static long _vq_quantlist__44cn1_s_p4_0[] = {
  139935. 4,
  139936. 3,
  139937. 5,
  139938. 2,
  139939. 6,
  139940. 1,
  139941. 7,
  139942. 0,
  139943. 8,
  139944. };
  139945. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  139946. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  139947. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139948. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139949. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  139950. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  139951. 11,
  139952. };
  139953. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  139954. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139955. };
  139956. static long _vq_quantmap__44cn1_s_p4_0[] = {
  139957. 7, 5, 3, 1, 0, 2, 4, 6,
  139958. 8,
  139959. };
  139960. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  139961. _vq_quantthresh__44cn1_s_p4_0,
  139962. _vq_quantmap__44cn1_s_p4_0,
  139963. 9,
  139964. 9
  139965. };
  139966. static static_codebook _44cn1_s_p4_0 = {
  139967. 2, 81,
  139968. _vq_lengthlist__44cn1_s_p4_0,
  139969. 1, -531628032, 1611661312, 4, 0,
  139970. _vq_quantlist__44cn1_s_p4_0,
  139971. NULL,
  139972. &_vq_auxt__44cn1_s_p4_0,
  139973. NULL,
  139974. 0
  139975. };
  139976. static long _vq_quantlist__44cn1_s_p5_0[] = {
  139977. 8,
  139978. 7,
  139979. 9,
  139980. 6,
  139981. 10,
  139982. 5,
  139983. 11,
  139984. 4,
  139985. 12,
  139986. 3,
  139987. 13,
  139988. 2,
  139989. 14,
  139990. 1,
  139991. 15,
  139992. 0,
  139993. 16,
  139994. };
  139995. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  139996. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  139997. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139998. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  139999. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140000. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140001. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140002. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140003. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140004. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140005. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140006. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140007. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140008. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140009. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140010. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140011. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140012. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140014. 14,
  140015. };
  140016. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140017. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140018. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140019. };
  140020. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140021. 15, 13, 11, 9, 7, 5, 3, 1,
  140022. 0, 2, 4, 6, 8, 10, 12, 14,
  140023. 16,
  140024. };
  140025. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140026. _vq_quantthresh__44cn1_s_p5_0,
  140027. _vq_quantmap__44cn1_s_p5_0,
  140028. 17,
  140029. 17
  140030. };
  140031. static static_codebook _44cn1_s_p5_0 = {
  140032. 2, 289,
  140033. _vq_lengthlist__44cn1_s_p5_0,
  140034. 1, -529530880, 1611661312, 5, 0,
  140035. _vq_quantlist__44cn1_s_p5_0,
  140036. NULL,
  140037. &_vq_auxt__44cn1_s_p5_0,
  140038. NULL,
  140039. 0
  140040. };
  140041. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140042. 1,
  140043. 0,
  140044. 2,
  140045. };
  140046. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140047. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140048. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140049. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140050. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140051. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140052. 10,
  140053. };
  140054. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140055. -5.5, 5.5,
  140056. };
  140057. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140058. 1, 0, 2,
  140059. };
  140060. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140061. _vq_quantthresh__44cn1_s_p6_0,
  140062. _vq_quantmap__44cn1_s_p6_0,
  140063. 3,
  140064. 3
  140065. };
  140066. static static_codebook _44cn1_s_p6_0 = {
  140067. 4, 81,
  140068. _vq_lengthlist__44cn1_s_p6_0,
  140069. 1, -529137664, 1618345984, 2, 0,
  140070. _vq_quantlist__44cn1_s_p6_0,
  140071. NULL,
  140072. &_vq_auxt__44cn1_s_p6_0,
  140073. NULL,
  140074. 0
  140075. };
  140076. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140077. 5,
  140078. 4,
  140079. 6,
  140080. 3,
  140081. 7,
  140082. 2,
  140083. 8,
  140084. 1,
  140085. 9,
  140086. 0,
  140087. 10,
  140088. };
  140089. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140090. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140091. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140092. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140093. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140094. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140095. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140096. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140097. 10,10,10, 9, 9, 9, 9, 9, 9,
  140098. };
  140099. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140100. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140101. 3.5, 4.5,
  140102. };
  140103. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140104. 9, 7, 5, 3, 1, 0, 2, 4,
  140105. 6, 8, 10,
  140106. };
  140107. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140108. _vq_quantthresh__44cn1_s_p6_1,
  140109. _vq_quantmap__44cn1_s_p6_1,
  140110. 11,
  140111. 11
  140112. };
  140113. static static_codebook _44cn1_s_p6_1 = {
  140114. 2, 121,
  140115. _vq_lengthlist__44cn1_s_p6_1,
  140116. 1, -531365888, 1611661312, 4, 0,
  140117. _vq_quantlist__44cn1_s_p6_1,
  140118. NULL,
  140119. &_vq_auxt__44cn1_s_p6_1,
  140120. NULL,
  140121. 0
  140122. };
  140123. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140124. 6,
  140125. 5,
  140126. 7,
  140127. 4,
  140128. 8,
  140129. 3,
  140130. 9,
  140131. 2,
  140132. 10,
  140133. 1,
  140134. 11,
  140135. 0,
  140136. 12,
  140137. };
  140138. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140139. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140140. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140141. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140142. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140143. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140144. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140145. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140146. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140147. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140148. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140149. 0,13,13,12,12,13,13,13,14,
  140150. };
  140151. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140152. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140153. 12.5, 17.5, 22.5, 27.5,
  140154. };
  140155. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140156. 11, 9, 7, 5, 3, 1, 0, 2,
  140157. 4, 6, 8, 10, 12,
  140158. };
  140159. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140160. _vq_quantthresh__44cn1_s_p7_0,
  140161. _vq_quantmap__44cn1_s_p7_0,
  140162. 13,
  140163. 13
  140164. };
  140165. static static_codebook _44cn1_s_p7_0 = {
  140166. 2, 169,
  140167. _vq_lengthlist__44cn1_s_p7_0,
  140168. 1, -526516224, 1616117760, 4, 0,
  140169. _vq_quantlist__44cn1_s_p7_0,
  140170. NULL,
  140171. &_vq_auxt__44cn1_s_p7_0,
  140172. NULL,
  140173. 0
  140174. };
  140175. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140176. 2,
  140177. 1,
  140178. 3,
  140179. 0,
  140180. 4,
  140181. };
  140182. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140183. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140184. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140185. };
  140186. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140187. -1.5, -0.5, 0.5, 1.5,
  140188. };
  140189. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140190. 3, 1, 0, 2, 4,
  140191. };
  140192. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140193. _vq_quantthresh__44cn1_s_p7_1,
  140194. _vq_quantmap__44cn1_s_p7_1,
  140195. 5,
  140196. 5
  140197. };
  140198. static static_codebook _44cn1_s_p7_1 = {
  140199. 2, 25,
  140200. _vq_lengthlist__44cn1_s_p7_1,
  140201. 1, -533725184, 1611661312, 3, 0,
  140202. _vq_quantlist__44cn1_s_p7_1,
  140203. NULL,
  140204. &_vq_auxt__44cn1_s_p7_1,
  140205. NULL,
  140206. 0
  140207. };
  140208. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140209. 2,
  140210. 1,
  140211. 3,
  140212. 0,
  140213. 4,
  140214. };
  140215. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140216. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140217. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140218. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140219. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140221. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140222. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140223. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140224. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140225. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140226. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140227. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140228. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140229. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140230. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140231. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140232. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140233. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140234. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140236. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140237. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140238. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140239. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140240. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140247. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140249. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140250. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140251. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140252. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140253. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140254. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140255. 12,
  140256. };
  140257. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140258. -331.5, -110.5, 110.5, 331.5,
  140259. };
  140260. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140261. 3, 1, 0, 2, 4,
  140262. };
  140263. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140264. _vq_quantthresh__44cn1_s_p8_0,
  140265. _vq_quantmap__44cn1_s_p8_0,
  140266. 5,
  140267. 5
  140268. };
  140269. static static_codebook _44cn1_s_p8_0 = {
  140270. 4, 625,
  140271. _vq_lengthlist__44cn1_s_p8_0,
  140272. 1, -518283264, 1627103232, 3, 0,
  140273. _vq_quantlist__44cn1_s_p8_0,
  140274. NULL,
  140275. &_vq_auxt__44cn1_s_p8_0,
  140276. NULL,
  140277. 0
  140278. };
  140279. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140280. 6,
  140281. 5,
  140282. 7,
  140283. 4,
  140284. 8,
  140285. 3,
  140286. 9,
  140287. 2,
  140288. 10,
  140289. 1,
  140290. 11,
  140291. 0,
  140292. 12,
  140293. };
  140294. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140295. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140296. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140297. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140298. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140299. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140300. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140301. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140302. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140303. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140304. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140305. 15,12,12,11,11,14,12,13,14,
  140306. };
  140307. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140308. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140309. 42.5, 59.5, 76.5, 93.5,
  140310. };
  140311. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140312. 11, 9, 7, 5, 3, 1, 0, 2,
  140313. 4, 6, 8, 10, 12,
  140314. };
  140315. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140316. _vq_quantthresh__44cn1_s_p8_1,
  140317. _vq_quantmap__44cn1_s_p8_1,
  140318. 13,
  140319. 13
  140320. };
  140321. static static_codebook _44cn1_s_p8_1 = {
  140322. 2, 169,
  140323. _vq_lengthlist__44cn1_s_p8_1,
  140324. 1, -522616832, 1620115456, 4, 0,
  140325. _vq_quantlist__44cn1_s_p8_1,
  140326. NULL,
  140327. &_vq_auxt__44cn1_s_p8_1,
  140328. NULL,
  140329. 0
  140330. };
  140331. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140332. 8,
  140333. 7,
  140334. 9,
  140335. 6,
  140336. 10,
  140337. 5,
  140338. 11,
  140339. 4,
  140340. 12,
  140341. 3,
  140342. 13,
  140343. 2,
  140344. 14,
  140345. 1,
  140346. 15,
  140347. 0,
  140348. 16,
  140349. };
  140350. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140351. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140352. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140353. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140354. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140355. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140356. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140357. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140358. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140359. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140360. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140361. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140362. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140363. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140364. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140365. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140366. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140367. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140368. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140369. 9,
  140370. };
  140371. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140372. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140373. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140374. };
  140375. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140376. 15, 13, 11, 9, 7, 5, 3, 1,
  140377. 0, 2, 4, 6, 8, 10, 12, 14,
  140378. 16,
  140379. };
  140380. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140381. _vq_quantthresh__44cn1_s_p8_2,
  140382. _vq_quantmap__44cn1_s_p8_2,
  140383. 17,
  140384. 17
  140385. };
  140386. static static_codebook _44cn1_s_p8_2 = {
  140387. 2, 289,
  140388. _vq_lengthlist__44cn1_s_p8_2,
  140389. 1, -529530880, 1611661312, 5, 0,
  140390. _vq_quantlist__44cn1_s_p8_2,
  140391. NULL,
  140392. &_vq_auxt__44cn1_s_p8_2,
  140393. NULL,
  140394. 0
  140395. };
  140396. static long _huff_lengthlist__44cn1_s_short[] = {
  140397. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140398. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140399. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140400. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140401. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140402. 10,
  140403. };
  140404. static static_codebook _huff_book__44cn1_s_short = {
  140405. 2, 81,
  140406. _huff_lengthlist__44cn1_s_short,
  140407. 0, 0, 0, 0, 0,
  140408. NULL,
  140409. NULL,
  140410. NULL,
  140411. NULL,
  140412. 0
  140413. };
  140414. static long _huff_lengthlist__44cn1_sm_long[] = {
  140415. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140416. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140417. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140418. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140419. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140420. 17,
  140421. };
  140422. static static_codebook _huff_book__44cn1_sm_long = {
  140423. 2, 81,
  140424. _huff_lengthlist__44cn1_sm_long,
  140425. 0, 0, 0, 0, 0,
  140426. NULL,
  140427. NULL,
  140428. NULL,
  140429. NULL,
  140430. 0
  140431. };
  140432. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140433. 1,
  140434. 0,
  140435. 2,
  140436. };
  140437. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140438. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140439. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140444. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140449. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140484. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140489. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140494. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140530. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140535. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140540. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140848. 0,
  140849. };
  140850. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  140851. -0.5, 0.5,
  140852. };
  140853. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  140854. 1, 0, 2,
  140855. };
  140856. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  140857. _vq_quantthresh__44cn1_sm_p1_0,
  140858. _vq_quantmap__44cn1_sm_p1_0,
  140859. 3,
  140860. 3
  140861. };
  140862. static static_codebook _44cn1_sm_p1_0 = {
  140863. 8, 6561,
  140864. _vq_lengthlist__44cn1_sm_p1_0,
  140865. 1, -535822336, 1611661312, 2, 0,
  140866. _vq_quantlist__44cn1_sm_p1_0,
  140867. NULL,
  140868. &_vq_auxt__44cn1_sm_p1_0,
  140869. NULL,
  140870. 0
  140871. };
  140872. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  140873. 2,
  140874. 1,
  140875. 3,
  140876. 0,
  140877. 4,
  140878. };
  140879. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  140880. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140883. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140886. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140919. 0,
  140920. };
  140921. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  140922. -1.5, -0.5, 0.5, 1.5,
  140923. };
  140924. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  140925. 3, 1, 0, 2, 4,
  140926. };
  140927. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  140928. _vq_quantthresh__44cn1_sm_p2_0,
  140929. _vq_quantmap__44cn1_sm_p2_0,
  140930. 5,
  140931. 5
  140932. };
  140933. static static_codebook _44cn1_sm_p2_0 = {
  140934. 4, 625,
  140935. _vq_lengthlist__44cn1_sm_p2_0,
  140936. 1, -533725184, 1611661312, 3, 0,
  140937. _vq_quantlist__44cn1_sm_p2_0,
  140938. NULL,
  140939. &_vq_auxt__44cn1_sm_p2_0,
  140940. NULL,
  140941. 0
  140942. };
  140943. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  140944. 4,
  140945. 3,
  140946. 5,
  140947. 2,
  140948. 6,
  140949. 1,
  140950. 7,
  140951. 0,
  140952. 8,
  140953. };
  140954. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  140955. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  140956. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  140957. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  140958. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  140959. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140960. 0,
  140961. };
  140962. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  140963. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140964. };
  140965. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  140966. 7, 5, 3, 1, 0, 2, 4, 6,
  140967. 8,
  140968. };
  140969. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  140970. _vq_quantthresh__44cn1_sm_p3_0,
  140971. _vq_quantmap__44cn1_sm_p3_0,
  140972. 9,
  140973. 9
  140974. };
  140975. static static_codebook _44cn1_sm_p3_0 = {
  140976. 2, 81,
  140977. _vq_lengthlist__44cn1_sm_p3_0,
  140978. 1, -531628032, 1611661312, 4, 0,
  140979. _vq_quantlist__44cn1_sm_p3_0,
  140980. NULL,
  140981. &_vq_auxt__44cn1_sm_p3_0,
  140982. NULL,
  140983. 0
  140984. };
  140985. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  140986. 4,
  140987. 3,
  140988. 5,
  140989. 2,
  140990. 6,
  140991. 1,
  140992. 7,
  140993. 0,
  140994. 8,
  140995. };
  140996. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  140997. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  140998. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  140999. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141000. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141001. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141002. 11,
  141003. };
  141004. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141005. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141006. };
  141007. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141008. 7, 5, 3, 1, 0, 2, 4, 6,
  141009. 8,
  141010. };
  141011. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141012. _vq_quantthresh__44cn1_sm_p4_0,
  141013. _vq_quantmap__44cn1_sm_p4_0,
  141014. 9,
  141015. 9
  141016. };
  141017. static static_codebook _44cn1_sm_p4_0 = {
  141018. 2, 81,
  141019. _vq_lengthlist__44cn1_sm_p4_0,
  141020. 1, -531628032, 1611661312, 4, 0,
  141021. _vq_quantlist__44cn1_sm_p4_0,
  141022. NULL,
  141023. &_vq_auxt__44cn1_sm_p4_0,
  141024. NULL,
  141025. 0
  141026. };
  141027. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141028. 8,
  141029. 7,
  141030. 9,
  141031. 6,
  141032. 10,
  141033. 5,
  141034. 11,
  141035. 4,
  141036. 12,
  141037. 3,
  141038. 13,
  141039. 2,
  141040. 14,
  141041. 1,
  141042. 15,
  141043. 0,
  141044. 16,
  141045. };
  141046. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141047. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141048. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141049. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141050. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141051. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141052. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141053. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141054. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141055. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141056. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141057. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141058. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141059. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141060. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141061. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141062. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141063. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141065. 14,
  141066. };
  141067. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141068. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141069. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141070. };
  141071. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141072. 15, 13, 11, 9, 7, 5, 3, 1,
  141073. 0, 2, 4, 6, 8, 10, 12, 14,
  141074. 16,
  141075. };
  141076. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141077. _vq_quantthresh__44cn1_sm_p5_0,
  141078. _vq_quantmap__44cn1_sm_p5_0,
  141079. 17,
  141080. 17
  141081. };
  141082. static static_codebook _44cn1_sm_p5_0 = {
  141083. 2, 289,
  141084. _vq_lengthlist__44cn1_sm_p5_0,
  141085. 1, -529530880, 1611661312, 5, 0,
  141086. _vq_quantlist__44cn1_sm_p5_0,
  141087. NULL,
  141088. &_vq_auxt__44cn1_sm_p5_0,
  141089. NULL,
  141090. 0
  141091. };
  141092. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141093. 1,
  141094. 0,
  141095. 2,
  141096. };
  141097. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141098. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141099. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141100. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141101. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141102. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141103. 10,
  141104. };
  141105. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141106. -5.5, 5.5,
  141107. };
  141108. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141109. 1, 0, 2,
  141110. };
  141111. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141112. _vq_quantthresh__44cn1_sm_p6_0,
  141113. _vq_quantmap__44cn1_sm_p6_0,
  141114. 3,
  141115. 3
  141116. };
  141117. static static_codebook _44cn1_sm_p6_0 = {
  141118. 4, 81,
  141119. _vq_lengthlist__44cn1_sm_p6_0,
  141120. 1, -529137664, 1618345984, 2, 0,
  141121. _vq_quantlist__44cn1_sm_p6_0,
  141122. NULL,
  141123. &_vq_auxt__44cn1_sm_p6_0,
  141124. NULL,
  141125. 0
  141126. };
  141127. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141128. 5,
  141129. 4,
  141130. 6,
  141131. 3,
  141132. 7,
  141133. 2,
  141134. 8,
  141135. 1,
  141136. 9,
  141137. 0,
  141138. 10,
  141139. };
  141140. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141141. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141142. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141143. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141144. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141145. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141146. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141147. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141148. 10,10,10, 8, 9, 8, 8, 9, 8,
  141149. };
  141150. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141151. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141152. 3.5, 4.5,
  141153. };
  141154. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141155. 9, 7, 5, 3, 1, 0, 2, 4,
  141156. 6, 8, 10,
  141157. };
  141158. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141159. _vq_quantthresh__44cn1_sm_p6_1,
  141160. _vq_quantmap__44cn1_sm_p6_1,
  141161. 11,
  141162. 11
  141163. };
  141164. static static_codebook _44cn1_sm_p6_1 = {
  141165. 2, 121,
  141166. _vq_lengthlist__44cn1_sm_p6_1,
  141167. 1, -531365888, 1611661312, 4, 0,
  141168. _vq_quantlist__44cn1_sm_p6_1,
  141169. NULL,
  141170. &_vq_auxt__44cn1_sm_p6_1,
  141171. NULL,
  141172. 0
  141173. };
  141174. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141175. 6,
  141176. 5,
  141177. 7,
  141178. 4,
  141179. 8,
  141180. 3,
  141181. 9,
  141182. 2,
  141183. 10,
  141184. 1,
  141185. 11,
  141186. 0,
  141187. 12,
  141188. };
  141189. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141190. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141191. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141192. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141193. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141194. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141195. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141196. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141197. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141198. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141199. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141200. 0,13,12,12,12,13,13,13,14,
  141201. };
  141202. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141203. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141204. 12.5, 17.5, 22.5, 27.5,
  141205. };
  141206. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141207. 11, 9, 7, 5, 3, 1, 0, 2,
  141208. 4, 6, 8, 10, 12,
  141209. };
  141210. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141211. _vq_quantthresh__44cn1_sm_p7_0,
  141212. _vq_quantmap__44cn1_sm_p7_0,
  141213. 13,
  141214. 13
  141215. };
  141216. static static_codebook _44cn1_sm_p7_0 = {
  141217. 2, 169,
  141218. _vq_lengthlist__44cn1_sm_p7_0,
  141219. 1, -526516224, 1616117760, 4, 0,
  141220. _vq_quantlist__44cn1_sm_p7_0,
  141221. NULL,
  141222. &_vq_auxt__44cn1_sm_p7_0,
  141223. NULL,
  141224. 0
  141225. };
  141226. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141227. 2,
  141228. 1,
  141229. 3,
  141230. 0,
  141231. 4,
  141232. };
  141233. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141234. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141235. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141236. };
  141237. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141238. -1.5, -0.5, 0.5, 1.5,
  141239. };
  141240. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141241. 3, 1, 0, 2, 4,
  141242. };
  141243. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141244. _vq_quantthresh__44cn1_sm_p7_1,
  141245. _vq_quantmap__44cn1_sm_p7_1,
  141246. 5,
  141247. 5
  141248. };
  141249. static static_codebook _44cn1_sm_p7_1 = {
  141250. 2, 25,
  141251. _vq_lengthlist__44cn1_sm_p7_1,
  141252. 1, -533725184, 1611661312, 3, 0,
  141253. _vq_quantlist__44cn1_sm_p7_1,
  141254. NULL,
  141255. &_vq_auxt__44cn1_sm_p7_1,
  141256. NULL,
  141257. 0
  141258. };
  141259. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141260. 4,
  141261. 3,
  141262. 5,
  141263. 2,
  141264. 6,
  141265. 1,
  141266. 7,
  141267. 0,
  141268. 8,
  141269. };
  141270. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141271. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141272. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141273. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141274. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141275. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141276. 14,
  141277. };
  141278. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141279. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141280. };
  141281. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141282. 7, 5, 3, 1, 0, 2, 4, 6,
  141283. 8,
  141284. };
  141285. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141286. _vq_quantthresh__44cn1_sm_p8_0,
  141287. _vq_quantmap__44cn1_sm_p8_0,
  141288. 9,
  141289. 9
  141290. };
  141291. static static_codebook _44cn1_sm_p8_0 = {
  141292. 2, 81,
  141293. _vq_lengthlist__44cn1_sm_p8_0,
  141294. 1, -516186112, 1627103232, 4, 0,
  141295. _vq_quantlist__44cn1_sm_p8_0,
  141296. NULL,
  141297. &_vq_auxt__44cn1_sm_p8_0,
  141298. NULL,
  141299. 0
  141300. };
  141301. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141302. 6,
  141303. 5,
  141304. 7,
  141305. 4,
  141306. 8,
  141307. 3,
  141308. 9,
  141309. 2,
  141310. 10,
  141311. 1,
  141312. 11,
  141313. 0,
  141314. 12,
  141315. };
  141316. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141317. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141318. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141319. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141320. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141321. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141322. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141323. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141324. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141325. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141326. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141327. 17,12,12,11,10,13,11,13,13,
  141328. };
  141329. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141330. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141331. 42.5, 59.5, 76.5, 93.5,
  141332. };
  141333. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141334. 11, 9, 7, 5, 3, 1, 0, 2,
  141335. 4, 6, 8, 10, 12,
  141336. };
  141337. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141338. _vq_quantthresh__44cn1_sm_p8_1,
  141339. _vq_quantmap__44cn1_sm_p8_1,
  141340. 13,
  141341. 13
  141342. };
  141343. static static_codebook _44cn1_sm_p8_1 = {
  141344. 2, 169,
  141345. _vq_lengthlist__44cn1_sm_p8_1,
  141346. 1, -522616832, 1620115456, 4, 0,
  141347. _vq_quantlist__44cn1_sm_p8_1,
  141348. NULL,
  141349. &_vq_auxt__44cn1_sm_p8_1,
  141350. NULL,
  141351. 0
  141352. };
  141353. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141354. 8,
  141355. 7,
  141356. 9,
  141357. 6,
  141358. 10,
  141359. 5,
  141360. 11,
  141361. 4,
  141362. 12,
  141363. 3,
  141364. 13,
  141365. 2,
  141366. 14,
  141367. 1,
  141368. 15,
  141369. 0,
  141370. 16,
  141371. };
  141372. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141373. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141374. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141375. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141376. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141377. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141378. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141379. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141380. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141381. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141382. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141383. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141384. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141385. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141386. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141387. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141388. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141389. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141390. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141391. 9,
  141392. };
  141393. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141394. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141395. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141396. };
  141397. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141398. 15, 13, 11, 9, 7, 5, 3, 1,
  141399. 0, 2, 4, 6, 8, 10, 12, 14,
  141400. 16,
  141401. };
  141402. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141403. _vq_quantthresh__44cn1_sm_p8_2,
  141404. _vq_quantmap__44cn1_sm_p8_2,
  141405. 17,
  141406. 17
  141407. };
  141408. static static_codebook _44cn1_sm_p8_2 = {
  141409. 2, 289,
  141410. _vq_lengthlist__44cn1_sm_p8_2,
  141411. 1, -529530880, 1611661312, 5, 0,
  141412. _vq_quantlist__44cn1_sm_p8_2,
  141413. NULL,
  141414. &_vq_auxt__44cn1_sm_p8_2,
  141415. NULL,
  141416. 0
  141417. };
  141418. static long _huff_lengthlist__44cn1_sm_short[] = {
  141419. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141420. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141421. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141422. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141423. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141424. 9,
  141425. };
  141426. static static_codebook _huff_book__44cn1_sm_short = {
  141427. 2, 81,
  141428. _huff_lengthlist__44cn1_sm_short,
  141429. 0, 0, 0, 0, 0,
  141430. NULL,
  141431. NULL,
  141432. NULL,
  141433. NULL,
  141434. 0
  141435. };
  141436. /*** End of inlined file: res_books_stereo.h ***/
  141437. /***** residue backends *********************************************/
  141438. static vorbis_info_residue0 _residue_44_low={
  141439. 0,-1, -1, 9,-1,
  141440. /* 0 1 2 3 4 5 6 7 */
  141441. {0},
  141442. {-1},
  141443. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141444. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141445. };
  141446. static vorbis_info_residue0 _residue_44_mid={
  141447. 0,-1, -1, 10,-1,
  141448. /* 0 1 2 3 4 5 6 7 8 */
  141449. {0},
  141450. {-1},
  141451. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141452. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141453. };
  141454. static vorbis_info_residue0 _residue_44_high={
  141455. 0,-1, -1, 10,-1,
  141456. /* 0 1 2 3 4 5 6 7 8 */
  141457. {0},
  141458. {-1},
  141459. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141460. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141461. };
  141462. static static_bookblock _resbook_44s_n1={
  141463. {
  141464. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141465. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141466. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141467. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141468. }
  141469. };
  141470. static static_bookblock _resbook_44sm_n1={
  141471. {
  141472. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141473. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141474. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141475. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141476. }
  141477. };
  141478. static static_bookblock _resbook_44s_0={
  141479. {
  141480. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141481. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141482. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141483. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141484. }
  141485. };
  141486. static static_bookblock _resbook_44sm_0={
  141487. {
  141488. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141489. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141490. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141491. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141492. }
  141493. };
  141494. static static_bookblock _resbook_44s_1={
  141495. {
  141496. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141497. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141498. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141499. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141500. }
  141501. };
  141502. static static_bookblock _resbook_44sm_1={
  141503. {
  141504. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141505. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141506. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141507. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141508. }
  141509. };
  141510. static static_bookblock _resbook_44s_2={
  141511. {
  141512. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141513. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141514. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141515. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141516. }
  141517. };
  141518. static static_bookblock _resbook_44s_3={
  141519. {
  141520. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141521. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141522. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141523. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141524. }
  141525. };
  141526. static static_bookblock _resbook_44s_4={
  141527. {
  141528. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141529. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141530. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141531. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141532. }
  141533. };
  141534. static static_bookblock _resbook_44s_5={
  141535. {
  141536. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141537. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141538. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141539. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141540. }
  141541. };
  141542. static static_bookblock _resbook_44s_6={
  141543. {
  141544. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141545. {0,0,&_44c6_s_p4_0},
  141546. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141547. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141548. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141549. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141550. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141551. }
  141552. };
  141553. static static_bookblock _resbook_44s_7={
  141554. {
  141555. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141556. {0,0,&_44c7_s_p4_0},
  141557. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141558. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141559. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141560. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141561. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141562. }
  141563. };
  141564. static static_bookblock _resbook_44s_8={
  141565. {
  141566. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141567. {0,0,&_44c8_s_p4_0},
  141568. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141569. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141570. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141571. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141572. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141573. }
  141574. };
  141575. static static_bookblock _resbook_44s_9={
  141576. {
  141577. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141578. {0,0,&_44c9_s_p4_0},
  141579. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141580. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141581. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141582. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141583. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141584. }
  141585. };
  141586. static vorbis_residue_template _res_44s_n1[]={
  141587. {2,0, &_residue_44_low,
  141588. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141589. &_resbook_44s_n1,&_resbook_44sm_n1},
  141590. {2,0, &_residue_44_low,
  141591. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141592. &_resbook_44s_n1,&_resbook_44sm_n1}
  141593. };
  141594. static vorbis_residue_template _res_44s_0[]={
  141595. {2,0, &_residue_44_low,
  141596. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141597. &_resbook_44s_0,&_resbook_44sm_0},
  141598. {2,0, &_residue_44_low,
  141599. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141600. &_resbook_44s_0,&_resbook_44sm_0}
  141601. };
  141602. static vorbis_residue_template _res_44s_1[]={
  141603. {2,0, &_residue_44_low,
  141604. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141605. &_resbook_44s_1,&_resbook_44sm_1},
  141606. {2,0, &_residue_44_low,
  141607. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141608. &_resbook_44s_1,&_resbook_44sm_1}
  141609. };
  141610. static vorbis_residue_template _res_44s_2[]={
  141611. {2,0, &_residue_44_mid,
  141612. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141613. &_resbook_44s_2,&_resbook_44s_2},
  141614. {2,0, &_residue_44_mid,
  141615. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141616. &_resbook_44s_2,&_resbook_44s_2}
  141617. };
  141618. static vorbis_residue_template _res_44s_3[]={
  141619. {2,0, &_residue_44_mid,
  141620. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141621. &_resbook_44s_3,&_resbook_44s_3},
  141622. {2,0, &_residue_44_mid,
  141623. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141624. &_resbook_44s_3,&_resbook_44s_3}
  141625. };
  141626. static vorbis_residue_template _res_44s_4[]={
  141627. {2,0, &_residue_44_mid,
  141628. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141629. &_resbook_44s_4,&_resbook_44s_4},
  141630. {2,0, &_residue_44_mid,
  141631. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141632. &_resbook_44s_4,&_resbook_44s_4}
  141633. };
  141634. static vorbis_residue_template _res_44s_5[]={
  141635. {2,0, &_residue_44_mid,
  141636. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141637. &_resbook_44s_5,&_resbook_44s_5},
  141638. {2,0, &_residue_44_mid,
  141639. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141640. &_resbook_44s_5,&_resbook_44s_5}
  141641. };
  141642. static vorbis_residue_template _res_44s_6[]={
  141643. {2,0, &_residue_44_high,
  141644. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141645. &_resbook_44s_6,&_resbook_44s_6},
  141646. {2,0, &_residue_44_high,
  141647. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141648. &_resbook_44s_6,&_resbook_44s_6}
  141649. };
  141650. static vorbis_residue_template _res_44s_7[]={
  141651. {2,0, &_residue_44_high,
  141652. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141653. &_resbook_44s_7,&_resbook_44s_7},
  141654. {2,0, &_residue_44_high,
  141655. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141656. &_resbook_44s_7,&_resbook_44s_7}
  141657. };
  141658. static vorbis_residue_template _res_44s_8[]={
  141659. {2,0, &_residue_44_high,
  141660. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141661. &_resbook_44s_8,&_resbook_44s_8},
  141662. {2,0, &_residue_44_high,
  141663. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141664. &_resbook_44s_8,&_resbook_44s_8}
  141665. };
  141666. static vorbis_residue_template _res_44s_9[]={
  141667. {2,0, &_residue_44_high,
  141668. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141669. &_resbook_44s_9,&_resbook_44s_9},
  141670. {2,0, &_residue_44_high,
  141671. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141672. &_resbook_44s_9,&_resbook_44s_9}
  141673. };
  141674. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141675. { _map_nominal, _res_44s_n1 }, /* -1 */
  141676. { _map_nominal, _res_44s_0 }, /* 0 */
  141677. { _map_nominal, _res_44s_1 }, /* 1 */
  141678. { _map_nominal, _res_44s_2 }, /* 2 */
  141679. { _map_nominal, _res_44s_3 }, /* 3 */
  141680. { _map_nominal, _res_44s_4 }, /* 4 */
  141681. { _map_nominal, _res_44s_5 }, /* 5 */
  141682. { _map_nominal, _res_44s_6 }, /* 6 */
  141683. { _map_nominal, _res_44s_7 }, /* 7 */
  141684. { _map_nominal, _res_44s_8 }, /* 8 */
  141685. { _map_nominal, _res_44s_9 }, /* 9 */
  141686. };
  141687. /*** End of inlined file: residue_44.h ***/
  141688. /*** Start of inlined file: psych_44.h ***/
  141689. /* preecho trigger settings *****************************************/
  141690. static vorbis_info_psy_global _psy_global_44[5]={
  141691. {8, /* lines per eighth octave */
  141692. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141693. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141694. -6.f,
  141695. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141696. },
  141697. {8, /* lines per eighth octave */
  141698. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141699. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141700. -6.f,
  141701. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141702. },
  141703. {8, /* lines per eighth octave */
  141704. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141705. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141706. -6.f,
  141707. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141708. },
  141709. {8, /* lines per eighth octave */
  141710. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141711. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141712. -6.f,
  141713. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141714. },
  141715. {8, /* lines per eighth octave */
  141716. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141717. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141718. -6.f,
  141719. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141720. },
  141721. };
  141722. /* noise compander lookups * low, mid, high quality ****************/
  141723. static compandblock _psy_compand_44[6]={
  141724. /* sub-mode Z short */
  141725. {{
  141726. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141727. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141728. 16,17,18,19,20,21,22, 23, /* 23dB */
  141729. 24,25,26,27,28,29,30, 31, /* 31dB */
  141730. 32,33,34,35,36,37,38, 39, /* 39dB */
  141731. }},
  141732. /* mode_Z nominal short */
  141733. {{
  141734. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141735. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141736. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141737. 15,16,17,17,17,18,18, 19, /* 31dB */
  141738. 19,19,20,21,22,23,24, 25, /* 39dB */
  141739. }},
  141740. /* mode A short */
  141741. {{
  141742. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141743. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141744. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141745. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141746. 11,12,13,14,15,16,17, 18, /* 39dB */
  141747. }},
  141748. /* sub-mode Z long */
  141749. {{
  141750. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141751. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141752. 16,17,18,19,20,21,22, 23, /* 23dB */
  141753. 24,25,26,27,28,29,30, 31, /* 31dB */
  141754. 32,33,34,35,36,37,38, 39, /* 39dB */
  141755. }},
  141756. /* mode_Z nominal long */
  141757. {{
  141758. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141759. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141760. 13,14,14,14,15,15,15, 15, /* 23dB */
  141761. 16,16,17,17,17,18,18, 19, /* 31dB */
  141762. 19,19,20,21,22,23,24, 25, /* 39dB */
  141763. }},
  141764. /* mode A long */
  141765. {{
  141766. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141767. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141768. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141769. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141770. 11,12,13,14,15,16,17, 18, /* 39dB */
  141771. }}
  141772. };
  141773. /* tonal masking curve level adjustments *************************/
  141774. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141775. /* 63 125 250 500 1 2 4 8 16 */
  141776. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141777. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141778. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141779. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141780. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141781. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141782. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141783. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141784. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141785. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141786. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141787. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141788. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141789. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141790. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141791. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141792. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141793. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141794. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141795. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141796. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141797. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141798. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141799. };
  141800. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141801. /* 63 125 250 500 1 2 4 8 16 */
  141802. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141803. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141804. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141805. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141806. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141807. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141808. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141809. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141810. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141811. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141812. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141813. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141814. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141815. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141816. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141817. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141818. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141819. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141820. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141821. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141822. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141823. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141824. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141825. };
  141826. /* noise bias (transition block) */
  141827. static noise3 _psy_noisebias_trans[12]={
  141828. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141829. /* -1 */
  141830. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141831. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141832. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141833. /* 0
  141834. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141835. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  141836. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141837. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141838. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  141839. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141840. /* 1
  141841. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141842. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141843. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141844. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141845. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141846. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141847. /* 2
  141848. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141849. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141850. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  141851. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141852. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141853. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  141854. /* 3
  141855. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141856. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141857. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141858. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141859. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141860. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141861. /* 4
  141862. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141863. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141864. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141865. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141866. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141867. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141868. /* 5
  141869. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141870. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141871. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  141872. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141873. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141874. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  141875. /* 6
  141876. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141877. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141878. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141879. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141880. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141881. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141882. /* 7
  141883. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141884. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  141885. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  141886. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141887. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141888. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141889. /* 8
  141890. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141891. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141892. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141893. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141894. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141895. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141896. /* 9
  141897. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141898. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141899. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141900. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141901. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  141902. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  141903. /* 10 */
  141904. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  141905. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  141906. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141907. };
  141908. /* noise bias (long block) */
  141909. static noise3 _psy_noisebias_long[12]={
  141910. /*63 125 250 500 1k 2k 4k 8k 16k*/
  141911. /* -1 */
  141912. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  141913. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  141914. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141915. /* 0 */
  141916. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141917. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  141918. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141919. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141920. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  141921. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141922. /* 1 */
  141923. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141924. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141925. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141926. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141927. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141928. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141929. /* 2 */
  141930. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141931. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141932. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141933. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141934. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141935. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141936. /* 3 */
  141937. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141938. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141939. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141940. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141941. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141942. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  141943. /* 4 */
  141944. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141945. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141946. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141947. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141948. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141949. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  141950. /* 5 */
  141951. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141952. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141953. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  141954. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141955. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141956. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  141957. /* 6 */
  141958. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141959. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141960. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141961. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141962. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141963. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  141964. /* 7 */
  141965. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141966. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  141967. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141968. /* 8 */
  141969. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  141970. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  141971. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141972. /* 9 */
  141973. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141974. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  141975. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141976. /* 10 */
  141977. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  141978. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  141979. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141980. };
  141981. /* noise bias (impulse block) */
  141982. static noise3 _psy_noisebias_impulse[12]={
  141983. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141984. /* -1 */
  141985. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141986. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141987. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141988. /* 0 */
  141989. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141990. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  141991. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  141992. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141993. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  141994. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141995. /* 1 */
  141996. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141997. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  141998. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  141999. /* 2 */
  142000. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142001. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142002. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142003. /* 3 */
  142004. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142005. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142006. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142007. /* 4 */
  142008. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142009. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142010. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142011. /* 5 */
  142012. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142013. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142014. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142015. /* 6
  142016. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142017. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142018. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142019. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142020. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142021. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142022. /* 7 */
  142023. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142024. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142025. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142026. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142027. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142028. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142029. /* 8 */
  142030. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142031. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142032. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142033. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142034. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142035. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142036. /* 9 */
  142037. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142038. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142039. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142040. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142041. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142042. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142043. /* 10 */
  142044. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142045. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142046. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142047. };
  142048. /* noise bias (padding block) */
  142049. static noise3 _psy_noisebias_padding[12]={
  142050. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142051. /* -1 */
  142052. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142053. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142054. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142055. /* 0 */
  142056. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142057. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142058. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142059. /* 1 */
  142060. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142061. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142062. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142063. /* 2 */
  142064. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142065. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142066. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142067. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142068. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142069. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142070. /* 3 */
  142071. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142072. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142073. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142074. /* 4 */
  142075. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142076. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142077. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142078. /* 5 */
  142079. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142080. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142081. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142082. /* 6 */
  142083. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142084. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142085. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142086. /* 7 */
  142087. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142088. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142089. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142090. /* 8 */
  142091. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142092. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142093. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142094. /* 9 */
  142095. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142096. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142097. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142098. /* 10 */
  142099. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142100. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142101. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142102. };
  142103. static noiseguard _psy_noiseguards_44[4]={
  142104. {3,3,15},
  142105. {3,3,15},
  142106. {10,10,100},
  142107. {10,10,100},
  142108. };
  142109. static int _psy_tone_suppress[12]={
  142110. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142111. };
  142112. static int _psy_tone_0dB[12]={
  142113. 90,90,95,95,95,95,105,105,105,105,105,105,
  142114. };
  142115. static int _psy_noise_suppress[12]={
  142116. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142117. };
  142118. static vorbis_info_psy _psy_info_template={
  142119. /* blockflag */
  142120. -1,
  142121. /* ath_adjatt, ath_maxatt */
  142122. -140.,-140.,
  142123. /* tonemask att boost/decay,suppr,curves */
  142124. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142125. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142126. 1, -0.f, .5f, .5f, 0,0,0,
  142127. /* noiseoffset*3, noisecompand, max_curve_dB */
  142128. {{-1},{-1},{-1}},{-1},105.f,
  142129. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142130. 0,0,-1,-1,0.,
  142131. };
  142132. /* ath ****************/
  142133. static int _psy_ath_floater[12]={
  142134. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142135. };
  142136. static int _psy_ath_abs[12]={
  142137. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142138. };
  142139. /* stereo setup. These don't map directly to quality level, there's
  142140. an additional indirection as several of the below may be used in a
  142141. single bitmanaged stream
  142142. ****************/
  142143. /* various stereo possibilities */
  142144. /* stereo mode by base quality level */
  142145. static adj_stereo _psy_stereo_modes_44[12]={
  142146. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142147. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142148. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142149. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142150. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142151. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142152. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142153. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142154. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142155. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142156. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142157. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142158. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142159. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142160. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142161. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142162. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142163. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142164. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142165. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142166. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142167. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142168. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142169. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142170. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142171. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142172. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142173. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142174. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142175. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142176. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142177. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142178. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142179. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142180. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142181. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142182. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142183. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142184. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142185. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142186. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142187. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142188. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142189. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142190. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142191. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142192. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142193. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142194. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142195. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142196. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142197. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142198. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142199. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142200. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142201. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142202. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142203. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142204. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142205. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142206. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142207. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142208. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142209. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142210. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142211. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142212. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142213. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142214. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142215. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142216. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142217. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142218. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142219. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142220. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142221. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142222. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142223. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142224. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142225. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142226. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142227. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142228. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142229. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142230. };
  142231. /* tone master attenuation by base quality mode and bitrate tweak */
  142232. static att3 _psy_tone_masteratt_44[12]={
  142233. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142234. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142235. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142236. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142237. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142238. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142239. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142240. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142241. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142242. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142243. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142244. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142245. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142246. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142247. };
  142248. /* lowpass by mode **************/
  142249. static double _psy_lowpass_44[12]={
  142250. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142251. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142252. };
  142253. /* noise normalization **********/
  142254. static int _noise_start_short_44[11]={
  142255. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142256. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142257. };
  142258. static int _noise_start_long_44[11]={
  142259. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142260. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142261. };
  142262. static int _noise_part_short_44[11]={
  142263. 8,8,8,8,8,8,8,8,8,8,8
  142264. };
  142265. static int _noise_part_long_44[11]={
  142266. 32,32,32,32,32,32,32,32,32,32,32
  142267. };
  142268. static double _noise_thresh_44[11]={
  142269. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142270. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142271. };
  142272. static double _noise_thresh_5only[2]={
  142273. .5,.5,
  142274. };
  142275. /*** End of inlined file: psych_44.h ***/
  142276. static double rate_mapping_44_stereo[12]={
  142277. 22500.,32000.,40000.,48000.,56000.,64000.,
  142278. 80000.,96000.,112000.,128000.,160000.,250001.
  142279. };
  142280. static double quality_mapping_44[12]={
  142281. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142282. };
  142283. static int blocksize_short_44[11]={
  142284. 512,256,256,256,256,256,256,256,256,256,256
  142285. };
  142286. static int blocksize_long_44[11]={
  142287. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142288. };
  142289. static double _psy_compand_short_mapping[12]={
  142290. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142291. };
  142292. static double _psy_compand_long_mapping[12]={
  142293. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142294. };
  142295. static double _global_mapping_44[12]={
  142296. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142297. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142298. };
  142299. static int _floor_short_mapping_44[11]={
  142300. 1,0,0,2,2,4,5,5,5,5,5
  142301. };
  142302. static int _floor_long_mapping_44[11]={
  142303. 8,7,7,7,7,7,7,7,7,7,7
  142304. };
  142305. ve_setup_data_template ve_setup_44_stereo={
  142306. 11,
  142307. rate_mapping_44_stereo,
  142308. quality_mapping_44,
  142309. 2,
  142310. 40000,
  142311. 50000,
  142312. blocksize_short_44,
  142313. blocksize_long_44,
  142314. _psy_tone_masteratt_44,
  142315. _psy_tone_0dB,
  142316. _psy_tone_suppress,
  142317. _vp_tonemask_adj_otherblock,
  142318. _vp_tonemask_adj_longblock,
  142319. _vp_tonemask_adj_otherblock,
  142320. _psy_noiseguards_44,
  142321. _psy_noisebias_impulse,
  142322. _psy_noisebias_padding,
  142323. _psy_noisebias_trans,
  142324. _psy_noisebias_long,
  142325. _psy_noise_suppress,
  142326. _psy_compand_44,
  142327. _psy_compand_short_mapping,
  142328. _psy_compand_long_mapping,
  142329. {_noise_start_short_44,_noise_start_long_44},
  142330. {_noise_part_short_44,_noise_part_long_44},
  142331. _noise_thresh_44,
  142332. _psy_ath_floater,
  142333. _psy_ath_abs,
  142334. _psy_lowpass_44,
  142335. _psy_global_44,
  142336. _global_mapping_44,
  142337. _psy_stereo_modes_44,
  142338. _floor_books,
  142339. _floor,
  142340. _floor_short_mapping_44,
  142341. _floor_long_mapping_44,
  142342. _mapres_template_44_stereo
  142343. };
  142344. /*** End of inlined file: setup_44.h ***/
  142345. /*** Start of inlined file: setup_44u.h ***/
  142346. /*** Start of inlined file: residue_44u.h ***/
  142347. /*** Start of inlined file: res_books_uncoupled.h ***/
  142348. static long _vq_quantlist__16u0__p1_0[] = {
  142349. 1,
  142350. 0,
  142351. 2,
  142352. };
  142353. static long _vq_lengthlist__16u0__p1_0[] = {
  142354. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142355. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142356. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142357. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142358. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142359. 12,
  142360. };
  142361. static float _vq_quantthresh__16u0__p1_0[] = {
  142362. -0.5, 0.5,
  142363. };
  142364. static long _vq_quantmap__16u0__p1_0[] = {
  142365. 1, 0, 2,
  142366. };
  142367. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142368. _vq_quantthresh__16u0__p1_0,
  142369. _vq_quantmap__16u0__p1_0,
  142370. 3,
  142371. 3
  142372. };
  142373. static static_codebook _16u0__p1_0 = {
  142374. 4, 81,
  142375. _vq_lengthlist__16u0__p1_0,
  142376. 1, -535822336, 1611661312, 2, 0,
  142377. _vq_quantlist__16u0__p1_0,
  142378. NULL,
  142379. &_vq_auxt__16u0__p1_0,
  142380. NULL,
  142381. 0
  142382. };
  142383. static long _vq_quantlist__16u0__p2_0[] = {
  142384. 1,
  142385. 0,
  142386. 2,
  142387. };
  142388. static long _vq_lengthlist__16u0__p2_0[] = {
  142389. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142390. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142391. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142392. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142393. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142394. 8,
  142395. };
  142396. static float _vq_quantthresh__16u0__p2_0[] = {
  142397. -0.5, 0.5,
  142398. };
  142399. static long _vq_quantmap__16u0__p2_0[] = {
  142400. 1, 0, 2,
  142401. };
  142402. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142403. _vq_quantthresh__16u0__p2_0,
  142404. _vq_quantmap__16u0__p2_0,
  142405. 3,
  142406. 3
  142407. };
  142408. static static_codebook _16u0__p2_0 = {
  142409. 4, 81,
  142410. _vq_lengthlist__16u0__p2_0,
  142411. 1, -535822336, 1611661312, 2, 0,
  142412. _vq_quantlist__16u0__p2_0,
  142413. NULL,
  142414. &_vq_auxt__16u0__p2_0,
  142415. NULL,
  142416. 0
  142417. };
  142418. static long _vq_quantlist__16u0__p3_0[] = {
  142419. 2,
  142420. 1,
  142421. 3,
  142422. 0,
  142423. 4,
  142424. };
  142425. static long _vq_lengthlist__16u0__p3_0[] = {
  142426. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142427. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142428. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142429. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142430. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142431. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142432. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142433. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142434. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142435. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142436. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142437. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142438. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142439. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142440. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142441. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142442. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142443. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142444. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142445. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142446. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142447. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142448. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142449. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142450. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142451. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142452. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142453. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142454. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142455. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142456. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142457. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142458. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142459. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142460. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142461. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142462. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142463. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142464. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142465. 18,
  142466. };
  142467. static float _vq_quantthresh__16u0__p3_0[] = {
  142468. -1.5, -0.5, 0.5, 1.5,
  142469. };
  142470. static long _vq_quantmap__16u0__p3_0[] = {
  142471. 3, 1, 0, 2, 4,
  142472. };
  142473. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142474. _vq_quantthresh__16u0__p3_0,
  142475. _vq_quantmap__16u0__p3_0,
  142476. 5,
  142477. 5
  142478. };
  142479. static static_codebook _16u0__p3_0 = {
  142480. 4, 625,
  142481. _vq_lengthlist__16u0__p3_0,
  142482. 1, -533725184, 1611661312, 3, 0,
  142483. _vq_quantlist__16u0__p3_0,
  142484. NULL,
  142485. &_vq_auxt__16u0__p3_0,
  142486. NULL,
  142487. 0
  142488. };
  142489. static long _vq_quantlist__16u0__p4_0[] = {
  142490. 2,
  142491. 1,
  142492. 3,
  142493. 0,
  142494. 4,
  142495. };
  142496. static long _vq_lengthlist__16u0__p4_0[] = {
  142497. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142498. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142499. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142500. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142501. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142502. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142503. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142504. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142505. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142506. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142507. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142508. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142509. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142510. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142511. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142512. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142513. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142514. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142515. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142516. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142517. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142518. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142519. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142520. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142521. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142522. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142523. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142524. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142525. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142526. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142527. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142528. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142529. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142530. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142531. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142532. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142533. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142534. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142535. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142536. 11,
  142537. };
  142538. static float _vq_quantthresh__16u0__p4_0[] = {
  142539. -1.5, -0.5, 0.5, 1.5,
  142540. };
  142541. static long _vq_quantmap__16u0__p4_0[] = {
  142542. 3, 1, 0, 2, 4,
  142543. };
  142544. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142545. _vq_quantthresh__16u0__p4_0,
  142546. _vq_quantmap__16u0__p4_0,
  142547. 5,
  142548. 5
  142549. };
  142550. static static_codebook _16u0__p4_0 = {
  142551. 4, 625,
  142552. _vq_lengthlist__16u0__p4_0,
  142553. 1, -533725184, 1611661312, 3, 0,
  142554. _vq_quantlist__16u0__p4_0,
  142555. NULL,
  142556. &_vq_auxt__16u0__p4_0,
  142557. NULL,
  142558. 0
  142559. };
  142560. static long _vq_quantlist__16u0__p5_0[] = {
  142561. 4,
  142562. 3,
  142563. 5,
  142564. 2,
  142565. 6,
  142566. 1,
  142567. 7,
  142568. 0,
  142569. 8,
  142570. };
  142571. static long _vq_lengthlist__16u0__p5_0[] = {
  142572. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142573. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142574. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142575. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142576. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142577. 12,
  142578. };
  142579. static float _vq_quantthresh__16u0__p5_0[] = {
  142580. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142581. };
  142582. static long _vq_quantmap__16u0__p5_0[] = {
  142583. 7, 5, 3, 1, 0, 2, 4, 6,
  142584. 8,
  142585. };
  142586. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142587. _vq_quantthresh__16u0__p5_0,
  142588. _vq_quantmap__16u0__p5_0,
  142589. 9,
  142590. 9
  142591. };
  142592. static static_codebook _16u0__p5_0 = {
  142593. 2, 81,
  142594. _vq_lengthlist__16u0__p5_0,
  142595. 1, -531628032, 1611661312, 4, 0,
  142596. _vq_quantlist__16u0__p5_0,
  142597. NULL,
  142598. &_vq_auxt__16u0__p5_0,
  142599. NULL,
  142600. 0
  142601. };
  142602. static long _vq_quantlist__16u0__p6_0[] = {
  142603. 6,
  142604. 5,
  142605. 7,
  142606. 4,
  142607. 8,
  142608. 3,
  142609. 9,
  142610. 2,
  142611. 10,
  142612. 1,
  142613. 11,
  142614. 0,
  142615. 12,
  142616. };
  142617. static long _vq_lengthlist__16u0__p6_0[] = {
  142618. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142619. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142620. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142621. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142622. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142623. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142624. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142625. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142626. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142627. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142628. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142629. };
  142630. static float _vq_quantthresh__16u0__p6_0[] = {
  142631. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142632. 12.5, 17.5, 22.5, 27.5,
  142633. };
  142634. static long _vq_quantmap__16u0__p6_0[] = {
  142635. 11, 9, 7, 5, 3, 1, 0, 2,
  142636. 4, 6, 8, 10, 12,
  142637. };
  142638. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142639. _vq_quantthresh__16u0__p6_0,
  142640. _vq_quantmap__16u0__p6_0,
  142641. 13,
  142642. 13
  142643. };
  142644. static static_codebook _16u0__p6_0 = {
  142645. 2, 169,
  142646. _vq_lengthlist__16u0__p6_0,
  142647. 1, -526516224, 1616117760, 4, 0,
  142648. _vq_quantlist__16u0__p6_0,
  142649. NULL,
  142650. &_vq_auxt__16u0__p6_0,
  142651. NULL,
  142652. 0
  142653. };
  142654. static long _vq_quantlist__16u0__p6_1[] = {
  142655. 2,
  142656. 1,
  142657. 3,
  142658. 0,
  142659. 4,
  142660. };
  142661. static long _vq_lengthlist__16u0__p6_1[] = {
  142662. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142663. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142664. };
  142665. static float _vq_quantthresh__16u0__p6_1[] = {
  142666. -1.5, -0.5, 0.5, 1.5,
  142667. };
  142668. static long _vq_quantmap__16u0__p6_1[] = {
  142669. 3, 1, 0, 2, 4,
  142670. };
  142671. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142672. _vq_quantthresh__16u0__p6_1,
  142673. _vq_quantmap__16u0__p6_1,
  142674. 5,
  142675. 5
  142676. };
  142677. static static_codebook _16u0__p6_1 = {
  142678. 2, 25,
  142679. _vq_lengthlist__16u0__p6_1,
  142680. 1, -533725184, 1611661312, 3, 0,
  142681. _vq_quantlist__16u0__p6_1,
  142682. NULL,
  142683. &_vq_auxt__16u0__p6_1,
  142684. NULL,
  142685. 0
  142686. };
  142687. static long _vq_quantlist__16u0__p7_0[] = {
  142688. 1,
  142689. 0,
  142690. 2,
  142691. };
  142692. static long _vq_lengthlist__16u0__p7_0[] = {
  142693. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142694. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142695. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142696. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142697. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142698. 7,
  142699. };
  142700. static float _vq_quantthresh__16u0__p7_0[] = {
  142701. -157.5, 157.5,
  142702. };
  142703. static long _vq_quantmap__16u0__p7_0[] = {
  142704. 1, 0, 2,
  142705. };
  142706. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142707. _vq_quantthresh__16u0__p7_0,
  142708. _vq_quantmap__16u0__p7_0,
  142709. 3,
  142710. 3
  142711. };
  142712. static static_codebook _16u0__p7_0 = {
  142713. 4, 81,
  142714. _vq_lengthlist__16u0__p7_0,
  142715. 1, -518803456, 1628680192, 2, 0,
  142716. _vq_quantlist__16u0__p7_0,
  142717. NULL,
  142718. &_vq_auxt__16u0__p7_0,
  142719. NULL,
  142720. 0
  142721. };
  142722. static long _vq_quantlist__16u0__p7_1[] = {
  142723. 7,
  142724. 6,
  142725. 8,
  142726. 5,
  142727. 9,
  142728. 4,
  142729. 10,
  142730. 3,
  142731. 11,
  142732. 2,
  142733. 12,
  142734. 1,
  142735. 13,
  142736. 0,
  142737. 14,
  142738. };
  142739. static long _vq_lengthlist__16u0__p7_1[] = {
  142740. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142741. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142742. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142743. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142744. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142745. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142746. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142752. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142753. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142754. 10,
  142755. };
  142756. static float _vq_quantthresh__16u0__p7_1[] = {
  142757. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142758. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142759. };
  142760. static long _vq_quantmap__16u0__p7_1[] = {
  142761. 13, 11, 9, 7, 5, 3, 1, 0,
  142762. 2, 4, 6, 8, 10, 12, 14,
  142763. };
  142764. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142765. _vq_quantthresh__16u0__p7_1,
  142766. _vq_quantmap__16u0__p7_1,
  142767. 15,
  142768. 15
  142769. };
  142770. static static_codebook _16u0__p7_1 = {
  142771. 2, 225,
  142772. _vq_lengthlist__16u0__p7_1,
  142773. 1, -520986624, 1620377600, 4, 0,
  142774. _vq_quantlist__16u0__p7_1,
  142775. NULL,
  142776. &_vq_auxt__16u0__p7_1,
  142777. NULL,
  142778. 0
  142779. };
  142780. static long _vq_quantlist__16u0__p7_2[] = {
  142781. 10,
  142782. 9,
  142783. 11,
  142784. 8,
  142785. 12,
  142786. 7,
  142787. 13,
  142788. 6,
  142789. 14,
  142790. 5,
  142791. 15,
  142792. 4,
  142793. 16,
  142794. 3,
  142795. 17,
  142796. 2,
  142797. 18,
  142798. 1,
  142799. 19,
  142800. 0,
  142801. 20,
  142802. };
  142803. static long _vq_lengthlist__16u0__p7_2[] = {
  142804. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142805. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142806. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142807. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142808. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142809. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142810. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142811. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142812. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142813. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  142814. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  142815. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  142816. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  142817. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  142818. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  142819. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  142820. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  142821. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  142822. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  142823. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  142824. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  142825. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  142826. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  142827. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  142828. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  142829. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  142830. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  142831. 10,10,12,11,10,11,11,11,10,
  142832. };
  142833. static float _vq_quantthresh__16u0__p7_2[] = {
  142834. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142835. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142836. 6.5, 7.5, 8.5, 9.5,
  142837. };
  142838. static long _vq_quantmap__16u0__p7_2[] = {
  142839. 19, 17, 15, 13, 11, 9, 7, 5,
  142840. 3, 1, 0, 2, 4, 6, 8, 10,
  142841. 12, 14, 16, 18, 20,
  142842. };
  142843. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  142844. _vq_quantthresh__16u0__p7_2,
  142845. _vq_quantmap__16u0__p7_2,
  142846. 21,
  142847. 21
  142848. };
  142849. static static_codebook _16u0__p7_2 = {
  142850. 2, 441,
  142851. _vq_lengthlist__16u0__p7_2,
  142852. 1, -529268736, 1611661312, 5, 0,
  142853. _vq_quantlist__16u0__p7_2,
  142854. NULL,
  142855. &_vq_auxt__16u0__p7_2,
  142856. NULL,
  142857. 0
  142858. };
  142859. static long _huff_lengthlist__16u0__single[] = {
  142860. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  142861. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  142862. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  142863. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  142864. };
  142865. static static_codebook _huff_book__16u0__single = {
  142866. 2, 64,
  142867. _huff_lengthlist__16u0__single,
  142868. 0, 0, 0, 0, 0,
  142869. NULL,
  142870. NULL,
  142871. NULL,
  142872. NULL,
  142873. 0
  142874. };
  142875. static long _huff_lengthlist__16u1__long[] = {
  142876. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  142877. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  142878. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  142879. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  142880. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  142881. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  142882. 16,13,16,18,
  142883. };
  142884. static static_codebook _huff_book__16u1__long = {
  142885. 2, 100,
  142886. _huff_lengthlist__16u1__long,
  142887. 0, 0, 0, 0, 0,
  142888. NULL,
  142889. NULL,
  142890. NULL,
  142891. NULL,
  142892. 0
  142893. };
  142894. static long _vq_quantlist__16u1__p1_0[] = {
  142895. 1,
  142896. 0,
  142897. 2,
  142898. };
  142899. static long _vq_lengthlist__16u1__p1_0[] = {
  142900. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  142901. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  142902. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  142903. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142904. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  142905. 11,
  142906. };
  142907. static float _vq_quantthresh__16u1__p1_0[] = {
  142908. -0.5, 0.5,
  142909. };
  142910. static long _vq_quantmap__16u1__p1_0[] = {
  142911. 1, 0, 2,
  142912. };
  142913. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  142914. _vq_quantthresh__16u1__p1_0,
  142915. _vq_quantmap__16u1__p1_0,
  142916. 3,
  142917. 3
  142918. };
  142919. static static_codebook _16u1__p1_0 = {
  142920. 4, 81,
  142921. _vq_lengthlist__16u1__p1_0,
  142922. 1, -535822336, 1611661312, 2, 0,
  142923. _vq_quantlist__16u1__p1_0,
  142924. NULL,
  142925. &_vq_auxt__16u1__p1_0,
  142926. NULL,
  142927. 0
  142928. };
  142929. static long _vq_quantlist__16u1__p2_0[] = {
  142930. 1,
  142931. 0,
  142932. 2,
  142933. };
  142934. static long _vq_lengthlist__16u1__p2_0[] = {
  142935. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  142936. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  142937. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  142938. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142939. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  142940. 8,
  142941. };
  142942. static float _vq_quantthresh__16u1__p2_0[] = {
  142943. -0.5, 0.5,
  142944. };
  142945. static long _vq_quantmap__16u1__p2_0[] = {
  142946. 1, 0, 2,
  142947. };
  142948. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  142949. _vq_quantthresh__16u1__p2_0,
  142950. _vq_quantmap__16u1__p2_0,
  142951. 3,
  142952. 3
  142953. };
  142954. static static_codebook _16u1__p2_0 = {
  142955. 4, 81,
  142956. _vq_lengthlist__16u1__p2_0,
  142957. 1, -535822336, 1611661312, 2, 0,
  142958. _vq_quantlist__16u1__p2_0,
  142959. NULL,
  142960. &_vq_auxt__16u1__p2_0,
  142961. NULL,
  142962. 0
  142963. };
  142964. static long _vq_quantlist__16u1__p3_0[] = {
  142965. 2,
  142966. 1,
  142967. 3,
  142968. 0,
  142969. 4,
  142970. };
  142971. static long _vq_lengthlist__16u1__p3_0[] = {
  142972. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  142973. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  142974. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  142975. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142976. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  142977. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  142978. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  142979. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  142980. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142981. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  142982. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  142983. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  142984. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  142985. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  142986. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  142987. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  142988. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142989. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  142990. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  142991. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  142992. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  142993. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  142994. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  142995. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  142996. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  142997. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  142998. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  142999. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143000. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143001. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143002. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143003. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143004. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143005. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143006. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143007. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143008. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143009. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143010. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143011. 16,
  143012. };
  143013. static float _vq_quantthresh__16u1__p3_0[] = {
  143014. -1.5, -0.5, 0.5, 1.5,
  143015. };
  143016. static long _vq_quantmap__16u1__p3_0[] = {
  143017. 3, 1, 0, 2, 4,
  143018. };
  143019. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143020. _vq_quantthresh__16u1__p3_0,
  143021. _vq_quantmap__16u1__p3_0,
  143022. 5,
  143023. 5
  143024. };
  143025. static static_codebook _16u1__p3_0 = {
  143026. 4, 625,
  143027. _vq_lengthlist__16u1__p3_0,
  143028. 1, -533725184, 1611661312, 3, 0,
  143029. _vq_quantlist__16u1__p3_0,
  143030. NULL,
  143031. &_vq_auxt__16u1__p3_0,
  143032. NULL,
  143033. 0
  143034. };
  143035. static long _vq_quantlist__16u1__p4_0[] = {
  143036. 2,
  143037. 1,
  143038. 3,
  143039. 0,
  143040. 4,
  143041. };
  143042. static long _vq_lengthlist__16u1__p4_0[] = {
  143043. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143044. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143045. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143046. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143047. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143048. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143049. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143050. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143051. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143052. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143053. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143054. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143055. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143056. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143057. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143058. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143059. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143060. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143061. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143062. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143063. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143064. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143065. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143066. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143067. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143068. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143069. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143070. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143071. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143072. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143073. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143074. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143075. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143076. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143077. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143078. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143079. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143080. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143081. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143082. 11,
  143083. };
  143084. static float _vq_quantthresh__16u1__p4_0[] = {
  143085. -1.5, -0.5, 0.5, 1.5,
  143086. };
  143087. static long _vq_quantmap__16u1__p4_0[] = {
  143088. 3, 1, 0, 2, 4,
  143089. };
  143090. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143091. _vq_quantthresh__16u1__p4_0,
  143092. _vq_quantmap__16u1__p4_0,
  143093. 5,
  143094. 5
  143095. };
  143096. static static_codebook _16u1__p4_0 = {
  143097. 4, 625,
  143098. _vq_lengthlist__16u1__p4_0,
  143099. 1, -533725184, 1611661312, 3, 0,
  143100. _vq_quantlist__16u1__p4_0,
  143101. NULL,
  143102. &_vq_auxt__16u1__p4_0,
  143103. NULL,
  143104. 0
  143105. };
  143106. static long _vq_quantlist__16u1__p5_0[] = {
  143107. 4,
  143108. 3,
  143109. 5,
  143110. 2,
  143111. 6,
  143112. 1,
  143113. 7,
  143114. 0,
  143115. 8,
  143116. };
  143117. static long _vq_lengthlist__16u1__p5_0[] = {
  143118. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143119. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143120. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143121. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143122. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143123. 13,
  143124. };
  143125. static float _vq_quantthresh__16u1__p5_0[] = {
  143126. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143127. };
  143128. static long _vq_quantmap__16u1__p5_0[] = {
  143129. 7, 5, 3, 1, 0, 2, 4, 6,
  143130. 8,
  143131. };
  143132. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143133. _vq_quantthresh__16u1__p5_0,
  143134. _vq_quantmap__16u1__p5_0,
  143135. 9,
  143136. 9
  143137. };
  143138. static static_codebook _16u1__p5_0 = {
  143139. 2, 81,
  143140. _vq_lengthlist__16u1__p5_0,
  143141. 1, -531628032, 1611661312, 4, 0,
  143142. _vq_quantlist__16u1__p5_0,
  143143. NULL,
  143144. &_vq_auxt__16u1__p5_0,
  143145. NULL,
  143146. 0
  143147. };
  143148. static long _vq_quantlist__16u1__p6_0[] = {
  143149. 4,
  143150. 3,
  143151. 5,
  143152. 2,
  143153. 6,
  143154. 1,
  143155. 7,
  143156. 0,
  143157. 8,
  143158. };
  143159. static long _vq_lengthlist__16u1__p6_0[] = {
  143160. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143161. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143162. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143163. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143164. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143165. 11,
  143166. };
  143167. static float _vq_quantthresh__16u1__p6_0[] = {
  143168. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143169. };
  143170. static long _vq_quantmap__16u1__p6_0[] = {
  143171. 7, 5, 3, 1, 0, 2, 4, 6,
  143172. 8,
  143173. };
  143174. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143175. _vq_quantthresh__16u1__p6_0,
  143176. _vq_quantmap__16u1__p6_0,
  143177. 9,
  143178. 9
  143179. };
  143180. static static_codebook _16u1__p6_0 = {
  143181. 2, 81,
  143182. _vq_lengthlist__16u1__p6_0,
  143183. 1, -531628032, 1611661312, 4, 0,
  143184. _vq_quantlist__16u1__p6_0,
  143185. NULL,
  143186. &_vq_auxt__16u1__p6_0,
  143187. NULL,
  143188. 0
  143189. };
  143190. static long _vq_quantlist__16u1__p7_0[] = {
  143191. 1,
  143192. 0,
  143193. 2,
  143194. };
  143195. static long _vq_lengthlist__16u1__p7_0[] = {
  143196. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143197. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143198. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143199. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143200. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143201. 13,
  143202. };
  143203. static float _vq_quantthresh__16u1__p7_0[] = {
  143204. -5.5, 5.5,
  143205. };
  143206. static long _vq_quantmap__16u1__p7_0[] = {
  143207. 1, 0, 2,
  143208. };
  143209. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143210. _vq_quantthresh__16u1__p7_0,
  143211. _vq_quantmap__16u1__p7_0,
  143212. 3,
  143213. 3
  143214. };
  143215. static static_codebook _16u1__p7_0 = {
  143216. 4, 81,
  143217. _vq_lengthlist__16u1__p7_0,
  143218. 1, -529137664, 1618345984, 2, 0,
  143219. _vq_quantlist__16u1__p7_0,
  143220. NULL,
  143221. &_vq_auxt__16u1__p7_0,
  143222. NULL,
  143223. 0
  143224. };
  143225. static long _vq_quantlist__16u1__p7_1[] = {
  143226. 5,
  143227. 4,
  143228. 6,
  143229. 3,
  143230. 7,
  143231. 2,
  143232. 8,
  143233. 1,
  143234. 9,
  143235. 0,
  143236. 10,
  143237. };
  143238. static long _vq_lengthlist__16u1__p7_1[] = {
  143239. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143240. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143241. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143242. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143243. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143244. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143245. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143246. 8, 9, 9,10,10,10,10,10,10,
  143247. };
  143248. static float _vq_quantthresh__16u1__p7_1[] = {
  143249. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143250. 3.5, 4.5,
  143251. };
  143252. static long _vq_quantmap__16u1__p7_1[] = {
  143253. 9, 7, 5, 3, 1, 0, 2, 4,
  143254. 6, 8, 10,
  143255. };
  143256. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143257. _vq_quantthresh__16u1__p7_1,
  143258. _vq_quantmap__16u1__p7_1,
  143259. 11,
  143260. 11
  143261. };
  143262. static static_codebook _16u1__p7_1 = {
  143263. 2, 121,
  143264. _vq_lengthlist__16u1__p7_1,
  143265. 1, -531365888, 1611661312, 4, 0,
  143266. _vq_quantlist__16u1__p7_1,
  143267. NULL,
  143268. &_vq_auxt__16u1__p7_1,
  143269. NULL,
  143270. 0
  143271. };
  143272. static long _vq_quantlist__16u1__p8_0[] = {
  143273. 5,
  143274. 4,
  143275. 6,
  143276. 3,
  143277. 7,
  143278. 2,
  143279. 8,
  143280. 1,
  143281. 9,
  143282. 0,
  143283. 10,
  143284. };
  143285. static long _vq_lengthlist__16u1__p8_0[] = {
  143286. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143287. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143288. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143289. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143290. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143291. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143292. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143293. 13,14,14,15,15,16,16,15,16,
  143294. };
  143295. static float _vq_quantthresh__16u1__p8_0[] = {
  143296. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143297. 38.5, 49.5,
  143298. };
  143299. static long _vq_quantmap__16u1__p8_0[] = {
  143300. 9, 7, 5, 3, 1, 0, 2, 4,
  143301. 6, 8, 10,
  143302. };
  143303. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143304. _vq_quantthresh__16u1__p8_0,
  143305. _vq_quantmap__16u1__p8_0,
  143306. 11,
  143307. 11
  143308. };
  143309. static static_codebook _16u1__p8_0 = {
  143310. 2, 121,
  143311. _vq_lengthlist__16u1__p8_0,
  143312. 1, -524582912, 1618345984, 4, 0,
  143313. _vq_quantlist__16u1__p8_0,
  143314. NULL,
  143315. &_vq_auxt__16u1__p8_0,
  143316. NULL,
  143317. 0
  143318. };
  143319. static long _vq_quantlist__16u1__p8_1[] = {
  143320. 5,
  143321. 4,
  143322. 6,
  143323. 3,
  143324. 7,
  143325. 2,
  143326. 8,
  143327. 1,
  143328. 9,
  143329. 0,
  143330. 10,
  143331. };
  143332. static long _vq_lengthlist__16u1__p8_1[] = {
  143333. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143334. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143335. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143336. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143337. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143338. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143339. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143340. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143341. };
  143342. static float _vq_quantthresh__16u1__p8_1[] = {
  143343. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143344. 3.5, 4.5,
  143345. };
  143346. static long _vq_quantmap__16u1__p8_1[] = {
  143347. 9, 7, 5, 3, 1, 0, 2, 4,
  143348. 6, 8, 10,
  143349. };
  143350. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143351. _vq_quantthresh__16u1__p8_1,
  143352. _vq_quantmap__16u1__p8_1,
  143353. 11,
  143354. 11
  143355. };
  143356. static static_codebook _16u1__p8_1 = {
  143357. 2, 121,
  143358. _vq_lengthlist__16u1__p8_1,
  143359. 1, -531365888, 1611661312, 4, 0,
  143360. _vq_quantlist__16u1__p8_1,
  143361. NULL,
  143362. &_vq_auxt__16u1__p8_1,
  143363. NULL,
  143364. 0
  143365. };
  143366. static long _vq_quantlist__16u1__p9_0[] = {
  143367. 7,
  143368. 6,
  143369. 8,
  143370. 5,
  143371. 9,
  143372. 4,
  143373. 10,
  143374. 3,
  143375. 11,
  143376. 2,
  143377. 12,
  143378. 1,
  143379. 13,
  143380. 0,
  143381. 14,
  143382. };
  143383. static long _vq_lengthlist__16u1__p9_0[] = {
  143384. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143385. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143386. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143387. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143388. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143389. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143390. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143391. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143392. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143393. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143394. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143395. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143396. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143397. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143398. 8,
  143399. };
  143400. static float _vq_quantthresh__16u1__p9_0[] = {
  143401. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143402. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143403. };
  143404. static long _vq_quantmap__16u1__p9_0[] = {
  143405. 13, 11, 9, 7, 5, 3, 1, 0,
  143406. 2, 4, 6, 8, 10, 12, 14,
  143407. };
  143408. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143409. _vq_quantthresh__16u1__p9_0,
  143410. _vq_quantmap__16u1__p9_0,
  143411. 15,
  143412. 15
  143413. };
  143414. static static_codebook _16u1__p9_0 = {
  143415. 2, 225,
  143416. _vq_lengthlist__16u1__p9_0,
  143417. 1, -514071552, 1627381760, 4, 0,
  143418. _vq_quantlist__16u1__p9_0,
  143419. NULL,
  143420. &_vq_auxt__16u1__p9_0,
  143421. NULL,
  143422. 0
  143423. };
  143424. static long _vq_quantlist__16u1__p9_1[] = {
  143425. 7,
  143426. 6,
  143427. 8,
  143428. 5,
  143429. 9,
  143430. 4,
  143431. 10,
  143432. 3,
  143433. 11,
  143434. 2,
  143435. 12,
  143436. 1,
  143437. 13,
  143438. 0,
  143439. 14,
  143440. };
  143441. static long _vq_lengthlist__16u1__p9_1[] = {
  143442. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143443. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143444. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143445. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143446. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143447. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143448. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143449. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143450. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143451. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143452. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143453. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143454. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143455. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143456. 9,
  143457. };
  143458. static float _vq_quantthresh__16u1__p9_1[] = {
  143459. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143460. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143461. };
  143462. static long _vq_quantmap__16u1__p9_1[] = {
  143463. 13, 11, 9, 7, 5, 3, 1, 0,
  143464. 2, 4, 6, 8, 10, 12, 14,
  143465. };
  143466. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143467. _vq_quantthresh__16u1__p9_1,
  143468. _vq_quantmap__16u1__p9_1,
  143469. 15,
  143470. 15
  143471. };
  143472. static static_codebook _16u1__p9_1 = {
  143473. 2, 225,
  143474. _vq_lengthlist__16u1__p9_1,
  143475. 1, -522338304, 1620115456, 4, 0,
  143476. _vq_quantlist__16u1__p9_1,
  143477. NULL,
  143478. &_vq_auxt__16u1__p9_1,
  143479. NULL,
  143480. 0
  143481. };
  143482. static long _vq_quantlist__16u1__p9_2[] = {
  143483. 8,
  143484. 7,
  143485. 9,
  143486. 6,
  143487. 10,
  143488. 5,
  143489. 11,
  143490. 4,
  143491. 12,
  143492. 3,
  143493. 13,
  143494. 2,
  143495. 14,
  143496. 1,
  143497. 15,
  143498. 0,
  143499. 16,
  143500. };
  143501. static long _vq_lengthlist__16u1__p9_2[] = {
  143502. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143503. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143504. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143505. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143506. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143507. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143508. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143509. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143510. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143511. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143512. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143513. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143514. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143515. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143516. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143517. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143518. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143519. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143520. 10,
  143521. };
  143522. static float _vq_quantthresh__16u1__p9_2[] = {
  143523. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143524. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143525. };
  143526. static long _vq_quantmap__16u1__p9_2[] = {
  143527. 15, 13, 11, 9, 7, 5, 3, 1,
  143528. 0, 2, 4, 6, 8, 10, 12, 14,
  143529. 16,
  143530. };
  143531. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143532. _vq_quantthresh__16u1__p9_2,
  143533. _vq_quantmap__16u1__p9_2,
  143534. 17,
  143535. 17
  143536. };
  143537. static static_codebook _16u1__p9_2 = {
  143538. 2, 289,
  143539. _vq_lengthlist__16u1__p9_2,
  143540. 1, -529530880, 1611661312, 5, 0,
  143541. _vq_quantlist__16u1__p9_2,
  143542. NULL,
  143543. &_vq_auxt__16u1__p9_2,
  143544. NULL,
  143545. 0
  143546. };
  143547. static long _huff_lengthlist__16u1__short[] = {
  143548. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143549. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143550. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143551. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143552. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143553. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143554. 16,16,16,16,
  143555. };
  143556. static static_codebook _huff_book__16u1__short = {
  143557. 2, 100,
  143558. _huff_lengthlist__16u1__short,
  143559. 0, 0, 0, 0, 0,
  143560. NULL,
  143561. NULL,
  143562. NULL,
  143563. NULL,
  143564. 0
  143565. };
  143566. static long _huff_lengthlist__16u2__long[] = {
  143567. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143568. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143569. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143570. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143571. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143572. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143573. 13,14,18,18,
  143574. };
  143575. static static_codebook _huff_book__16u2__long = {
  143576. 2, 100,
  143577. _huff_lengthlist__16u2__long,
  143578. 0, 0, 0, 0, 0,
  143579. NULL,
  143580. NULL,
  143581. NULL,
  143582. NULL,
  143583. 0
  143584. };
  143585. static long _huff_lengthlist__16u2__short[] = {
  143586. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143587. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143588. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143589. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143590. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143591. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143592. 16,16,16,16,
  143593. };
  143594. static static_codebook _huff_book__16u2__short = {
  143595. 2, 100,
  143596. _huff_lengthlist__16u2__short,
  143597. 0, 0, 0, 0, 0,
  143598. NULL,
  143599. NULL,
  143600. NULL,
  143601. NULL,
  143602. 0
  143603. };
  143604. static long _vq_quantlist__16u2_p1_0[] = {
  143605. 1,
  143606. 0,
  143607. 2,
  143608. };
  143609. static long _vq_lengthlist__16u2_p1_0[] = {
  143610. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143611. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143612. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143613. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143614. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143615. 10,
  143616. };
  143617. static float _vq_quantthresh__16u2_p1_0[] = {
  143618. -0.5, 0.5,
  143619. };
  143620. static long _vq_quantmap__16u2_p1_0[] = {
  143621. 1, 0, 2,
  143622. };
  143623. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143624. _vq_quantthresh__16u2_p1_0,
  143625. _vq_quantmap__16u2_p1_0,
  143626. 3,
  143627. 3
  143628. };
  143629. static static_codebook _16u2_p1_0 = {
  143630. 4, 81,
  143631. _vq_lengthlist__16u2_p1_0,
  143632. 1, -535822336, 1611661312, 2, 0,
  143633. _vq_quantlist__16u2_p1_0,
  143634. NULL,
  143635. &_vq_auxt__16u2_p1_0,
  143636. NULL,
  143637. 0
  143638. };
  143639. static long _vq_quantlist__16u2_p2_0[] = {
  143640. 2,
  143641. 1,
  143642. 3,
  143643. 0,
  143644. 4,
  143645. };
  143646. static long _vq_lengthlist__16u2_p2_0[] = {
  143647. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143648. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143649. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143650. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143651. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143652. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143653. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143654. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143655. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143656. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143657. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143658. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143659. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143660. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143661. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143662. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143663. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143664. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143665. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143666. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143667. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143668. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143669. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143670. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143671. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143672. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143673. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143674. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143675. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143676. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143677. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143678. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143679. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143680. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143681. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143682. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143683. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143684. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143685. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143686. 13,
  143687. };
  143688. static float _vq_quantthresh__16u2_p2_0[] = {
  143689. -1.5, -0.5, 0.5, 1.5,
  143690. };
  143691. static long _vq_quantmap__16u2_p2_0[] = {
  143692. 3, 1, 0, 2, 4,
  143693. };
  143694. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143695. _vq_quantthresh__16u2_p2_0,
  143696. _vq_quantmap__16u2_p2_0,
  143697. 5,
  143698. 5
  143699. };
  143700. static static_codebook _16u2_p2_0 = {
  143701. 4, 625,
  143702. _vq_lengthlist__16u2_p2_0,
  143703. 1, -533725184, 1611661312, 3, 0,
  143704. _vq_quantlist__16u2_p2_0,
  143705. NULL,
  143706. &_vq_auxt__16u2_p2_0,
  143707. NULL,
  143708. 0
  143709. };
  143710. static long _vq_quantlist__16u2_p3_0[] = {
  143711. 4,
  143712. 3,
  143713. 5,
  143714. 2,
  143715. 6,
  143716. 1,
  143717. 7,
  143718. 0,
  143719. 8,
  143720. };
  143721. static long _vq_lengthlist__16u2_p3_0[] = {
  143722. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143723. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143724. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143725. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143726. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143727. 11,
  143728. };
  143729. static float _vq_quantthresh__16u2_p3_0[] = {
  143730. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143731. };
  143732. static long _vq_quantmap__16u2_p3_0[] = {
  143733. 7, 5, 3, 1, 0, 2, 4, 6,
  143734. 8,
  143735. };
  143736. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143737. _vq_quantthresh__16u2_p3_0,
  143738. _vq_quantmap__16u2_p3_0,
  143739. 9,
  143740. 9
  143741. };
  143742. static static_codebook _16u2_p3_0 = {
  143743. 2, 81,
  143744. _vq_lengthlist__16u2_p3_0,
  143745. 1, -531628032, 1611661312, 4, 0,
  143746. _vq_quantlist__16u2_p3_0,
  143747. NULL,
  143748. &_vq_auxt__16u2_p3_0,
  143749. NULL,
  143750. 0
  143751. };
  143752. static long _vq_quantlist__16u2_p4_0[] = {
  143753. 8,
  143754. 7,
  143755. 9,
  143756. 6,
  143757. 10,
  143758. 5,
  143759. 11,
  143760. 4,
  143761. 12,
  143762. 3,
  143763. 13,
  143764. 2,
  143765. 14,
  143766. 1,
  143767. 15,
  143768. 0,
  143769. 16,
  143770. };
  143771. static long _vq_lengthlist__16u2_p4_0[] = {
  143772. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143773. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143774. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143775. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143776. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143777. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143778. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143779. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143780. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143781. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143782. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143783. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143784. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143785. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143786. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143787. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143788. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143789. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143790. 14,
  143791. };
  143792. static float _vq_quantthresh__16u2_p4_0[] = {
  143793. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143794. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143795. };
  143796. static long _vq_quantmap__16u2_p4_0[] = {
  143797. 15, 13, 11, 9, 7, 5, 3, 1,
  143798. 0, 2, 4, 6, 8, 10, 12, 14,
  143799. 16,
  143800. };
  143801. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143802. _vq_quantthresh__16u2_p4_0,
  143803. _vq_quantmap__16u2_p4_0,
  143804. 17,
  143805. 17
  143806. };
  143807. static static_codebook _16u2_p4_0 = {
  143808. 2, 289,
  143809. _vq_lengthlist__16u2_p4_0,
  143810. 1, -529530880, 1611661312, 5, 0,
  143811. _vq_quantlist__16u2_p4_0,
  143812. NULL,
  143813. &_vq_auxt__16u2_p4_0,
  143814. NULL,
  143815. 0
  143816. };
  143817. static long _vq_quantlist__16u2_p5_0[] = {
  143818. 1,
  143819. 0,
  143820. 2,
  143821. };
  143822. static long _vq_lengthlist__16u2_p5_0[] = {
  143823. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  143824. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  143825. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  143826. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  143827. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  143828. 10,
  143829. };
  143830. static float _vq_quantthresh__16u2_p5_0[] = {
  143831. -5.5, 5.5,
  143832. };
  143833. static long _vq_quantmap__16u2_p5_0[] = {
  143834. 1, 0, 2,
  143835. };
  143836. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  143837. _vq_quantthresh__16u2_p5_0,
  143838. _vq_quantmap__16u2_p5_0,
  143839. 3,
  143840. 3
  143841. };
  143842. static static_codebook _16u2_p5_0 = {
  143843. 4, 81,
  143844. _vq_lengthlist__16u2_p5_0,
  143845. 1, -529137664, 1618345984, 2, 0,
  143846. _vq_quantlist__16u2_p5_0,
  143847. NULL,
  143848. &_vq_auxt__16u2_p5_0,
  143849. NULL,
  143850. 0
  143851. };
  143852. static long _vq_quantlist__16u2_p5_1[] = {
  143853. 5,
  143854. 4,
  143855. 6,
  143856. 3,
  143857. 7,
  143858. 2,
  143859. 8,
  143860. 1,
  143861. 9,
  143862. 0,
  143863. 10,
  143864. };
  143865. static long _vq_lengthlist__16u2_p5_1[] = {
  143866. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  143867. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  143868. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143869. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143870. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143871. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143872. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143873. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143874. };
  143875. static float _vq_quantthresh__16u2_p5_1[] = {
  143876. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143877. 3.5, 4.5,
  143878. };
  143879. static long _vq_quantmap__16u2_p5_1[] = {
  143880. 9, 7, 5, 3, 1, 0, 2, 4,
  143881. 6, 8, 10,
  143882. };
  143883. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  143884. _vq_quantthresh__16u2_p5_1,
  143885. _vq_quantmap__16u2_p5_1,
  143886. 11,
  143887. 11
  143888. };
  143889. static static_codebook _16u2_p5_1 = {
  143890. 2, 121,
  143891. _vq_lengthlist__16u2_p5_1,
  143892. 1, -531365888, 1611661312, 4, 0,
  143893. _vq_quantlist__16u2_p5_1,
  143894. NULL,
  143895. &_vq_auxt__16u2_p5_1,
  143896. NULL,
  143897. 0
  143898. };
  143899. static long _vq_quantlist__16u2_p6_0[] = {
  143900. 6,
  143901. 5,
  143902. 7,
  143903. 4,
  143904. 8,
  143905. 3,
  143906. 9,
  143907. 2,
  143908. 10,
  143909. 1,
  143910. 11,
  143911. 0,
  143912. 12,
  143913. };
  143914. static long _vq_lengthlist__16u2_p6_0[] = {
  143915. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  143916. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  143917. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  143918. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  143919. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  143920. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  143921. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  143922. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  143923. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  143924. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  143925. 12,13,13,14,14,14,14,15,15,
  143926. };
  143927. static float _vq_quantthresh__16u2_p6_0[] = {
  143928. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143929. 12.5, 17.5, 22.5, 27.5,
  143930. };
  143931. static long _vq_quantmap__16u2_p6_0[] = {
  143932. 11, 9, 7, 5, 3, 1, 0, 2,
  143933. 4, 6, 8, 10, 12,
  143934. };
  143935. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  143936. _vq_quantthresh__16u2_p6_0,
  143937. _vq_quantmap__16u2_p6_0,
  143938. 13,
  143939. 13
  143940. };
  143941. static static_codebook _16u2_p6_0 = {
  143942. 2, 169,
  143943. _vq_lengthlist__16u2_p6_0,
  143944. 1, -526516224, 1616117760, 4, 0,
  143945. _vq_quantlist__16u2_p6_0,
  143946. NULL,
  143947. &_vq_auxt__16u2_p6_0,
  143948. NULL,
  143949. 0
  143950. };
  143951. static long _vq_quantlist__16u2_p6_1[] = {
  143952. 2,
  143953. 1,
  143954. 3,
  143955. 0,
  143956. 4,
  143957. };
  143958. static long _vq_lengthlist__16u2_p6_1[] = {
  143959. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143960. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  143961. };
  143962. static float _vq_quantthresh__16u2_p6_1[] = {
  143963. -1.5, -0.5, 0.5, 1.5,
  143964. };
  143965. static long _vq_quantmap__16u2_p6_1[] = {
  143966. 3, 1, 0, 2, 4,
  143967. };
  143968. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  143969. _vq_quantthresh__16u2_p6_1,
  143970. _vq_quantmap__16u2_p6_1,
  143971. 5,
  143972. 5
  143973. };
  143974. static static_codebook _16u2_p6_1 = {
  143975. 2, 25,
  143976. _vq_lengthlist__16u2_p6_1,
  143977. 1, -533725184, 1611661312, 3, 0,
  143978. _vq_quantlist__16u2_p6_1,
  143979. NULL,
  143980. &_vq_auxt__16u2_p6_1,
  143981. NULL,
  143982. 0
  143983. };
  143984. static long _vq_quantlist__16u2_p7_0[] = {
  143985. 6,
  143986. 5,
  143987. 7,
  143988. 4,
  143989. 8,
  143990. 3,
  143991. 9,
  143992. 2,
  143993. 10,
  143994. 1,
  143995. 11,
  143996. 0,
  143997. 12,
  143998. };
  143999. static long _vq_lengthlist__16u2_p7_0[] = {
  144000. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144001. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144002. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144003. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144004. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144005. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144006. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144007. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144008. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144009. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144010. 12,13,13,13,14,14,14,15,14,
  144011. };
  144012. static float _vq_quantthresh__16u2_p7_0[] = {
  144013. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144014. 27.5, 38.5, 49.5, 60.5,
  144015. };
  144016. static long _vq_quantmap__16u2_p7_0[] = {
  144017. 11, 9, 7, 5, 3, 1, 0, 2,
  144018. 4, 6, 8, 10, 12,
  144019. };
  144020. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144021. _vq_quantthresh__16u2_p7_0,
  144022. _vq_quantmap__16u2_p7_0,
  144023. 13,
  144024. 13
  144025. };
  144026. static static_codebook _16u2_p7_0 = {
  144027. 2, 169,
  144028. _vq_lengthlist__16u2_p7_0,
  144029. 1, -523206656, 1618345984, 4, 0,
  144030. _vq_quantlist__16u2_p7_0,
  144031. NULL,
  144032. &_vq_auxt__16u2_p7_0,
  144033. NULL,
  144034. 0
  144035. };
  144036. static long _vq_quantlist__16u2_p7_1[] = {
  144037. 5,
  144038. 4,
  144039. 6,
  144040. 3,
  144041. 7,
  144042. 2,
  144043. 8,
  144044. 1,
  144045. 9,
  144046. 0,
  144047. 10,
  144048. };
  144049. static long _vq_lengthlist__16u2_p7_1[] = {
  144050. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144051. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144052. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144053. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144054. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144055. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144056. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144057. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144058. };
  144059. static float _vq_quantthresh__16u2_p7_1[] = {
  144060. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144061. 3.5, 4.5,
  144062. };
  144063. static long _vq_quantmap__16u2_p7_1[] = {
  144064. 9, 7, 5, 3, 1, 0, 2, 4,
  144065. 6, 8, 10,
  144066. };
  144067. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144068. _vq_quantthresh__16u2_p7_1,
  144069. _vq_quantmap__16u2_p7_1,
  144070. 11,
  144071. 11
  144072. };
  144073. static static_codebook _16u2_p7_1 = {
  144074. 2, 121,
  144075. _vq_lengthlist__16u2_p7_1,
  144076. 1, -531365888, 1611661312, 4, 0,
  144077. _vq_quantlist__16u2_p7_1,
  144078. NULL,
  144079. &_vq_auxt__16u2_p7_1,
  144080. NULL,
  144081. 0
  144082. };
  144083. static long _vq_quantlist__16u2_p8_0[] = {
  144084. 7,
  144085. 6,
  144086. 8,
  144087. 5,
  144088. 9,
  144089. 4,
  144090. 10,
  144091. 3,
  144092. 11,
  144093. 2,
  144094. 12,
  144095. 1,
  144096. 13,
  144097. 0,
  144098. 14,
  144099. };
  144100. static long _vq_lengthlist__16u2_p8_0[] = {
  144101. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144102. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144103. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144104. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144105. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144106. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144107. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144108. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144109. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144110. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144111. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144112. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144113. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144114. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144115. 14,
  144116. };
  144117. static float _vq_quantthresh__16u2_p8_0[] = {
  144118. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144119. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144120. };
  144121. static long _vq_quantmap__16u2_p8_0[] = {
  144122. 13, 11, 9, 7, 5, 3, 1, 0,
  144123. 2, 4, 6, 8, 10, 12, 14,
  144124. };
  144125. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144126. _vq_quantthresh__16u2_p8_0,
  144127. _vq_quantmap__16u2_p8_0,
  144128. 15,
  144129. 15
  144130. };
  144131. static static_codebook _16u2_p8_0 = {
  144132. 2, 225,
  144133. _vq_lengthlist__16u2_p8_0,
  144134. 1, -520986624, 1620377600, 4, 0,
  144135. _vq_quantlist__16u2_p8_0,
  144136. NULL,
  144137. &_vq_auxt__16u2_p8_0,
  144138. NULL,
  144139. 0
  144140. };
  144141. static long _vq_quantlist__16u2_p8_1[] = {
  144142. 10,
  144143. 9,
  144144. 11,
  144145. 8,
  144146. 12,
  144147. 7,
  144148. 13,
  144149. 6,
  144150. 14,
  144151. 5,
  144152. 15,
  144153. 4,
  144154. 16,
  144155. 3,
  144156. 17,
  144157. 2,
  144158. 18,
  144159. 1,
  144160. 19,
  144161. 0,
  144162. 20,
  144163. };
  144164. static long _vq_lengthlist__16u2_p8_1[] = {
  144165. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144166. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144167. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144168. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144169. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144170. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144171. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144172. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144173. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144174. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144175. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144176. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144177. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144178. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144179. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144180. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144181. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144182. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144183. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144184. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144185. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144186. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144187. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144188. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144189. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144190. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144191. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144192. 11,11,10,11,11,11,10,11,11,
  144193. };
  144194. static float _vq_quantthresh__16u2_p8_1[] = {
  144195. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144196. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144197. 6.5, 7.5, 8.5, 9.5,
  144198. };
  144199. static long _vq_quantmap__16u2_p8_1[] = {
  144200. 19, 17, 15, 13, 11, 9, 7, 5,
  144201. 3, 1, 0, 2, 4, 6, 8, 10,
  144202. 12, 14, 16, 18, 20,
  144203. };
  144204. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144205. _vq_quantthresh__16u2_p8_1,
  144206. _vq_quantmap__16u2_p8_1,
  144207. 21,
  144208. 21
  144209. };
  144210. static static_codebook _16u2_p8_1 = {
  144211. 2, 441,
  144212. _vq_lengthlist__16u2_p8_1,
  144213. 1, -529268736, 1611661312, 5, 0,
  144214. _vq_quantlist__16u2_p8_1,
  144215. NULL,
  144216. &_vq_auxt__16u2_p8_1,
  144217. NULL,
  144218. 0
  144219. };
  144220. static long _vq_quantlist__16u2_p9_0[] = {
  144221. 5586,
  144222. 4655,
  144223. 6517,
  144224. 3724,
  144225. 7448,
  144226. 2793,
  144227. 8379,
  144228. 1862,
  144229. 9310,
  144230. 931,
  144231. 10241,
  144232. 0,
  144233. 11172,
  144234. 5521,
  144235. 5651,
  144236. };
  144237. static long _vq_lengthlist__16u2_p9_0[] = {
  144238. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144239. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144240. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144241. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144242. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144243. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144244. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144245. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144246. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144247. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144248. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144249. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144250. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144251. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144252. 5,
  144253. };
  144254. static float _vq_quantthresh__16u2_p9_0[] = {
  144255. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144256. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144257. };
  144258. static long _vq_quantmap__16u2_p9_0[] = {
  144259. 11, 9, 7, 5, 3, 1, 13, 0,
  144260. 14, 2, 4, 6, 8, 10, 12,
  144261. };
  144262. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144263. _vq_quantthresh__16u2_p9_0,
  144264. _vq_quantmap__16u2_p9_0,
  144265. 15,
  144266. 15
  144267. };
  144268. static static_codebook _16u2_p9_0 = {
  144269. 2, 225,
  144270. _vq_lengthlist__16u2_p9_0,
  144271. 1, -510275072, 1611661312, 14, 0,
  144272. _vq_quantlist__16u2_p9_0,
  144273. NULL,
  144274. &_vq_auxt__16u2_p9_0,
  144275. NULL,
  144276. 0
  144277. };
  144278. static long _vq_quantlist__16u2_p9_1[] = {
  144279. 392,
  144280. 343,
  144281. 441,
  144282. 294,
  144283. 490,
  144284. 245,
  144285. 539,
  144286. 196,
  144287. 588,
  144288. 147,
  144289. 637,
  144290. 98,
  144291. 686,
  144292. 49,
  144293. 735,
  144294. 0,
  144295. 784,
  144296. 388,
  144297. 396,
  144298. };
  144299. static long _vq_lengthlist__16u2_p9_1[] = {
  144300. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144301. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144302. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144303. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144304. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144305. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144306. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144307. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144308. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144309. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144310. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144311. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144312. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144313. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144314. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144315. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144316. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144317. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144318. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144319. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144320. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144321. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144322. 11,11,11,11,11,11,11, 5, 4,
  144323. };
  144324. static float _vq_quantthresh__16u2_p9_1[] = {
  144325. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144326. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144327. 318.5, 367.5,
  144328. };
  144329. static long _vq_quantmap__16u2_p9_1[] = {
  144330. 15, 13, 11, 9, 7, 5, 3, 1,
  144331. 17, 0, 18, 2, 4, 6, 8, 10,
  144332. 12, 14, 16,
  144333. };
  144334. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144335. _vq_quantthresh__16u2_p9_1,
  144336. _vq_quantmap__16u2_p9_1,
  144337. 19,
  144338. 19
  144339. };
  144340. static static_codebook _16u2_p9_1 = {
  144341. 2, 361,
  144342. _vq_lengthlist__16u2_p9_1,
  144343. 1, -518488064, 1611661312, 10, 0,
  144344. _vq_quantlist__16u2_p9_1,
  144345. NULL,
  144346. &_vq_auxt__16u2_p9_1,
  144347. NULL,
  144348. 0
  144349. };
  144350. static long _vq_quantlist__16u2_p9_2[] = {
  144351. 24,
  144352. 23,
  144353. 25,
  144354. 22,
  144355. 26,
  144356. 21,
  144357. 27,
  144358. 20,
  144359. 28,
  144360. 19,
  144361. 29,
  144362. 18,
  144363. 30,
  144364. 17,
  144365. 31,
  144366. 16,
  144367. 32,
  144368. 15,
  144369. 33,
  144370. 14,
  144371. 34,
  144372. 13,
  144373. 35,
  144374. 12,
  144375. 36,
  144376. 11,
  144377. 37,
  144378. 10,
  144379. 38,
  144380. 9,
  144381. 39,
  144382. 8,
  144383. 40,
  144384. 7,
  144385. 41,
  144386. 6,
  144387. 42,
  144388. 5,
  144389. 43,
  144390. 4,
  144391. 44,
  144392. 3,
  144393. 45,
  144394. 2,
  144395. 46,
  144396. 1,
  144397. 47,
  144398. 0,
  144399. 48,
  144400. };
  144401. static long _vq_lengthlist__16u2_p9_2[] = {
  144402. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144403. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144404. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144405. 11,
  144406. };
  144407. static float _vq_quantthresh__16u2_p9_2[] = {
  144408. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144409. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144410. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144411. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144412. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144413. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144414. };
  144415. static long _vq_quantmap__16u2_p9_2[] = {
  144416. 47, 45, 43, 41, 39, 37, 35, 33,
  144417. 31, 29, 27, 25, 23, 21, 19, 17,
  144418. 15, 13, 11, 9, 7, 5, 3, 1,
  144419. 0, 2, 4, 6, 8, 10, 12, 14,
  144420. 16, 18, 20, 22, 24, 26, 28, 30,
  144421. 32, 34, 36, 38, 40, 42, 44, 46,
  144422. 48,
  144423. };
  144424. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144425. _vq_quantthresh__16u2_p9_2,
  144426. _vq_quantmap__16u2_p9_2,
  144427. 49,
  144428. 49
  144429. };
  144430. static static_codebook _16u2_p9_2 = {
  144431. 1, 49,
  144432. _vq_lengthlist__16u2_p9_2,
  144433. 1, -526909440, 1611661312, 6, 0,
  144434. _vq_quantlist__16u2_p9_2,
  144435. NULL,
  144436. &_vq_auxt__16u2_p9_2,
  144437. NULL,
  144438. 0
  144439. };
  144440. static long _vq_quantlist__8u0__p1_0[] = {
  144441. 1,
  144442. 0,
  144443. 2,
  144444. };
  144445. static long _vq_lengthlist__8u0__p1_0[] = {
  144446. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144447. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144448. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144449. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144450. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144451. 11,
  144452. };
  144453. static float _vq_quantthresh__8u0__p1_0[] = {
  144454. -0.5, 0.5,
  144455. };
  144456. static long _vq_quantmap__8u0__p1_0[] = {
  144457. 1, 0, 2,
  144458. };
  144459. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144460. _vq_quantthresh__8u0__p1_0,
  144461. _vq_quantmap__8u0__p1_0,
  144462. 3,
  144463. 3
  144464. };
  144465. static static_codebook _8u0__p1_0 = {
  144466. 4, 81,
  144467. _vq_lengthlist__8u0__p1_0,
  144468. 1, -535822336, 1611661312, 2, 0,
  144469. _vq_quantlist__8u0__p1_0,
  144470. NULL,
  144471. &_vq_auxt__8u0__p1_0,
  144472. NULL,
  144473. 0
  144474. };
  144475. static long _vq_quantlist__8u0__p2_0[] = {
  144476. 1,
  144477. 0,
  144478. 2,
  144479. };
  144480. static long _vq_lengthlist__8u0__p2_0[] = {
  144481. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144482. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144483. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144484. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144485. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144486. 8,
  144487. };
  144488. static float _vq_quantthresh__8u0__p2_0[] = {
  144489. -0.5, 0.5,
  144490. };
  144491. static long _vq_quantmap__8u0__p2_0[] = {
  144492. 1, 0, 2,
  144493. };
  144494. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144495. _vq_quantthresh__8u0__p2_0,
  144496. _vq_quantmap__8u0__p2_0,
  144497. 3,
  144498. 3
  144499. };
  144500. static static_codebook _8u0__p2_0 = {
  144501. 4, 81,
  144502. _vq_lengthlist__8u0__p2_0,
  144503. 1, -535822336, 1611661312, 2, 0,
  144504. _vq_quantlist__8u0__p2_0,
  144505. NULL,
  144506. &_vq_auxt__8u0__p2_0,
  144507. NULL,
  144508. 0
  144509. };
  144510. static long _vq_quantlist__8u0__p3_0[] = {
  144511. 2,
  144512. 1,
  144513. 3,
  144514. 0,
  144515. 4,
  144516. };
  144517. static long _vq_lengthlist__8u0__p3_0[] = {
  144518. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144519. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144520. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144521. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144522. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144523. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144524. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144525. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144526. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144527. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144528. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144529. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144530. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144531. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144532. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144533. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144534. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144535. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144536. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144537. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144538. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144539. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144540. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144541. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144542. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144543. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144544. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144545. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144546. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144547. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144548. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144549. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144550. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144551. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144552. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144553. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144554. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144555. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144556. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144557. 16,
  144558. };
  144559. static float _vq_quantthresh__8u0__p3_0[] = {
  144560. -1.5, -0.5, 0.5, 1.5,
  144561. };
  144562. static long _vq_quantmap__8u0__p3_0[] = {
  144563. 3, 1, 0, 2, 4,
  144564. };
  144565. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144566. _vq_quantthresh__8u0__p3_0,
  144567. _vq_quantmap__8u0__p3_0,
  144568. 5,
  144569. 5
  144570. };
  144571. static static_codebook _8u0__p3_0 = {
  144572. 4, 625,
  144573. _vq_lengthlist__8u0__p3_0,
  144574. 1, -533725184, 1611661312, 3, 0,
  144575. _vq_quantlist__8u0__p3_0,
  144576. NULL,
  144577. &_vq_auxt__8u0__p3_0,
  144578. NULL,
  144579. 0
  144580. };
  144581. static long _vq_quantlist__8u0__p4_0[] = {
  144582. 2,
  144583. 1,
  144584. 3,
  144585. 0,
  144586. 4,
  144587. };
  144588. static long _vq_lengthlist__8u0__p4_0[] = {
  144589. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144590. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144591. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144592. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144593. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144594. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144595. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144596. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144597. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144598. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144599. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144600. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144601. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144602. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144603. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144604. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144605. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144606. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144607. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144608. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144609. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144610. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144611. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144612. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144613. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144614. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144615. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144616. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144617. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144618. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144619. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144620. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144621. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144622. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144623. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144624. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144625. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144626. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144627. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144628. 12,
  144629. };
  144630. static float _vq_quantthresh__8u0__p4_0[] = {
  144631. -1.5, -0.5, 0.5, 1.5,
  144632. };
  144633. static long _vq_quantmap__8u0__p4_0[] = {
  144634. 3, 1, 0, 2, 4,
  144635. };
  144636. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144637. _vq_quantthresh__8u0__p4_0,
  144638. _vq_quantmap__8u0__p4_0,
  144639. 5,
  144640. 5
  144641. };
  144642. static static_codebook _8u0__p4_0 = {
  144643. 4, 625,
  144644. _vq_lengthlist__8u0__p4_0,
  144645. 1, -533725184, 1611661312, 3, 0,
  144646. _vq_quantlist__8u0__p4_0,
  144647. NULL,
  144648. &_vq_auxt__8u0__p4_0,
  144649. NULL,
  144650. 0
  144651. };
  144652. static long _vq_quantlist__8u0__p5_0[] = {
  144653. 4,
  144654. 3,
  144655. 5,
  144656. 2,
  144657. 6,
  144658. 1,
  144659. 7,
  144660. 0,
  144661. 8,
  144662. };
  144663. static long _vq_lengthlist__8u0__p5_0[] = {
  144664. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144665. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144666. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144667. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144668. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144669. 12,
  144670. };
  144671. static float _vq_quantthresh__8u0__p5_0[] = {
  144672. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144673. };
  144674. static long _vq_quantmap__8u0__p5_0[] = {
  144675. 7, 5, 3, 1, 0, 2, 4, 6,
  144676. 8,
  144677. };
  144678. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144679. _vq_quantthresh__8u0__p5_0,
  144680. _vq_quantmap__8u0__p5_0,
  144681. 9,
  144682. 9
  144683. };
  144684. static static_codebook _8u0__p5_0 = {
  144685. 2, 81,
  144686. _vq_lengthlist__8u0__p5_0,
  144687. 1, -531628032, 1611661312, 4, 0,
  144688. _vq_quantlist__8u0__p5_0,
  144689. NULL,
  144690. &_vq_auxt__8u0__p5_0,
  144691. NULL,
  144692. 0
  144693. };
  144694. static long _vq_quantlist__8u0__p6_0[] = {
  144695. 6,
  144696. 5,
  144697. 7,
  144698. 4,
  144699. 8,
  144700. 3,
  144701. 9,
  144702. 2,
  144703. 10,
  144704. 1,
  144705. 11,
  144706. 0,
  144707. 12,
  144708. };
  144709. static long _vq_lengthlist__8u0__p6_0[] = {
  144710. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144711. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144712. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144713. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144714. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144715. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144716. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144717. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144718. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144719. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144720. 16, 0,15, 0,17, 0, 0, 0, 0,
  144721. };
  144722. static float _vq_quantthresh__8u0__p6_0[] = {
  144723. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144724. 12.5, 17.5, 22.5, 27.5,
  144725. };
  144726. static long _vq_quantmap__8u0__p6_0[] = {
  144727. 11, 9, 7, 5, 3, 1, 0, 2,
  144728. 4, 6, 8, 10, 12,
  144729. };
  144730. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144731. _vq_quantthresh__8u0__p6_0,
  144732. _vq_quantmap__8u0__p6_0,
  144733. 13,
  144734. 13
  144735. };
  144736. static static_codebook _8u0__p6_0 = {
  144737. 2, 169,
  144738. _vq_lengthlist__8u0__p6_0,
  144739. 1, -526516224, 1616117760, 4, 0,
  144740. _vq_quantlist__8u0__p6_0,
  144741. NULL,
  144742. &_vq_auxt__8u0__p6_0,
  144743. NULL,
  144744. 0
  144745. };
  144746. static long _vq_quantlist__8u0__p6_1[] = {
  144747. 2,
  144748. 1,
  144749. 3,
  144750. 0,
  144751. 4,
  144752. };
  144753. static long _vq_lengthlist__8u0__p6_1[] = {
  144754. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144755. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144756. };
  144757. static float _vq_quantthresh__8u0__p6_1[] = {
  144758. -1.5, -0.5, 0.5, 1.5,
  144759. };
  144760. static long _vq_quantmap__8u0__p6_1[] = {
  144761. 3, 1, 0, 2, 4,
  144762. };
  144763. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144764. _vq_quantthresh__8u0__p6_1,
  144765. _vq_quantmap__8u0__p6_1,
  144766. 5,
  144767. 5
  144768. };
  144769. static static_codebook _8u0__p6_1 = {
  144770. 2, 25,
  144771. _vq_lengthlist__8u0__p6_1,
  144772. 1, -533725184, 1611661312, 3, 0,
  144773. _vq_quantlist__8u0__p6_1,
  144774. NULL,
  144775. &_vq_auxt__8u0__p6_1,
  144776. NULL,
  144777. 0
  144778. };
  144779. static long _vq_quantlist__8u0__p7_0[] = {
  144780. 1,
  144781. 0,
  144782. 2,
  144783. };
  144784. static long _vq_lengthlist__8u0__p7_0[] = {
  144785. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144786. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144787. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144788. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144789. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144790. 7,
  144791. };
  144792. static float _vq_quantthresh__8u0__p7_0[] = {
  144793. -157.5, 157.5,
  144794. };
  144795. static long _vq_quantmap__8u0__p7_0[] = {
  144796. 1, 0, 2,
  144797. };
  144798. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144799. _vq_quantthresh__8u0__p7_0,
  144800. _vq_quantmap__8u0__p7_0,
  144801. 3,
  144802. 3
  144803. };
  144804. static static_codebook _8u0__p7_0 = {
  144805. 4, 81,
  144806. _vq_lengthlist__8u0__p7_0,
  144807. 1, -518803456, 1628680192, 2, 0,
  144808. _vq_quantlist__8u0__p7_0,
  144809. NULL,
  144810. &_vq_auxt__8u0__p7_0,
  144811. NULL,
  144812. 0
  144813. };
  144814. static long _vq_quantlist__8u0__p7_1[] = {
  144815. 7,
  144816. 6,
  144817. 8,
  144818. 5,
  144819. 9,
  144820. 4,
  144821. 10,
  144822. 3,
  144823. 11,
  144824. 2,
  144825. 12,
  144826. 1,
  144827. 13,
  144828. 0,
  144829. 14,
  144830. };
  144831. static long _vq_lengthlist__8u0__p7_1[] = {
  144832. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  144833. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  144834. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  144835. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  144836. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  144837. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  144838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144840. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144844. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  144845. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144846. 10,
  144847. };
  144848. static float _vq_quantthresh__8u0__p7_1[] = {
  144849. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144850. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144851. };
  144852. static long _vq_quantmap__8u0__p7_1[] = {
  144853. 13, 11, 9, 7, 5, 3, 1, 0,
  144854. 2, 4, 6, 8, 10, 12, 14,
  144855. };
  144856. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  144857. _vq_quantthresh__8u0__p7_1,
  144858. _vq_quantmap__8u0__p7_1,
  144859. 15,
  144860. 15
  144861. };
  144862. static static_codebook _8u0__p7_1 = {
  144863. 2, 225,
  144864. _vq_lengthlist__8u0__p7_1,
  144865. 1, -520986624, 1620377600, 4, 0,
  144866. _vq_quantlist__8u0__p7_1,
  144867. NULL,
  144868. &_vq_auxt__8u0__p7_1,
  144869. NULL,
  144870. 0
  144871. };
  144872. static long _vq_quantlist__8u0__p7_2[] = {
  144873. 10,
  144874. 9,
  144875. 11,
  144876. 8,
  144877. 12,
  144878. 7,
  144879. 13,
  144880. 6,
  144881. 14,
  144882. 5,
  144883. 15,
  144884. 4,
  144885. 16,
  144886. 3,
  144887. 17,
  144888. 2,
  144889. 18,
  144890. 1,
  144891. 19,
  144892. 0,
  144893. 20,
  144894. };
  144895. static long _vq_lengthlist__8u0__p7_2[] = {
  144896. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  144897. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  144898. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  144899. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  144900. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  144901. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  144902. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  144903. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  144904. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  144905. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  144906. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  144907. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  144908. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  144909. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  144910. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  144911. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  144912. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  144913. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  144914. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  144915. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  144916. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  144917. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  144918. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  144919. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  144920. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  144921. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  144922. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  144923. 11,12,11,11,11,10,10,11,11,
  144924. };
  144925. static float _vq_quantthresh__8u0__p7_2[] = {
  144926. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144927. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144928. 6.5, 7.5, 8.5, 9.5,
  144929. };
  144930. static long _vq_quantmap__8u0__p7_2[] = {
  144931. 19, 17, 15, 13, 11, 9, 7, 5,
  144932. 3, 1, 0, 2, 4, 6, 8, 10,
  144933. 12, 14, 16, 18, 20,
  144934. };
  144935. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  144936. _vq_quantthresh__8u0__p7_2,
  144937. _vq_quantmap__8u0__p7_2,
  144938. 21,
  144939. 21
  144940. };
  144941. static static_codebook _8u0__p7_2 = {
  144942. 2, 441,
  144943. _vq_lengthlist__8u0__p7_2,
  144944. 1, -529268736, 1611661312, 5, 0,
  144945. _vq_quantlist__8u0__p7_2,
  144946. NULL,
  144947. &_vq_auxt__8u0__p7_2,
  144948. NULL,
  144949. 0
  144950. };
  144951. static long _huff_lengthlist__8u0__single[] = {
  144952. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  144953. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  144954. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  144955. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  144956. };
  144957. static static_codebook _huff_book__8u0__single = {
  144958. 2, 64,
  144959. _huff_lengthlist__8u0__single,
  144960. 0, 0, 0, 0, 0,
  144961. NULL,
  144962. NULL,
  144963. NULL,
  144964. NULL,
  144965. 0
  144966. };
  144967. static long _vq_quantlist__8u1__p1_0[] = {
  144968. 1,
  144969. 0,
  144970. 2,
  144971. };
  144972. static long _vq_lengthlist__8u1__p1_0[] = {
  144973. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  144974. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  144975. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  144976. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144977. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  144978. 10,
  144979. };
  144980. static float _vq_quantthresh__8u1__p1_0[] = {
  144981. -0.5, 0.5,
  144982. };
  144983. static long _vq_quantmap__8u1__p1_0[] = {
  144984. 1, 0, 2,
  144985. };
  144986. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  144987. _vq_quantthresh__8u1__p1_0,
  144988. _vq_quantmap__8u1__p1_0,
  144989. 3,
  144990. 3
  144991. };
  144992. static static_codebook _8u1__p1_0 = {
  144993. 4, 81,
  144994. _vq_lengthlist__8u1__p1_0,
  144995. 1, -535822336, 1611661312, 2, 0,
  144996. _vq_quantlist__8u1__p1_0,
  144997. NULL,
  144998. &_vq_auxt__8u1__p1_0,
  144999. NULL,
  145000. 0
  145001. };
  145002. static long _vq_quantlist__8u1__p2_0[] = {
  145003. 1,
  145004. 0,
  145005. 2,
  145006. };
  145007. static long _vq_lengthlist__8u1__p2_0[] = {
  145008. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145009. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145010. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145011. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145012. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145013. 7,
  145014. };
  145015. static float _vq_quantthresh__8u1__p2_0[] = {
  145016. -0.5, 0.5,
  145017. };
  145018. static long _vq_quantmap__8u1__p2_0[] = {
  145019. 1, 0, 2,
  145020. };
  145021. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145022. _vq_quantthresh__8u1__p2_0,
  145023. _vq_quantmap__8u1__p2_0,
  145024. 3,
  145025. 3
  145026. };
  145027. static static_codebook _8u1__p2_0 = {
  145028. 4, 81,
  145029. _vq_lengthlist__8u1__p2_0,
  145030. 1, -535822336, 1611661312, 2, 0,
  145031. _vq_quantlist__8u1__p2_0,
  145032. NULL,
  145033. &_vq_auxt__8u1__p2_0,
  145034. NULL,
  145035. 0
  145036. };
  145037. static long _vq_quantlist__8u1__p3_0[] = {
  145038. 2,
  145039. 1,
  145040. 3,
  145041. 0,
  145042. 4,
  145043. };
  145044. static long _vq_lengthlist__8u1__p3_0[] = {
  145045. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145046. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145047. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145048. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145049. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145050. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145051. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145052. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145053. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145054. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145055. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145056. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145057. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145058. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145059. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145060. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145061. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145062. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145063. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145064. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145065. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145066. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145067. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145068. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145069. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145070. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145071. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145072. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145073. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145074. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145075. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145076. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145077. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145078. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145079. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145080. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145081. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145082. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145083. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145084. 16,
  145085. };
  145086. static float _vq_quantthresh__8u1__p3_0[] = {
  145087. -1.5, -0.5, 0.5, 1.5,
  145088. };
  145089. static long _vq_quantmap__8u1__p3_0[] = {
  145090. 3, 1, 0, 2, 4,
  145091. };
  145092. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145093. _vq_quantthresh__8u1__p3_0,
  145094. _vq_quantmap__8u1__p3_0,
  145095. 5,
  145096. 5
  145097. };
  145098. static static_codebook _8u1__p3_0 = {
  145099. 4, 625,
  145100. _vq_lengthlist__8u1__p3_0,
  145101. 1, -533725184, 1611661312, 3, 0,
  145102. _vq_quantlist__8u1__p3_0,
  145103. NULL,
  145104. &_vq_auxt__8u1__p3_0,
  145105. NULL,
  145106. 0
  145107. };
  145108. static long _vq_quantlist__8u1__p4_0[] = {
  145109. 2,
  145110. 1,
  145111. 3,
  145112. 0,
  145113. 4,
  145114. };
  145115. static long _vq_lengthlist__8u1__p4_0[] = {
  145116. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145117. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145118. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145119. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145120. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145121. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145122. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145123. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145124. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145125. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145126. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145127. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145128. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145129. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145130. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145131. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145132. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145133. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145134. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145135. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145136. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145137. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145138. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145139. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145140. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145141. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145142. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145143. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145144. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145145. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145146. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145147. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145148. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145149. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145150. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145151. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145152. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145153. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145154. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145155. 10,
  145156. };
  145157. static float _vq_quantthresh__8u1__p4_0[] = {
  145158. -1.5, -0.5, 0.5, 1.5,
  145159. };
  145160. static long _vq_quantmap__8u1__p4_0[] = {
  145161. 3, 1, 0, 2, 4,
  145162. };
  145163. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145164. _vq_quantthresh__8u1__p4_0,
  145165. _vq_quantmap__8u1__p4_0,
  145166. 5,
  145167. 5
  145168. };
  145169. static static_codebook _8u1__p4_0 = {
  145170. 4, 625,
  145171. _vq_lengthlist__8u1__p4_0,
  145172. 1, -533725184, 1611661312, 3, 0,
  145173. _vq_quantlist__8u1__p4_0,
  145174. NULL,
  145175. &_vq_auxt__8u1__p4_0,
  145176. NULL,
  145177. 0
  145178. };
  145179. static long _vq_quantlist__8u1__p5_0[] = {
  145180. 4,
  145181. 3,
  145182. 5,
  145183. 2,
  145184. 6,
  145185. 1,
  145186. 7,
  145187. 0,
  145188. 8,
  145189. };
  145190. static long _vq_lengthlist__8u1__p5_0[] = {
  145191. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145192. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145193. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145194. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145195. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145196. 13,
  145197. };
  145198. static float _vq_quantthresh__8u1__p5_0[] = {
  145199. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145200. };
  145201. static long _vq_quantmap__8u1__p5_0[] = {
  145202. 7, 5, 3, 1, 0, 2, 4, 6,
  145203. 8,
  145204. };
  145205. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145206. _vq_quantthresh__8u1__p5_0,
  145207. _vq_quantmap__8u1__p5_0,
  145208. 9,
  145209. 9
  145210. };
  145211. static static_codebook _8u1__p5_0 = {
  145212. 2, 81,
  145213. _vq_lengthlist__8u1__p5_0,
  145214. 1, -531628032, 1611661312, 4, 0,
  145215. _vq_quantlist__8u1__p5_0,
  145216. NULL,
  145217. &_vq_auxt__8u1__p5_0,
  145218. NULL,
  145219. 0
  145220. };
  145221. static long _vq_quantlist__8u1__p6_0[] = {
  145222. 4,
  145223. 3,
  145224. 5,
  145225. 2,
  145226. 6,
  145227. 1,
  145228. 7,
  145229. 0,
  145230. 8,
  145231. };
  145232. static long _vq_lengthlist__8u1__p6_0[] = {
  145233. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145234. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145235. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145236. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145237. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145238. 10,
  145239. };
  145240. static float _vq_quantthresh__8u1__p6_0[] = {
  145241. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145242. };
  145243. static long _vq_quantmap__8u1__p6_0[] = {
  145244. 7, 5, 3, 1, 0, 2, 4, 6,
  145245. 8,
  145246. };
  145247. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145248. _vq_quantthresh__8u1__p6_0,
  145249. _vq_quantmap__8u1__p6_0,
  145250. 9,
  145251. 9
  145252. };
  145253. static static_codebook _8u1__p6_0 = {
  145254. 2, 81,
  145255. _vq_lengthlist__8u1__p6_0,
  145256. 1, -531628032, 1611661312, 4, 0,
  145257. _vq_quantlist__8u1__p6_0,
  145258. NULL,
  145259. &_vq_auxt__8u1__p6_0,
  145260. NULL,
  145261. 0
  145262. };
  145263. static long _vq_quantlist__8u1__p7_0[] = {
  145264. 1,
  145265. 0,
  145266. 2,
  145267. };
  145268. static long _vq_lengthlist__8u1__p7_0[] = {
  145269. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145270. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145271. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145272. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145273. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145274. 11,
  145275. };
  145276. static float _vq_quantthresh__8u1__p7_0[] = {
  145277. -5.5, 5.5,
  145278. };
  145279. static long _vq_quantmap__8u1__p7_0[] = {
  145280. 1, 0, 2,
  145281. };
  145282. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145283. _vq_quantthresh__8u1__p7_0,
  145284. _vq_quantmap__8u1__p7_0,
  145285. 3,
  145286. 3
  145287. };
  145288. static static_codebook _8u1__p7_0 = {
  145289. 4, 81,
  145290. _vq_lengthlist__8u1__p7_0,
  145291. 1, -529137664, 1618345984, 2, 0,
  145292. _vq_quantlist__8u1__p7_0,
  145293. NULL,
  145294. &_vq_auxt__8u1__p7_0,
  145295. NULL,
  145296. 0
  145297. };
  145298. static long _vq_quantlist__8u1__p7_1[] = {
  145299. 5,
  145300. 4,
  145301. 6,
  145302. 3,
  145303. 7,
  145304. 2,
  145305. 8,
  145306. 1,
  145307. 9,
  145308. 0,
  145309. 10,
  145310. };
  145311. static long _vq_lengthlist__8u1__p7_1[] = {
  145312. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145313. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145314. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145315. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145316. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145317. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145318. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145319. 9, 9, 9, 9, 9,10,10,10,10,
  145320. };
  145321. static float _vq_quantthresh__8u1__p7_1[] = {
  145322. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145323. 3.5, 4.5,
  145324. };
  145325. static long _vq_quantmap__8u1__p7_1[] = {
  145326. 9, 7, 5, 3, 1, 0, 2, 4,
  145327. 6, 8, 10,
  145328. };
  145329. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145330. _vq_quantthresh__8u1__p7_1,
  145331. _vq_quantmap__8u1__p7_1,
  145332. 11,
  145333. 11
  145334. };
  145335. static static_codebook _8u1__p7_1 = {
  145336. 2, 121,
  145337. _vq_lengthlist__8u1__p7_1,
  145338. 1, -531365888, 1611661312, 4, 0,
  145339. _vq_quantlist__8u1__p7_1,
  145340. NULL,
  145341. &_vq_auxt__8u1__p7_1,
  145342. NULL,
  145343. 0
  145344. };
  145345. static long _vq_quantlist__8u1__p8_0[] = {
  145346. 5,
  145347. 4,
  145348. 6,
  145349. 3,
  145350. 7,
  145351. 2,
  145352. 8,
  145353. 1,
  145354. 9,
  145355. 0,
  145356. 10,
  145357. };
  145358. static long _vq_lengthlist__8u1__p8_0[] = {
  145359. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145360. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145361. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145362. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145363. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145364. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145365. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145366. 12,13,13,14,14,15,15,15,15,
  145367. };
  145368. static float _vq_quantthresh__8u1__p8_0[] = {
  145369. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145370. 38.5, 49.5,
  145371. };
  145372. static long _vq_quantmap__8u1__p8_0[] = {
  145373. 9, 7, 5, 3, 1, 0, 2, 4,
  145374. 6, 8, 10,
  145375. };
  145376. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145377. _vq_quantthresh__8u1__p8_0,
  145378. _vq_quantmap__8u1__p8_0,
  145379. 11,
  145380. 11
  145381. };
  145382. static static_codebook _8u1__p8_0 = {
  145383. 2, 121,
  145384. _vq_lengthlist__8u1__p8_0,
  145385. 1, -524582912, 1618345984, 4, 0,
  145386. _vq_quantlist__8u1__p8_0,
  145387. NULL,
  145388. &_vq_auxt__8u1__p8_0,
  145389. NULL,
  145390. 0
  145391. };
  145392. static long _vq_quantlist__8u1__p8_1[] = {
  145393. 5,
  145394. 4,
  145395. 6,
  145396. 3,
  145397. 7,
  145398. 2,
  145399. 8,
  145400. 1,
  145401. 9,
  145402. 0,
  145403. 10,
  145404. };
  145405. static long _vq_lengthlist__8u1__p8_1[] = {
  145406. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145407. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145408. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145409. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145410. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145411. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145412. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145413. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145414. };
  145415. static float _vq_quantthresh__8u1__p8_1[] = {
  145416. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145417. 3.5, 4.5,
  145418. };
  145419. static long _vq_quantmap__8u1__p8_1[] = {
  145420. 9, 7, 5, 3, 1, 0, 2, 4,
  145421. 6, 8, 10,
  145422. };
  145423. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145424. _vq_quantthresh__8u1__p8_1,
  145425. _vq_quantmap__8u1__p8_1,
  145426. 11,
  145427. 11
  145428. };
  145429. static static_codebook _8u1__p8_1 = {
  145430. 2, 121,
  145431. _vq_lengthlist__8u1__p8_1,
  145432. 1, -531365888, 1611661312, 4, 0,
  145433. _vq_quantlist__8u1__p8_1,
  145434. NULL,
  145435. &_vq_auxt__8u1__p8_1,
  145436. NULL,
  145437. 0
  145438. };
  145439. static long _vq_quantlist__8u1__p9_0[] = {
  145440. 7,
  145441. 6,
  145442. 8,
  145443. 5,
  145444. 9,
  145445. 4,
  145446. 10,
  145447. 3,
  145448. 11,
  145449. 2,
  145450. 12,
  145451. 1,
  145452. 13,
  145453. 0,
  145454. 14,
  145455. };
  145456. static long _vq_lengthlist__8u1__p9_0[] = {
  145457. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145458. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145459. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145461. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145462. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145469. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145470. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145471. 10,
  145472. };
  145473. static float _vq_quantthresh__8u1__p9_0[] = {
  145474. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145475. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145476. };
  145477. static long _vq_quantmap__8u1__p9_0[] = {
  145478. 13, 11, 9, 7, 5, 3, 1, 0,
  145479. 2, 4, 6, 8, 10, 12, 14,
  145480. };
  145481. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145482. _vq_quantthresh__8u1__p9_0,
  145483. _vq_quantmap__8u1__p9_0,
  145484. 15,
  145485. 15
  145486. };
  145487. static static_codebook _8u1__p9_0 = {
  145488. 2, 225,
  145489. _vq_lengthlist__8u1__p9_0,
  145490. 1, -514071552, 1627381760, 4, 0,
  145491. _vq_quantlist__8u1__p9_0,
  145492. NULL,
  145493. &_vq_auxt__8u1__p9_0,
  145494. NULL,
  145495. 0
  145496. };
  145497. static long _vq_quantlist__8u1__p9_1[] = {
  145498. 7,
  145499. 6,
  145500. 8,
  145501. 5,
  145502. 9,
  145503. 4,
  145504. 10,
  145505. 3,
  145506. 11,
  145507. 2,
  145508. 12,
  145509. 1,
  145510. 13,
  145511. 0,
  145512. 14,
  145513. };
  145514. static long _vq_lengthlist__8u1__p9_1[] = {
  145515. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145516. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145517. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145518. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145519. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145520. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145521. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145522. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145523. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145524. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145525. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145526. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145527. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145528. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145529. 13,
  145530. };
  145531. static float _vq_quantthresh__8u1__p9_1[] = {
  145532. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145533. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145534. };
  145535. static long _vq_quantmap__8u1__p9_1[] = {
  145536. 13, 11, 9, 7, 5, 3, 1, 0,
  145537. 2, 4, 6, 8, 10, 12, 14,
  145538. };
  145539. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145540. _vq_quantthresh__8u1__p9_1,
  145541. _vq_quantmap__8u1__p9_1,
  145542. 15,
  145543. 15
  145544. };
  145545. static static_codebook _8u1__p9_1 = {
  145546. 2, 225,
  145547. _vq_lengthlist__8u1__p9_1,
  145548. 1, -522338304, 1620115456, 4, 0,
  145549. _vq_quantlist__8u1__p9_1,
  145550. NULL,
  145551. &_vq_auxt__8u1__p9_1,
  145552. NULL,
  145553. 0
  145554. };
  145555. static long _vq_quantlist__8u1__p9_2[] = {
  145556. 8,
  145557. 7,
  145558. 9,
  145559. 6,
  145560. 10,
  145561. 5,
  145562. 11,
  145563. 4,
  145564. 12,
  145565. 3,
  145566. 13,
  145567. 2,
  145568. 14,
  145569. 1,
  145570. 15,
  145571. 0,
  145572. 16,
  145573. };
  145574. static long _vq_lengthlist__8u1__p9_2[] = {
  145575. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145576. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145577. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145578. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145579. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145580. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145581. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145582. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145583. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145584. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145585. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145586. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145587. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145588. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145589. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145590. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145591. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145592. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145593. 10,
  145594. };
  145595. static float _vq_quantthresh__8u1__p9_2[] = {
  145596. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145597. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145598. };
  145599. static long _vq_quantmap__8u1__p9_2[] = {
  145600. 15, 13, 11, 9, 7, 5, 3, 1,
  145601. 0, 2, 4, 6, 8, 10, 12, 14,
  145602. 16,
  145603. };
  145604. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145605. _vq_quantthresh__8u1__p9_2,
  145606. _vq_quantmap__8u1__p9_2,
  145607. 17,
  145608. 17
  145609. };
  145610. static static_codebook _8u1__p9_2 = {
  145611. 2, 289,
  145612. _vq_lengthlist__8u1__p9_2,
  145613. 1, -529530880, 1611661312, 5, 0,
  145614. _vq_quantlist__8u1__p9_2,
  145615. NULL,
  145616. &_vq_auxt__8u1__p9_2,
  145617. NULL,
  145618. 0
  145619. };
  145620. static long _huff_lengthlist__8u1__single[] = {
  145621. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145622. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145623. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145624. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145625. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145626. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145627. 13, 8, 8,15,
  145628. };
  145629. static static_codebook _huff_book__8u1__single = {
  145630. 2, 100,
  145631. _huff_lengthlist__8u1__single,
  145632. 0, 0, 0, 0, 0,
  145633. NULL,
  145634. NULL,
  145635. NULL,
  145636. NULL,
  145637. 0
  145638. };
  145639. static long _huff_lengthlist__44u0__long[] = {
  145640. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145641. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145642. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145643. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145644. };
  145645. static static_codebook _huff_book__44u0__long = {
  145646. 2, 64,
  145647. _huff_lengthlist__44u0__long,
  145648. 0, 0, 0, 0, 0,
  145649. NULL,
  145650. NULL,
  145651. NULL,
  145652. NULL,
  145653. 0
  145654. };
  145655. static long _vq_quantlist__44u0__p1_0[] = {
  145656. 1,
  145657. 0,
  145658. 2,
  145659. };
  145660. static long _vq_lengthlist__44u0__p1_0[] = {
  145661. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145662. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145663. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145664. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145665. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145666. 13,
  145667. };
  145668. static float _vq_quantthresh__44u0__p1_0[] = {
  145669. -0.5, 0.5,
  145670. };
  145671. static long _vq_quantmap__44u0__p1_0[] = {
  145672. 1, 0, 2,
  145673. };
  145674. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145675. _vq_quantthresh__44u0__p1_0,
  145676. _vq_quantmap__44u0__p1_0,
  145677. 3,
  145678. 3
  145679. };
  145680. static static_codebook _44u0__p1_0 = {
  145681. 4, 81,
  145682. _vq_lengthlist__44u0__p1_0,
  145683. 1, -535822336, 1611661312, 2, 0,
  145684. _vq_quantlist__44u0__p1_0,
  145685. NULL,
  145686. &_vq_auxt__44u0__p1_0,
  145687. NULL,
  145688. 0
  145689. };
  145690. static long _vq_quantlist__44u0__p2_0[] = {
  145691. 1,
  145692. 0,
  145693. 2,
  145694. };
  145695. static long _vq_lengthlist__44u0__p2_0[] = {
  145696. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145697. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145698. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145699. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145700. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145701. 9,
  145702. };
  145703. static float _vq_quantthresh__44u0__p2_0[] = {
  145704. -0.5, 0.5,
  145705. };
  145706. static long _vq_quantmap__44u0__p2_0[] = {
  145707. 1, 0, 2,
  145708. };
  145709. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145710. _vq_quantthresh__44u0__p2_0,
  145711. _vq_quantmap__44u0__p2_0,
  145712. 3,
  145713. 3
  145714. };
  145715. static static_codebook _44u0__p2_0 = {
  145716. 4, 81,
  145717. _vq_lengthlist__44u0__p2_0,
  145718. 1, -535822336, 1611661312, 2, 0,
  145719. _vq_quantlist__44u0__p2_0,
  145720. NULL,
  145721. &_vq_auxt__44u0__p2_0,
  145722. NULL,
  145723. 0
  145724. };
  145725. static long _vq_quantlist__44u0__p3_0[] = {
  145726. 2,
  145727. 1,
  145728. 3,
  145729. 0,
  145730. 4,
  145731. };
  145732. static long _vq_lengthlist__44u0__p3_0[] = {
  145733. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145734. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145735. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145736. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145737. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145738. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145739. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145740. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145741. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145742. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145743. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145744. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145745. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145746. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145747. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145748. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145749. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145750. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145751. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145752. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145753. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145754. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145755. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145756. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145757. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145758. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145759. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145760. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145761. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145762. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145763. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145764. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145765. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145766. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145767. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145768. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145769. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145770. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145771. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145772. 19,
  145773. };
  145774. static float _vq_quantthresh__44u0__p3_0[] = {
  145775. -1.5, -0.5, 0.5, 1.5,
  145776. };
  145777. static long _vq_quantmap__44u0__p3_0[] = {
  145778. 3, 1, 0, 2, 4,
  145779. };
  145780. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145781. _vq_quantthresh__44u0__p3_0,
  145782. _vq_quantmap__44u0__p3_0,
  145783. 5,
  145784. 5
  145785. };
  145786. static static_codebook _44u0__p3_0 = {
  145787. 4, 625,
  145788. _vq_lengthlist__44u0__p3_0,
  145789. 1, -533725184, 1611661312, 3, 0,
  145790. _vq_quantlist__44u0__p3_0,
  145791. NULL,
  145792. &_vq_auxt__44u0__p3_0,
  145793. NULL,
  145794. 0
  145795. };
  145796. static long _vq_quantlist__44u0__p4_0[] = {
  145797. 2,
  145798. 1,
  145799. 3,
  145800. 0,
  145801. 4,
  145802. };
  145803. static long _vq_lengthlist__44u0__p4_0[] = {
  145804. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145805. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145806. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145807. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145808. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145809. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145810. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145811. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145812. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145813. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145814. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145815. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145816. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145817. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145818. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145819. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145820. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145821. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145822. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145823. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145824. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145825. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145826. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145827. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145828. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145829. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145830. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145831. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145832. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145833. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145834. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145835. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145836. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145837. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145838. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145839. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145840. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145841. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145842. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145843. 12,
  145844. };
  145845. static float _vq_quantthresh__44u0__p4_0[] = {
  145846. -1.5, -0.5, 0.5, 1.5,
  145847. };
  145848. static long _vq_quantmap__44u0__p4_0[] = {
  145849. 3, 1, 0, 2, 4,
  145850. };
  145851. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  145852. _vq_quantthresh__44u0__p4_0,
  145853. _vq_quantmap__44u0__p4_0,
  145854. 5,
  145855. 5
  145856. };
  145857. static static_codebook _44u0__p4_0 = {
  145858. 4, 625,
  145859. _vq_lengthlist__44u0__p4_0,
  145860. 1, -533725184, 1611661312, 3, 0,
  145861. _vq_quantlist__44u0__p4_0,
  145862. NULL,
  145863. &_vq_auxt__44u0__p4_0,
  145864. NULL,
  145865. 0
  145866. };
  145867. static long _vq_quantlist__44u0__p5_0[] = {
  145868. 4,
  145869. 3,
  145870. 5,
  145871. 2,
  145872. 6,
  145873. 1,
  145874. 7,
  145875. 0,
  145876. 8,
  145877. };
  145878. static long _vq_lengthlist__44u0__p5_0[] = {
  145879. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145880. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145881. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145882. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145883. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145884. 12,
  145885. };
  145886. static float _vq_quantthresh__44u0__p5_0[] = {
  145887. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145888. };
  145889. static long _vq_quantmap__44u0__p5_0[] = {
  145890. 7, 5, 3, 1, 0, 2, 4, 6,
  145891. 8,
  145892. };
  145893. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  145894. _vq_quantthresh__44u0__p5_0,
  145895. _vq_quantmap__44u0__p5_0,
  145896. 9,
  145897. 9
  145898. };
  145899. static static_codebook _44u0__p5_0 = {
  145900. 2, 81,
  145901. _vq_lengthlist__44u0__p5_0,
  145902. 1, -531628032, 1611661312, 4, 0,
  145903. _vq_quantlist__44u0__p5_0,
  145904. NULL,
  145905. &_vq_auxt__44u0__p5_0,
  145906. NULL,
  145907. 0
  145908. };
  145909. static long _vq_quantlist__44u0__p6_0[] = {
  145910. 6,
  145911. 5,
  145912. 7,
  145913. 4,
  145914. 8,
  145915. 3,
  145916. 9,
  145917. 2,
  145918. 10,
  145919. 1,
  145920. 11,
  145921. 0,
  145922. 12,
  145923. };
  145924. static long _vq_lengthlist__44u0__p6_0[] = {
  145925. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145926. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145927. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145928. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145929. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145930. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145931. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145932. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145933. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145934. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145935. 15,17,16,17,18,17,17,18, 0,
  145936. };
  145937. static float _vq_quantthresh__44u0__p6_0[] = {
  145938. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145939. 12.5, 17.5, 22.5, 27.5,
  145940. };
  145941. static long _vq_quantmap__44u0__p6_0[] = {
  145942. 11, 9, 7, 5, 3, 1, 0, 2,
  145943. 4, 6, 8, 10, 12,
  145944. };
  145945. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  145946. _vq_quantthresh__44u0__p6_0,
  145947. _vq_quantmap__44u0__p6_0,
  145948. 13,
  145949. 13
  145950. };
  145951. static static_codebook _44u0__p6_0 = {
  145952. 2, 169,
  145953. _vq_lengthlist__44u0__p6_0,
  145954. 1, -526516224, 1616117760, 4, 0,
  145955. _vq_quantlist__44u0__p6_0,
  145956. NULL,
  145957. &_vq_auxt__44u0__p6_0,
  145958. NULL,
  145959. 0
  145960. };
  145961. static long _vq_quantlist__44u0__p6_1[] = {
  145962. 2,
  145963. 1,
  145964. 3,
  145965. 0,
  145966. 4,
  145967. };
  145968. static long _vq_lengthlist__44u0__p6_1[] = {
  145969. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145970. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  145971. };
  145972. static float _vq_quantthresh__44u0__p6_1[] = {
  145973. -1.5, -0.5, 0.5, 1.5,
  145974. };
  145975. static long _vq_quantmap__44u0__p6_1[] = {
  145976. 3, 1, 0, 2, 4,
  145977. };
  145978. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  145979. _vq_quantthresh__44u0__p6_1,
  145980. _vq_quantmap__44u0__p6_1,
  145981. 5,
  145982. 5
  145983. };
  145984. static static_codebook _44u0__p6_1 = {
  145985. 2, 25,
  145986. _vq_lengthlist__44u0__p6_1,
  145987. 1, -533725184, 1611661312, 3, 0,
  145988. _vq_quantlist__44u0__p6_1,
  145989. NULL,
  145990. &_vq_auxt__44u0__p6_1,
  145991. NULL,
  145992. 0
  145993. };
  145994. static long _vq_quantlist__44u0__p7_0[] = {
  145995. 2,
  145996. 1,
  145997. 3,
  145998. 0,
  145999. 4,
  146000. };
  146001. static long _vq_lengthlist__44u0__p7_0[] = {
  146002. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146003. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146005. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146009. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146031. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146032. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146033. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146034. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146035. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146036. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146037. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146038. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146039. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146040. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146041. 10,
  146042. };
  146043. static float _vq_quantthresh__44u0__p7_0[] = {
  146044. -253.5, -84.5, 84.5, 253.5,
  146045. };
  146046. static long _vq_quantmap__44u0__p7_0[] = {
  146047. 3, 1, 0, 2, 4,
  146048. };
  146049. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146050. _vq_quantthresh__44u0__p7_0,
  146051. _vq_quantmap__44u0__p7_0,
  146052. 5,
  146053. 5
  146054. };
  146055. static static_codebook _44u0__p7_0 = {
  146056. 4, 625,
  146057. _vq_lengthlist__44u0__p7_0,
  146058. 1, -518709248, 1626677248, 3, 0,
  146059. _vq_quantlist__44u0__p7_0,
  146060. NULL,
  146061. &_vq_auxt__44u0__p7_0,
  146062. NULL,
  146063. 0
  146064. };
  146065. static long _vq_quantlist__44u0__p7_1[] = {
  146066. 6,
  146067. 5,
  146068. 7,
  146069. 4,
  146070. 8,
  146071. 3,
  146072. 9,
  146073. 2,
  146074. 10,
  146075. 1,
  146076. 11,
  146077. 0,
  146078. 12,
  146079. };
  146080. static long _vq_lengthlist__44u0__p7_1[] = {
  146081. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146082. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146083. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146084. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146085. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146086. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146087. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146088. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146089. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146090. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146091. 15,15,15,15,15,15,15,15,15,
  146092. };
  146093. static float _vq_quantthresh__44u0__p7_1[] = {
  146094. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146095. 32.5, 45.5, 58.5, 71.5,
  146096. };
  146097. static long _vq_quantmap__44u0__p7_1[] = {
  146098. 11, 9, 7, 5, 3, 1, 0, 2,
  146099. 4, 6, 8, 10, 12,
  146100. };
  146101. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146102. _vq_quantthresh__44u0__p7_1,
  146103. _vq_quantmap__44u0__p7_1,
  146104. 13,
  146105. 13
  146106. };
  146107. static static_codebook _44u0__p7_1 = {
  146108. 2, 169,
  146109. _vq_lengthlist__44u0__p7_1,
  146110. 1, -523010048, 1618608128, 4, 0,
  146111. _vq_quantlist__44u0__p7_1,
  146112. NULL,
  146113. &_vq_auxt__44u0__p7_1,
  146114. NULL,
  146115. 0
  146116. };
  146117. static long _vq_quantlist__44u0__p7_2[] = {
  146118. 6,
  146119. 5,
  146120. 7,
  146121. 4,
  146122. 8,
  146123. 3,
  146124. 9,
  146125. 2,
  146126. 10,
  146127. 1,
  146128. 11,
  146129. 0,
  146130. 12,
  146131. };
  146132. static long _vq_lengthlist__44u0__p7_2[] = {
  146133. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146134. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146135. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146136. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146137. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146138. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146139. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146140. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146141. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146142. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146143. 9, 9, 9,10, 9, 9,10,10, 9,
  146144. };
  146145. static float _vq_quantthresh__44u0__p7_2[] = {
  146146. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146147. 2.5, 3.5, 4.5, 5.5,
  146148. };
  146149. static long _vq_quantmap__44u0__p7_2[] = {
  146150. 11, 9, 7, 5, 3, 1, 0, 2,
  146151. 4, 6, 8, 10, 12,
  146152. };
  146153. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146154. _vq_quantthresh__44u0__p7_2,
  146155. _vq_quantmap__44u0__p7_2,
  146156. 13,
  146157. 13
  146158. };
  146159. static static_codebook _44u0__p7_2 = {
  146160. 2, 169,
  146161. _vq_lengthlist__44u0__p7_2,
  146162. 1, -531103744, 1611661312, 4, 0,
  146163. _vq_quantlist__44u0__p7_2,
  146164. NULL,
  146165. &_vq_auxt__44u0__p7_2,
  146166. NULL,
  146167. 0
  146168. };
  146169. static long _huff_lengthlist__44u0__short[] = {
  146170. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146171. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146172. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146173. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146174. };
  146175. static static_codebook _huff_book__44u0__short = {
  146176. 2, 64,
  146177. _huff_lengthlist__44u0__short,
  146178. 0, 0, 0, 0, 0,
  146179. NULL,
  146180. NULL,
  146181. NULL,
  146182. NULL,
  146183. 0
  146184. };
  146185. static long _huff_lengthlist__44u1__long[] = {
  146186. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146187. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146188. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146189. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146190. };
  146191. static static_codebook _huff_book__44u1__long = {
  146192. 2, 64,
  146193. _huff_lengthlist__44u1__long,
  146194. 0, 0, 0, 0, 0,
  146195. NULL,
  146196. NULL,
  146197. NULL,
  146198. NULL,
  146199. 0
  146200. };
  146201. static long _vq_quantlist__44u1__p1_0[] = {
  146202. 1,
  146203. 0,
  146204. 2,
  146205. };
  146206. static long _vq_lengthlist__44u1__p1_0[] = {
  146207. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146208. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146209. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146210. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146211. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146212. 13,
  146213. };
  146214. static float _vq_quantthresh__44u1__p1_0[] = {
  146215. -0.5, 0.5,
  146216. };
  146217. static long _vq_quantmap__44u1__p1_0[] = {
  146218. 1, 0, 2,
  146219. };
  146220. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146221. _vq_quantthresh__44u1__p1_0,
  146222. _vq_quantmap__44u1__p1_0,
  146223. 3,
  146224. 3
  146225. };
  146226. static static_codebook _44u1__p1_0 = {
  146227. 4, 81,
  146228. _vq_lengthlist__44u1__p1_0,
  146229. 1, -535822336, 1611661312, 2, 0,
  146230. _vq_quantlist__44u1__p1_0,
  146231. NULL,
  146232. &_vq_auxt__44u1__p1_0,
  146233. NULL,
  146234. 0
  146235. };
  146236. static long _vq_quantlist__44u1__p2_0[] = {
  146237. 1,
  146238. 0,
  146239. 2,
  146240. };
  146241. static long _vq_lengthlist__44u1__p2_0[] = {
  146242. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146243. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146244. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146245. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146246. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146247. 9,
  146248. };
  146249. static float _vq_quantthresh__44u1__p2_0[] = {
  146250. -0.5, 0.5,
  146251. };
  146252. static long _vq_quantmap__44u1__p2_0[] = {
  146253. 1, 0, 2,
  146254. };
  146255. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146256. _vq_quantthresh__44u1__p2_0,
  146257. _vq_quantmap__44u1__p2_0,
  146258. 3,
  146259. 3
  146260. };
  146261. static static_codebook _44u1__p2_0 = {
  146262. 4, 81,
  146263. _vq_lengthlist__44u1__p2_0,
  146264. 1, -535822336, 1611661312, 2, 0,
  146265. _vq_quantlist__44u1__p2_0,
  146266. NULL,
  146267. &_vq_auxt__44u1__p2_0,
  146268. NULL,
  146269. 0
  146270. };
  146271. static long _vq_quantlist__44u1__p3_0[] = {
  146272. 2,
  146273. 1,
  146274. 3,
  146275. 0,
  146276. 4,
  146277. };
  146278. static long _vq_lengthlist__44u1__p3_0[] = {
  146279. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146280. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146281. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146282. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146283. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146284. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146285. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146286. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146287. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146288. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146289. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146290. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146291. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146292. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146293. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146294. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146295. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146296. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146297. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146298. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146299. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146300. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146301. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146302. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146303. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146304. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146305. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146306. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146307. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146308. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146309. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146310. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146311. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146312. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146313. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146314. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146315. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146316. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146317. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146318. 19,
  146319. };
  146320. static float _vq_quantthresh__44u1__p3_0[] = {
  146321. -1.5, -0.5, 0.5, 1.5,
  146322. };
  146323. static long _vq_quantmap__44u1__p3_0[] = {
  146324. 3, 1, 0, 2, 4,
  146325. };
  146326. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146327. _vq_quantthresh__44u1__p3_0,
  146328. _vq_quantmap__44u1__p3_0,
  146329. 5,
  146330. 5
  146331. };
  146332. static static_codebook _44u1__p3_0 = {
  146333. 4, 625,
  146334. _vq_lengthlist__44u1__p3_0,
  146335. 1, -533725184, 1611661312, 3, 0,
  146336. _vq_quantlist__44u1__p3_0,
  146337. NULL,
  146338. &_vq_auxt__44u1__p3_0,
  146339. NULL,
  146340. 0
  146341. };
  146342. static long _vq_quantlist__44u1__p4_0[] = {
  146343. 2,
  146344. 1,
  146345. 3,
  146346. 0,
  146347. 4,
  146348. };
  146349. static long _vq_lengthlist__44u1__p4_0[] = {
  146350. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146351. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146352. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146353. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146354. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146355. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146356. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146357. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146358. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146359. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146360. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146361. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146362. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146363. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146364. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146365. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146366. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146367. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146368. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146369. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146370. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146371. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146372. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146373. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146374. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146375. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146376. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146377. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146378. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146379. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146380. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146381. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146382. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146383. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146384. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146385. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146386. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146387. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146388. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146389. 12,
  146390. };
  146391. static float _vq_quantthresh__44u1__p4_0[] = {
  146392. -1.5, -0.5, 0.5, 1.5,
  146393. };
  146394. static long _vq_quantmap__44u1__p4_0[] = {
  146395. 3, 1, 0, 2, 4,
  146396. };
  146397. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146398. _vq_quantthresh__44u1__p4_0,
  146399. _vq_quantmap__44u1__p4_0,
  146400. 5,
  146401. 5
  146402. };
  146403. static static_codebook _44u1__p4_0 = {
  146404. 4, 625,
  146405. _vq_lengthlist__44u1__p4_0,
  146406. 1, -533725184, 1611661312, 3, 0,
  146407. _vq_quantlist__44u1__p4_0,
  146408. NULL,
  146409. &_vq_auxt__44u1__p4_0,
  146410. NULL,
  146411. 0
  146412. };
  146413. static long _vq_quantlist__44u1__p5_0[] = {
  146414. 4,
  146415. 3,
  146416. 5,
  146417. 2,
  146418. 6,
  146419. 1,
  146420. 7,
  146421. 0,
  146422. 8,
  146423. };
  146424. static long _vq_lengthlist__44u1__p5_0[] = {
  146425. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146426. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146427. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146428. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146429. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146430. 12,
  146431. };
  146432. static float _vq_quantthresh__44u1__p5_0[] = {
  146433. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146434. };
  146435. static long _vq_quantmap__44u1__p5_0[] = {
  146436. 7, 5, 3, 1, 0, 2, 4, 6,
  146437. 8,
  146438. };
  146439. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146440. _vq_quantthresh__44u1__p5_0,
  146441. _vq_quantmap__44u1__p5_0,
  146442. 9,
  146443. 9
  146444. };
  146445. static static_codebook _44u1__p5_0 = {
  146446. 2, 81,
  146447. _vq_lengthlist__44u1__p5_0,
  146448. 1, -531628032, 1611661312, 4, 0,
  146449. _vq_quantlist__44u1__p5_0,
  146450. NULL,
  146451. &_vq_auxt__44u1__p5_0,
  146452. NULL,
  146453. 0
  146454. };
  146455. static long _vq_quantlist__44u1__p6_0[] = {
  146456. 6,
  146457. 5,
  146458. 7,
  146459. 4,
  146460. 8,
  146461. 3,
  146462. 9,
  146463. 2,
  146464. 10,
  146465. 1,
  146466. 11,
  146467. 0,
  146468. 12,
  146469. };
  146470. static long _vq_lengthlist__44u1__p6_0[] = {
  146471. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146472. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146473. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146474. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146475. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146476. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146477. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146478. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146479. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146480. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146481. 15,17,16,17,18,17,17,18, 0,
  146482. };
  146483. static float _vq_quantthresh__44u1__p6_0[] = {
  146484. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146485. 12.5, 17.5, 22.5, 27.5,
  146486. };
  146487. static long _vq_quantmap__44u1__p6_0[] = {
  146488. 11, 9, 7, 5, 3, 1, 0, 2,
  146489. 4, 6, 8, 10, 12,
  146490. };
  146491. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146492. _vq_quantthresh__44u1__p6_0,
  146493. _vq_quantmap__44u1__p6_0,
  146494. 13,
  146495. 13
  146496. };
  146497. static static_codebook _44u1__p6_0 = {
  146498. 2, 169,
  146499. _vq_lengthlist__44u1__p6_0,
  146500. 1, -526516224, 1616117760, 4, 0,
  146501. _vq_quantlist__44u1__p6_0,
  146502. NULL,
  146503. &_vq_auxt__44u1__p6_0,
  146504. NULL,
  146505. 0
  146506. };
  146507. static long _vq_quantlist__44u1__p6_1[] = {
  146508. 2,
  146509. 1,
  146510. 3,
  146511. 0,
  146512. 4,
  146513. };
  146514. static long _vq_lengthlist__44u1__p6_1[] = {
  146515. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146516. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146517. };
  146518. static float _vq_quantthresh__44u1__p6_1[] = {
  146519. -1.5, -0.5, 0.5, 1.5,
  146520. };
  146521. static long _vq_quantmap__44u1__p6_1[] = {
  146522. 3, 1, 0, 2, 4,
  146523. };
  146524. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146525. _vq_quantthresh__44u1__p6_1,
  146526. _vq_quantmap__44u1__p6_1,
  146527. 5,
  146528. 5
  146529. };
  146530. static static_codebook _44u1__p6_1 = {
  146531. 2, 25,
  146532. _vq_lengthlist__44u1__p6_1,
  146533. 1, -533725184, 1611661312, 3, 0,
  146534. _vq_quantlist__44u1__p6_1,
  146535. NULL,
  146536. &_vq_auxt__44u1__p6_1,
  146537. NULL,
  146538. 0
  146539. };
  146540. static long _vq_quantlist__44u1__p7_0[] = {
  146541. 3,
  146542. 2,
  146543. 4,
  146544. 1,
  146545. 5,
  146546. 0,
  146547. 6,
  146548. };
  146549. static long _vq_lengthlist__44u1__p7_0[] = {
  146550. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146551. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146552. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146553. 8,
  146554. };
  146555. static float _vq_quantthresh__44u1__p7_0[] = {
  146556. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146557. };
  146558. static long _vq_quantmap__44u1__p7_0[] = {
  146559. 5, 3, 1, 0, 2, 4, 6,
  146560. };
  146561. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146562. _vq_quantthresh__44u1__p7_0,
  146563. _vq_quantmap__44u1__p7_0,
  146564. 7,
  146565. 7
  146566. };
  146567. static static_codebook _44u1__p7_0 = {
  146568. 2, 49,
  146569. _vq_lengthlist__44u1__p7_0,
  146570. 1, -518017024, 1626677248, 3, 0,
  146571. _vq_quantlist__44u1__p7_0,
  146572. NULL,
  146573. &_vq_auxt__44u1__p7_0,
  146574. NULL,
  146575. 0
  146576. };
  146577. static long _vq_quantlist__44u1__p7_1[] = {
  146578. 6,
  146579. 5,
  146580. 7,
  146581. 4,
  146582. 8,
  146583. 3,
  146584. 9,
  146585. 2,
  146586. 10,
  146587. 1,
  146588. 11,
  146589. 0,
  146590. 12,
  146591. };
  146592. static long _vq_lengthlist__44u1__p7_1[] = {
  146593. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146594. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146595. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146596. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146597. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146598. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146599. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146600. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146601. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146602. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146603. 15,15,15,15,15,15,15,15,15,
  146604. };
  146605. static float _vq_quantthresh__44u1__p7_1[] = {
  146606. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146607. 32.5, 45.5, 58.5, 71.5,
  146608. };
  146609. static long _vq_quantmap__44u1__p7_1[] = {
  146610. 11, 9, 7, 5, 3, 1, 0, 2,
  146611. 4, 6, 8, 10, 12,
  146612. };
  146613. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146614. _vq_quantthresh__44u1__p7_1,
  146615. _vq_quantmap__44u1__p7_1,
  146616. 13,
  146617. 13
  146618. };
  146619. static static_codebook _44u1__p7_1 = {
  146620. 2, 169,
  146621. _vq_lengthlist__44u1__p7_1,
  146622. 1, -523010048, 1618608128, 4, 0,
  146623. _vq_quantlist__44u1__p7_1,
  146624. NULL,
  146625. &_vq_auxt__44u1__p7_1,
  146626. NULL,
  146627. 0
  146628. };
  146629. static long _vq_quantlist__44u1__p7_2[] = {
  146630. 6,
  146631. 5,
  146632. 7,
  146633. 4,
  146634. 8,
  146635. 3,
  146636. 9,
  146637. 2,
  146638. 10,
  146639. 1,
  146640. 11,
  146641. 0,
  146642. 12,
  146643. };
  146644. static long _vq_lengthlist__44u1__p7_2[] = {
  146645. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146646. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146647. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146648. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146649. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146650. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146651. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146652. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146653. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146654. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146655. 9, 9, 9,10, 9, 9,10,10, 9,
  146656. };
  146657. static float _vq_quantthresh__44u1__p7_2[] = {
  146658. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146659. 2.5, 3.5, 4.5, 5.5,
  146660. };
  146661. static long _vq_quantmap__44u1__p7_2[] = {
  146662. 11, 9, 7, 5, 3, 1, 0, 2,
  146663. 4, 6, 8, 10, 12,
  146664. };
  146665. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146666. _vq_quantthresh__44u1__p7_2,
  146667. _vq_quantmap__44u1__p7_2,
  146668. 13,
  146669. 13
  146670. };
  146671. static static_codebook _44u1__p7_2 = {
  146672. 2, 169,
  146673. _vq_lengthlist__44u1__p7_2,
  146674. 1, -531103744, 1611661312, 4, 0,
  146675. _vq_quantlist__44u1__p7_2,
  146676. NULL,
  146677. &_vq_auxt__44u1__p7_2,
  146678. NULL,
  146679. 0
  146680. };
  146681. static long _huff_lengthlist__44u1__short[] = {
  146682. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146683. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146684. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146685. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146686. };
  146687. static static_codebook _huff_book__44u1__short = {
  146688. 2, 64,
  146689. _huff_lengthlist__44u1__short,
  146690. 0, 0, 0, 0, 0,
  146691. NULL,
  146692. NULL,
  146693. NULL,
  146694. NULL,
  146695. 0
  146696. };
  146697. static long _huff_lengthlist__44u2__long[] = {
  146698. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146699. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146700. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146701. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146702. };
  146703. static static_codebook _huff_book__44u2__long = {
  146704. 2, 64,
  146705. _huff_lengthlist__44u2__long,
  146706. 0, 0, 0, 0, 0,
  146707. NULL,
  146708. NULL,
  146709. NULL,
  146710. NULL,
  146711. 0
  146712. };
  146713. static long _vq_quantlist__44u2__p1_0[] = {
  146714. 1,
  146715. 0,
  146716. 2,
  146717. };
  146718. static long _vq_lengthlist__44u2__p1_0[] = {
  146719. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146720. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146721. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146722. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146723. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146724. 13,
  146725. };
  146726. static float _vq_quantthresh__44u2__p1_0[] = {
  146727. -0.5, 0.5,
  146728. };
  146729. static long _vq_quantmap__44u2__p1_0[] = {
  146730. 1, 0, 2,
  146731. };
  146732. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146733. _vq_quantthresh__44u2__p1_0,
  146734. _vq_quantmap__44u2__p1_0,
  146735. 3,
  146736. 3
  146737. };
  146738. static static_codebook _44u2__p1_0 = {
  146739. 4, 81,
  146740. _vq_lengthlist__44u2__p1_0,
  146741. 1, -535822336, 1611661312, 2, 0,
  146742. _vq_quantlist__44u2__p1_0,
  146743. NULL,
  146744. &_vq_auxt__44u2__p1_0,
  146745. NULL,
  146746. 0
  146747. };
  146748. static long _vq_quantlist__44u2__p2_0[] = {
  146749. 1,
  146750. 0,
  146751. 2,
  146752. };
  146753. static long _vq_lengthlist__44u2__p2_0[] = {
  146754. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146755. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146756. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146757. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146758. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146759. 9,
  146760. };
  146761. static float _vq_quantthresh__44u2__p2_0[] = {
  146762. -0.5, 0.5,
  146763. };
  146764. static long _vq_quantmap__44u2__p2_0[] = {
  146765. 1, 0, 2,
  146766. };
  146767. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146768. _vq_quantthresh__44u2__p2_0,
  146769. _vq_quantmap__44u2__p2_0,
  146770. 3,
  146771. 3
  146772. };
  146773. static static_codebook _44u2__p2_0 = {
  146774. 4, 81,
  146775. _vq_lengthlist__44u2__p2_0,
  146776. 1, -535822336, 1611661312, 2, 0,
  146777. _vq_quantlist__44u2__p2_0,
  146778. NULL,
  146779. &_vq_auxt__44u2__p2_0,
  146780. NULL,
  146781. 0
  146782. };
  146783. static long _vq_quantlist__44u2__p3_0[] = {
  146784. 2,
  146785. 1,
  146786. 3,
  146787. 0,
  146788. 4,
  146789. };
  146790. static long _vq_lengthlist__44u2__p3_0[] = {
  146791. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146792. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146793. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146794. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146795. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146796. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146797. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146798. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146799. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146800. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146801. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146802. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146803. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146804. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146805. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146806. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146807. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146808. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146809. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146810. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146811. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146812. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146813. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  146814. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  146815. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  146816. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  146817. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  146818. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  146819. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  146820. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  146821. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  146822. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  146823. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  146824. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  146825. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  146826. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  146827. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  146828. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  146829. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  146830. 0,
  146831. };
  146832. static float _vq_quantthresh__44u2__p3_0[] = {
  146833. -1.5, -0.5, 0.5, 1.5,
  146834. };
  146835. static long _vq_quantmap__44u2__p3_0[] = {
  146836. 3, 1, 0, 2, 4,
  146837. };
  146838. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  146839. _vq_quantthresh__44u2__p3_0,
  146840. _vq_quantmap__44u2__p3_0,
  146841. 5,
  146842. 5
  146843. };
  146844. static static_codebook _44u2__p3_0 = {
  146845. 4, 625,
  146846. _vq_lengthlist__44u2__p3_0,
  146847. 1, -533725184, 1611661312, 3, 0,
  146848. _vq_quantlist__44u2__p3_0,
  146849. NULL,
  146850. &_vq_auxt__44u2__p3_0,
  146851. NULL,
  146852. 0
  146853. };
  146854. static long _vq_quantlist__44u2__p4_0[] = {
  146855. 2,
  146856. 1,
  146857. 3,
  146858. 0,
  146859. 4,
  146860. };
  146861. static long _vq_lengthlist__44u2__p4_0[] = {
  146862. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146863. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146864. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  146865. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  146866. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  146867. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146868. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  146869. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  146870. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146871. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146872. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  146873. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146874. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  146875. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  146876. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  146877. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  146878. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  146879. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146880. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146881. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  146882. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146883. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  146884. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  146885. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146886. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  146887. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  146888. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  146889. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  146890. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146891. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  146892. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  146893. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  146894. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  146895. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146896. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  146897. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  146898. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  146899. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  146900. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  146901. 13,
  146902. };
  146903. static float _vq_quantthresh__44u2__p4_0[] = {
  146904. -1.5, -0.5, 0.5, 1.5,
  146905. };
  146906. static long _vq_quantmap__44u2__p4_0[] = {
  146907. 3, 1, 0, 2, 4,
  146908. };
  146909. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  146910. _vq_quantthresh__44u2__p4_0,
  146911. _vq_quantmap__44u2__p4_0,
  146912. 5,
  146913. 5
  146914. };
  146915. static static_codebook _44u2__p4_0 = {
  146916. 4, 625,
  146917. _vq_lengthlist__44u2__p4_0,
  146918. 1, -533725184, 1611661312, 3, 0,
  146919. _vq_quantlist__44u2__p4_0,
  146920. NULL,
  146921. &_vq_auxt__44u2__p4_0,
  146922. NULL,
  146923. 0
  146924. };
  146925. static long _vq_quantlist__44u2__p5_0[] = {
  146926. 4,
  146927. 3,
  146928. 5,
  146929. 2,
  146930. 6,
  146931. 1,
  146932. 7,
  146933. 0,
  146934. 8,
  146935. };
  146936. static long _vq_lengthlist__44u2__p5_0[] = {
  146937. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  146938. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146939. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146940. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  146941. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  146942. 13,
  146943. };
  146944. static float _vq_quantthresh__44u2__p5_0[] = {
  146945. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146946. };
  146947. static long _vq_quantmap__44u2__p5_0[] = {
  146948. 7, 5, 3, 1, 0, 2, 4, 6,
  146949. 8,
  146950. };
  146951. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  146952. _vq_quantthresh__44u2__p5_0,
  146953. _vq_quantmap__44u2__p5_0,
  146954. 9,
  146955. 9
  146956. };
  146957. static static_codebook _44u2__p5_0 = {
  146958. 2, 81,
  146959. _vq_lengthlist__44u2__p5_0,
  146960. 1, -531628032, 1611661312, 4, 0,
  146961. _vq_quantlist__44u2__p5_0,
  146962. NULL,
  146963. &_vq_auxt__44u2__p5_0,
  146964. NULL,
  146965. 0
  146966. };
  146967. static long _vq_quantlist__44u2__p6_0[] = {
  146968. 6,
  146969. 5,
  146970. 7,
  146971. 4,
  146972. 8,
  146973. 3,
  146974. 9,
  146975. 2,
  146976. 10,
  146977. 1,
  146978. 11,
  146979. 0,
  146980. 12,
  146981. };
  146982. static long _vq_lengthlist__44u2__p6_0[] = {
  146983. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  146984. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  146985. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  146986. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  146987. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  146988. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  146989. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  146990. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  146991. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  146992. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  146993. 15,17,17,16,18,17,18, 0, 0,
  146994. };
  146995. static float _vq_quantthresh__44u2__p6_0[] = {
  146996. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146997. 12.5, 17.5, 22.5, 27.5,
  146998. };
  146999. static long _vq_quantmap__44u2__p6_0[] = {
  147000. 11, 9, 7, 5, 3, 1, 0, 2,
  147001. 4, 6, 8, 10, 12,
  147002. };
  147003. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147004. _vq_quantthresh__44u2__p6_0,
  147005. _vq_quantmap__44u2__p6_0,
  147006. 13,
  147007. 13
  147008. };
  147009. static static_codebook _44u2__p6_0 = {
  147010. 2, 169,
  147011. _vq_lengthlist__44u2__p6_0,
  147012. 1, -526516224, 1616117760, 4, 0,
  147013. _vq_quantlist__44u2__p6_0,
  147014. NULL,
  147015. &_vq_auxt__44u2__p6_0,
  147016. NULL,
  147017. 0
  147018. };
  147019. static long _vq_quantlist__44u2__p6_1[] = {
  147020. 2,
  147021. 1,
  147022. 3,
  147023. 0,
  147024. 4,
  147025. };
  147026. static long _vq_lengthlist__44u2__p6_1[] = {
  147027. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147028. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147029. };
  147030. static float _vq_quantthresh__44u2__p6_1[] = {
  147031. -1.5, -0.5, 0.5, 1.5,
  147032. };
  147033. static long _vq_quantmap__44u2__p6_1[] = {
  147034. 3, 1, 0, 2, 4,
  147035. };
  147036. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147037. _vq_quantthresh__44u2__p6_1,
  147038. _vq_quantmap__44u2__p6_1,
  147039. 5,
  147040. 5
  147041. };
  147042. static static_codebook _44u2__p6_1 = {
  147043. 2, 25,
  147044. _vq_lengthlist__44u2__p6_1,
  147045. 1, -533725184, 1611661312, 3, 0,
  147046. _vq_quantlist__44u2__p6_1,
  147047. NULL,
  147048. &_vq_auxt__44u2__p6_1,
  147049. NULL,
  147050. 0
  147051. };
  147052. static long _vq_quantlist__44u2__p7_0[] = {
  147053. 4,
  147054. 3,
  147055. 5,
  147056. 2,
  147057. 6,
  147058. 1,
  147059. 7,
  147060. 0,
  147061. 8,
  147062. };
  147063. static long _vq_lengthlist__44u2__p7_0[] = {
  147064. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147065. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147066. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147067. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147068. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147069. 11,
  147070. };
  147071. static float _vq_quantthresh__44u2__p7_0[] = {
  147072. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147073. };
  147074. static long _vq_quantmap__44u2__p7_0[] = {
  147075. 7, 5, 3, 1, 0, 2, 4, 6,
  147076. 8,
  147077. };
  147078. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147079. _vq_quantthresh__44u2__p7_0,
  147080. _vq_quantmap__44u2__p7_0,
  147081. 9,
  147082. 9
  147083. };
  147084. static static_codebook _44u2__p7_0 = {
  147085. 2, 81,
  147086. _vq_lengthlist__44u2__p7_0,
  147087. 1, -516612096, 1626677248, 4, 0,
  147088. _vq_quantlist__44u2__p7_0,
  147089. NULL,
  147090. &_vq_auxt__44u2__p7_0,
  147091. NULL,
  147092. 0
  147093. };
  147094. static long _vq_quantlist__44u2__p7_1[] = {
  147095. 6,
  147096. 5,
  147097. 7,
  147098. 4,
  147099. 8,
  147100. 3,
  147101. 9,
  147102. 2,
  147103. 10,
  147104. 1,
  147105. 11,
  147106. 0,
  147107. 12,
  147108. };
  147109. static long _vq_lengthlist__44u2__p7_1[] = {
  147110. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147111. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147112. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147113. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147114. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147115. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147116. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147117. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147118. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147119. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147120. 14,14,14,17,15,17,17,17,17,
  147121. };
  147122. static float _vq_quantthresh__44u2__p7_1[] = {
  147123. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147124. 32.5, 45.5, 58.5, 71.5,
  147125. };
  147126. static long _vq_quantmap__44u2__p7_1[] = {
  147127. 11, 9, 7, 5, 3, 1, 0, 2,
  147128. 4, 6, 8, 10, 12,
  147129. };
  147130. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147131. _vq_quantthresh__44u2__p7_1,
  147132. _vq_quantmap__44u2__p7_1,
  147133. 13,
  147134. 13
  147135. };
  147136. static static_codebook _44u2__p7_1 = {
  147137. 2, 169,
  147138. _vq_lengthlist__44u2__p7_1,
  147139. 1, -523010048, 1618608128, 4, 0,
  147140. _vq_quantlist__44u2__p7_1,
  147141. NULL,
  147142. &_vq_auxt__44u2__p7_1,
  147143. NULL,
  147144. 0
  147145. };
  147146. static long _vq_quantlist__44u2__p7_2[] = {
  147147. 6,
  147148. 5,
  147149. 7,
  147150. 4,
  147151. 8,
  147152. 3,
  147153. 9,
  147154. 2,
  147155. 10,
  147156. 1,
  147157. 11,
  147158. 0,
  147159. 12,
  147160. };
  147161. static long _vq_lengthlist__44u2__p7_2[] = {
  147162. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147163. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147164. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147165. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147166. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147167. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147168. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147169. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147170. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147171. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147172. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147173. };
  147174. static float _vq_quantthresh__44u2__p7_2[] = {
  147175. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147176. 2.5, 3.5, 4.5, 5.5,
  147177. };
  147178. static long _vq_quantmap__44u2__p7_2[] = {
  147179. 11, 9, 7, 5, 3, 1, 0, 2,
  147180. 4, 6, 8, 10, 12,
  147181. };
  147182. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147183. _vq_quantthresh__44u2__p7_2,
  147184. _vq_quantmap__44u2__p7_2,
  147185. 13,
  147186. 13
  147187. };
  147188. static static_codebook _44u2__p7_2 = {
  147189. 2, 169,
  147190. _vq_lengthlist__44u2__p7_2,
  147191. 1, -531103744, 1611661312, 4, 0,
  147192. _vq_quantlist__44u2__p7_2,
  147193. NULL,
  147194. &_vq_auxt__44u2__p7_2,
  147195. NULL,
  147196. 0
  147197. };
  147198. static long _huff_lengthlist__44u2__short[] = {
  147199. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147200. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147201. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147202. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147203. };
  147204. static static_codebook _huff_book__44u2__short = {
  147205. 2, 64,
  147206. _huff_lengthlist__44u2__short,
  147207. 0, 0, 0, 0, 0,
  147208. NULL,
  147209. NULL,
  147210. NULL,
  147211. NULL,
  147212. 0
  147213. };
  147214. static long _huff_lengthlist__44u3__long[] = {
  147215. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147216. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147217. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147218. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147219. };
  147220. static static_codebook _huff_book__44u3__long = {
  147221. 2, 64,
  147222. _huff_lengthlist__44u3__long,
  147223. 0, 0, 0, 0, 0,
  147224. NULL,
  147225. NULL,
  147226. NULL,
  147227. NULL,
  147228. 0
  147229. };
  147230. static long _vq_quantlist__44u3__p1_0[] = {
  147231. 1,
  147232. 0,
  147233. 2,
  147234. };
  147235. static long _vq_lengthlist__44u3__p1_0[] = {
  147236. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147237. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147238. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147239. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147240. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147241. 13,
  147242. };
  147243. static float _vq_quantthresh__44u3__p1_0[] = {
  147244. -0.5, 0.5,
  147245. };
  147246. static long _vq_quantmap__44u3__p1_0[] = {
  147247. 1, 0, 2,
  147248. };
  147249. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147250. _vq_quantthresh__44u3__p1_0,
  147251. _vq_quantmap__44u3__p1_0,
  147252. 3,
  147253. 3
  147254. };
  147255. static static_codebook _44u3__p1_0 = {
  147256. 4, 81,
  147257. _vq_lengthlist__44u3__p1_0,
  147258. 1, -535822336, 1611661312, 2, 0,
  147259. _vq_quantlist__44u3__p1_0,
  147260. NULL,
  147261. &_vq_auxt__44u3__p1_0,
  147262. NULL,
  147263. 0
  147264. };
  147265. static long _vq_quantlist__44u3__p2_0[] = {
  147266. 1,
  147267. 0,
  147268. 2,
  147269. };
  147270. static long _vq_lengthlist__44u3__p2_0[] = {
  147271. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147272. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147273. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147274. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147275. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147276. 9,
  147277. };
  147278. static float _vq_quantthresh__44u3__p2_0[] = {
  147279. -0.5, 0.5,
  147280. };
  147281. static long _vq_quantmap__44u3__p2_0[] = {
  147282. 1, 0, 2,
  147283. };
  147284. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147285. _vq_quantthresh__44u3__p2_0,
  147286. _vq_quantmap__44u3__p2_0,
  147287. 3,
  147288. 3
  147289. };
  147290. static static_codebook _44u3__p2_0 = {
  147291. 4, 81,
  147292. _vq_lengthlist__44u3__p2_0,
  147293. 1, -535822336, 1611661312, 2, 0,
  147294. _vq_quantlist__44u3__p2_0,
  147295. NULL,
  147296. &_vq_auxt__44u3__p2_0,
  147297. NULL,
  147298. 0
  147299. };
  147300. static long _vq_quantlist__44u3__p3_0[] = {
  147301. 2,
  147302. 1,
  147303. 3,
  147304. 0,
  147305. 4,
  147306. };
  147307. static long _vq_lengthlist__44u3__p3_0[] = {
  147308. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147309. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147310. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147311. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147312. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147313. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147314. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147315. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147316. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147317. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147318. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147319. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147320. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147321. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147322. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147323. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147324. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147325. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147326. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147327. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147328. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147329. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147330. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147331. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147332. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147333. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147334. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147335. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147336. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147337. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147338. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147339. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147340. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147341. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147342. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147343. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147344. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147345. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147346. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147347. 0,
  147348. };
  147349. static float _vq_quantthresh__44u3__p3_0[] = {
  147350. -1.5, -0.5, 0.5, 1.5,
  147351. };
  147352. static long _vq_quantmap__44u3__p3_0[] = {
  147353. 3, 1, 0, 2, 4,
  147354. };
  147355. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147356. _vq_quantthresh__44u3__p3_0,
  147357. _vq_quantmap__44u3__p3_0,
  147358. 5,
  147359. 5
  147360. };
  147361. static static_codebook _44u3__p3_0 = {
  147362. 4, 625,
  147363. _vq_lengthlist__44u3__p3_0,
  147364. 1, -533725184, 1611661312, 3, 0,
  147365. _vq_quantlist__44u3__p3_0,
  147366. NULL,
  147367. &_vq_auxt__44u3__p3_0,
  147368. NULL,
  147369. 0
  147370. };
  147371. static long _vq_quantlist__44u3__p4_0[] = {
  147372. 2,
  147373. 1,
  147374. 3,
  147375. 0,
  147376. 4,
  147377. };
  147378. static long _vq_lengthlist__44u3__p4_0[] = {
  147379. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147380. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147381. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147382. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147383. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147384. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147385. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147386. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147387. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147388. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147389. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147390. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147391. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147392. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147393. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147394. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147395. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147396. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147397. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147398. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147399. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147400. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147401. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147402. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147403. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147404. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147405. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147406. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147407. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147408. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147409. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147410. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147411. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147412. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147413. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147414. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147415. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147416. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147417. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147418. 13,
  147419. };
  147420. static float _vq_quantthresh__44u3__p4_0[] = {
  147421. -1.5, -0.5, 0.5, 1.5,
  147422. };
  147423. static long _vq_quantmap__44u3__p4_0[] = {
  147424. 3, 1, 0, 2, 4,
  147425. };
  147426. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147427. _vq_quantthresh__44u3__p4_0,
  147428. _vq_quantmap__44u3__p4_0,
  147429. 5,
  147430. 5
  147431. };
  147432. static static_codebook _44u3__p4_0 = {
  147433. 4, 625,
  147434. _vq_lengthlist__44u3__p4_0,
  147435. 1, -533725184, 1611661312, 3, 0,
  147436. _vq_quantlist__44u3__p4_0,
  147437. NULL,
  147438. &_vq_auxt__44u3__p4_0,
  147439. NULL,
  147440. 0
  147441. };
  147442. static long _vq_quantlist__44u3__p5_0[] = {
  147443. 4,
  147444. 3,
  147445. 5,
  147446. 2,
  147447. 6,
  147448. 1,
  147449. 7,
  147450. 0,
  147451. 8,
  147452. };
  147453. static long _vq_lengthlist__44u3__p5_0[] = {
  147454. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147455. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147456. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147457. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147458. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147459. 12,
  147460. };
  147461. static float _vq_quantthresh__44u3__p5_0[] = {
  147462. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147463. };
  147464. static long _vq_quantmap__44u3__p5_0[] = {
  147465. 7, 5, 3, 1, 0, 2, 4, 6,
  147466. 8,
  147467. };
  147468. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147469. _vq_quantthresh__44u3__p5_0,
  147470. _vq_quantmap__44u3__p5_0,
  147471. 9,
  147472. 9
  147473. };
  147474. static static_codebook _44u3__p5_0 = {
  147475. 2, 81,
  147476. _vq_lengthlist__44u3__p5_0,
  147477. 1, -531628032, 1611661312, 4, 0,
  147478. _vq_quantlist__44u3__p5_0,
  147479. NULL,
  147480. &_vq_auxt__44u3__p5_0,
  147481. NULL,
  147482. 0
  147483. };
  147484. static long _vq_quantlist__44u3__p6_0[] = {
  147485. 6,
  147486. 5,
  147487. 7,
  147488. 4,
  147489. 8,
  147490. 3,
  147491. 9,
  147492. 2,
  147493. 10,
  147494. 1,
  147495. 11,
  147496. 0,
  147497. 12,
  147498. };
  147499. static long _vq_lengthlist__44u3__p6_0[] = {
  147500. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147501. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147502. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147503. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147504. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147505. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147506. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147507. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147508. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147509. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147510. 15,16,16,16,17,18,16,20,18,
  147511. };
  147512. static float _vq_quantthresh__44u3__p6_0[] = {
  147513. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147514. 12.5, 17.5, 22.5, 27.5,
  147515. };
  147516. static long _vq_quantmap__44u3__p6_0[] = {
  147517. 11, 9, 7, 5, 3, 1, 0, 2,
  147518. 4, 6, 8, 10, 12,
  147519. };
  147520. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147521. _vq_quantthresh__44u3__p6_0,
  147522. _vq_quantmap__44u3__p6_0,
  147523. 13,
  147524. 13
  147525. };
  147526. static static_codebook _44u3__p6_0 = {
  147527. 2, 169,
  147528. _vq_lengthlist__44u3__p6_0,
  147529. 1, -526516224, 1616117760, 4, 0,
  147530. _vq_quantlist__44u3__p6_0,
  147531. NULL,
  147532. &_vq_auxt__44u3__p6_0,
  147533. NULL,
  147534. 0
  147535. };
  147536. static long _vq_quantlist__44u3__p6_1[] = {
  147537. 2,
  147538. 1,
  147539. 3,
  147540. 0,
  147541. 4,
  147542. };
  147543. static long _vq_lengthlist__44u3__p6_1[] = {
  147544. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147545. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147546. };
  147547. static float _vq_quantthresh__44u3__p6_1[] = {
  147548. -1.5, -0.5, 0.5, 1.5,
  147549. };
  147550. static long _vq_quantmap__44u3__p6_1[] = {
  147551. 3, 1, 0, 2, 4,
  147552. };
  147553. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147554. _vq_quantthresh__44u3__p6_1,
  147555. _vq_quantmap__44u3__p6_1,
  147556. 5,
  147557. 5
  147558. };
  147559. static static_codebook _44u3__p6_1 = {
  147560. 2, 25,
  147561. _vq_lengthlist__44u3__p6_1,
  147562. 1, -533725184, 1611661312, 3, 0,
  147563. _vq_quantlist__44u3__p6_1,
  147564. NULL,
  147565. &_vq_auxt__44u3__p6_1,
  147566. NULL,
  147567. 0
  147568. };
  147569. static long _vq_quantlist__44u3__p7_0[] = {
  147570. 4,
  147571. 3,
  147572. 5,
  147573. 2,
  147574. 6,
  147575. 1,
  147576. 7,
  147577. 0,
  147578. 8,
  147579. };
  147580. static long _vq_lengthlist__44u3__p7_0[] = {
  147581. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147582. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147583. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147584. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147585. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147586. 9,
  147587. };
  147588. static float _vq_quantthresh__44u3__p7_0[] = {
  147589. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147590. };
  147591. static long _vq_quantmap__44u3__p7_0[] = {
  147592. 7, 5, 3, 1, 0, 2, 4, 6,
  147593. 8,
  147594. };
  147595. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147596. _vq_quantthresh__44u3__p7_0,
  147597. _vq_quantmap__44u3__p7_0,
  147598. 9,
  147599. 9
  147600. };
  147601. static static_codebook _44u3__p7_0 = {
  147602. 2, 81,
  147603. _vq_lengthlist__44u3__p7_0,
  147604. 1, -515907584, 1627381760, 4, 0,
  147605. _vq_quantlist__44u3__p7_0,
  147606. NULL,
  147607. &_vq_auxt__44u3__p7_0,
  147608. NULL,
  147609. 0
  147610. };
  147611. static long _vq_quantlist__44u3__p7_1[] = {
  147612. 7,
  147613. 6,
  147614. 8,
  147615. 5,
  147616. 9,
  147617. 4,
  147618. 10,
  147619. 3,
  147620. 11,
  147621. 2,
  147622. 12,
  147623. 1,
  147624. 13,
  147625. 0,
  147626. 14,
  147627. };
  147628. static long _vq_lengthlist__44u3__p7_1[] = {
  147629. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147630. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147631. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147632. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147633. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147634. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147635. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147636. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147637. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147638. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147639. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147640. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147641. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147642. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147643. 17,
  147644. };
  147645. static float _vq_quantthresh__44u3__p7_1[] = {
  147646. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147647. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147648. };
  147649. static long _vq_quantmap__44u3__p7_1[] = {
  147650. 13, 11, 9, 7, 5, 3, 1, 0,
  147651. 2, 4, 6, 8, 10, 12, 14,
  147652. };
  147653. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147654. _vq_quantthresh__44u3__p7_1,
  147655. _vq_quantmap__44u3__p7_1,
  147656. 15,
  147657. 15
  147658. };
  147659. static static_codebook _44u3__p7_1 = {
  147660. 2, 225,
  147661. _vq_lengthlist__44u3__p7_1,
  147662. 1, -522338304, 1620115456, 4, 0,
  147663. _vq_quantlist__44u3__p7_1,
  147664. NULL,
  147665. &_vq_auxt__44u3__p7_1,
  147666. NULL,
  147667. 0
  147668. };
  147669. static long _vq_quantlist__44u3__p7_2[] = {
  147670. 8,
  147671. 7,
  147672. 9,
  147673. 6,
  147674. 10,
  147675. 5,
  147676. 11,
  147677. 4,
  147678. 12,
  147679. 3,
  147680. 13,
  147681. 2,
  147682. 14,
  147683. 1,
  147684. 15,
  147685. 0,
  147686. 16,
  147687. };
  147688. static long _vq_lengthlist__44u3__p7_2[] = {
  147689. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147690. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147691. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147692. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147693. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147694. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147695. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147696. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147697. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147698. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147699. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147700. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147701. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147702. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147703. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147704. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147705. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147706. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147707. 11,
  147708. };
  147709. static float _vq_quantthresh__44u3__p7_2[] = {
  147710. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147711. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147712. };
  147713. static long _vq_quantmap__44u3__p7_2[] = {
  147714. 15, 13, 11, 9, 7, 5, 3, 1,
  147715. 0, 2, 4, 6, 8, 10, 12, 14,
  147716. 16,
  147717. };
  147718. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147719. _vq_quantthresh__44u3__p7_2,
  147720. _vq_quantmap__44u3__p7_2,
  147721. 17,
  147722. 17
  147723. };
  147724. static static_codebook _44u3__p7_2 = {
  147725. 2, 289,
  147726. _vq_lengthlist__44u3__p7_2,
  147727. 1, -529530880, 1611661312, 5, 0,
  147728. _vq_quantlist__44u3__p7_2,
  147729. NULL,
  147730. &_vq_auxt__44u3__p7_2,
  147731. NULL,
  147732. 0
  147733. };
  147734. static long _huff_lengthlist__44u3__short[] = {
  147735. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147736. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147737. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147738. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147739. };
  147740. static static_codebook _huff_book__44u3__short = {
  147741. 2, 64,
  147742. _huff_lengthlist__44u3__short,
  147743. 0, 0, 0, 0, 0,
  147744. NULL,
  147745. NULL,
  147746. NULL,
  147747. NULL,
  147748. 0
  147749. };
  147750. static long _huff_lengthlist__44u4__long[] = {
  147751. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147752. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147753. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147754. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147755. };
  147756. static static_codebook _huff_book__44u4__long = {
  147757. 2, 64,
  147758. _huff_lengthlist__44u4__long,
  147759. 0, 0, 0, 0, 0,
  147760. NULL,
  147761. NULL,
  147762. NULL,
  147763. NULL,
  147764. 0
  147765. };
  147766. static long _vq_quantlist__44u4__p1_0[] = {
  147767. 1,
  147768. 0,
  147769. 2,
  147770. };
  147771. static long _vq_lengthlist__44u4__p1_0[] = {
  147772. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147773. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147774. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147775. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147776. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147777. 13,
  147778. };
  147779. static float _vq_quantthresh__44u4__p1_0[] = {
  147780. -0.5, 0.5,
  147781. };
  147782. static long _vq_quantmap__44u4__p1_0[] = {
  147783. 1, 0, 2,
  147784. };
  147785. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147786. _vq_quantthresh__44u4__p1_0,
  147787. _vq_quantmap__44u4__p1_0,
  147788. 3,
  147789. 3
  147790. };
  147791. static static_codebook _44u4__p1_0 = {
  147792. 4, 81,
  147793. _vq_lengthlist__44u4__p1_0,
  147794. 1, -535822336, 1611661312, 2, 0,
  147795. _vq_quantlist__44u4__p1_0,
  147796. NULL,
  147797. &_vq_auxt__44u4__p1_0,
  147798. NULL,
  147799. 0
  147800. };
  147801. static long _vq_quantlist__44u4__p2_0[] = {
  147802. 1,
  147803. 0,
  147804. 2,
  147805. };
  147806. static long _vq_lengthlist__44u4__p2_0[] = {
  147807. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147808. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147809. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147810. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147811. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147812. 9,
  147813. };
  147814. static float _vq_quantthresh__44u4__p2_0[] = {
  147815. -0.5, 0.5,
  147816. };
  147817. static long _vq_quantmap__44u4__p2_0[] = {
  147818. 1, 0, 2,
  147819. };
  147820. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  147821. _vq_quantthresh__44u4__p2_0,
  147822. _vq_quantmap__44u4__p2_0,
  147823. 3,
  147824. 3
  147825. };
  147826. static static_codebook _44u4__p2_0 = {
  147827. 4, 81,
  147828. _vq_lengthlist__44u4__p2_0,
  147829. 1, -535822336, 1611661312, 2, 0,
  147830. _vq_quantlist__44u4__p2_0,
  147831. NULL,
  147832. &_vq_auxt__44u4__p2_0,
  147833. NULL,
  147834. 0
  147835. };
  147836. static long _vq_quantlist__44u4__p3_0[] = {
  147837. 2,
  147838. 1,
  147839. 3,
  147840. 0,
  147841. 4,
  147842. };
  147843. static long _vq_lengthlist__44u4__p3_0[] = {
  147844. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147845. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147846. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  147847. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  147848. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147849. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  147850. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  147851. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  147852. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  147853. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  147854. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  147855. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  147856. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  147857. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  147858. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  147859. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  147860. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  147861. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  147862. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  147863. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  147864. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  147865. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  147866. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  147867. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  147868. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  147869. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  147870. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  147871. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  147872. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  147873. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  147874. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  147875. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  147876. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  147877. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  147878. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  147879. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  147880. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  147881. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  147882. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  147883. 0,
  147884. };
  147885. static float _vq_quantthresh__44u4__p3_0[] = {
  147886. -1.5, -0.5, 0.5, 1.5,
  147887. };
  147888. static long _vq_quantmap__44u4__p3_0[] = {
  147889. 3, 1, 0, 2, 4,
  147890. };
  147891. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  147892. _vq_quantthresh__44u4__p3_0,
  147893. _vq_quantmap__44u4__p3_0,
  147894. 5,
  147895. 5
  147896. };
  147897. static static_codebook _44u4__p3_0 = {
  147898. 4, 625,
  147899. _vq_lengthlist__44u4__p3_0,
  147900. 1, -533725184, 1611661312, 3, 0,
  147901. _vq_quantlist__44u4__p3_0,
  147902. NULL,
  147903. &_vq_auxt__44u4__p3_0,
  147904. NULL,
  147905. 0
  147906. };
  147907. static long _vq_quantlist__44u4__p4_0[] = {
  147908. 2,
  147909. 1,
  147910. 3,
  147911. 0,
  147912. 4,
  147913. };
  147914. static long _vq_lengthlist__44u4__p4_0[] = {
  147915. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147916. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147917. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147918. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147919. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147920. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  147921. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  147922. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  147923. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147924. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147925. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147926. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147927. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147928. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  147929. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147930. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147931. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147932. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147933. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147934. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147935. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147936. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147937. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147938. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147939. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147940. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  147941. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  147942. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  147943. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  147944. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  147945. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  147946. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147947. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147948. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  147949. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147950. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  147951. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147952. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  147953. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  147954. 13,
  147955. };
  147956. static float _vq_quantthresh__44u4__p4_0[] = {
  147957. -1.5, -0.5, 0.5, 1.5,
  147958. };
  147959. static long _vq_quantmap__44u4__p4_0[] = {
  147960. 3, 1, 0, 2, 4,
  147961. };
  147962. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  147963. _vq_quantthresh__44u4__p4_0,
  147964. _vq_quantmap__44u4__p4_0,
  147965. 5,
  147966. 5
  147967. };
  147968. static static_codebook _44u4__p4_0 = {
  147969. 4, 625,
  147970. _vq_lengthlist__44u4__p4_0,
  147971. 1, -533725184, 1611661312, 3, 0,
  147972. _vq_quantlist__44u4__p4_0,
  147973. NULL,
  147974. &_vq_auxt__44u4__p4_0,
  147975. NULL,
  147976. 0
  147977. };
  147978. static long _vq_quantlist__44u4__p5_0[] = {
  147979. 4,
  147980. 3,
  147981. 5,
  147982. 2,
  147983. 6,
  147984. 1,
  147985. 7,
  147986. 0,
  147987. 8,
  147988. };
  147989. static long _vq_lengthlist__44u4__p5_0[] = {
  147990. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147991. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147992. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  147993. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147994. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147995. 12,
  147996. };
  147997. static float _vq_quantthresh__44u4__p5_0[] = {
  147998. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147999. };
  148000. static long _vq_quantmap__44u4__p5_0[] = {
  148001. 7, 5, 3, 1, 0, 2, 4, 6,
  148002. 8,
  148003. };
  148004. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148005. _vq_quantthresh__44u4__p5_0,
  148006. _vq_quantmap__44u4__p5_0,
  148007. 9,
  148008. 9
  148009. };
  148010. static static_codebook _44u4__p5_0 = {
  148011. 2, 81,
  148012. _vq_lengthlist__44u4__p5_0,
  148013. 1, -531628032, 1611661312, 4, 0,
  148014. _vq_quantlist__44u4__p5_0,
  148015. NULL,
  148016. &_vq_auxt__44u4__p5_0,
  148017. NULL,
  148018. 0
  148019. };
  148020. static long _vq_quantlist__44u4__p6_0[] = {
  148021. 6,
  148022. 5,
  148023. 7,
  148024. 4,
  148025. 8,
  148026. 3,
  148027. 9,
  148028. 2,
  148029. 10,
  148030. 1,
  148031. 11,
  148032. 0,
  148033. 12,
  148034. };
  148035. static long _vq_lengthlist__44u4__p6_0[] = {
  148036. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148037. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148038. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148039. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148040. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148041. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148042. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148043. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148044. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148045. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148046. 16,16,16,17,17,18,17,20,21,
  148047. };
  148048. static float _vq_quantthresh__44u4__p6_0[] = {
  148049. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148050. 12.5, 17.5, 22.5, 27.5,
  148051. };
  148052. static long _vq_quantmap__44u4__p6_0[] = {
  148053. 11, 9, 7, 5, 3, 1, 0, 2,
  148054. 4, 6, 8, 10, 12,
  148055. };
  148056. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148057. _vq_quantthresh__44u4__p6_0,
  148058. _vq_quantmap__44u4__p6_0,
  148059. 13,
  148060. 13
  148061. };
  148062. static static_codebook _44u4__p6_0 = {
  148063. 2, 169,
  148064. _vq_lengthlist__44u4__p6_0,
  148065. 1, -526516224, 1616117760, 4, 0,
  148066. _vq_quantlist__44u4__p6_0,
  148067. NULL,
  148068. &_vq_auxt__44u4__p6_0,
  148069. NULL,
  148070. 0
  148071. };
  148072. static long _vq_quantlist__44u4__p6_1[] = {
  148073. 2,
  148074. 1,
  148075. 3,
  148076. 0,
  148077. 4,
  148078. };
  148079. static long _vq_lengthlist__44u4__p6_1[] = {
  148080. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148081. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148082. };
  148083. static float _vq_quantthresh__44u4__p6_1[] = {
  148084. -1.5, -0.5, 0.5, 1.5,
  148085. };
  148086. static long _vq_quantmap__44u4__p6_1[] = {
  148087. 3, 1, 0, 2, 4,
  148088. };
  148089. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148090. _vq_quantthresh__44u4__p6_1,
  148091. _vq_quantmap__44u4__p6_1,
  148092. 5,
  148093. 5
  148094. };
  148095. static static_codebook _44u4__p6_1 = {
  148096. 2, 25,
  148097. _vq_lengthlist__44u4__p6_1,
  148098. 1, -533725184, 1611661312, 3, 0,
  148099. _vq_quantlist__44u4__p6_1,
  148100. NULL,
  148101. &_vq_auxt__44u4__p6_1,
  148102. NULL,
  148103. 0
  148104. };
  148105. static long _vq_quantlist__44u4__p7_0[] = {
  148106. 6,
  148107. 5,
  148108. 7,
  148109. 4,
  148110. 8,
  148111. 3,
  148112. 9,
  148113. 2,
  148114. 10,
  148115. 1,
  148116. 11,
  148117. 0,
  148118. 12,
  148119. };
  148120. static long _vq_lengthlist__44u4__p7_0[] = {
  148121. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148122. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148123. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148124. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148125. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148126. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148127. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148128. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148129. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148130. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148131. 11,11,11,11,11,11,11,11,11,
  148132. };
  148133. static float _vq_quantthresh__44u4__p7_0[] = {
  148134. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148135. 637.5, 892.5, 1147.5, 1402.5,
  148136. };
  148137. static long _vq_quantmap__44u4__p7_0[] = {
  148138. 11, 9, 7, 5, 3, 1, 0, 2,
  148139. 4, 6, 8, 10, 12,
  148140. };
  148141. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148142. _vq_quantthresh__44u4__p7_0,
  148143. _vq_quantmap__44u4__p7_0,
  148144. 13,
  148145. 13
  148146. };
  148147. static static_codebook _44u4__p7_0 = {
  148148. 2, 169,
  148149. _vq_lengthlist__44u4__p7_0,
  148150. 1, -514332672, 1627381760, 4, 0,
  148151. _vq_quantlist__44u4__p7_0,
  148152. NULL,
  148153. &_vq_auxt__44u4__p7_0,
  148154. NULL,
  148155. 0
  148156. };
  148157. static long _vq_quantlist__44u4__p7_1[] = {
  148158. 7,
  148159. 6,
  148160. 8,
  148161. 5,
  148162. 9,
  148163. 4,
  148164. 10,
  148165. 3,
  148166. 11,
  148167. 2,
  148168. 12,
  148169. 1,
  148170. 13,
  148171. 0,
  148172. 14,
  148173. };
  148174. static long _vq_lengthlist__44u4__p7_1[] = {
  148175. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148176. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148177. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148178. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148179. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148180. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148181. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148182. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148183. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148184. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148185. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148186. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148187. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148188. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148189. 16,
  148190. };
  148191. static float _vq_quantthresh__44u4__p7_1[] = {
  148192. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148193. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148194. };
  148195. static long _vq_quantmap__44u4__p7_1[] = {
  148196. 13, 11, 9, 7, 5, 3, 1, 0,
  148197. 2, 4, 6, 8, 10, 12, 14,
  148198. };
  148199. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148200. _vq_quantthresh__44u4__p7_1,
  148201. _vq_quantmap__44u4__p7_1,
  148202. 15,
  148203. 15
  148204. };
  148205. static static_codebook _44u4__p7_1 = {
  148206. 2, 225,
  148207. _vq_lengthlist__44u4__p7_1,
  148208. 1, -522338304, 1620115456, 4, 0,
  148209. _vq_quantlist__44u4__p7_1,
  148210. NULL,
  148211. &_vq_auxt__44u4__p7_1,
  148212. NULL,
  148213. 0
  148214. };
  148215. static long _vq_quantlist__44u4__p7_2[] = {
  148216. 8,
  148217. 7,
  148218. 9,
  148219. 6,
  148220. 10,
  148221. 5,
  148222. 11,
  148223. 4,
  148224. 12,
  148225. 3,
  148226. 13,
  148227. 2,
  148228. 14,
  148229. 1,
  148230. 15,
  148231. 0,
  148232. 16,
  148233. };
  148234. static long _vq_lengthlist__44u4__p7_2[] = {
  148235. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148236. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148237. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148238. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148239. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148240. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148241. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148242. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148243. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148244. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148245. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148246. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148247. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148248. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148249. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148250. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148251. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148252. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148253. 10,
  148254. };
  148255. static float _vq_quantthresh__44u4__p7_2[] = {
  148256. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148257. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148258. };
  148259. static long _vq_quantmap__44u4__p7_2[] = {
  148260. 15, 13, 11, 9, 7, 5, 3, 1,
  148261. 0, 2, 4, 6, 8, 10, 12, 14,
  148262. 16,
  148263. };
  148264. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148265. _vq_quantthresh__44u4__p7_2,
  148266. _vq_quantmap__44u4__p7_2,
  148267. 17,
  148268. 17
  148269. };
  148270. static static_codebook _44u4__p7_2 = {
  148271. 2, 289,
  148272. _vq_lengthlist__44u4__p7_2,
  148273. 1, -529530880, 1611661312, 5, 0,
  148274. _vq_quantlist__44u4__p7_2,
  148275. NULL,
  148276. &_vq_auxt__44u4__p7_2,
  148277. NULL,
  148278. 0
  148279. };
  148280. static long _huff_lengthlist__44u4__short[] = {
  148281. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148282. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148283. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148284. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148285. };
  148286. static static_codebook _huff_book__44u4__short = {
  148287. 2, 64,
  148288. _huff_lengthlist__44u4__short,
  148289. 0, 0, 0, 0, 0,
  148290. NULL,
  148291. NULL,
  148292. NULL,
  148293. NULL,
  148294. 0
  148295. };
  148296. static long _huff_lengthlist__44u5__long[] = {
  148297. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148298. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148299. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148300. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148301. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148302. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148303. 14, 8, 7, 8,
  148304. };
  148305. static static_codebook _huff_book__44u5__long = {
  148306. 2, 100,
  148307. _huff_lengthlist__44u5__long,
  148308. 0, 0, 0, 0, 0,
  148309. NULL,
  148310. NULL,
  148311. NULL,
  148312. NULL,
  148313. 0
  148314. };
  148315. static long _vq_quantlist__44u5__p1_0[] = {
  148316. 1,
  148317. 0,
  148318. 2,
  148319. };
  148320. static long _vq_lengthlist__44u5__p1_0[] = {
  148321. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148322. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148323. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148324. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148325. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148326. 12,
  148327. };
  148328. static float _vq_quantthresh__44u5__p1_0[] = {
  148329. -0.5, 0.5,
  148330. };
  148331. static long _vq_quantmap__44u5__p1_0[] = {
  148332. 1, 0, 2,
  148333. };
  148334. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148335. _vq_quantthresh__44u5__p1_0,
  148336. _vq_quantmap__44u5__p1_0,
  148337. 3,
  148338. 3
  148339. };
  148340. static static_codebook _44u5__p1_0 = {
  148341. 4, 81,
  148342. _vq_lengthlist__44u5__p1_0,
  148343. 1, -535822336, 1611661312, 2, 0,
  148344. _vq_quantlist__44u5__p1_0,
  148345. NULL,
  148346. &_vq_auxt__44u5__p1_0,
  148347. NULL,
  148348. 0
  148349. };
  148350. static long _vq_quantlist__44u5__p2_0[] = {
  148351. 1,
  148352. 0,
  148353. 2,
  148354. };
  148355. static long _vq_lengthlist__44u5__p2_0[] = {
  148356. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148357. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148358. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148359. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148360. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148361. 9,
  148362. };
  148363. static float _vq_quantthresh__44u5__p2_0[] = {
  148364. -0.5, 0.5,
  148365. };
  148366. static long _vq_quantmap__44u5__p2_0[] = {
  148367. 1, 0, 2,
  148368. };
  148369. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148370. _vq_quantthresh__44u5__p2_0,
  148371. _vq_quantmap__44u5__p2_0,
  148372. 3,
  148373. 3
  148374. };
  148375. static static_codebook _44u5__p2_0 = {
  148376. 4, 81,
  148377. _vq_lengthlist__44u5__p2_0,
  148378. 1, -535822336, 1611661312, 2, 0,
  148379. _vq_quantlist__44u5__p2_0,
  148380. NULL,
  148381. &_vq_auxt__44u5__p2_0,
  148382. NULL,
  148383. 0
  148384. };
  148385. static long _vq_quantlist__44u5__p3_0[] = {
  148386. 2,
  148387. 1,
  148388. 3,
  148389. 0,
  148390. 4,
  148391. };
  148392. static long _vq_lengthlist__44u5__p3_0[] = {
  148393. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148394. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148395. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148396. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148397. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148398. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148399. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148400. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148401. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148402. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148403. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148404. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148405. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148406. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148407. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148408. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148409. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148410. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148411. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148412. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148413. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148414. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148415. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148416. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148417. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148418. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148419. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148420. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148421. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148422. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148423. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148424. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148425. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148426. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148427. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148428. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148429. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148430. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148431. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148432. 0,
  148433. };
  148434. static float _vq_quantthresh__44u5__p3_0[] = {
  148435. -1.5, -0.5, 0.5, 1.5,
  148436. };
  148437. static long _vq_quantmap__44u5__p3_0[] = {
  148438. 3, 1, 0, 2, 4,
  148439. };
  148440. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148441. _vq_quantthresh__44u5__p3_0,
  148442. _vq_quantmap__44u5__p3_0,
  148443. 5,
  148444. 5
  148445. };
  148446. static static_codebook _44u5__p3_0 = {
  148447. 4, 625,
  148448. _vq_lengthlist__44u5__p3_0,
  148449. 1, -533725184, 1611661312, 3, 0,
  148450. _vq_quantlist__44u5__p3_0,
  148451. NULL,
  148452. &_vq_auxt__44u5__p3_0,
  148453. NULL,
  148454. 0
  148455. };
  148456. static long _vq_quantlist__44u5__p4_0[] = {
  148457. 2,
  148458. 1,
  148459. 3,
  148460. 0,
  148461. 4,
  148462. };
  148463. static long _vq_lengthlist__44u5__p4_0[] = {
  148464. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148465. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148466. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148467. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148468. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148469. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148470. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148471. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148472. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148473. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148474. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148475. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148476. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148477. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148478. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148479. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148480. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148481. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148482. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148483. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148484. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148485. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148486. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148487. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148488. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148489. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148490. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148491. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148492. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148493. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148494. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148495. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148496. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148497. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148498. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148499. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148500. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148501. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148502. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148503. 12,
  148504. };
  148505. static float _vq_quantthresh__44u5__p4_0[] = {
  148506. -1.5, -0.5, 0.5, 1.5,
  148507. };
  148508. static long _vq_quantmap__44u5__p4_0[] = {
  148509. 3, 1, 0, 2, 4,
  148510. };
  148511. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148512. _vq_quantthresh__44u5__p4_0,
  148513. _vq_quantmap__44u5__p4_0,
  148514. 5,
  148515. 5
  148516. };
  148517. static static_codebook _44u5__p4_0 = {
  148518. 4, 625,
  148519. _vq_lengthlist__44u5__p4_0,
  148520. 1, -533725184, 1611661312, 3, 0,
  148521. _vq_quantlist__44u5__p4_0,
  148522. NULL,
  148523. &_vq_auxt__44u5__p4_0,
  148524. NULL,
  148525. 0
  148526. };
  148527. static long _vq_quantlist__44u5__p5_0[] = {
  148528. 4,
  148529. 3,
  148530. 5,
  148531. 2,
  148532. 6,
  148533. 1,
  148534. 7,
  148535. 0,
  148536. 8,
  148537. };
  148538. static long _vq_lengthlist__44u5__p5_0[] = {
  148539. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148540. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148541. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148542. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148543. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148544. 14,
  148545. };
  148546. static float _vq_quantthresh__44u5__p5_0[] = {
  148547. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148548. };
  148549. static long _vq_quantmap__44u5__p5_0[] = {
  148550. 7, 5, 3, 1, 0, 2, 4, 6,
  148551. 8,
  148552. };
  148553. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148554. _vq_quantthresh__44u5__p5_0,
  148555. _vq_quantmap__44u5__p5_0,
  148556. 9,
  148557. 9
  148558. };
  148559. static static_codebook _44u5__p5_0 = {
  148560. 2, 81,
  148561. _vq_lengthlist__44u5__p5_0,
  148562. 1, -531628032, 1611661312, 4, 0,
  148563. _vq_quantlist__44u5__p5_0,
  148564. NULL,
  148565. &_vq_auxt__44u5__p5_0,
  148566. NULL,
  148567. 0
  148568. };
  148569. static long _vq_quantlist__44u5__p6_0[] = {
  148570. 4,
  148571. 3,
  148572. 5,
  148573. 2,
  148574. 6,
  148575. 1,
  148576. 7,
  148577. 0,
  148578. 8,
  148579. };
  148580. static long _vq_lengthlist__44u5__p6_0[] = {
  148581. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148582. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148583. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148584. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148585. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148586. 11,
  148587. };
  148588. static float _vq_quantthresh__44u5__p6_0[] = {
  148589. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148590. };
  148591. static long _vq_quantmap__44u5__p6_0[] = {
  148592. 7, 5, 3, 1, 0, 2, 4, 6,
  148593. 8,
  148594. };
  148595. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148596. _vq_quantthresh__44u5__p6_0,
  148597. _vq_quantmap__44u5__p6_0,
  148598. 9,
  148599. 9
  148600. };
  148601. static static_codebook _44u5__p6_0 = {
  148602. 2, 81,
  148603. _vq_lengthlist__44u5__p6_0,
  148604. 1, -531628032, 1611661312, 4, 0,
  148605. _vq_quantlist__44u5__p6_0,
  148606. NULL,
  148607. &_vq_auxt__44u5__p6_0,
  148608. NULL,
  148609. 0
  148610. };
  148611. static long _vq_quantlist__44u5__p7_0[] = {
  148612. 1,
  148613. 0,
  148614. 2,
  148615. };
  148616. static long _vq_lengthlist__44u5__p7_0[] = {
  148617. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148618. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148619. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148620. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148621. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148622. 12,
  148623. };
  148624. static float _vq_quantthresh__44u5__p7_0[] = {
  148625. -5.5, 5.5,
  148626. };
  148627. static long _vq_quantmap__44u5__p7_0[] = {
  148628. 1, 0, 2,
  148629. };
  148630. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148631. _vq_quantthresh__44u5__p7_0,
  148632. _vq_quantmap__44u5__p7_0,
  148633. 3,
  148634. 3
  148635. };
  148636. static static_codebook _44u5__p7_0 = {
  148637. 4, 81,
  148638. _vq_lengthlist__44u5__p7_0,
  148639. 1, -529137664, 1618345984, 2, 0,
  148640. _vq_quantlist__44u5__p7_0,
  148641. NULL,
  148642. &_vq_auxt__44u5__p7_0,
  148643. NULL,
  148644. 0
  148645. };
  148646. static long _vq_quantlist__44u5__p7_1[] = {
  148647. 5,
  148648. 4,
  148649. 6,
  148650. 3,
  148651. 7,
  148652. 2,
  148653. 8,
  148654. 1,
  148655. 9,
  148656. 0,
  148657. 10,
  148658. };
  148659. static long _vq_lengthlist__44u5__p7_1[] = {
  148660. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148661. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148662. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148663. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148664. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148665. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148666. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148667. 9, 9, 9, 9, 9,10,10,10,10,
  148668. };
  148669. static float _vq_quantthresh__44u5__p7_1[] = {
  148670. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148671. 3.5, 4.5,
  148672. };
  148673. static long _vq_quantmap__44u5__p7_1[] = {
  148674. 9, 7, 5, 3, 1, 0, 2, 4,
  148675. 6, 8, 10,
  148676. };
  148677. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148678. _vq_quantthresh__44u5__p7_1,
  148679. _vq_quantmap__44u5__p7_1,
  148680. 11,
  148681. 11
  148682. };
  148683. static static_codebook _44u5__p7_1 = {
  148684. 2, 121,
  148685. _vq_lengthlist__44u5__p7_1,
  148686. 1, -531365888, 1611661312, 4, 0,
  148687. _vq_quantlist__44u5__p7_1,
  148688. NULL,
  148689. &_vq_auxt__44u5__p7_1,
  148690. NULL,
  148691. 0
  148692. };
  148693. static long _vq_quantlist__44u5__p8_0[] = {
  148694. 5,
  148695. 4,
  148696. 6,
  148697. 3,
  148698. 7,
  148699. 2,
  148700. 8,
  148701. 1,
  148702. 9,
  148703. 0,
  148704. 10,
  148705. };
  148706. static long _vq_lengthlist__44u5__p8_0[] = {
  148707. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148708. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148709. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148710. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148711. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148712. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148713. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148714. 12,13,13,14,14,14,14,15,15,
  148715. };
  148716. static float _vq_quantthresh__44u5__p8_0[] = {
  148717. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148718. 38.5, 49.5,
  148719. };
  148720. static long _vq_quantmap__44u5__p8_0[] = {
  148721. 9, 7, 5, 3, 1, 0, 2, 4,
  148722. 6, 8, 10,
  148723. };
  148724. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148725. _vq_quantthresh__44u5__p8_0,
  148726. _vq_quantmap__44u5__p8_0,
  148727. 11,
  148728. 11
  148729. };
  148730. static static_codebook _44u5__p8_0 = {
  148731. 2, 121,
  148732. _vq_lengthlist__44u5__p8_0,
  148733. 1, -524582912, 1618345984, 4, 0,
  148734. _vq_quantlist__44u5__p8_0,
  148735. NULL,
  148736. &_vq_auxt__44u5__p8_0,
  148737. NULL,
  148738. 0
  148739. };
  148740. static long _vq_quantlist__44u5__p8_1[] = {
  148741. 5,
  148742. 4,
  148743. 6,
  148744. 3,
  148745. 7,
  148746. 2,
  148747. 8,
  148748. 1,
  148749. 9,
  148750. 0,
  148751. 10,
  148752. };
  148753. static long _vq_lengthlist__44u5__p8_1[] = {
  148754. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148755. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148756. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148757. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148758. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148759. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148760. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148761. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148762. };
  148763. static float _vq_quantthresh__44u5__p8_1[] = {
  148764. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148765. 3.5, 4.5,
  148766. };
  148767. static long _vq_quantmap__44u5__p8_1[] = {
  148768. 9, 7, 5, 3, 1, 0, 2, 4,
  148769. 6, 8, 10,
  148770. };
  148771. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148772. _vq_quantthresh__44u5__p8_1,
  148773. _vq_quantmap__44u5__p8_1,
  148774. 11,
  148775. 11
  148776. };
  148777. static static_codebook _44u5__p8_1 = {
  148778. 2, 121,
  148779. _vq_lengthlist__44u5__p8_1,
  148780. 1, -531365888, 1611661312, 4, 0,
  148781. _vq_quantlist__44u5__p8_1,
  148782. NULL,
  148783. &_vq_auxt__44u5__p8_1,
  148784. NULL,
  148785. 0
  148786. };
  148787. static long _vq_quantlist__44u5__p9_0[] = {
  148788. 6,
  148789. 5,
  148790. 7,
  148791. 4,
  148792. 8,
  148793. 3,
  148794. 9,
  148795. 2,
  148796. 10,
  148797. 1,
  148798. 11,
  148799. 0,
  148800. 12,
  148801. };
  148802. static long _vq_lengthlist__44u5__p9_0[] = {
  148803. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148804. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148805. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148806. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  148807. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148808. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148809. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148810. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148811. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148812. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148813. 12,12,12,12,12,12,12,12,12,
  148814. };
  148815. static float _vq_quantthresh__44u5__p9_0[] = {
  148816. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148817. 637.5, 892.5, 1147.5, 1402.5,
  148818. };
  148819. static long _vq_quantmap__44u5__p9_0[] = {
  148820. 11, 9, 7, 5, 3, 1, 0, 2,
  148821. 4, 6, 8, 10, 12,
  148822. };
  148823. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  148824. _vq_quantthresh__44u5__p9_0,
  148825. _vq_quantmap__44u5__p9_0,
  148826. 13,
  148827. 13
  148828. };
  148829. static static_codebook _44u5__p9_0 = {
  148830. 2, 169,
  148831. _vq_lengthlist__44u5__p9_0,
  148832. 1, -514332672, 1627381760, 4, 0,
  148833. _vq_quantlist__44u5__p9_0,
  148834. NULL,
  148835. &_vq_auxt__44u5__p9_0,
  148836. NULL,
  148837. 0
  148838. };
  148839. static long _vq_quantlist__44u5__p9_1[] = {
  148840. 7,
  148841. 6,
  148842. 8,
  148843. 5,
  148844. 9,
  148845. 4,
  148846. 10,
  148847. 3,
  148848. 11,
  148849. 2,
  148850. 12,
  148851. 1,
  148852. 13,
  148853. 0,
  148854. 14,
  148855. };
  148856. static long _vq_lengthlist__44u5__p9_1[] = {
  148857. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  148858. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  148859. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  148860. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  148861. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  148862. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  148863. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  148864. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  148865. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  148866. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  148867. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  148868. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  148869. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  148870. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  148871. 14,
  148872. };
  148873. static float _vq_quantthresh__44u5__p9_1[] = {
  148874. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148875. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148876. };
  148877. static long _vq_quantmap__44u5__p9_1[] = {
  148878. 13, 11, 9, 7, 5, 3, 1, 0,
  148879. 2, 4, 6, 8, 10, 12, 14,
  148880. };
  148881. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  148882. _vq_quantthresh__44u5__p9_1,
  148883. _vq_quantmap__44u5__p9_1,
  148884. 15,
  148885. 15
  148886. };
  148887. static static_codebook _44u5__p9_1 = {
  148888. 2, 225,
  148889. _vq_lengthlist__44u5__p9_1,
  148890. 1, -522338304, 1620115456, 4, 0,
  148891. _vq_quantlist__44u5__p9_1,
  148892. NULL,
  148893. &_vq_auxt__44u5__p9_1,
  148894. NULL,
  148895. 0
  148896. };
  148897. static long _vq_quantlist__44u5__p9_2[] = {
  148898. 8,
  148899. 7,
  148900. 9,
  148901. 6,
  148902. 10,
  148903. 5,
  148904. 11,
  148905. 4,
  148906. 12,
  148907. 3,
  148908. 13,
  148909. 2,
  148910. 14,
  148911. 1,
  148912. 15,
  148913. 0,
  148914. 16,
  148915. };
  148916. static long _vq_lengthlist__44u5__p9_2[] = {
  148917. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148918. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148919. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148920. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148921. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148922. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148923. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148924. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148925. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148926. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  148927. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  148928. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148929. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148930. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148931. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148932. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148933. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148934. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  148935. 10,
  148936. };
  148937. static float _vq_quantthresh__44u5__p9_2[] = {
  148938. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148939. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148940. };
  148941. static long _vq_quantmap__44u5__p9_2[] = {
  148942. 15, 13, 11, 9, 7, 5, 3, 1,
  148943. 0, 2, 4, 6, 8, 10, 12, 14,
  148944. 16,
  148945. };
  148946. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  148947. _vq_quantthresh__44u5__p9_2,
  148948. _vq_quantmap__44u5__p9_2,
  148949. 17,
  148950. 17
  148951. };
  148952. static static_codebook _44u5__p9_2 = {
  148953. 2, 289,
  148954. _vq_lengthlist__44u5__p9_2,
  148955. 1, -529530880, 1611661312, 5, 0,
  148956. _vq_quantlist__44u5__p9_2,
  148957. NULL,
  148958. &_vq_auxt__44u5__p9_2,
  148959. NULL,
  148960. 0
  148961. };
  148962. static long _huff_lengthlist__44u5__short[] = {
  148963. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  148964. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  148965. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  148966. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  148967. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  148968. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  148969. 6, 8,15,17,
  148970. };
  148971. static static_codebook _huff_book__44u5__short = {
  148972. 2, 100,
  148973. _huff_lengthlist__44u5__short,
  148974. 0, 0, 0, 0, 0,
  148975. NULL,
  148976. NULL,
  148977. NULL,
  148978. NULL,
  148979. 0
  148980. };
  148981. static long _huff_lengthlist__44u6__long[] = {
  148982. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  148983. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  148984. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  148985. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  148986. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  148987. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  148988. 13, 8, 7, 7,
  148989. };
  148990. static static_codebook _huff_book__44u6__long = {
  148991. 2, 100,
  148992. _huff_lengthlist__44u6__long,
  148993. 0, 0, 0, 0, 0,
  148994. NULL,
  148995. NULL,
  148996. NULL,
  148997. NULL,
  148998. 0
  148999. };
  149000. static long _vq_quantlist__44u6__p1_0[] = {
  149001. 1,
  149002. 0,
  149003. 2,
  149004. };
  149005. static long _vq_lengthlist__44u6__p1_0[] = {
  149006. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149007. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149008. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149009. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149010. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149011. 12,
  149012. };
  149013. static float _vq_quantthresh__44u6__p1_0[] = {
  149014. -0.5, 0.5,
  149015. };
  149016. static long _vq_quantmap__44u6__p1_0[] = {
  149017. 1, 0, 2,
  149018. };
  149019. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149020. _vq_quantthresh__44u6__p1_0,
  149021. _vq_quantmap__44u6__p1_0,
  149022. 3,
  149023. 3
  149024. };
  149025. static static_codebook _44u6__p1_0 = {
  149026. 4, 81,
  149027. _vq_lengthlist__44u6__p1_0,
  149028. 1, -535822336, 1611661312, 2, 0,
  149029. _vq_quantlist__44u6__p1_0,
  149030. NULL,
  149031. &_vq_auxt__44u6__p1_0,
  149032. NULL,
  149033. 0
  149034. };
  149035. static long _vq_quantlist__44u6__p2_0[] = {
  149036. 1,
  149037. 0,
  149038. 2,
  149039. };
  149040. static long _vq_lengthlist__44u6__p2_0[] = {
  149041. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149042. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149043. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149044. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149045. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149046. 9,
  149047. };
  149048. static float _vq_quantthresh__44u6__p2_0[] = {
  149049. -0.5, 0.5,
  149050. };
  149051. static long _vq_quantmap__44u6__p2_0[] = {
  149052. 1, 0, 2,
  149053. };
  149054. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149055. _vq_quantthresh__44u6__p2_0,
  149056. _vq_quantmap__44u6__p2_0,
  149057. 3,
  149058. 3
  149059. };
  149060. static static_codebook _44u6__p2_0 = {
  149061. 4, 81,
  149062. _vq_lengthlist__44u6__p2_0,
  149063. 1, -535822336, 1611661312, 2, 0,
  149064. _vq_quantlist__44u6__p2_0,
  149065. NULL,
  149066. &_vq_auxt__44u6__p2_0,
  149067. NULL,
  149068. 0
  149069. };
  149070. static long _vq_quantlist__44u6__p3_0[] = {
  149071. 2,
  149072. 1,
  149073. 3,
  149074. 0,
  149075. 4,
  149076. };
  149077. static long _vq_lengthlist__44u6__p3_0[] = {
  149078. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149079. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149080. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149081. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149082. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149083. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149084. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149085. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149086. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149087. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149088. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149089. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149090. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149091. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149092. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149093. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149094. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149095. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149096. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149097. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149098. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149099. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149100. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149101. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149102. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149103. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149104. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149105. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149106. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149107. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149108. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149109. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149110. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149111. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149112. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149113. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149114. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149115. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149116. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149117. 19,
  149118. };
  149119. static float _vq_quantthresh__44u6__p3_0[] = {
  149120. -1.5, -0.5, 0.5, 1.5,
  149121. };
  149122. static long _vq_quantmap__44u6__p3_0[] = {
  149123. 3, 1, 0, 2, 4,
  149124. };
  149125. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149126. _vq_quantthresh__44u6__p3_0,
  149127. _vq_quantmap__44u6__p3_0,
  149128. 5,
  149129. 5
  149130. };
  149131. static static_codebook _44u6__p3_0 = {
  149132. 4, 625,
  149133. _vq_lengthlist__44u6__p3_0,
  149134. 1, -533725184, 1611661312, 3, 0,
  149135. _vq_quantlist__44u6__p3_0,
  149136. NULL,
  149137. &_vq_auxt__44u6__p3_0,
  149138. NULL,
  149139. 0
  149140. };
  149141. static long _vq_quantlist__44u6__p4_0[] = {
  149142. 2,
  149143. 1,
  149144. 3,
  149145. 0,
  149146. 4,
  149147. };
  149148. static long _vq_lengthlist__44u6__p4_0[] = {
  149149. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149150. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149151. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149152. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149153. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149154. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149155. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149156. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149157. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149158. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149159. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149160. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149161. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149162. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149163. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149164. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149165. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149166. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149167. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149168. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149169. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149170. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149171. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149172. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149173. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149174. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149175. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149176. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149177. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149178. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149179. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149180. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149181. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149182. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149183. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149184. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149185. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149186. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149187. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149188. 13,
  149189. };
  149190. static float _vq_quantthresh__44u6__p4_0[] = {
  149191. -1.5, -0.5, 0.5, 1.5,
  149192. };
  149193. static long _vq_quantmap__44u6__p4_0[] = {
  149194. 3, 1, 0, 2, 4,
  149195. };
  149196. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149197. _vq_quantthresh__44u6__p4_0,
  149198. _vq_quantmap__44u6__p4_0,
  149199. 5,
  149200. 5
  149201. };
  149202. static static_codebook _44u6__p4_0 = {
  149203. 4, 625,
  149204. _vq_lengthlist__44u6__p4_0,
  149205. 1, -533725184, 1611661312, 3, 0,
  149206. _vq_quantlist__44u6__p4_0,
  149207. NULL,
  149208. &_vq_auxt__44u6__p4_0,
  149209. NULL,
  149210. 0
  149211. };
  149212. static long _vq_quantlist__44u6__p5_0[] = {
  149213. 4,
  149214. 3,
  149215. 5,
  149216. 2,
  149217. 6,
  149218. 1,
  149219. 7,
  149220. 0,
  149221. 8,
  149222. };
  149223. static long _vq_lengthlist__44u6__p5_0[] = {
  149224. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149225. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149226. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149227. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149228. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149229. 14,
  149230. };
  149231. static float _vq_quantthresh__44u6__p5_0[] = {
  149232. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149233. };
  149234. static long _vq_quantmap__44u6__p5_0[] = {
  149235. 7, 5, 3, 1, 0, 2, 4, 6,
  149236. 8,
  149237. };
  149238. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149239. _vq_quantthresh__44u6__p5_0,
  149240. _vq_quantmap__44u6__p5_0,
  149241. 9,
  149242. 9
  149243. };
  149244. static static_codebook _44u6__p5_0 = {
  149245. 2, 81,
  149246. _vq_lengthlist__44u6__p5_0,
  149247. 1, -531628032, 1611661312, 4, 0,
  149248. _vq_quantlist__44u6__p5_0,
  149249. NULL,
  149250. &_vq_auxt__44u6__p5_0,
  149251. NULL,
  149252. 0
  149253. };
  149254. static long _vq_quantlist__44u6__p6_0[] = {
  149255. 4,
  149256. 3,
  149257. 5,
  149258. 2,
  149259. 6,
  149260. 1,
  149261. 7,
  149262. 0,
  149263. 8,
  149264. };
  149265. static long _vq_lengthlist__44u6__p6_0[] = {
  149266. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149267. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149268. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149269. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149270. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149271. 12,
  149272. };
  149273. static float _vq_quantthresh__44u6__p6_0[] = {
  149274. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149275. };
  149276. static long _vq_quantmap__44u6__p6_0[] = {
  149277. 7, 5, 3, 1, 0, 2, 4, 6,
  149278. 8,
  149279. };
  149280. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149281. _vq_quantthresh__44u6__p6_0,
  149282. _vq_quantmap__44u6__p6_0,
  149283. 9,
  149284. 9
  149285. };
  149286. static static_codebook _44u6__p6_0 = {
  149287. 2, 81,
  149288. _vq_lengthlist__44u6__p6_0,
  149289. 1, -531628032, 1611661312, 4, 0,
  149290. _vq_quantlist__44u6__p6_0,
  149291. NULL,
  149292. &_vq_auxt__44u6__p6_0,
  149293. NULL,
  149294. 0
  149295. };
  149296. static long _vq_quantlist__44u6__p7_0[] = {
  149297. 1,
  149298. 0,
  149299. 2,
  149300. };
  149301. static long _vq_lengthlist__44u6__p7_0[] = {
  149302. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149303. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149304. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149305. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149306. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149307. 10,
  149308. };
  149309. static float _vq_quantthresh__44u6__p7_0[] = {
  149310. -5.5, 5.5,
  149311. };
  149312. static long _vq_quantmap__44u6__p7_0[] = {
  149313. 1, 0, 2,
  149314. };
  149315. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149316. _vq_quantthresh__44u6__p7_0,
  149317. _vq_quantmap__44u6__p7_0,
  149318. 3,
  149319. 3
  149320. };
  149321. static static_codebook _44u6__p7_0 = {
  149322. 4, 81,
  149323. _vq_lengthlist__44u6__p7_0,
  149324. 1, -529137664, 1618345984, 2, 0,
  149325. _vq_quantlist__44u6__p7_0,
  149326. NULL,
  149327. &_vq_auxt__44u6__p7_0,
  149328. NULL,
  149329. 0
  149330. };
  149331. static long _vq_quantlist__44u6__p7_1[] = {
  149332. 5,
  149333. 4,
  149334. 6,
  149335. 3,
  149336. 7,
  149337. 2,
  149338. 8,
  149339. 1,
  149340. 9,
  149341. 0,
  149342. 10,
  149343. };
  149344. static long _vq_lengthlist__44u6__p7_1[] = {
  149345. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149346. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149347. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149348. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149349. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149350. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149351. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149352. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149353. };
  149354. static float _vq_quantthresh__44u6__p7_1[] = {
  149355. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149356. 3.5, 4.5,
  149357. };
  149358. static long _vq_quantmap__44u6__p7_1[] = {
  149359. 9, 7, 5, 3, 1, 0, 2, 4,
  149360. 6, 8, 10,
  149361. };
  149362. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149363. _vq_quantthresh__44u6__p7_1,
  149364. _vq_quantmap__44u6__p7_1,
  149365. 11,
  149366. 11
  149367. };
  149368. static static_codebook _44u6__p7_1 = {
  149369. 2, 121,
  149370. _vq_lengthlist__44u6__p7_1,
  149371. 1, -531365888, 1611661312, 4, 0,
  149372. _vq_quantlist__44u6__p7_1,
  149373. NULL,
  149374. &_vq_auxt__44u6__p7_1,
  149375. NULL,
  149376. 0
  149377. };
  149378. static long _vq_quantlist__44u6__p8_0[] = {
  149379. 5,
  149380. 4,
  149381. 6,
  149382. 3,
  149383. 7,
  149384. 2,
  149385. 8,
  149386. 1,
  149387. 9,
  149388. 0,
  149389. 10,
  149390. };
  149391. static long _vq_lengthlist__44u6__p8_0[] = {
  149392. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149393. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149394. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149395. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149396. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149397. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149398. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149399. 12,13,13,14,14,14,15,15,15,
  149400. };
  149401. static float _vq_quantthresh__44u6__p8_0[] = {
  149402. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149403. 38.5, 49.5,
  149404. };
  149405. static long _vq_quantmap__44u6__p8_0[] = {
  149406. 9, 7, 5, 3, 1, 0, 2, 4,
  149407. 6, 8, 10,
  149408. };
  149409. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149410. _vq_quantthresh__44u6__p8_0,
  149411. _vq_quantmap__44u6__p8_0,
  149412. 11,
  149413. 11
  149414. };
  149415. static static_codebook _44u6__p8_0 = {
  149416. 2, 121,
  149417. _vq_lengthlist__44u6__p8_0,
  149418. 1, -524582912, 1618345984, 4, 0,
  149419. _vq_quantlist__44u6__p8_0,
  149420. NULL,
  149421. &_vq_auxt__44u6__p8_0,
  149422. NULL,
  149423. 0
  149424. };
  149425. static long _vq_quantlist__44u6__p8_1[] = {
  149426. 5,
  149427. 4,
  149428. 6,
  149429. 3,
  149430. 7,
  149431. 2,
  149432. 8,
  149433. 1,
  149434. 9,
  149435. 0,
  149436. 10,
  149437. };
  149438. static long _vq_lengthlist__44u6__p8_1[] = {
  149439. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149440. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149441. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149442. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149443. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149444. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149445. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149446. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149447. };
  149448. static float _vq_quantthresh__44u6__p8_1[] = {
  149449. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149450. 3.5, 4.5,
  149451. };
  149452. static long _vq_quantmap__44u6__p8_1[] = {
  149453. 9, 7, 5, 3, 1, 0, 2, 4,
  149454. 6, 8, 10,
  149455. };
  149456. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149457. _vq_quantthresh__44u6__p8_1,
  149458. _vq_quantmap__44u6__p8_1,
  149459. 11,
  149460. 11
  149461. };
  149462. static static_codebook _44u6__p8_1 = {
  149463. 2, 121,
  149464. _vq_lengthlist__44u6__p8_1,
  149465. 1, -531365888, 1611661312, 4, 0,
  149466. _vq_quantlist__44u6__p8_1,
  149467. NULL,
  149468. &_vq_auxt__44u6__p8_1,
  149469. NULL,
  149470. 0
  149471. };
  149472. static long _vq_quantlist__44u6__p9_0[] = {
  149473. 7,
  149474. 6,
  149475. 8,
  149476. 5,
  149477. 9,
  149478. 4,
  149479. 10,
  149480. 3,
  149481. 11,
  149482. 2,
  149483. 12,
  149484. 1,
  149485. 13,
  149486. 0,
  149487. 14,
  149488. };
  149489. static long _vq_lengthlist__44u6__p9_0[] = {
  149490. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149491. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149492. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149493. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149494. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149495. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149496. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149497. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149498. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149499. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149500. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149501. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149502. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149503. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149504. 14,
  149505. };
  149506. static float _vq_quantthresh__44u6__p9_0[] = {
  149507. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149508. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149509. };
  149510. static long _vq_quantmap__44u6__p9_0[] = {
  149511. 13, 11, 9, 7, 5, 3, 1, 0,
  149512. 2, 4, 6, 8, 10, 12, 14,
  149513. };
  149514. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149515. _vq_quantthresh__44u6__p9_0,
  149516. _vq_quantmap__44u6__p9_0,
  149517. 15,
  149518. 15
  149519. };
  149520. static static_codebook _44u6__p9_0 = {
  149521. 2, 225,
  149522. _vq_lengthlist__44u6__p9_0,
  149523. 1, -514071552, 1627381760, 4, 0,
  149524. _vq_quantlist__44u6__p9_0,
  149525. NULL,
  149526. &_vq_auxt__44u6__p9_0,
  149527. NULL,
  149528. 0
  149529. };
  149530. static long _vq_quantlist__44u6__p9_1[] = {
  149531. 7,
  149532. 6,
  149533. 8,
  149534. 5,
  149535. 9,
  149536. 4,
  149537. 10,
  149538. 3,
  149539. 11,
  149540. 2,
  149541. 12,
  149542. 1,
  149543. 13,
  149544. 0,
  149545. 14,
  149546. };
  149547. static long _vq_lengthlist__44u6__p9_1[] = {
  149548. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149549. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149550. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149551. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149552. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149553. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149554. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149555. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149556. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149557. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149558. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149559. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149560. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149561. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149562. 13,
  149563. };
  149564. static float _vq_quantthresh__44u6__p9_1[] = {
  149565. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149566. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149567. };
  149568. static long _vq_quantmap__44u6__p9_1[] = {
  149569. 13, 11, 9, 7, 5, 3, 1, 0,
  149570. 2, 4, 6, 8, 10, 12, 14,
  149571. };
  149572. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149573. _vq_quantthresh__44u6__p9_1,
  149574. _vq_quantmap__44u6__p9_1,
  149575. 15,
  149576. 15
  149577. };
  149578. static static_codebook _44u6__p9_1 = {
  149579. 2, 225,
  149580. _vq_lengthlist__44u6__p9_1,
  149581. 1, -522338304, 1620115456, 4, 0,
  149582. _vq_quantlist__44u6__p9_1,
  149583. NULL,
  149584. &_vq_auxt__44u6__p9_1,
  149585. NULL,
  149586. 0
  149587. };
  149588. static long _vq_quantlist__44u6__p9_2[] = {
  149589. 8,
  149590. 7,
  149591. 9,
  149592. 6,
  149593. 10,
  149594. 5,
  149595. 11,
  149596. 4,
  149597. 12,
  149598. 3,
  149599. 13,
  149600. 2,
  149601. 14,
  149602. 1,
  149603. 15,
  149604. 0,
  149605. 16,
  149606. };
  149607. static long _vq_lengthlist__44u6__p9_2[] = {
  149608. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149609. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149610. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149611. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149612. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149613. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149614. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149615. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149616. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149617. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149618. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149619. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149620. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149621. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149622. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149623. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149624. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149625. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149626. 10,
  149627. };
  149628. static float _vq_quantthresh__44u6__p9_2[] = {
  149629. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149630. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149631. };
  149632. static long _vq_quantmap__44u6__p9_2[] = {
  149633. 15, 13, 11, 9, 7, 5, 3, 1,
  149634. 0, 2, 4, 6, 8, 10, 12, 14,
  149635. 16,
  149636. };
  149637. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149638. _vq_quantthresh__44u6__p9_2,
  149639. _vq_quantmap__44u6__p9_2,
  149640. 17,
  149641. 17
  149642. };
  149643. static static_codebook _44u6__p9_2 = {
  149644. 2, 289,
  149645. _vq_lengthlist__44u6__p9_2,
  149646. 1, -529530880, 1611661312, 5, 0,
  149647. _vq_quantlist__44u6__p9_2,
  149648. NULL,
  149649. &_vq_auxt__44u6__p9_2,
  149650. NULL,
  149651. 0
  149652. };
  149653. static long _huff_lengthlist__44u6__short[] = {
  149654. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149655. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149656. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149657. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149658. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149659. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149660. 7, 6, 9,16,
  149661. };
  149662. static static_codebook _huff_book__44u6__short = {
  149663. 2, 100,
  149664. _huff_lengthlist__44u6__short,
  149665. 0, 0, 0, 0, 0,
  149666. NULL,
  149667. NULL,
  149668. NULL,
  149669. NULL,
  149670. 0
  149671. };
  149672. static long _huff_lengthlist__44u7__long[] = {
  149673. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149674. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149675. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149676. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149677. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149678. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149679. 12, 8, 6, 7,
  149680. };
  149681. static static_codebook _huff_book__44u7__long = {
  149682. 2, 100,
  149683. _huff_lengthlist__44u7__long,
  149684. 0, 0, 0, 0, 0,
  149685. NULL,
  149686. NULL,
  149687. NULL,
  149688. NULL,
  149689. 0
  149690. };
  149691. static long _vq_quantlist__44u7__p1_0[] = {
  149692. 1,
  149693. 0,
  149694. 2,
  149695. };
  149696. static long _vq_lengthlist__44u7__p1_0[] = {
  149697. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149698. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149699. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149700. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149701. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149702. 12,
  149703. };
  149704. static float _vq_quantthresh__44u7__p1_0[] = {
  149705. -0.5, 0.5,
  149706. };
  149707. static long _vq_quantmap__44u7__p1_0[] = {
  149708. 1, 0, 2,
  149709. };
  149710. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149711. _vq_quantthresh__44u7__p1_0,
  149712. _vq_quantmap__44u7__p1_0,
  149713. 3,
  149714. 3
  149715. };
  149716. static static_codebook _44u7__p1_0 = {
  149717. 4, 81,
  149718. _vq_lengthlist__44u7__p1_0,
  149719. 1, -535822336, 1611661312, 2, 0,
  149720. _vq_quantlist__44u7__p1_0,
  149721. NULL,
  149722. &_vq_auxt__44u7__p1_0,
  149723. NULL,
  149724. 0
  149725. };
  149726. static long _vq_quantlist__44u7__p2_0[] = {
  149727. 1,
  149728. 0,
  149729. 2,
  149730. };
  149731. static long _vq_lengthlist__44u7__p2_0[] = {
  149732. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149733. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149734. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149735. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149736. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149737. 9,
  149738. };
  149739. static float _vq_quantthresh__44u7__p2_0[] = {
  149740. -0.5, 0.5,
  149741. };
  149742. static long _vq_quantmap__44u7__p2_0[] = {
  149743. 1, 0, 2,
  149744. };
  149745. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149746. _vq_quantthresh__44u7__p2_0,
  149747. _vq_quantmap__44u7__p2_0,
  149748. 3,
  149749. 3
  149750. };
  149751. static static_codebook _44u7__p2_0 = {
  149752. 4, 81,
  149753. _vq_lengthlist__44u7__p2_0,
  149754. 1, -535822336, 1611661312, 2, 0,
  149755. _vq_quantlist__44u7__p2_0,
  149756. NULL,
  149757. &_vq_auxt__44u7__p2_0,
  149758. NULL,
  149759. 0
  149760. };
  149761. static long _vq_quantlist__44u7__p3_0[] = {
  149762. 2,
  149763. 1,
  149764. 3,
  149765. 0,
  149766. 4,
  149767. };
  149768. static long _vq_lengthlist__44u7__p3_0[] = {
  149769. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149770. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149771. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149772. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149773. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149774. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149775. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149776. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149777. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149778. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149779. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149780. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149781. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149782. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149783. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149784. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149785. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149786. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149787. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149788. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149789. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149790. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149791. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149792. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149793. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149794. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149795. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149796. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149797. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149798. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149799. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149800. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149801. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149802. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149803. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149804. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149805. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149806. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149807. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149808. 0,
  149809. };
  149810. static float _vq_quantthresh__44u7__p3_0[] = {
  149811. -1.5, -0.5, 0.5, 1.5,
  149812. };
  149813. static long _vq_quantmap__44u7__p3_0[] = {
  149814. 3, 1, 0, 2, 4,
  149815. };
  149816. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  149817. _vq_quantthresh__44u7__p3_0,
  149818. _vq_quantmap__44u7__p3_0,
  149819. 5,
  149820. 5
  149821. };
  149822. static static_codebook _44u7__p3_0 = {
  149823. 4, 625,
  149824. _vq_lengthlist__44u7__p3_0,
  149825. 1, -533725184, 1611661312, 3, 0,
  149826. _vq_quantlist__44u7__p3_0,
  149827. NULL,
  149828. &_vq_auxt__44u7__p3_0,
  149829. NULL,
  149830. 0
  149831. };
  149832. static long _vq_quantlist__44u7__p4_0[] = {
  149833. 2,
  149834. 1,
  149835. 3,
  149836. 0,
  149837. 4,
  149838. };
  149839. static long _vq_lengthlist__44u7__p4_0[] = {
  149840. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149841. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  149842. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  149843. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149844. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149845. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149846. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  149847. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  149848. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149849. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149850. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  149851. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149852. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149853. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  149854. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  149855. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149856. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  149857. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149858. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  149859. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  149860. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149861. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149862. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  149863. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149864. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  149865. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149866. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149867. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  149868. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  149869. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  149870. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  149871. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149872. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  149873. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149874. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  149875. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149876. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  149877. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  149878. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  149879. 14,
  149880. };
  149881. static float _vq_quantthresh__44u7__p4_0[] = {
  149882. -1.5, -0.5, 0.5, 1.5,
  149883. };
  149884. static long _vq_quantmap__44u7__p4_0[] = {
  149885. 3, 1, 0, 2, 4,
  149886. };
  149887. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  149888. _vq_quantthresh__44u7__p4_0,
  149889. _vq_quantmap__44u7__p4_0,
  149890. 5,
  149891. 5
  149892. };
  149893. static static_codebook _44u7__p4_0 = {
  149894. 4, 625,
  149895. _vq_lengthlist__44u7__p4_0,
  149896. 1, -533725184, 1611661312, 3, 0,
  149897. _vq_quantlist__44u7__p4_0,
  149898. NULL,
  149899. &_vq_auxt__44u7__p4_0,
  149900. NULL,
  149901. 0
  149902. };
  149903. static long _vq_quantlist__44u7__p5_0[] = {
  149904. 4,
  149905. 3,
  149906. 5,
  149907. 2,
  149908. 6,
  149909. 1,
  149910. 7,
  149911. 0,
  149912. 8,
  149913. };
  149914. static long _vq_lengthlist__44u7__p5_0[] = {
  149915. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149916. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  149917. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  149918. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  149919. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  149920. 14,
  149921. };
  149922. static float _vq_quantthresh__44u7__p5_0[] = {
  149923. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149924. };
  149925. static long _vq_quantmap__44u7__p5_0[] = {
  149926. 7, 5, 3, 1, 0, 2, 4, 6,
  149927. 8,
  149928. };
  149929. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  149930. _vq_quantthresh__44u7__p5_0,
  149931. _vq_quantmap__44u7__p5_0,
  149932. 9,
  149933. 9
  149934. };
  149935. static static_codebook _44u7__p5_0 = {
  149936. 2, 81,
  149937. _vq_lengthlist__44u7__p5_0,
  149938. 1, -531628032, 1611661312, 4, 0,
  149939. _vq_quantlist__44u7__p5_0,
  149940. NULL,
  149941. &_vq_auxt__44u7__p5_0,
  149942. NULL,
  149943. 0
  149944. };
  149945. static long _vq_quantlist__44u7__p6_0[] = {
  149946. 4,
  149947. 3,
  149948. 5,
  149949. 2,
  149950. 6,
  149951. 1,
  149952. 7,
  149953. 0,
  149954. 8,
  149955. };
  149956. static long _vq_lengthlist__44u7__p6_0[] = {
  149957. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  149958. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149959. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149960. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  149961. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  149962. 12,
  149963. };
  149964. static float _vq_quantthresh__44u7__p6_0[] = {
  149965. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149966. };
  149967. static long _vq_quantmap__44u7__p6_0[] = {
  149968. 7, 5, 3, 1, 0, 2, 4, 6,
  149969. 8,
  149970. };
  149971. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  149972. _vq_quantthresh__44u7__p6_0,
  149973. _vq_quantmap__44u7__p6_0,
  149974. 9,
  149975. 9
  149976. };
  149977. static static_codebook _44u7__p6_0 = {
  149978. 2, 81,
  149979. _vq_lengthlist__44u7__p6_0,
  149980. 1, -531628032, 1611661312, 4, 0,
  149981. _vq_quantlist__44u7__p6_0,
  149982. NULL,
  149983. &_vq_auxt__44u7__p6_0,
  149984. NULL,
  149985. 0
  149986. };
  149987. static long _vq_quantlist__44u7__p7_0[] = {
  149988. 1,
  149989. 0,
  149990. 2,
  149991. };
  149992. static long _vq_lengthlist__44u7__p7_0[] = {
  149993. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  149994. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  149995. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  149996. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  149997. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  149998. 10,
  149999. };
  150000. static float _vq_quantthresh__44u7__p7_0[] = {
  150001. -5.5, 5.5,
  150002. };
  150003. static long _vq_quantmap__44u7__p7_0[] = {
  150004. 1, 0, 2,
  150005. };
  150006. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150007. _vq_quantthresh__44u7__p7_0,
  150008. _vq_quantmap__44u7__p7_0,
  150009. 3,
  150010. 3
  150011. };
  150012. static static_codebook _44u7__p7_0 = {
  150013. 4, 81,
  150014. _vq_lengthlist__44u7__p7_0,
  150015. 1, -529137664, 1618345984, 2, 0,
  150016. _vq_quantlist__44u7__p7_0,
  150017. NULL,
  150018. &_vq_auxt__44u7__p7_0,
  150019. NULL,
  150020. 0
  150021. };
  150022. static long _vq_quantlist__44u7__p7_1[] = {
  150023. 5,
  150024. 4,
  150025. 6,
  150026. 3,
  150027. 7,
  150028. 2,
  150029. 8,
  150030. 1,
  150031. 9,
  150032. 0,
  150033. 10,
  150034. };
  150035. static long _vq_lengthlist__44u7__p7_1[] = {
  150036. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150037. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150038. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150039. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150040. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150041. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150042. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150043. 8, 9, 9, 9, 9, 9,10,10,10,
  150044. };
  150045. static float _vq_quantthresh__44u7__p7_1[] = {
  150046. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150047. 3.5, 4.5,
  150048. };
  150049. static long _vq_quantmap__44u7__p7_1[] = {
  150050. 9, 7, 5, 3, 1, 0, 2, 4,
  150051. 6, 8, 10,
  150052. };
  150053. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150054. _vq_quantthresh__44u7__p7_1,
  150055. _vq_quantmap__44u7__p7_1,
  150056. 11,
  150057. 11
  150058. };
  150059. static static_codebook _44u7__p7_1 = {
  150060. 2, 121,
  150061. _vq_lengthlist__44u7__p7_1,
  150062. 1, -531365888, 1611661312, 4, 0,
  150063. _vq_quantlist__44u7__p7_1,
  150064. NULL,
  150065. &_vq_auxt__44u7__p7_1,
  150066. NULL,
  150067. 0
  150068. };
  150069. static long _vq_quantlist__44u7__p8_0[] = {
  150070. 5,
  150071. 4,
  150072. 6,
  150073. 3,
  150074. 7,
  150075. 2,
  150076. 8,
  150077. 1,
  150078. 9,
  150079. 0,
  150080. 10,
  150081. };
  150082. static long _vq_lengthlist__44u7__p8_0[] = {
  150083. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150084. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150085. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150086. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150087. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150088. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150089. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150090. 12,13,13,14,14,15,15,15,16,
  150091. };
  150092. static float _vq_quantthresh__44u7__p8_0[] = {
  150093. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150094. 38.5, 49.5,
  150095. };
  150096. static long _vq_quantmap__44u7__p8_0[] = {
  150097. 9, 7, 5, 3, 1, 0, 2, 4,
  150098. 6, 8, 10,
  150099. };
  150100. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150101. _vq_quantthresh__44u7__p8_0,
  150102. _vq_quantmap__44u7__p8_0,
  150103. 11,
  150104. 11
  150105. };
  150106. static static_codebook _44u7__p8_0 = {
  150107. 2, 121,
  150108. _vq_lengthlist__44u7__p8_0,
  150109. 1, -524582912, 1618345984, 4, 0,
  150110. _vq_quantlist__44u7__p8_0,
  150111. NULL,
  150112. &_vq_auxt__44u7__p8_0,
  150113. NULL,
  150114. 0
  150115. };
  150116. static long _vq_quantlist__44u7__p8_1[] = {
  150117. 5,
  150118. 4,
  150119. 6,
  150120. 3,
  150121. 7,
  150122. 2,
  150123. 8,
  150124. 1,
  150125. 9,
  150126. 0,
  150127. 10,
  150128. };
  150129. static long _vq_lengthlist__44u7__p8_1[] = {
  150130. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150131. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150132. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150133. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150134. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150135. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150136. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150137. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150138. };
  150139. static float _vq_quantthresh__44u7__p8_1[] = {
  150140. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150141. 3.5, 4.5,
  150142. };
  150143. static long _vq_quantmap__44u7__p8_1[] = {
  150144. 9, 7, 5, 3, 1, 0, 2, 4,
  150145. 6, 8, 10,
  150146. };
  150147. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150148. _vq_quantthresh__44u7__p8_1,
  150149. _vq_quantmap__44u7__p8_1,
  150150. 11,
  150151. 11
  150152. };
  150153. static static_codebook _44u7__p8_1 = {
  150154. 2, 121,
  150155. _vq_lengthlist__44u7__p8_1,
  150156. 1, -531365888, 1611661312, 4, 0,
  150157. _vq_quantlist__44u7__p8_1,
  150158. NULL,
  150159. &_vq_auxt__44u7__p8_1,
  150160. NULL,
  150161. 0
  150162. };
  150163. static long _vq_quantlist__44u7__p9_0[] = {
  150164. 5,
  150165. 4,
  150166. 6,
  150167. 3,
  150168. 7,
  150169. 2,
  150170. 8,
  150171. 1,
  150172. 9,
  150173. 0,
  150174. 10,
  150175. };
  150176. static long _vq_lengthlist__44u7__p9_0[] = {
  150177. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150178. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150179. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150180. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150181. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150182. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150183. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150184. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150185. };
  150186. static float _vq_quantthresh__44u7__p9_0[] = {
  150187. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150188. 2229.5, 2866.5,
  150189. };
  150190. static long _vq_quantmap__44u7__p9_0[] = {
  150191. 9, 7, 5, 3, 1, 0, 2, 4,
  150192. 6, 8, 10,
  150193. };
  150194. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150195. _vq_quantthresh__44u7__p9_0,
  150196. _vq_quantmap__44u7__p9_0,
  150197. 11,
  150198. 11
  150199. };
  150200. static static_codebook _44u7__p9_0 = {
  150201. 2, 121,
  150202. _vq_lengthlist__44u7__p9_0,
  150203. 1, -512171520, 1630791680, 4, 0,
  150204. _vq_quantlist__44u7__p9_0,
  150205. NULL,
  150206. &_vq_auxt__44u7__p9_0,
  150207. NULL,
  150208. 0
  150209. };
  150210. static long _vq_quantlist__44u7__p9_1[] = {
  150211. 6,
  150212. 5,
  150213. 7,
  150214. 4,
  150215. 8,
  150216. 3,
  150217. 9,
  150218. 2,
  150219. 10,
  150220. 1,
  150221. 11,
  150222. 0,
  150223. 12,
  150224. };
  150225. static long _vq_lengthlist__44u7__p9_1[] = {
  150226. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150227. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150228. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150229. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150230. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150231. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150232. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150233. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150234. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150235. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150236. 15,15,15,15,17,17,16,17,16,
  150237. };
  150238. static float _vq_quantthresh__44u7__p9_1[] = {
  150239. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150240. 122.5, 171.5, 220.5, 269.5,
  150241. };
  150242. static long _vq_quantmap__44u7__p9_1[] = {
  150243. 11, 9, 7, 5, 3, 1, 0, 2,
  150244. 4, 6, 8, 10, 12,
  150245. };
  150246. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150247. _vq_quantthresh__44u7__p9_1,
  150248. _vq_quantmap__44u7__p9_1,
  150249. 13,
  150250. 13
  150251. };
  150252. static static_codebook _44u7__p9_1 = {
  150253. 2, 169,
  150254. _vq_lengthlist__44u7__p9_1,
  150255. 1, -518889472, 1622704128, 4, 0,
  150256. _vq_quantlist__44u7__p9_1,
  150257. NULL,
  150258. &_vq_auxt__44u7__p9_1,
  150259. NULL,
  150260. 0
  150261. };
  150262. static long _vq_quantlist__44u7__p9_2[] = {
  150263. 24,
  150264. 23,
  150265. 25,
  150266. 22,
  150267. 26,
  150268. 21,
  150269. 27,
  150270. 20,
  150271. 28,
  150272. 19,
  150273. 29,
  150274. 18,
  150275. 30,
  150276. 17,
  150277. 31,
  150278. 16,
  150279. 32,
  150280. 15,
  150281. 33,
  150282. 14,
  150283. 34,
  150284. 13,
  150285. 35,
  150286. 12,
  150287. 36,
  150288. 11,
  150289. 37,
  150290. 10,
  150291. 38,
  150292. 9,
  150293. 39,
  150294. 8,
  150295. 40,
  150296. 7,
  150297. 41,
  150298. 6,
  150299. 42,
  150300. 5,
  150301. 43,
  150302. 4,
  150303. 44,
  150304. 3,
  150305. 45,
  150306. 2,
  150307. 46,
  150308. 1,
  150309. 47,
  150310. 0,
  150311. 48,
  150312. };
  150313. static long _vq_lengthlist__44u7__p9_2[] = {
  150314. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150315. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150316. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150317. 8,
  150318. };
  150319. static float _vq_quantthresh__44u7__p9_2[] = {
  150320. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150321. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150322. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150323. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150324. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150325. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150326. };
  150327. static long _vq_quantmap__44u7__p9_2[] = {
  150328. 47, 45, 43, 41, 39, 37, 35, 33,
  150329. 31, 29, 27, 25, 23, 21, 19, 17,
  150330. 15, 13, 11, 9, 7, 5, 3, 1,
  150331. 0, 2, 4, 6, 8, 10, 12, 14,
  150332. 16, 18, 20, 22, 24, 26, 28, 30,
  150333. 32, 34, 36, 38, 40, 42, 44, 46,
  150334. 48,
  150335. };
  150336. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150337. _vq_quantthresh__44u7__p9_2,
  150338. _vq_quantmap__44u7__p9_2,
  150339. 49,
  150340. 49
  150341. };
  150342. static static_codebook _44u7__p9_2 = {
  150343. 1, 49,
  150344. _vq_lengthlist__44u7__p9_2,
  150345. 1, -526909440, 1611661312, 6, 0,
  150346. _vq_quantlist__44u7__p9_2,
  150347. NULL,
  150348. &_vq_auxt__44u7__p9_2,
  150349. NULL,
  150350. 0
  150351. };
  150352. static long _huff_lengthlist__44u7__short[] = {
  150353. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150354. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150355. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150356. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150357. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150358. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150359. 6, 8, 5, 9,
  150360. };
  150361. static static_codebook _huff_book__44u7__short = {
  150362. 2, 100,
  150363. _huff_lengthlist__44u7__short,
  150364. 0, 0, 0, 0, 0,
  150365. NULL,
  150366. NULL,
  150367. NULL,
  150368. NULL,
  150369. 0
  150370. };
  150371. static long _huff_lengthlist__44u8__long[] = {
  150372. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150373. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150374. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150375. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150376. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150377. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150378. 10, 8, 8, 9,
  150379. };
  150380. static static_codebook _huff_book__44u8__long = {
  150381. 2, 100,
  150382. _huff_lengthlist__44u8__long,
  150383. 0, 0, 0, 0, 0,
  150384. NULL,
  150385. NULL,
  150386. NULL,
  150387. NULL,
  150388. 0
  150389. };
  150390. static long _huff_lengthlist__44u8__short[] = {
  150391. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150392. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150393. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150394. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150395. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150396. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150397. 10,10,15,17,
  150398. };
  150399. static static_codebook _huff_book__44u8__short = {
  150400. 2, 100,
  150401. _huff_lengthlist__44u8__short,
  150402. 0, 0, 0, 0, 0,
  150403. NULL,
  150404. NULL,
  150405. NULL,
  150406. NULL,
  150407. 0
  150408. };
  150409. static long _vq_quantlist__44u8_p1_0[] = {
  150410. 1,
  150411. 0,
  150412. 2,
  150413. };
  150414. static long _vq_lengthlist__44u8_p1_0[] = {
  150415. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150416. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150417. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150418. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150419. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150420. 10,
  150421. };
  150422. static float _vq_quantthresh__44u8_p1_0[] = {
  150423. -0.5, 0.5,
  150424. };
  150425. static long _vq_quantmap__44u8_p1_0[] = {
  150426. 1, 0, 2,
  150427. };
  150428. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150429. _vq_quantthresh__44u8_p1_0,
  150430. _vq_quantmap__44u8_p1_0,
  150431. 3,
  150432. 3
  150433. };
  150434. static static_codebook _44u8_p1_0 = {
  150435. 4, 81,
  150436. _vq_lengthlist__44u8_p1_0,
  150437. 1, -535822336, 1611661312, 2, 0,
  150438. _vq_quantlist__44u8_p1_0,
  150439. NULL,
  150440. &_vq_auxt__44u8_p1_0,
  150441. NULL,
  150442. 0
  150443. };
  150444. static long _vq_quantlist__44u8_p2_0[] = {
  150445. 2,
  150446. 1,
  150447. 3,
  150448. 0,
  150449. 4,
  150450. };
  150451. static long _vq_lengthlist__44u8_p2_0[] = {
  150452. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150453. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150454. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150455. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150456. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150457. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150458. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150459. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150460. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150461. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150462. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150463. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150464. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150465. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150466. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150467. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150468. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150469. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150470. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150471. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150472. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150473. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150474. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150475. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150476. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150477. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150478. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150479. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150480. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150481. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150482. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150483. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150484. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150485. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150486. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150487. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150488. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150489. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150490. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150491. 14,
  150492. };
  150493. static float _vq_quantthresh__44u8_p2_0[] = {
  150494. -1.5, -0.5, 0.5, 1.5,
  150495. };
  150496. static long _vq_quantmap__44u8_p2_0[] = {
  150497. 3, 1, 0, 2, 4,
  150498. };
  150499. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150500. _vq_quantthresh__44u8_p2_0,
  150501. _vq_quantmap__44u8_p2_0,
  150502. 5,
  150503. 5
  150504. };
  150505. static static_codebook _44u8_p2_0 = {
  150506. 4, 625,
  150507. _vq_lengthlist__44u8_p2_0,
  150508. 1, -533725184, 1611661312, 3, 0,
  150509. _vq_quantlist__44u8_p2_0,
  150510. NULL,
  150511. &_vq_auxt__44u8_p2_0,
  150512. NULL,
  150513. 0
  150514. };
  150515. static long _vq_quantlist__44u8_p3_0[] = {
  150516. 4,
  150517. 3,
  150518. 5,
  150519. 2,
  150520. 6,
  150521. 1,
  150522. 7,
  150523. 0,
  150524. 8,
  150525. };
  150526. static long _vq_lengthlist__44u8_p3_0[] = {
  150527. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150528. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150529. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150530. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150531. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150532. 12,
  150533. };
  150534. static float _vq_quantthresh__44u8_p3_0[] = {
  150535. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150536. };
  150537. static long _vq_quantmap__44u8_p3_0[] = {
  150538. 7, 5, 3, 1, 0, 2, 4, 6,
  150539. 8,
  150540. };
  150541. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150542. _vq_quantthresh__44u8_p3_0,
  150543. _vq_quantmap__44u8_p3_0,
  150544. 9,
  150545. 9
  150546. };
  150547. static static_codebook _44u8_p3_0 = {
  150548. 2, 81,
  150549. _vq_lengthlist__44u8_p3_0,
  150550. 1, -531628032, 1611661312, 4, 0,
  150551. _vq_quantlist__44u8_p3_0,
  150552. NULL,
  150553. &_vq_auxt__44u8_p3_0,
  150554. NULL,
  150555. 0
  150556. };
  150557. static long _vq_quantlist__44u8_p4_0[] = {
  150558. 8,
  150559. 7,
  150560. 9,
  150561. 6,
  150562. 10,
  150563. 5,
  150564. 11,
  150565. 4,
  150566. 12,
  150567. 3,
  150568. 13,
  150569. 2,
  150570. 14,
  150571. 1,
  150572. 15,
  150573. 0,
  150574. 16,
  150575. };
  150576. static long _vq_lengthlist__44u8_p4_0[] = {
  150577. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150578. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150579. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150580. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150581. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150582. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150583. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150584. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150585. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150586. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150587. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150588. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150589. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150590. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150591. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150592. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150593. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150594. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150595. 14,
  150596. };
  150597. static float _vq_quantthresh__44u8_p4_0[] = {
  150598. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150599. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150600. };
  150601. static long _vq_quantmap__44u8_p4_0[] = {
  150602. 15, 13, 11, 9, 7, 5, 3, 1,
  150603. 0, 2, 4, 6, 8, 10, 12, 14,
  150604. 16,
  150605. };
  150606. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150607. _vq_quantthresh__44u8_p4_0,
  150608. _vq_quantmap__44u8_p4_0,
  150609. 17,
  150610. 17
  150611. };
  150612. static static_codebook _44u8_p4_0 = {
  150613. 2, 289,
  150614. _vq_lengthlist__44u8_p4_0,
  150615. 1, -529530880, 1611661312, 5, 0,
  150616. _vq_quantlist__44u8_p4_0,
  150617. NULL,
  150618. &_vq_auxt__44u8_p4_0,
  150619. NULL,
  150620. 0
  150621. };
  150622. static long _vq_quantlist__44u8_p5_0[] = {
  150623. 1,
  150624. 0,
  150625. 2,
  150626. };
  150627. static long _vq_lengthlist__44u8_p5_0[] = {
  150628. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150629. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150630. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150631. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150632. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150633. 10,
  150634. };
  150635. static float _vq_quantthresh__44u8_p5_0[] = {
  150636. -5.5, 5.5,
  150637. };
  150638. static long _vq_quantmap__44u8_p5_0[] = {
  150639. 1, 0, 2,
  150640. };
  150641. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150642. _vq_quantthresh__44u8_p5_0,
  150643. _vq_quantmap__44u8_p5_0,
  150644. 3,
  150645. 3
  150646. };
  150647. static static_codebook _44u8_p5_0 = {
  150648. 4, 81,
  150649. _vq_lengthlist__44u8_p5_0,
  150650. 1, -529137664, 1618345984, 2, 0,
  150651. _vq_quantlist__44u8_p5_0,
  150652. NULL,
  150653. &_vq_auxt__44u8_p5_0,
  150654. NULL,
  150655. 0
  150656. };
  150657. static long _vq_quantlist__44u8_p5_1[] = {
  150658. 5,
  150659. 4,
  150660. 6,
  150661. 3,
  150662. 7,
  150663. 2,
  150664. 8,
  150665. 1,
  150666. 9,
  150667. 0,
  150668. 10,
  150669. };
  150670. static long _vq_lengthlist__44u8_p5_1[] = {
  150671. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150672. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150673. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150674. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150675. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150676. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150677. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150678. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150679. };
  150680. static float _vq_quantthresh__44u8_p5_1[] = {
  150681. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150682. 3.5, 4.5,
  150683. };
  150684. static long _vq_quantmap__44u8_p5_1[] = {
  150685. 9, 7, 5, 3, 1, 0, 2, 4,
  150686. 6, 8, 10,
  150687. };
  150688. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150689. _vq_quantthresh__44u8_p5_1,
  150690. _vq_quantmap__44u8_p5_1,
  150691. 11,
  150692. 11
  150693. };
  150694. static static_codebook _44u8_p5_1 = {
  150695. 2, 121,
  150696. _vq_lengthlist__44u8_p5_1,
  150697. 1, -531365888, 1611661312, 4, 0,
  150698. _vq_quantlist__44u8_p5_1,
  150699. NULL,
  150700. &_vq_auxt__44u8_p5_1,
  150701. NULL,
  150702. 0
  150703. };
  150704. static long _vq_quantlist__44u8_p6_0[] = {
  150705. 6,
  150706. 5,
  150707. 7,
  150708. 4,
  150709. 8,
  150710. 3,
  150711. 9,
  150712. 2,
  150713. 10,
  150714. 1,
  150715. 11,
  150716. 0,
  150717. 12,
  150718. };
  150719. static long _vq_lengthlist__44u8_p6_0[] = {
  150720. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150721. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150722. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150723. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150724. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150725. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150726. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150727. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150728. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150729. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150730. 11,11,11,11,11,12,11,12,12,
  150731. };
  150732. static float _vq_quantthresh__44u8_p6_0[] = {
  150733. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150734. 12.5, 17.5, 22.5, 27.5,
  150735. };
  150736. static long _vq_quantmap__44u8_p6_0[] = {
  150737. 11, 9, 7, 5, 3, 1, 0, 2,
  150738. 4, 6, 8, 10, 12,
  150739. };
  150740. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150741. _vq_quantthresh__44u8_p6_0,
  150742. _vq_quantmap__44u8_p6_0,
  150743. 13,
  150744. 13
  150745. };
  150746. static static_codebook _44u8_p6_0 = {
  150747. 2, 169,
  150748. _vq_lengthlist__44u8_p6_0,
  150749. 1, -526516224, 1616117760, 4, 0,
  150750. _vq_quantlist__44u8_p6_0,
  150751. NULL,
  150752. &_vq_auxt__44u8_p6_0,
  150753. NULL,
  150754. 0
  150755. };
  150756. static long _vq_quantlist__44u8_p6_1[] = {
  150757. 2,
  150758. 1,
  150759. 3,
  150760. 0,
  150761. 4,
  150762. };
  150763. static long _vq_lengthlist__44u8_p6_1[] = {
  150764. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150765. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150766. };
  150767. static float _vq_quantthresh__44u8_p6_1[] = {
  150768. -1.5, -0.5, 0.5, 1.5,
  150769. };
  150770. static long _vq_quantmap__44u8_p6_1[] = {
  150771. 3, 1, 0, 2, 4,
  150772. };
  150773. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150774. _vq_quantthresh__44u8_p6_1,
  150775. _vq_quantmap__44u8_p6_1,
  150776. 5,
  150777. 5
  150778. };
  150779. static static_codebook _44u8_p6_1 = {
  150780. 2, 25,
  150781. _vq_lengthlist__44u8_p6_1,
  150782. 1, -533725184, 1611661312, 3, 0,
  150783. _vq_quantlist__44u8_p6_1,
  150784. NULL,
  150785. &_vq_auxt__44u8_p6_1,
  150786. NULL,
  150787. 0
  150788. };
  150789. static long _vq_quantlist__44u8_p7_0[] = {
  150790. 6,
  150791. 5,
  150792. 7,
  150793. 4,
  150794. 8,
  150795. 3,
  150796. 9,
  150797. 2,
  150798. 10,
  150799. 1,
  150800. 11,
  150801. 0,
  150802. 12,
  150803. };
  150804. static long _vq_lengthlist__44u8_p7_0[] = {
  150805. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150806. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150807. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150808. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150809. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150810. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150811. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150812. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150813. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  150814. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  150815. 13,13,14,14,14,15,15,15,16,
  150816. };
  150817. static float _vq_quantthresh__44u8_p7_0[] = {
  150818. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  150819. 27.5, 38.5, 49.5, 60.5,
  150820. };
  150821. static long _vq_quantmap__44u8_p7_0[] = {
  150822. 11, 9, 7, 5, 3, 1, 0, 2,
  150823. 4, 6, 8, 10, 12,
  150824. };
  150825. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  150826. _vq_quantthresh__44u8_p7_0,
  150827. _vq_quantmap__44u8_p7_0,
  150828. 13,
  150829. 13
  150830. };
  150831. static static_codebook _44u8_p7_0 = {
  150832. 2, 169,
  150833. _vq_lengthlist__44u8_p7_0,
  150834. 1, -523206656, 1618345984, 4, 0,
  150835. _vq_quantlist__44u8_p7_0,
  150836. NULL,
  150837. &_vq_auxt__44u8_p7_0,
  150838. NULL,
  150839. 0
  150840. };
  150841. static long _vq_quantlist__44u8_p7_1[] = {
  150842. 5,
  150843. 4,
  150844. 6,
  150845. 3,
  150846. 7,
  150847. 2,
  150848. 8,
  150849. 1,
  150850. 9,
  150851. 0,
  150852. 10,
  150853. };
  150854. static long _vq_lengthlist__44u8_p7_1[] = {
  150855. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150856. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  150857. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150858. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  150859. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  150860. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150861. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150862. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150863. };
  150864. static float _vq_quantthresh__44u8_p7_1[] = {
  150865. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150866. 3.5, 4.5,
  150867. };
  150868. static long _vq_quantmap__44u8_p7_1[] = {
  150869. 9, 7, 5, 3, 1, 0, 2, 4,
  150870. 6, 8, 10,
  150871. };
  150872. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  150873. _vq_quantthresh__44u8_p7_1,
  150874. _vq_quantmap__44u8_p7_1,
  150875. 11,
  150876. 11
  150877. };
  150878. static static_codebook _44u8_p7_1 = {
  150879. 2, 121,
  150880. _vq_lengthlist__44u8_p7_1,
  150881. 1, -531365888, 1611661312, 4, 0,
  150882. _vq_quantlist__44u8_p7_1,
  150883. NULL,
  150884. &_vq_auxt__44u8_p7_1,
  150885. NULL,
  150886. 0
  150887. };
  150888. static long _vq_quantlist__44u8_p8_0[] = {
  150889. 7,
  150890. 6,
  150891. 8,
  150892. 5,
  150893. 9,
  150894. 4,
  150895. 10,
  150896. 3,
  150897. 11,
  150898. 2,
  150899. 12,
  150900. 1,
  150901. 13,
  150902. 0,
  150903. 14,
  150904. };
  150905. static long _vq_lengthlist__44u8_p8_0[] = {
  150906. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  150907. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  150908. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  150909. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  150910. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  150911. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  150912. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  150913. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  150914. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  150915. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  150916. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  150917. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  150918. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  150919. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  150920. 17,
  150921. };
  150922. static float _vq_quantthresh__44u8_p8_0[] = {
  150923. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  150924. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  150925. };
  150926. static long _vq_quantmap__44u8_p8_0[] = {
  150927. 13, 11, 9, 7, 5, 3, 1, 0,
  150928. 2, 4, 6, 8, 10, 12, 14,
  150929. };
  150930. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  150931. _vq_quantthresh__44u8_p8_0,
  150932. _vq_quantmap__44u8_p8_0,
  150933. 15,
  150934. 15
  150935. };
  150936. static static_codebook _44u8_p8_0 = {
  150937. 2, 225,
  150938. _vq_lengthlist__44u8_p8_0,
  150939. 1, -520986624, 1620377600, 4, 0,
  150940. _vq_quantlist__44u8_p8_0,
  150941. NULL,
  150942. &_vq_auxt__44u8_p8_0,
  150943. NULL,
  150944. 0
  150945. };
  150946. static long _vq_quantlist__44u8_p8_1[] = {
  150947. 10,
  150948. 9,
  150949. 11,
  150950. 8,
  150951. 12,
  150952. 7,
  150953. 13,
  150954. 6,
  150955. 14,
  150956. 5,
  150957. 15,
  150958. 4,
  150959. 16,
  150960. 3,
  150961. 17,
  150962. 2,
  150963. 18,
  150964. 1,
  150965. 19,
  150966. 0,
  150967. 20,
  150968. };
  150969. static long _vq_lengthlist__44u8_p8_1[] = {
  150970. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  150971. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  150972. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  150973. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  150974. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150975. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150976. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  150977. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  150978. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150979. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150980. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  150981. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  150982. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150983. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150984. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150985. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  150986. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  150987. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  150988. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  150989. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  150990. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150991. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150992. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150993. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  150994. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  150995. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150996. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  150997. 10,10,10,10,10,10,10,10,10,
  150998. };
  150999. static float _vq_quantthresh__44u8_p8_1[] = {
  151000. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151001. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151002. 6.5, 7.5, 8.5, 9.5,
  151003. };
  151004. static long _vq_quantmap__44u8_p8_1[] = {
  151005. 19, 17, 15, 13, 11, 9, 7, 5,
  151006. 3, 1, 0, 2, 4, 6, 8, 10,
  151007. 12, 14, 16, 18, 20,
  151008. };
  151009. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151010. _vq_quantthresh__44u8_p8_1,
  151011. _vq_quantmap__44u8_p8_1,
  151012. 21,
  151013. 21
  151014. };
  151015. static static_codebook _44u8_p8_1 = {
  151016. 2, 441,
  151017. _vq_lengthlist__44u8_p8_1,
  151018. 1, -529268736, 1611661312, 5, 0,
  151019. _vq_quantlist__44u8_p8_1,
  151020. NULL,
  151021. &_vq_auxt__44u8_p8_1,
  151022. NULL,
  151023. 0
  151024. };
  151025. static long _vq_quantlist__44u8_p9_0[] = {
  151026. 4,
  151027. 3,
  151028. 5,
  151029. 2,
  151030. 6,
  151031. 1,
  151032. 7,
  151033. 0,
  151034. 8,
  151035. };
  151036. static long _vq_lengthlist__44u8_p9_0[] = {
  151037. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151038. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151039. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151040. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151041. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151042. 8,
  151043. };
  151044. static float _vq_quantthresh__44u8_p9_0[] = {
  151045. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151046. };
  151047. static long _vq_quantmap__44u8_p9_0[] = {
  151048. 7, 5, 3, 1, 0, 2, 4, 6,
  151049. 8,
  151050. };
  151051. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151052. _vq_quantthresh__44u8_p9_0,
  151053. _vq_quantmap__44u8_p9_0,
  151054. 9,
  151055. 9
  151056. };
  151057. static static_codebook _44u8_p9_0 = {
  151058. 2, 81,
  151059. _vq_lengthlist__44u8_p9_0,
  151060. 1, -511895552, 1631393792, 4, 0,
  151061. _vq_quantlist__44u8_p9_0,
  151062. NULL,
  151063. &_vq_auxt__44u8_p9_0,
  151064. NULL,
  151065. 0
  151066. };
  151067. static long _vq_quantlist__44u8_p9_1[] = {
  151068. 9,
  151069. 8,
  151070. 10,
  151071. 7,
  151072. 11,
  151073. 6,
  151074. 12,
  151075. 5,
  151076. 13,
  151077. 4,
  151078. 14,
  151079. 3,
  151080. 15,
  151081. 2,
  151082. 16,
  151083. 1,
  151084. 17,
  151085. 0,
  151086. 18,
  151087. };
  151088. static long _vq_lengthlist__44u8_p9_1[] = {
  151089. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151090. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151091. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151092. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151093. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151094. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151095. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151096. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151097. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151098. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151099. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151100. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151101. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151102. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151103. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151104. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151105. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151106. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151107. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151108. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151109. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151110. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151111. 16,15,16,16,16,16,16,16,16,
  151112. };
  151113. static float _vq_quantthresh__44u8_p9_1[] = {
  151114. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151115. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151116. 367.5, 416.5,
  151117. };
  151118. static long _vq_quantmap__44u8_p9_1[] = {
  151119. 17, 15, 13, 11, 9, 7, 5, 3,
  151120. 1, 0, 2, 4, 6, 8, 10, 12,
  151121. 14, 16, 18,
  151122. };
  151123. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151124. _vq_quantthresh__44u8_p9_1,
  151125. _vq_quantmap__44u8_p9_1,
  151126. 19,
  151127. 19
  151128. };
  151129. static static_codebook _44u8_p9_1 = {
  151130. 2, 361,
  151131. _vq_lengthlist__44u8_p9_1,
  151132. 1, -518287360, 1622704128, 5, 0,
  151133. _vq_quantlist__44u8_p9_1,
  151134. NULL,
  151135. &_vq_auxt__44u8_p9_1,
  151136. NULL,
  151137. 0
  151138. };
  151139. static long _vq_quantlist__44u8_p9_2[] = {
  151140. 24,
  151141. 23,
  151142. 25,
  151143. 22,
  151144. 26,
  151145. 21,
  151146. 27,
  151147. 20,
  151148. 28,
  151149. 19,
  151150. 29,
  151151. 18,
  151152. 30,
  151153. 17,
  151154. 31,
  151155. 16,
  151156. 32,
  151157. 15,
  151158. 33,
  151159. 14,
  151160. 34,
  151161. 13,
  151162. 35,
  151163. 12,
  151164. 36,
  151165. 11,
  151166. 37,
  151167. 10,
  151168. 38,
  151169. 9,
  151170. 39,
  151171. 8,
  151172. 40,
  151173. 7,
  151174. 41,
  151175. 6,
  151176. 42,
  151177. 5,
  151178. 43,
  151179. 4,
  151180. 44,
  151181. 3,
  151182. 45,
  151183. 2,
  151184. 46,
  151185. 1,
  151186. 47,
  151187. 0,
  151188. 48,
  151189. };
  151190. static long _vq_lengthlist__44u8_p9_2[] = {
  151191. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151192. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151193. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151194. 7,
  151195. };
  151196. static float _vq_quantthresh__44u8_p9_2[] = {
  151197. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151198. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151199. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151200. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151201. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151202. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151203. };
  151204. static long _vq_quantmap__44u8_p9_2[] = {
  151205. 47, 45, 43, 41, 39, 37, 35, 33,
  151206. 31, 29, 27, 25, 23, 21, 19, 17,
  151207. 15, 13, 11, 9, 7, 5, 3, 1,
  151208. 0, 2, 4, 6, 8, 10, 12, 14,
  151209. 16, 18, 20, 22, 24, 26, 28, 30,
  151210. 32, 34, 36, 38, 40, 42, 44, 46,
  151211. 48,
  151212. };
  151213. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151214. _vq_quantthresh__44u8_p9_2,
  151215. _vq_quantmap__44u8_p9_2,
  151216. 49,
  151217. 49
  151218. };
  151219. static static_codebook _44u8_p9_2 = {
  151220. 1, 49,
  151221. _vq_lengthlist__44u8_p9_2,
  151222. 1, -526909440, 1611661312, 6, 0,
  151223. _vq_quantlist__44u8_p9_2,
  151224. NULL,
  151225. &_vq_auxt__44u8_p9_2,
  151226. NULL,
  151227. 0
  151228. };
  151229. static long _huff_lengthlist__44u9__long[] = {
  151230. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151231. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151232. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151233. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151234. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151235. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151236. 10, 8, 8, 9,
  151237. };
  151238. static static_codebook _huff_book__44u9__long = {
  151239. 2, 100,
  151240. _huff_lengthlist__44u9__long,
  151241. 0, 0, 0, 0, 0,
  151242. NULL,
  151243. NULL,
  151244. NULL,
  151245. NULL,
  151246. 0
  151247. };
  151248. static long _huff_lengthlist__44u9__short[] = {
  151249. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151250. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151251. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151252. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151253. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151254. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151255. 9, 9,12,15,
  151256. };
  151257. static static_codebook _huff_book__44u9__short = {
  151258. 2, 100,
  151259. _huff_lengthlist__44u9__short,
  151260. 0, 0, 0, 0, 0,
  151261. NULL,
  151262. NULL,
  151263. NULL,
  151264. NULL,
  151265. 0
  151266. };
  151267. static long _vq_quantlist__44u9_p1_0[] = {
  151268. 1,
  151269. 0,
  151270. 2,
  151271. };
  151272. static long _vq_lengthlist__44u9_p1_0[] = {
  151273. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151274. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151275. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151276. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151277. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151278. 10,
  151279. };
  151280. static float _vq_quantthresh__44u9_p1_0[] = {
  151281. -0.5, 0.5,
  151282. };
  151283. static long _vq_quantmap__44u9_p1_0[] = {
  151284. 1, 0, 2,
  151285. };
  151286. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151287. _vq_quantthresh__44u9_p1_0,
  151288. _vq_quantmap__44u9_p1_0,
  151289. 3,
  151290. 3
  151291. };
  151292. static static_codebook _44u9_p1_0 = {
  151293. 4, 81,
  151294. _vq_lengthlist__44u9_p1_0,
  151295. 1, -535822336, 1611661312, 2, 0,
  151296. _vq_quantlist__44u9_p1_0,
  151297. NULL,
  151298. &_vq_auxt__44u9_p1_0,
  151299. NULL,
  151300. 0
  151301. };
  151302. static long _vq_quantlist__44u9_p2_0[] = {
  151303. 2,
  151304. 1,
  151305. 3,
  151306. 0,
  151307. 4,
  151308. };
  151309. static long _vq_lengthlist__44u9_p2_0[] = {
  151310. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151311. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151312. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151313. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151314. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151315. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151316. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151317. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151318. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151319. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151320. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151321. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151322. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151323. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151324. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151325. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151326. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151327. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151328. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151329. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151330. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151331. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151332. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151333. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151334. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151335. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151336. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151337. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151338. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151339. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151340. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151341. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151342. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151343. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151344. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151345. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151346. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151347. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151348. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151349. 14,
  151350. };
  151351. static float _vq_quantthresh__44u9_p2_0[] = {
  151352. -1.5, -0.5, 0.5, 1.5,
  151353. };
  151354. static long _vq_quantmap__44u9_p2_0[] = {
  151355. 3, 1, 0, 2, 4,
  151356. };
  151357. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151358. _vq_quantthresh__44u9_p2_0,
  151359. _vq_quantmap__44u9_p2_0,
  151360. 5,
  151361. 5
  151362. };
  151363. static static_codebook _44u9_p2_0 = {
  151364. 4, 625,
  151365. _vq_lengthlist__44u9_p2_0,
  151366. 1, -533725184, 1611661312, 3, 0,
  151367. _vq_quantlist__44u9_p2_0,
  151368. NULL,
  151369. &_vq_auxt__44u9_p2_0,
  151370. NULL,
  151371. 0
  151372. };
  151373. static long _vq_quantlist__44u9_p3_0[] = {
  151374. 4,
  151375. 3,
  151376. 5,
  151377. 2,
  151378. 6,
  151379. 1,
  151380. 7,
  151381. 0,
  151382. 8,
  151383. };
  151384. static long _vq_lengthlist__44u9_p3_0[] = {
  151385. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151386. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151387. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151388. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151389. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151390. 11,
  151391. };
  151392. static float _vq_quantthresh__44u9_p3_0[] = {
  151393. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151394. };
  151395. static long _vq_quantmap__44u9_p3_0[] = {
  151396. 7, 5, 3, 1, 0, 2, 4, 6,
  151397. 8,
  151398. };
  151399. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151400. _vq_quantthresh__44u9_p3_0,
  151401. _vq_quantmap__44u9_p3_0,
  151402. 9,
  151403. 9
  151404. };
  151405. static static_codebook _44u9_p3_0 = {
  151406. 2, 81,
  151407. _vq_lengthlist__44u9_p3_0,
  151408. 1, -531628032, 1611661312, 4, 0,
  151409. _vq_quantlist__44u9_p3_0,
  151410. NULL,
  151411. &_vq_auxt__44u9_p3_0,
  151412. NULL,
  151413. 0
  151414. };
  151415. static long _vq_quantlist__44u9_p4_0[] = {
  151416. 8,
  151417. 7,
  151418. 9,
  151419. 6,
  151420. 10,
  151421. 5,
  151422. 11,
  151423. 4,
  151424. 12,
  151425. 3,
  151426. 13,
  151427. 2,
  151428. 14,
  151429. 1,
  151430. 15,
  151431. 0,
  151432. 16,
  151433. };
  151434. static long _vq_lengthlist__44u9_p4_0[] = {
  151435. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151436. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151437. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151438. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151439. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151440. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151441. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151442. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151443. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151444. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151445. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151446. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151447. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151448. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151449. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151450. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151451. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151452. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151453. 14,
  151454. };
  151455. static float _vq_quantthresh__44u9_p4_0[] = {
  151456. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151457. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151458. };
  151459. static long _vq_quantmap__44u9_p4_0[] = {
  151460. 15, 13, 11, 9, 7, 5, 3, 1,
  151461. 0, 2, 4, 6, 8, 10, 12, 14,
  151462. 16,
  151463. };
  151464. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151465. _vq_quantthresh__44u9_p4_0,
  151466. _vq_quantmap__44u9_p4_0,
  151467. 17,
  151468. 17
  151469. };
  151470. static static_codebook _44u9_p4_0 = {
  151471. 2, 289,
  151472. _vq_lengthlist__44u9_p4_0,
  151473. 1, -529530880, 1611661312, 5, 0,
  151474. _vq_quantlist__44u9_p4_0,
  151475. NULL,
  151476. &_vq_auxt__44u9_p4_0,
  151477. NULL,
  151478. 0
  151479. };
  151480. static long _vq_quantlist__44u9_p5_0[] = {
  151481. 1,
  151482. 0,
  151483. 2,
  151484. };
  151485. static long _vq_lengthlist__44u9_p5_0[] = {
  151486. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151487. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151488. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151489. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151490. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151491. 10,
  151492. };
  151493. static float _vq_quantthresh__44u9_p5_0[] = {
  151494. -5.5, 5.5,
  151495. };
  151496. static long _vq_quantmap__44u9_p5_0[] = {
  151497. 1, 0, 2,
  151498. };
  151499. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151500. _vq_quantthresh__44u9_p5_0,
  151501. _vq_quantmap__44u9_p5_0,
  151502. 3,
  151503. 3
  151504. };
  151505. static static_codebook _44u9_p5_0 = {
  151506. 4, 81,
  151507. _vq_lengthlist__44u9_p5_0,
  151508. 1, -529137664, 1618345984, 2, 0,
  151509. _vq_quantlist__44u9_p5_0,
  151510. NULL,
  151511. &_vq_auxt__44u9_p5_0,
  151512. NULL,
  151513. 0
  151514. };
  151515. static long _vq_quantlist__44u9_p5_1[] = {
  151516. 5,
  151517. 4,
  151518. 6,
  151519. 3,
  151520. 7,
  151521. 2,
  151522. 8,
  151523. 1,
  151524. 9,
  151525. 0,
  151526. 10,
  151527. };
  151528. static long _vq_lengthlist__44u9_p5_1[] = {
  151529. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151530. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151531. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151532. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151533. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151534. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151535. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151536. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151537. };
  151538. static float _vq_quantthresh__44u9_p5_1[] = {
  151539. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151540. 3.5, 4.5,
  151541. };
  151542. static long _vq_quantmap__44u9_p5_1[] = {
  151543. 9, 7, 5, 3, 1, 0, 2, 4,
  151544. 6, 8, 10,
  151545. };
  151546. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151547. _vq_quantthresh__44u9_p5_1,
  151548. _vq_quantmap__44u9_p5_1,
  151549. 11,
  151550. 11
  151551. };
  151552. static static_codebook _44u9_p5_1 = {
  151553. 2, 121,
  151554. _vq_lengthlist__44u9_p5_1,
  151555. 1, -531365888, 1611661312, 4, 0,
  151556. _vq_quantlist__44u9_p5_1,
  151557. NULL,
  151558. &_vq_auxt__44u9_p5_1,
  151559. NULL,
  151560. 0
  151561. };
  151562. static long _vq_quantlist__44u9_p6_0[] = {
  151563. 6,
  151564. 5,
  151565. 7,
  151566. 4,
  151567. 8,
  151568. 3,
  151569. 9,
  151570. 2,
  151571. 10,
  151572. 1,
  151573. 11,
  151574. 0,
  151575. 12,
  151576. };
  151577. static long _vq_lengthlist__44u9_p6_0[] = {
  151578. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151579. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151580. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151581. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151582. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151583. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151584. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151585. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151586. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151587. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151588. 10,11,11,11,11,12,11,12,12,
  151589. };
  151590. static float _vq_quantthresh__44u9_p6_0[] = {
  151591. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151592. 12.5, 17.5, 22.5, 27.5,
  151593. };
  151594. static long _vq_quantmap__44u9_p6_0[] = {
  151595. 11, 9, 7, 5, 3, 1, 0, 2,
  151596. 4, 6, 8, 10, 12,
  151597. };
  151598. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151599. _vq_quantthresh__44u9_p6_0,
  151600. _vq_quantmap__44u9_p6_0,
  151601. 13,
  151602. 13
  151603. };
  151604. static static_codebook _44u9_p6_0 = {
  151605. 2, 169,
  151606. _vq_lengthlist__44u9_p6_0,
  151607. 1, -526516224, 1616117760, 4, 0,
  151608. _vq_quantlist__44u9_p6_0,
  151609. NULL,
  151610. &_vq_auxt__44u9_p6_0,
  151611. NULL,
  151612. 0
  151613. };
  151614. static long _vq_quantlist__44u9_p6_1[] = {
  151615. 2,
  151616. 1,
  151617. 3,
  151618. 0,
  151619. 4,
  151620. };
  151621. static long _vq_lengthlist__44u9_p6_1[] = {
  151622. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151623. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151624. };
  151625. static float _vq_quantthresh__44u9_p6_1[] = {
  151626. -1.5, -0.5, 0.5, 1.5,
  151627. };
  151628. static long _vq_quantmap__44u9_p6_1[] = {
  151629. 3, 1, 0, 2, 4,
  151630. };
  151631. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151632. _vq_quantthresh__44u9_p6_1,
  151633. _vq_quantmap__44u9_p6_1,
  151634. 5,
  151635. 5
  151636. };
  151637. static static_codebook _44u9_p6_1 = {
  151638. 2, 25,
  151639. _vq_lengthlist__44u9_p6_1,
  151640. 1, -533725184, 1611661312, 3, 0,
  151641. _vq_quantlist__44u9_p6_1,
  151642. NULL,
  151643. &_vq_auxt__44u9_p6_1,
  151644. NULL,
  151645. 0
  151646. };
  151647. static long _vq_quantlist__44u9_p7_0[] = {
  151648. 6,
  151649. 5,
  151650. 7,
  151651. 4,
  151652. 8,
  151653. 3,
  151654. 9,
  151655. 2,
  151656. 10,
  151657. 1,
  151658. 11,
  151659. 0,
  151660. 12,
  151661. };
  151662. static long _vq_lengthlist__44u9_p7_0[] = {
  151663. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151664. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151665. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151666. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151667. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151668. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151669. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151670. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151671. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151672. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151673. 12,13,13,14,14,14,15,15,15,
  151674. };
  151675. static float _vq_quantthresh__44u9_p7_0[] = {
  151676. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151677. 27.5, 38.5, 49.5, 60.5,
  151678. };
  151679. static long _vq_quantmap__44u9_p7_0[] = {
  151680. 11, 9, 7, 5, 3, 1, 0, 2,
  151681. 4, 6, 8, 10, 12,
  151682. };
  151683. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151684. _vq_quantthresh__44u9_p7_0,
  151685. _vq_quantmap__44u9_p7_0,
  151686. 13,
  151687. 13
  151688. };
  151689. static static_codebook _44u9_p7_0 = {
  151690. 2, 169,
  151691. _vq_lengthlist__44u9_p7_0,
  151692. 1, -523206656, 1618345984, 4, 0,
  151693. _vq_quantlist__44u9_p7_0,
  151694. NULL,
  151695. &_vq_auxt__44u9_p7_0,
  151696. NULL,
  151697. 0
  151698. };
  151699. static long _vq_quantlist__44u9_p7_1[] = {
  151700. 5,
  151701. 4,
  151702. 6,
  151703. 3,
  151704. 7,
  151705. 2,
  151706. 8,
  151707. 1,
  151708. 9,
  151709. 0,
  151710. 10,
  151711. };
  151712. static long _vq_lengthlist__44u9_p7_1[] = {
  151713. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151714. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151715. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151716. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151717. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151718. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151719. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151720. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151721. };
  151722. static float _vq_quantthresh__44u9_p7_1[] = {
  151723. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151724. 3.5, 4.5,
  151725. };
  151726. static long _vq_quantmap__44u9_p7_1[] = {
  151727. 9, 7, 5, 3, 1, 0, 2, 4,
  151728. 6, 8, 10,
  151729. };
  151730. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151731. _vq_quantthresh__44u9_p7_1,
  151732. _vq_quantmap__44u9_p7_1,
  151733. 11,
  151734. 11
  151735. };
  151736. static static_codebook _44u9_p7_1 = {
  151737. 2, 121,
  151738. _vq_lengthlist__44u9_p7_1,
  151739. 1, -531365888, 1611661312, 4, 0,
  151740. _vq_quantlist__44u9_p7_1,
  151741. NULL,
  151742. &_vq_auxt__44u9_p7_1,
  151743. NULL,
  151744. 0
  151745. };
  151746. static long _vq_quantlist__44u9_p8_0[] = {
  151747. 7,
  151748. 6,
  151749. 8,
  151750. 5,
  151751. 9,
  151752. 4,
  151753. 10,
  151754. 3,
  151755. 11,
  151756. 2,
  151757. 12,
  151758. 1,
  151759. 13,
  151760. 0,
  151761. 14,
  151762. };
  151763. static long _vq_lengthlist__44u9_p8_0[] = {
  151764. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151765. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151766. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151767. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151768. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151769. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151770. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151771. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151772. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151773. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151774. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151775. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151776. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151777. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151778. 15,
  151779. };
  151780. static float _vq_quantthresh__44u9_p8_0[] = {
  151781. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151782. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151783. };
  151784. static long _vq_quantmap__44u9_p8_0[] = {
  151785. 13, 11, 9, 7, 5, 3, 1, 0,
  151786. 2, 4, 6, 8, 10, 12, 14,
  151787. };
  151788. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151789. _vq_quantthresh__44u9_p8_0,
  151790. _vq_quantmap__44u9_p8_0,
  151791. 15,
  151792. 15
  151793. };
  151794. static static_codebook _44u9_p8_0 = {
  151795. 2, 225,
  151796. _vq_lengthlist__44u9_p8_0,
  151797. 1, -520986624, 1620377600, 4, 0,
  151798. _vq_quantlist__44u9_p8_0,
  151799. NULL,
  151800. &_vq_auxt__44u9_p8_0,
  151801. NULL,
  151802. 0
  151803. };
  151804. static long _vq_quantlist__44u9_p8_1[] = {
  151805. 10,
  151806. 9,
  151807. 11,
  151808. 8,
  151809. 12,
  151810. 7,
  151811. 13,
  151812. 6,
  151813. 14,
  151814. 5,
  151815. 15,
  151816. 4,
  151817. 16,
  151818. 3,
  151819. 17,
  151820. 2,
  151821. 18,
  151822. 1,
  151823. 19,
  151824. 0,
  151825. 20,
  151826. };
  151827. static long _vq_lengthlist__44u9_p8_1[] = {
  151828. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151829. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151830. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  151831. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151832. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  151833. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151834. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151835. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  151836. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151837. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151838. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  151839. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  151840. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151841. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151842. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151843. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151844. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151845. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151846. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  151847. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151848. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151849. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  151850. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  151851. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  151852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151853. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  151854. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151855. 10,10,10,10,10,10,10,10,10,
  151856. };
  151857. static float _vq_quantthresh__44u9_p8_1[] = {
  151858. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151859. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151860. 6.5, 7.5, 8.5, 9.5,
  151861. };
  151862. static long _vq_quantmap__44u9_p8_1[] = {
  151863. 19, 17, 15, 13, 11, 9, 7, 5,
  151864. 3, 1, 0, 2, 4, 6, 8, 10,
  151865. 12, 14, 16, 18, 20,
  151866. };
  151867. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  151868. _vq_quantthresh__44u9_p8_1,
  151869. _vq_quantmap__44u9_p8_1,
  151870. 21,
  151871. 21
  151872. };
  151873. static static_codebook _44u9_p8_1 = {
  151874. 2, 441,
  151875. _vq_lengthlist__44u9_p8_1,
  151876. 1, -529268736, 1611661312, 5, 0,
  151877. _vq_quantlist__44u9_p8_1,
  151878. NULL,
  151879. &_vq_auxt__44u9_p8_1,
  151880. NULL,
  151881. 0
  151882. };
  151883. static long _vq_quantlist__44u9_p9_0[] = {
  151884. 7,
  151885. 6,
  151886. 8,
  151887. 5,
  151888. 9,
  151889. 4,
  151890. 10,
  151891. 3,
  151892. 11,
  151893. 2,
  151894. 12,
  151895. 1,
  151896. 13,
  151897. 0,
  151898. 14,
  151899. };
  151900. static long _vq_lengthlist__44u9_p9_0[] = {
  151901. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  151902. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  151903. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151904. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151905. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151906. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151909. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151913. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151914. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151915. 10,
  151916. };
  151917. static float _vq_quantthresh__44u9_p9_0[] = {
  151918. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  151919. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  151920. };
  151921. static long _vq_quantmap__44u9_p9_0[] = {
  151922. 13, 11, 9, 7, 5, 3, 1, 0,
  151923. 2, 4, 6, 8, 10, 12, 14,
  151924. };
  151925. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  151926. _vq_quantthresh__44u9_p9_0,
  151927. _vq_quantmap__44u9_p9_0,
  151928. 15,
  151929. 15
  151930. };
  151931. static static_codebook _44u9_p9_0 = {
  151932. 2, 225,
  151933. _vq_lengthlist__44u9_p9_0,
  151934. 1, -510036736, 1631393792, 4, 0,
  151935. _vq_quantlist__44u9_p9_0,
  151936. NULL,
  151937. &_vq_auxt__44u9_p9_0,
  151938. NULL,
  151939. 0
  151940. };
  151941. static long _vq_quantlist__44u9_p9_1[] = {
  151942. 9,
  151943. 8,
  151944. 10,
  151945. 7,
  151946. 11,
  151947. 6,
  151948. 12,
  151949. 5,
  151950. 13,
  151951. 4,
  151952. 14,
  151953. 3,
  151954. 15,
  151955. 2,
  151956. 16,
  151957. 1,
  151958. 17,
  151959. 0,
  151960. 18,
  151961. };
  151962. static long _vq_lengthlist__44u9_p9_1[] = {
  151963. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  151964. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  151965. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  151966. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  151967. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  151968. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  151969. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  151970. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  151971. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  151972. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  151973. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  151974. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  151975. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  151976. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  151977. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  151978. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  151979. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  151980. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  151981. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  151982. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  151983. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  151984. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  151985. 17,17,15,17,15,17,16,16,17,
  151986. };
  151987. static float _vq_quantthresh__44u9_p9_1[] = {
  151988. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151989. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151990. 367.5, 416.5,
  151991. };
  151992. static long _vq_quantmap__44u9_p9_1[] = {
  151993. 17, 15, 13, 11, 9, 7, 5, 3,
  151994. 1, 0, 2, 4, 6, 8, 10, 12,
  151995. 14, 16, 18,
  151996. };
  151997. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  151998. _vq_quantthresh__44u9_p9_1,
  151999. _vq_quantmap__44u9_p9_1,
  152000. 19,
  152001. 19
  152002. };
  152003. static static_codebook _44u9_p9_1 = {
  152004. 2, 361,
  152005. _vq_lengthlist__44u9_p9_1,
  152006. 1, -518287360, 1622704128, 5, 0,
  152007. _vq_quantlist__44u9_p9_1,
  152008. NULL,
  152009. &_vq_auxt__44u9_p9_1,
  152010. NULL,
  152011. 0
  152012. };
  152013. static long _vq_quantlist__44u9_p9_2[] = {
  152014. 24,
  152015. 23,
  152016. 25,
  152017. 22,
  152018. 26,
  152019. 21,
  152020. 27,
  152021. 20,
  152022. 28,
  152023. 19,
  152024. 29,
  152025. 18,
  152026. 30,
  152027. 17,
  152028. 31,
  152029. 16,
  152030. 32,
  152031. 15,
  152032. 33,
  152033. 14,
  152034. 34,
  152035. 13,
  152036. 35,
  152037. 12,
  152038. 36,
  152039. 11,
  152040. 37,
  152041. 10,
  152042. 38,
  152043. 9,
  152044. 39,
  152045. 8,
  152046. 40,
  152047. 7,
  152048. 41,
  152049. 6,
  152050. 42,
  152051. 5,
  152052. 43,
  152053. 4,
  152054. 44,
  152055. 3,
  152056. 45,
  152057. 2,
  152058. 46,
  152059. 1,
  152060. 47,
  152061. 0,
  152062. 48,
  152063. };
  152064. static long _vq_lengthlist__44u9_p9_2[] = {
  152065. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152066. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152067. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152068. 7,
  152069. };
  152070. static float _vq_quantthresh__44u9_p9_2[] = {
  152071. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152072. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152073. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152074. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152075. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152076. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152077. };
  152078. static long _vq_quantmap__44u9_p9_2[] = {
  152079. 47, 45, 43, 41, 39, 37, 35, 33,
  152080. 31, 29, 27, 25, 23, 21, 19, 17,
  152081. 15, 13, 11, 9, 7, 5, 3, 1,
  152082. 0, 2, 4, 6, 8, 10, 12, 14,
  152083. 16, 18, 20, 22, 24, 26, 28, 30,
  152084. 32, 34, 36, 38, 40, 42, 44, 46,
  152085. 48,
  152086. };
  152087. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152088. _vq_quantthresh__44u9_p9_2,
  152089. _vq_quantmap__44u9_p9_2,
  152090. 49,
  152091. 49
  152092. };
  152093. static static_codebook _44u9_p9_2 = {
  152094. 1, 49,
  152095. _vq_lengthlist__44u9_p9_2,
  152096. 1, -526909440, 1611661312, 6, 0,
  152097. _vq_quantlist__44u9_p9_2,
  152098. NULL,
  152099. &_vq_auxt__44u9_p9_2,
  152100. NULL,
  152101. 0
  152102. };
  152103. static long _huff_lengthlist__44un1__long[] = {
  152104. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152105. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152106. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152107. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152108. };
  152109. static static_codebook _huff_book__44un1__long = {
  152110. 2, 64,
  152111. _huff_lengthlist__44un1__long,
  152112. 0, 0, 0, 0, 0,
  152113. NULL,
  152114. NULL,
  152115. NULL,
  152116. NULL,
  152117. 0
  152118. };
  152119. static long _vq_quantlist__44un1__p1_0[] = {
  152120. 1,
  152121. 0,
  152122. 2,
  152123. };
  152124. static long _vq_lengthlist__44un1__p1_0[] = {
  152125. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152126. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152127. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152128. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152129. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152130. 12,
  152131. };
  152132. static float _vq_quantthresh__44un1__p1_0[] = {
  152133. -0.5, 0.5,
  152134. };
  152135. static long _vq_quantmap__44un1__p1_0[] = {
  152136. 1, 0, 2,
  152137. };
  152138. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152139. _vq_quantthresh__44un1__p1_0,
  152140. _vq_quantmap__44un1__p1_0,
  152141. 3,
  152142. 3
  152143. };
  152144. static static_codebook _44un1__p1_0 = {
  152145. 4, 81,
  152146. _vq_lengthlist__44un1__p1_0,
  152147. 1, -535822336, 1611661312, 2, 0,
  152148. _vq_quantlist__44un1__p1_0,
  152149. NULL,
  152150. &_vq_auxt__44un1__p1_0,
  152151. NULL,
  152152. 0
  152153. };
  152154. static long _vq_quantlist__44un1__p2_0[] = {
  152155. 1,
  152156. 0,
  152157. 2,
  152158. };
  152159. static long _vq_lengthlist__44un1__p2_0[] = {
  152160. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152161. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152162. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152163. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152164. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152165. 8,
  152166. };
  152167. static float _vq_quantthresh__44un1__p2_0[] = {
  152168. -0.5, 0.5,
  152169. };
  152170. static long _vq_quantmap__44un1__p2_0[] = {
  152171. 1, 0, 2,
  152172. };
  152173. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152174. _vq_quantthresh__44un1__p2_0,
  152175. _vq_quantmap__44un1__p2_0,
  152176. 3,
  152177. 3
  152178. };
  152179. static static_codebook _44un1__p2_0 = {
  152180. 4, 81,
  152181. _vq_lengthlist__44un1__p2_0,
  152182. 1, -535822336, 1611661312, 2, 0,
  152183. _vq_quantlist__44un1__p2_0,
  152184. NULL,
  152185. &_vq_auxt__44un1__p2_0,
  152186. NULL,
  152187. 0
  152188. };
  152189. static long _vq_quantlist__44un1__p3_0[] = {
  152190. 2,
  152191. 1,
  152192. 3,
  152193. 0,
  152194. 4,
  152195. };
  152196. static long _vq_lengthlist__44un1__p3_0[] = {
  152197. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152198. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152199. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152200. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152201. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152202. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152203. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152204. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152205. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152206. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152207. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152208. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152209. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152210. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152211. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152212. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152213. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152214. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152215. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152216. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152217. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152218. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152219. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152220. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152221. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152222. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152223. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152224. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152225. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152226. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152227. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152228. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152229. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152230. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152231. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152232. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152233. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152234. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152235. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152236. 17,
  152237. };
  152238. static float _vq_quantthresh__44un1__p3_0[] = {
  152239. -1.5, -0.5, 0.5, 1.5,
  152240. };
  152241. static long _vq_quantmap__44un1__p3_0[] = {
  152242. 3, 1, 0, 2, 4,
  152243. };
  152244. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152245. _vq_quantthresh__44un1__p3_0,
  152246. _vq_quantmap__44un1__p3_0,
  152247. 5,
  152248. 5
  152249. };
  152250. static static_codebook _44un1__p3_0 = {
  152251. 4, 625,
  152252. _vq_lengthlist__44un1__p3_0,
  152253. 1, -533725184, 1611661312, 3, 0,
  152254. _vq_quantlist__44un1__p3_0,
  152255. NULL,
  152256. &_vq_auxt__44un1__p3_0,
  152257. NULL,
  152258. 0
  152259. };
  152260. static long _vq_quantlist__44un1__p4_0[] = {
  152261. 2,
  152262. 1,
  152263. 3,
  152264. 0,
  152265. 4,
  152266. };
  152267. static long _vq_lengthlist__44un1__p4_0[] = {
  152268. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152269. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152270. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152271. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152272. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152273. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152274. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152275. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152276. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152277. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152278. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152279. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152280. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152281. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152282. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152283. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152284. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152285. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152286. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152287. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152288. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152289. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152290. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152291. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152292. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152293. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152294. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152295. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152296. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152297. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152298. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152299. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152300. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152301. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152302. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152303. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152304. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152305. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152306. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152307. 12,
  152308. };
  152309. static float _vq_quantthresh__44un1__p4_0[] = {
  152310. -1.5, -0.5, 0.5, 1.5,
  152311. };
  152312. static long _vq_quantmap__44un1__p4_0[] = {
  152313. 3, 1, 0, 2, 4,
  152314. };
  152315. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152316. _vq_quantthresh__44un1__p4_0,
  152317. _vq_quantmap__44un1__p4_0,
  152318. 5,
  152319. 5
  152320. };
  152321. static static_codebook _44un1__p4_0 = {
  152322. 4, 625,
  152323. _vq_lengthlist__44un1__p4_0,
  152324. 1, -533725184, 1611661312, 3, 0,
  152325. _vq_quantlist__44un1__p4_0,
  152326. NULL,
  152327. &_vq_auxt__44un1__p4_0,
  152328. NULL,
  152329. 0
  152330. };
  152331. static long _vq_quantlist__44un1__p5_0[] = {
  152332. 4,
  152333. 3,
  152334. 5,
  152335. 2,
  152336. 6,
  152337. 1,
  152338. 7,
  152339. 0,
  152340. 8,
  152341. };
  152342. static long _vq_lengthlist__44un1__p5_0[] = {
  152343. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152344. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152345. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152346. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152347. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152348. 12,
  152349. };
  152350. static float _vq_quantthresh__44un1__p5_0[] = {
  152351. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152352. };
  152353. static long _vq_quantmap__44un1__p5_0[] = {
  152354. 7, 5, 3, 1, 0, 2, 4, 6,
  152355. 8,
  152356. };
  152357. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152358. _vq_quantthresh__44un1__p5_0,
  152359. _vq_quantmap__44un1__p5_0,
  152360. 9,
  152361. 9
  152362. };
  152363. static static_codebook _44un1__p5_0 = {
  152364. 2, 81,
  152365. _vq_lengthlist__44un1__p5_0,
  152366. 1, -531628032, 1611661312, 4, 0,
  152367. _vq_quantlist__44un1__p5_0,
  152368. NULL,
  152369. &_vq_auxt__44un1__p5_0,
  152370. NULL,
  152371. 0
  152372. };
  152373. static long _vq_quantlist__44un1__p6_0[] = {
  152374. 6,
  152375. 5,
  152376. 7,
  152377. 4,
  152378. 8,
  152379. 3,
  152380. 9,
  152381. 2,
  152382. 10,
  152383. 1,
  152384. 11,
  152385. 0,
  152386. 12,
  152387. };
  152388. static long _vq_lengthlist__44un1__p6_0[] = {
  152389. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152390. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152391. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152392. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152393. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152394. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152395. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152396. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152397. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152398. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152399. 16, 0,15,18,18, 0,16, 0, 0,
  152400. };
  152401. static float _vq_quantthresh__44un1__p6_0[] = {
  152402. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152403. 12.5, 17.5, 22.5, 27.5,
  152404. };
  152405. static long _vq_quantmap__44un1__p6_0[] = {
  152406. 11, 9, 7, 5, 3, 1, 0, 2,
  152407. 4, 6, 8, 10, 12,
  152408. };
  152409. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152410. _vq_quantthresh__44un1__p6_0,
  152411. _vq_quantmap__44un1__p6_0,
  152412. 13,
  152413. 13
  152414. };
  152415. static static_codebook _44un1__p6_0 = {
  152416. 2, 169,
  152417. _vq_lengthlist__44un1__p6_0,
  152418. 1, -526516224, 1616117760, 4, 0,
  152419. _vq_quantlist__44un1__p6_0,
  152420. NULL,
  152421. &_vq_auxt__44un1__p6_0,
  152422. NULL,
  152423. 0
  152424. };
  152425. static long _vq_quantlist__44un1__p6_1[] = {
  152426. 2,
  152427. 1,
  152428. 3,
  152429. 0,
  152430. 4,
  152431. };
  152432. static long _vq_lengthlist__44un1__p6_1[] = {
  152433. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152434. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152435. };
  152436. static float _vq_quantthresh__44un1__p6_1[] = {
  152437. -1.5, -0.5, 0.5, 1.5,
  152438. };
  152439. static long _vq_quantmap__44un1__p6_1[] = {
  152440. 3, 1, 0, 2, 4,
  152441. };
  152442. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152443. _vq_quantthresh__44un1__p6_1,
  152444. _vq_quantmap__44un1__p6_1,
  152445. 5,
  152446. 5
  152447. };
  152448. static static_codebook _44un1__p6_1 = {
  152449. 2, 25,
  152450. _vq_lengthlist__44un1__p6_1,
  152451. 1, -533725184, 1611661312, 3, 0,
  152452. _vq_quantlist__44un1__p6_1,
  152453. NULL,
  152454. &_vq_auxt__44un1__p6_1,
  152455. NULL,
  152456. 0
  152457. };
  152458. static long _vq_quantlist__44un1__p7_0[] = {
  152459. 2,
  152460. 1,
  152461. 3,
  152462. 0,
  152463. 4,
  152464. };
  152465. static long _vq_lengthlist__44un1__p7_0[] = {
  152466. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152467. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152469. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152471. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152472. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152473. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152476. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152479. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152480. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152481. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152482. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152483. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152502. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152503. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152504. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152505. 10,
  152506. };
  152507. static float _vq_quantthresh__44un1__p7_0[] = {
  152508. -253.5, -84.5, 84.5, 253.5,
  152509. };
  152510. static long _vq_quantmap__44un1__p7_0[] = {
  152511. 3, 1, 0, 2, 4,
  152512. };
  152513. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152514. _vq_quantthresh__44un1__p7_0,
  152515. _vq_quantmap__44un1__p7_0,
  152516. 5,
  152517. 5
  152518. };
  152519. static static_codebook _44un1__p7_0 = {
  152520. 4, 625,
  152521. _vq_lengthlist__44un1__p7_0,
  152522. 1, -518709248, 1626677248, 3, 0,
  152523. _vq_quantlist__44un1__p7_0,
  152524. NULL,
  152525. &_vq_auxt__44un1__p7_0,
  152526. NULL,
  152527. 0
  152528. };
  152529. static long _vq_quantlist__44un1__p7_1[] = {
  152530. 6,
  152531. 5,
  152532. 7,
  152533. 4,
  152534. 8,
  152535. 3,
  152536. 9,
  152537. 2,
  152538. 10,
  152539. 1,
  152540. 11,
  152541. 0,
  152542. 12,
  152543. };
  152544. static long _vq_lengthlist__44un1__p7_1[] = {
  152545. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152546. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152547. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152548. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152549. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152550. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152551. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152552. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152553. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152554. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152555. 12,13,13,12,13,13,14,14,14,
  152556. };
  152557. static float _vq_quantthresh__44un1__p7_1[] = {
  152558. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152559. 32.5, 45.5, 58.5, 71.5,
  152560. };
  152561. static long _vq_quantmap__44un1__p7_1[] = {
  152562. 11, 9, 7, 5, 3, 1, 0, 2,
  152563. 4, 6, 8, 10, 12,
  152564. };
  152565. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152566. _vq_quantthresh__44un1__p7_1,
  152567. _vq_quantmap__44un1__p7_1,
  152568. 13,
  152569. 13
  152570. };
  152571. static static_codebook _44un1__p7_1 = {
  152572. 2, 169,
  152573. _vq_lengthlist__44un1__p7_1,
  152574. 1, -523010048, 1618608128, 4, 0,
  152575. _vq_quantlist__44un1__p7_1,
  152576. NULL,
  152577. &_vq_auxt__44un1__p7_1,
  152578. NULL,
  152579. 0
  152580. };
  152581. static long _vq_quantlist__44un1__p7_2[] = {
  152582. 6,
  152583. 5,
  152584. 7,
  152585. 4,
  152586. 8,
  152587. 3,
  152588. 9,
  152589. 2,
  152590. 10,
  152591. 1,
  152592. 11,
  152593. 0,
  152594. 12,
  152595. };
  152596. static long _vq_lengthlist__44un1__p7_2[] = {
  152597. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152598. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152599. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152600. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152601. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152602. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152603. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152604. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152605. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152606. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152607. 9, 9, 9,10,10,10,10,10,10,
  152608. };
  152609. static float _vq_quantthresh__44un1__p7_2[] = {
  152610. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152611. 2.5, 3.5, 4.5, 5.5,
  152612. };
  152613. static long _vq_quantmap__44un1__p7_2[] = {
  152614. 11, 9, 7, 5, 3, 1, 0, 2,
  152615. 4, 6, 8, 10, 12,
  152616. };
  152617. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152618. _vq_quantthresh__44un1__p7_2,
  152619. _vq_quantmap__44un1__p7_2,
  152620. 13,
  152621. 13
  152622. };
  152623. static static_codebook _44un1__p7_2 = {
  152624. 2, 169,
  152625. _vq_lengthlist__44un1__p7_2,
  152626. 1, -531103744, 1611661312, 4, 0,
  152627. _vq_quantlist__44un1__p7_2,
  152628. NULL,
  152629. &_vq_auxt__44un1__p7_2,
  152630. NULL,
  152631. 0
  152632. };
  152633. static long _huff_lengthlist__44un1__short[] = {
  152634. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152635. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152636. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152637. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152638. };
  152639. static static_codebook _huff_book__44un1__short = {
  152640. 2, 64,
  152641. _huff_lengthlist__44un1__short,
  152642. 0, 0, 0, 0, 0,
  152643. NULL,
  152644. NULL,
  152645. NULL,
  152646. NULL,
  152647. 0
  152648. };
  152649. /*** End of inlined file: res_books_uncoupled.h ***/
  152650. /***** residue backends *********************************************/
  152651. static vorbis_info_residue0 _residue_44_low_un={
  152652. 0,-1, -1, 8,-1,
  152653. {0},
  152654. {-1},
  152655. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152656. { -1, 25, -1, 45, -1, -1, -1}
  152657. };
  152658. static vorbis_info_residue0 _residue_44_mid_un={
  152659. 0,-1, -1, 10,-1,
  152660. /* 0 1 2 3 4 5 6 7 8 9 */
  152661. {0},
  152662. {-1},
  152663. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152664. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152665. };
  152666. static vorbis_info_residue0 _residue_44_hi_un={
  152667. 0,-1, -1, 10,-1,
  152668. /* 0 1 2 3 4 5 6 7 8 9 */
  152669. {0},
  152670. {-1},
  152671. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152672. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152673. };
  152674. /* mapping conventions:
  152675. only one submap (this would change for efficient 5.1 support for example)*/
  152676. /* Four psychoacoustic profiles are used, one for each blocktype */
  152677. static vorbis_info_mapping0 _map_nominal_u[2]={
  152678. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152679. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152680. };
  152681. static static_bookblock _resbook_44u_n1={
  152682. {
  152683. {0},
  152684. {0,0,&_44un1__p1_0},
  152685. {0,0,&_44un1__p2_0},
  152686. {0,0,&_44un1__p3_0},
  152687. {0,0,&_44un1__p4_0},
  152688. {0,0,&_44un1__p5_0},
  152689. {&_44un1__p6_0,&_44un1__p6_1},
  152690. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152691. }
  152692. };
  152693. static static_bookblock _resbook_44u_0={
  152694. {
  152695. {0},
  152696. {0,0,&_44u0__p1_0},
  152697. {0,0,&_44u0__p2_0},
  152698. {0,0,&_44u0__p3_0},
  152699. {0,0,&_44u0__p4_0},
  152700. {0,0,&_44u0__p5_0},
  152701. {&_44u0__p6_0,&_44u0__p6_1},
  152702. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152703. }
  152704. };
  152705. static static_bookblock _resbook_44u_1={
  152706. {
  152707. {0},
  152708. {0,0,&_44u1__p1_0},
  152709. {0,0,&_44u1__p2_0},
  152710. {0,0,&_44u1__p3_0},
  152711. {0,0,&_44u1__p4_0},
  152712. {0,0,&_44u1__p5_0},
  152713. {&_44u1__p6_0,&_44u1__p6_1},
  152714. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152715. }
  152716. };
  152717. static static_bookblock _resbook_44u_2={
  152718. {
  152719. {0},
  152720. {0,0,&_44u2__p1_0},
  152721. {0,0,&_44u2__p2_0},
  152722. {0,0,&_44u2__p3_0},
  152723. {0,0,&_44u2__p4_0},
  152724. {0,0,&_44u2__p5_0},
  152725. {&_44u2__p6_0,&_44u2__p6_1},
  152726. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152727. }
  152728. };
  152729. static static_bookblock _resbook_44u_3={
  152730. {
  152731. {0},
  152732. {0,0,&_44u3__p1_0},
  152733. {0,0,&_44u3__p2_0},
  152734. {0,0,&_44u3__p3_0},
  152735. {0,0,&_44u3__p4_0},
  152736. {0,0,&_44u3__p5_0},
  152737. {&_44u3__p6_0,&_44u3__p6_1},
  152738. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152739. }
  152740. };
  152741. static static_bookblock _resbook_44u_4={
  152742. {
  152743. {0},
  152744. {0,0,&_44u4__p1_0},
  152745. {0,0,&_44u4__p2_0},
  152746. {0,0,&_44u4__p3_0},
  152747. {0,0,&_44u4__p4_0},
  152748. {0,0,&_44u4__p5_0},
  152749. {&_44u4__p6_0,&_44u4__p6_1},
  152750. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152751. }
  152752. };
  152753. static static_bookblock _resbook_44u_5={
  152754. {
  152755. {0},
  152756. {0,0,&_44u5__p1_0},
  152757. {0,0,&_44u5__p2_0},
  152758. {0,0,&_44u5__p3_0},
  152759. {0,0,&_44u5__p4_0},
  152760. {0,0,&_44u5__p5_0},
  152761. {0,0,&_44u5__p6_0},
  152762. {&_44u5__p7_0,&_44u5__p7_1},
  152763. {&_44u5__p8_0,&_44u5__p8_1},
  152764. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152765. }
  152766. };
  152767. static static_bookblock _resbook_44u_6={
  152768. {
  152769. {0},
  152770. {0,0,&_44u6__p1_0},
  152771. {0,0,&_44u6__p2_0},
  152772. {0,0,&_44u6__p3_0},
  152773. {0,0,&_44u6__p4_0},
  152774. {0,0,&_44u6__p5_0},
  152775. {0,0,&_44u6__p6_0},
  152776. {&_44u6__p7_0,&_44u6__p7_1},
  152777. {&_44u6__p8_0,&_44u6__p8_1},
  152778. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152779. }
  152780. };
  152781. static static_bookblock _resbook_44u_7={
  152782. {
  152783. {0},
  152784. {0,0,&_44u7__p1_0},
  152785. {0,0,&_44u7__p2_0},
  152786. {0,0,&_44u7__p3_0},
  152787. {0,0,&_44u7__p4_0},
  152788. {0,0,&_44u7__p5_0},
  152789. {0,0,&_44u7__p6_0},
  152790. {&_44u7__p7_0,&_44u7__p7_1},
  152791. {&_44u7__p8_0,&_44u7__p8_1},
  152792. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152793. }
  152794. };
  152795. static static_bookblock _resbook_44u_8={
  152796. {
  152797. {0},
  152798. {0,0,&_44u8_p1_0},
  152799. {0,0,&_44u8_p2_0},
  152800. {0,0,&_44u8_p3_0},
  152801. {0,0,&_44u8_p4_0},
  152802. {&_44u8_p5_0,&_44u8_p5_1},
  152803. {&_44u8_p6_0,&_44u8_p6_1},
  152804. {&_44u8_p7_0,&_44u8_p7_1},
  152805. {&_44u8_p8_0,&_44u8_p8_1},
  152806. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152807. }
  152808. };
  152809. static static_bookblock _resbook_44u_9={
  152810. {
  152811. {0},
  152812. {0,0,&_44u9_p1_0},
  152813. {0,0,&_44u9_p2_0},
  152814. {0,0,&_44u9_p3_0},
  152815. {0,0,&_44u9_p4_0},
  152816. {&_44u9_p5_0,&_44u9_p5_1},
  152817. {&_44u9_p6_0,&_44u9_p6_1},
  152818. {&_44u9_p7_0,&_44u9_p7_1},
  152819. {&_44u9_p8_0,&_44u9_p8_1},
  152820. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  152821. }
  152822. };
  152823. static vorbis_residue_template _res_44u_n1[]={
  152824. {1,0, &_residue_44_low_un,
  152825. &_huff_book__44un1__short,&_huff_book__44un1__short,
  152826. &_resbook_44u_n1,&_resbook_44u_n1},
  152827. {1,0, &_residue_44_low_un,
  152828. &_huff_book__44un1__long,&_huff_book__44un1__long,
  152829. &_resbook_44u_n1,&_resbook_44u_n1}
  152830. };
  152831. static vorbis_residue_template _res_44u_0[]={
  152832. {1,0, &_residue_44_low_un,
  152833. &_huff_book__44u0__short,&_huff_book__44u0__short,
  152834. &_resbook_44u_0,&_resbook_44u_0},
  152835. {1,0, &_residue_44_low_un,
  152836. &_huff_book__44u0__long,&_huff_book__44u0__long,
  152837. &_resbook_44u_0,&_resbook_44u_0}
  152838. };
  152839. static vorbis_residue_template _res_44u_1[]={
  152840. {1,0, &_residue_44_low_un,
  152841. &_huff_book__44u1__short,&_huff_book__44u1__short,
  152842. &_resbook_44u_1,&_resbook_44u_1},
  152843. {1,0, &_residue_44_low_un,
  152844. &_huff_book__44u1__long,&_huff_book__44u1__long,
  152845. &_resbook_44u_1,&_resbook_44u_1}
  152846. };
  152847. static vorbis_residue_template _res_44u_2[]={
  152848. {1,0, &_residue_44_low_un,
  152849. &_huff_book__44u2__short,&_huff_book__44u2__short,
  152850. &_resbook_44u_2,&_resbook_44u_2},
  152851. {1,0, &_residue_44_low_un,
  152852. &_huff_book__44u2__long,&_huff_book__44u2__long,
  152853. &_resbook_44u_2,&_resbook_44u_2}
  152854. };
  152855. static vorbis_residue_template _res_44u_3[]={
  152856. {1,0, &_residue_44_low_un,
  152857. &_huff_book__44u3__short,&_huff_book__44u3__short,
  152858. &_resbook_44u_3,&_resbook_44u_3},
  152859. {1,0, &_residue_44_low_un,
  152860. &_huff_book__44u3__long,&_huff_book__44u3__long,
  152861. &_resbook_44u_3,&_resbook_44u_3}
  152862. };
  152863. static vorbis_residue_template _res_44u_4[]={
  152864. {1,0, &_residue_44_low_un,
  152865. &_huff_book__44u4__short,&_huff_book__44u4__short,
  152866. &_resbook_44u_4,&_resbook_44u_4},
  152867. {1,0, &_residue_44_low_un,
  152868. &_huff_book__44u4__long,&_huff_book__44u4__long,
  152869. &_resbook_44u_4,&_resbook_44u_4}
  152870. };
  152871. static vorbis_residue_template _res_44u_5[]={
  152872. {1,0, &_residue_44_mid_un,
  152873. &_huff_book__44u5__short,&_huff_book__44u5__short,
  152874. &_resbook_44u_5,&_resbook_44u_5},
  152875. {1,0, &_residue_44_mid_un,
  152876. &_huff_book__44u5__long,&_huff_book__44u5__long,
  152877. &_resbook_44u_5,&_resbook_44u_5}
  152878. };
  152879. static vorbis_residue_template _res_44u_6[]={
  152880. {1,0, &_residue_44_mid_un,
  152881. &_huff_book__44u6__short,&_huff_book__44u6__short,
  152882. &_resbook_44u_6,&_resbook_44u_6},
  152883. {1,0, &_residue_44_mid_un,
  152884. &_huff_book__44u6__long,&_huff_book__44u6__long,
  152885. &_resbook_44u_6,&_resbook_44u_6}
  152886. };
  152887. static vorbis_residue_template _res_44u_7[]={
  152888. {1,0, &_residue_44_mid_un,
  152889. &_huff_book__44u7__short,&_huff_book__44u7__short,
  152890. &_resbook_44u_7,&_resbook_44u_7},
  152891. {1,0, &_residue_44_mid_un,
  152892. &_huff_book__44u7__long,&_huff_book__44u7__long,
  152893. &_resbook_44u_7,&_resbook_44u_7}
  152894. };
  152895. static vorbis_residue_template _res_44u_8[]={
  152896. {1,0, &_residue_44_hi_un,
  152897. &_huff_book__44u8__short,&_huff_book__44u8__short,
  152898. &_resbook_44u_8,&_resbook_44u_8},
  152899. {1,0, &_residue_44_hi_un,
  152900. &_huff_book__44u8__long,&_huff_book__44u8__long,
  152901. &_resbook_44u_8,&_resbook_44u_8}
  152902. };
  152903. static vorbis_residue_template _res_44u_9[]={
  152904. {1,0, &_residue_44_hi_un,
  152905. &_huff_book__44u9__short,&_huff_book__44u9__short,
  152906. &_resbook_44u_9,&_resbook_44u_9},
  152907. {1,0, &_residue_44_hi_un,
  152908. &_huff_book__44u9__long,&_huff_book__44u9__long,
  152909. &_resbook_44u_9,&_resbook_44u_9}
  152910. };
  152911. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  152912. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  152913. { _map_nominal_u, _res_44u_0 }, /* 0 */
  152914. { _map_nominal_u, _res_44u_1 }, /* 1 */
  152915. { _map_nominal_u, _res_44u_2 }, /* 2 */
  152916. { _map_nominal_u, _res_44u_3 }, /* 3 */
  152917. { _map_nominal_u, _res_44u_4 }, /* 4 */
  152918. { _map_nominal_u, _res_44u_5 }, /* 5 */
  152919. { _map_nominal_u, _res_44u_6 }, /* 6 */
  152920. { _map_nominal_u, _res_44u_7 }, /* 7 */
  152921. { _map_nominal_u, _res_44u_8 }, /* 8 */
  152922. { _map_nominal_u, _res_44u_9 }, /* 9 */
  152923. };
  152924. /*** End of inlined file: residue_44u.h ***/
  152925. static double rate_mapping_44_un[12]={
  152926. 32000.,48000.,60000.,70000.,80000.,86000.,
  152927. 96000.,110000.,120000.,140000.,160000.,240001.
  152928. };
  152929. ve_setup_data_template ve_setup_44_uncoupled={
  152930. 11,
  152931. rate_mapping_44_un,
  152932. quality_mapping_44,
  152933. -1,
  152934. 40000,
  152935. 50000,
  152936. blocksize_short_44,
  152937. blocksize_long_44,
  152938. _psy_tone_masteratt_44,
  152939. _psy_tone_0dB,
  152940. _psy_tone_suppress,
  152941. _vp_tonemask_adj_otherblock,
  152942. _vp_tonemask_adj_longblock,
  152943. _vp_tonemask_adj_otherblock,
  152944. _psy_noiseguards_44,
  152945. _psy_noisebias_impulse,
  152946. _psy_noisebias_padding,
  152947. _psy_noisebias_trans,
  152948. _psy_noisebias_long,
  152949. _psy_noise_suppress,
  152950. _psy_compand_44,
  152951. _psy_compand_short_mapping,
  152952. _psy_compand_long_mapping,
  152953. {_noise_start_short_44,_noise_start_long_44},
  152954. {_noise_part_short_44,_noise_part_long_44},
  152955. _noise_thresh_44,
  152956. _psy_ath_floater,
  152957. _psy_ath_abs,
  152958. _psy_lowpass_44,
  152959. _psy_global_44,
  152960. _global_mapping_44,
  152961. NULL,
  152962. _floor_books,
  152963. _floor,
  152964. _floor_short_mapping_44,
  152965. _floor_long_mapping_44,
  152966. _mapres_template_44_uncoupled
  152967. };
  152968. /*** End of inlined file: setup_44u.h ***/
  152969. /*** Start of inlined file: setup_32.h ***/
  152970. static double rate_mapping_32[12]={
  152971. 18000.,28000.,35000.,45000.,56000.,60000.,
  152972. 75000.,90000.,100000.,115000.,150000.,190000.,
  152973. };
  152974. static double rate_mapping_32_un[12]={
  152975. 30000.,42000.,52000.,64000.,72000.,78000.,
  152976. 86000.,92000.,110000.,120000.,140000.,190000.,
  152977. };
  152978. static double _psy_lowpass_32[12]={
  152979. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  152980. };
  152981. ve_setup_data_template ve_setup_32_stereo={
  152982. 11,
  152983. rate_mapping_32,
  152984. quality_mapping_44,
  152985. 2,
  152986. 26000,
  152987. 40000,
  152988. blocksize_short_44,
  152989. blocksize_long_44,
  152990. _psy_tone_masteratt_44,
  152991. _psy_tone_0dB,
  152992. _psy_tone_suppress,
  152993. _vp_tonemask_adj_otherblock,
  152994. _vp_tonemask_adj_longblock,
  152995. _vp_tonemask_adj_otherblock,
  152996. _psy_noiseguards_44,
  152997. _psy_noisebias_impulse,
  152998. _psy_noisebias_padding,
  152999. _psy_noisebias_trans,
  153000. _psy_noisebias_long,
  153001. _psy_noise_suppress,
  153002. _psy_compand_44,
  153003. _psy_compand_short_mapping,
  153004. _psy_compand_long_mapping,
  153005. {_noise_start_short_44,_noise_start_long_44},
  153006. {_noise_part_short_44,_noise_part_long_44},
  153007. _noise_thresh_44,
  153008. _psy_ath_floater,
  153009. _psy_ath_abs,
  153010. _psy_lowpass_32,
  153011. _psy_global_44,
  153012. _global_mapping_44,
  153013. _psy_stereo_modes_44,
  153014. _floor_books,
  153015. _floor,
  153016. _floor_short_mapping_44,
  153017. _floor_long_mapping_44,
  153018. _mapres_template_44_stereo
  153019. };
  153020. ve_setup_data_template ve_setup_32_uncoupled={
  153021. 11,
  153022. rate_mapping_32_un,
  153023. quality_mapping_44,
  153024. -1,
  153025. 26000,
  153026. 40000,
  153027. blocksize_short_44,
  153028. blocksize_long_44,
  153029. _psy_tone_masteratt_44,
  153030. _psy_tone_0dB,
  153031. _psy_tone_suppress,
  153032. _vp_tonemask_adj_otherblock,
  153033. _vp_tonemask_adj_longblock,
  153034. _vp_tonemask_adj_otherblock,
  153035. _psy_noiseguards_44,
  153036. _psy_noisebias_impulse,
  153037. _psy_noisebias_padding,
  153038. _psy_noisebias_trans,
  153039. _psy_noisebias_long,
  153040. _psy_noise_suppress,
  153041. _psy_compand_44,
  153042. _psy_compand_short_mapping,
  153043. _psy_compand_long_mapping,
  153044. {_noise_start_short_44,_noise_start_long_44},
  153045. {_noise_part_short_44,_noise_part_long_44},
  153046. _noise_thresh_44,
  153047. _psy_ath_floater,
  153048. _psy_ath_abs,
  153049. _psy_lowpass_32,
  153050. _psy_global_44,
  153051. _global_mapping_44,
  153052. NULL,
  153053. _floor_books,
  153054. _floor,
  153055. _floor_short_mapping_44,
  153056. _floor_long_mapping_44,
  153057. _mapres_template_44_uncoupled
  153058. };
  153059. /*** End of inlined file: setup_32.h ***/
  153060. /*** Start of inlined file: setup_8.h ***/
  153061. /*** Start of inlined file: psych_8.h ***/
  153062. static att3 _psy_tone_masteratt_8[3]={
  153063. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153064. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153065. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153066. };
  153067. static vp_adjblock _vp_tonemask_adj_8[3]={
  153068. /* adjust for mode zero */
  153069. /* 63 125 250 500 1 2 4 8 16 */
  153070. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153071. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153072. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153073. };
  153074. static noise3 _psy_noisebias_8[3]={
  153075. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153076. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153077. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153078. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153079. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153080. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153081. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153082. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153083. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153084. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153085. };
  153086. /* stereo mode by base quality level */
  153087. static adj_stereo _psy_stereo_modes_8[3]={
  153088. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153089. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153090. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153091. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153092. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153093. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153094. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153095. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153096. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153097. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153098. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153099. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153100. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153101. };
  153102. static noiseguard _psy_noiseguards_8[2]={
  153103. {10,10,-1},
  153104. {10,10,-1},
  153105. };
  153106. static compandblock _psy_compand_8[2]={
  153107. {{
  153108. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153109. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153110. 12,12,13,13,14,14,15, 15, /* 23dB */
  153111. 16,16,17,17,17,18,18, 19, /* 31dB */
  153112. 19,19,20,21,22,23,24, 25, /* 39dB */
  153113. }},
  153114. {{
  153115. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153116. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153117. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153118. 9,10,11,12,13,14,15, 16, /* 31dB */
  153119. 17,18,19,20,21,22,23, 24, /* 39dB */
  153120. }},
  153121. };
  153122. static double _psy_lowpass_8[3]={3.,4.,4.};
  153123. static int _noise_start_8[2]={
  153124. 64,64,
  153125. };
  153126. static int _noise_part_8[2]={
  153127. 8,8,
  153128. };
  153129. static int _psy_ath_floater_8[3]={
  153130. -100,-100,-105,
  153131. };
  153132. static int _psy_ath_abs_8[3]={
  153133. -130,-130,-140,
  153134. };
  153135. /*** End of inlined file: psych_8.h ***/
  153136. /*** Start of inlined file: residue_8.h ***/
  153137. /***** residue backends *********************************************/
  153138. static static_bookblock _resbook_8s_0={
  153139. {
  153140. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153141. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153142. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153143. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153144. }
  153145. };
  153146. static static_bookblock _resbook_8s_1={
  153147. {
  153148. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153149. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153150. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153151. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153152. }
  153153. };
  153154. static vorbis_residue_template _res_8s_0[]={
  153155. {2,0, &_residue_44_mid,
  153156. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153157. &_resbook_8s_0,&_resbook_8s_0},
  153158. };
  153159. static vorbis_residue_template _res_8s_1[]={
  153160. {2,0, &_residue_44_mid,
  153161. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153162. &_resbook_8s_1,&_resbook_8s_1},
  153163. };
  153164. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153165. { _map_nominal, _res_8s_0 }, /* 0 */
  153166. { _map_nominal, _res_8s_1 }, /* 1 */
  153167. };
  153168. static static_bookblock _resbook_8u_0={
  153169. {
  153170. {0},
  153171. {0,0,&_8u0__p1_0},
  153172. {0,0,&_8u0__p2_0},
  153173. {0,0,&_8u0__p3_0},
  153174. {0,0,&_8u0__p4_0},
  153175. {0,0,&_8u0__p5_0},
  153176. {&_8u0__p6_0,&_8u0__p6_1},
  153177. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153178. }
  153179. };
  153180. static static_bookblock _resbook_8u_1={
  153181. {
  153182. {0},
  153183. {0,0,&_8u1__p1_0},
  153184. {0,0,&_8u1__p2_0},
  153185. {0,0,&_8u1__p3_0},
  153186. {0,0,&_8u1__p4_0},
  153187. {0,0,&_8u1__p5_0},
  153188. {0,0,&_8u1__p6_0},
  153189. {&_8u1__p7_0,&_8u1__p7_1},
  153190. {&_8u1__p8_0,&_8u1__p8_1},
  153191. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153192. }
  153193. };
  153194. static vorbis_residue_template _res_8u_0[]={
  153195. {1,0, &_residue_44_low_un,
  153196. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153197. &_resbook_8u_0,&_resbook_8u_0},
  153198. };
  153199. static vorbis_residue_template _res_8u_1[]={
  153200. {1,0, &_residue_44_mid_un,
  153201. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153202. &_resbook_8u_1,&_resbook_8u_1},
  153203. };
  153204. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153205. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153206. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153207. };
  153208. /*** End of inlined file: residue_8.h ***/
  153209. static int blocksize_8[2]={
  153210. 512,512
  153211. };
  153212. static int _floor_mapping_8[2]={
  153213. 6,6,
  153214. };
  153215. static double rate_mapping_8[3]={
  153216. 6000.,9000.,32000.,
  153217. };
  153218. static double rate_mapping_8_uncoupled[3]={
  153219. 8000.,14000.,42000.,
  153220. };
  153221. static double quality_mapping_8[3]={
  153222. -.1,.0,1.
  153223. };
  153224. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153225. static double _global_mapping_8[3]={ 1., 2., 3. };
  153226. ve_setup_data_template ve_setup_8_stereo={
  153227. 2,
  153228. rate_mapping_8,
  153229. quality_mapping_8,
  153230. 2,
  153231. 8000,
  153232. 9000,
  153233. blocksize_8,
  153234. blocksize_8,
  153235. _psy_tone_masteratt_8,
  153236. _psy_tone_0dB,
  153237. _psy_tone_suppress,
  153238. _vp_tonemask_adj_8,
  153239. NULL,
  153240. _vp_tonemask_adj_8,
  153241. _psy_noiseguards_8,
  153242. _psy_noisebias_8,
  153243. _psy_noisebias_8,
  153244. NULL,
  153245. NULL,
  153246. _psy_noise_suppress,
  153247. _psy_compand_8,
  153248. _psy_compand_8_mapping,
  153249. NULL,
  153250. {_noise_start_8,_noise_start_8},
  153251. {_noise_part_8,_noise_part_8},
  153252. _noise_thresh_5only,
  153253. _psy_ath_floater_8,
  153254. _psy_ath_abs_8,
  153255. _psy_lowpass_8,
  153256. _psy_global_44,
  153257. _global_mapping_8,
  153258. _psy_stereo_modes_8,
  153259. _floor_books,
  153260. _floor,
  153261. _floor_mapping_8,
  153262. NULL,
  153263. _mapres_template_8_stereo
  153264. };
  153265. ve_setup_data_template ve_setup_8_uncoupled={
  153266. 2,
  153267. rate_mapping_8_uncoupled,
  153268. quality_mapping_8,
  153269. -1,
  153270. 8000,
  153271. 9000,
  153272. blocksize_8,
  153273. blocksize_8,
  153274. _psy_tone_masteratt_8,
  153275. _psy_tone_0dB,
  153276. _psy_tone_suppress,
  153277. _vp_tonemask_adj_8,
  153278. NULL,
  153279. _vp_tonemask_adj_8,
  153280. _psy_noiseguards_8,
  153281. _psy_noisebias_8,
  153282. _psy_noisebias_8,
  153283. NULL,
  153284. NULL,
  153285. _psy_noise_suppress,
  153286. _psy_compand_8,
  153287. _psy_compand_8_mapping,
  153288. NULL,
  153289. {_noise_start_8,_noise_start_8},
  153290. {_noise_part_8,_noise_part_8},
  153291. _noise_thresh_5only,
  153292. _psy_ath_floater_8,
  153293. _psy_ath_abs_8,
  153294. _psy_lowpass_8,
  153295. _psy_global_44,
  153296. _global_mapping_8,
  153297. _psy_stereo_modes_8,
  153298. _floor_books,
  153299. _floor,
  153300. _floor_mapping_8,
  153301. NULL,
  153302. _mapres_template_8_uncoupled
  153303. };
  153304. /*** End of inlined file: setup_8.h ***/
  153305. /*** Start of inlined file: setup_11.h ***/
  153306. /*** Start of inlined file: psych_11.h ***/
  153307. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153308. static att3 _psy_tone_masteratt_11[3]={
  153309. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153310. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153311. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153312. };
  153313. static vp_adjblock _vp_tonemask_adj_11[3]={
  153314. /* adjust for mode zero */
  153315. /* 63 125 250 500 1 2 4 8 16 */
  153316. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153317. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153318. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153319. };
  153320. static noise3 _psy_noisebias_11[3]={
  153321. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153322. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153323. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153324. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153325. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153326. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153327. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153328. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153329. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153330. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153331. };
  153332. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153333. /*** End of inlined file: psych_11.h ***/
  153334. static int blocksize_11[2]={
  153335. 512,512
  153336. };
  153337. static int _floor_mapping_11[2]={
  153338. 6,6,
  153339. };
  153340. static double rate_mapping_11[3]={
  153341. 8000.,13000.,44000.,
  153342. };
  153343. static double rate_mapping_11_uncoupled[3]={
  153344. 12000.,20000.,50000.,
  153345. };
  153346. static double quality_mapping_11[3]={
  153347. -.1,.0,1.
  153348. };
  153349. ve_setup_data_template ve_setup_11_stereo={
  153350. 2,
  153351. rate_mapping_11,
  153352. quality_mapping_11,
  153353. 2,
  153354. 9000,
  153355. 15000,
  153356. blocksize_11,
  153357. blocksize_11,
  153358. _psy_tone_masteratt_11,
  153359. _psy_tone_0dB,
  153360. _psy_tone_suppress,
  153361. _vp_tonemask_adj_11,
  153362. NULL,
  153363. _vp_tonemask_adj_11,
  153364. _psy_noiseguards_8,
  153365. _psy_noisebias_11,
  153366. _psy_noisebias_11,
  153367. NULL,
  153368. NULL,
  153369. _psy_noise_suppress,
  153370. _psy_compand_8,
  153371. _psy_compand_8_mapping,
  153372. NULL,
  153373. {_noise_start_8,_noise_start_8},
  153374. {_noise_part_8,_noise_part_8},
  153375. _noise_thresh_11,
  153376. _psy_ath_floater_8,
  153377. _psy_ath_abs_8,
  153378. _psy_lowpass_11,
  153379. _psy_global_44,
  153380. _global_mapping_8,
  153381. _psy_stereo_modes_8,
  153382. _floor_books,
  153383. _floor,
  153384. _floor_mapping_11,
  153385. NULL,
  153386. _mapres_template_8_stereo
  153387. };
  153388. ve_setup_data_template ve_setup_11_uncoupled={
  153389. 2,
  153390. rate_mapping_11_uncoupled,
  153391. quality_mapping_11,
  153392. -1,
  153393. 9000,
  153394. 15000,
  153395. blocksize_11,
  153396. blocksize_11,
  153397. _psy_tone_masteratt_11,
  153398. _psy_tone_0dB,
  153399. _psy_tone_suppress,
  153400. _vp_tonemask_adj_11,
  153401. NULL,
  153402. _vp_tonemask_adj_11,
  153403. _psy_noiseguards_8,
  153404. _psy_noisebias_11,
  153405. _psy_noisebias_11,
  153406. NULL,
  153407. NULL,
  153408. _psy_noise_suppress,
  153409. _psy_compand_8,
  153410. _psy_compand_8_mapping,
  153411. NULL,
  153412. {_noise_start_8,_noise_start_8},
  153413. {_noise_part_8,_noise_part_8},
  153414. _noise_thresh_11,
  153415. _psy_ath_floater_8,
  153416. _psy_ath_abs_8,
  153417. _psy_lowpass_11,
  153418. _psy_global_44,
  153419. _global_mapping_8,
  153420. _psy_stereo_modes_8,
  153421. _floor_books,
  153422. _floor,
  153423. _floor_mapping_11,
  153424. NULL,
  153425. _mapres_template_8_uncoupled
  153426. };
  153427. /*** End of inlined file: setup_11.h ***/
  153428. /*** Start of inlined file: setup_16.h ***/
  153429. /*** Start of inlined file: psych_16.h ***/
  153430. /* stereo mode by base quality level */
  153431. static adj_stereo _psy_stereo_modes_16[4]={
  153432. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153433. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153434. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153435. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153436. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153437. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153438. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153439. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153440. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153441. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153442. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153443. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153444. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153445. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153446. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153447. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153448. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153449. };
  153450. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153451. static att3 _psy_tone_masteratt_16[4]={
  153452. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153453. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153454. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153455. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153456. };
  153457. static vp_adjblock _vp_tonemask_adj_16[4]={
  153458. /* adjust for mode zero */
  153459. /* 63 125 250 500 1 2 4 8 16 */
  153460. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153461. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153462. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153463. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153464. };
  153465. static noise3 _psy_noisebias_16_short[4]={
  153466. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153467. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153468. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153469. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153470. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153471. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153472. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153473. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153474. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153475. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153476. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153477. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153478. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153479. };
  153480. static noise3 _psy_noisebias_16_impulse[4]={
  153481. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153482. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153483. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153484. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153485. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153486. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153487. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153488. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153489. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153490. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153491. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153492. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153493. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153494. };
  153495. static noise3 _psy_noisebias_16[4]={
  153496. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153497. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153498. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153499. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153500. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153501. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153502. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153503. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153504. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153505. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153506. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153507. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153508. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153509. };
  153510. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153511. static int _noise_start_16[3]={ 256,256,9999 };
  153512. static int _noise_part_16[4]={ 8,8,8,8 };
  153513. static int _psy_ath_floater_16[4]={
  153514. -100,-100,-100,-105,
  153515. };
  153516. static int _psy_ath_abs_16[4]={
  153517. -130,-130,-130,-140,
  153518. };
  153519. /*** End of inlined file: psych_16.h ***/
  153520. /*** Start of inlined file: residue_16.h ***/
  153521. /***** residue backends *********************************************/
  153522. static static_bookblock _resbook_16s_0={
  153523. {
  153524. {0},
  153525. {0,0,&_16c0_s_p1_0},
  153526. {0,0,&_16c0_s_p2_0},
  153527. {0,0,&_16c0_s_p3_0},
  153528. {0,0,&_16c0_s_p4_0},
  153529. {0,0,&_16c0_s_p5_0},
  153530. {0,0,&_16c0_s_p6_0},
  153531. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153532. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153533. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153534. }
  153535. };
  153536. static static_bookblock _resbook_16s_1={
  153537. {
  153538. {0},
  153539. {0,0,&_16c1_s_p1_0},
  153540. {0,0,&_16c1_s_p2_0},
  153541. {0,0,&_16c1_s_p3_0},
  153542. {0,0,&_16c1_s_p4_0},
  153543. {0,0,&_16c1_s_p5_0},
  153544. {0,0,&_16c1_s_p6_0},
  153545. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153546. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153547. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153548. }
  153549. };
  153550. static static_bookblock _resbook_16s_2={
  153551. {
  153552. {0},
  153553. {0,0,&_16c2_s_p1_0},
  153554. {0,0,&_16c2_s_p2_0},
  153555. {0,0,&_16c2_s_p3_0},
  153556. {0,0,&_16c2_s_p4_0},
  153557. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153558. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153559. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153560. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153561. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153562. }
  153563. };
  153564. static vorbis_residue_template _res_16s_0[]={
  153565. {2,0, &_residue_44_mid,
  153566. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153567. &_resbook_16s_0,&_resbook_16s_0},
  153568. };
  153569. static vorbis_residue_template _res_16s_1[]={
  153570. {2,0, &_residue_44_mid,
  153571. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153572. &_resbook_16s_1,&_resbook_16s_1},
  153573. {2,0, &_residue_44_mid,
  153574. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153575. &_resbook_16s_1,&_resbook_16s_1}
  153576. };
  153577. static vorbis_residue_template _res_16s_2[]={
  153578. {2,0, &_residue_44_high,
  153579. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153580. &_resbook_16s_2,&_resbook_16s_2},
  153581. {2,0, &_residue_44_high,
  153582. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153583. &_resbook_16s_2,&_resbook_16s_2}
  153584. };
  153585. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153586. { _map_nominal, _res_16s_0 }, /* 0 */
  153587. { _map_nominal, _res_16s_1 }, /* 1 */
  153588. { _map_nominal, _res_16s_2 }, /* 2 */
  153589. };
  153590. static static_bookblock _resbook_16u_0={
  153591. {
  153592. {0},
  153593. {0,0,&_16u0__p1_0},
  153594. {0,0,&_16u0__p2_0},
  153595. {0,0,&_16u0__p3_0},
  153596. {0,0,&_16u0__p4_0},
  153597. {0,0,&_16u0__p5_0},
  153598. {&_16u0__p6_0,&_16u0__p6_1},
  153599. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153600. }
  153601. };
  153602. static static_bookblock _resbook_16u_1={
  153603. {
  153604. {0},
  153605. {0,0,&_16u1__p1_0},
  153606. {0,0,&_16u1__p2_0},
  153607. {0,0,&_16u1__p3_0},
  153608. {0,0,&_16u1__p4_0},
  153609. {0,0,&_16u1__p5_0},
  153610. {0,0,&_16u1__p6_0},
  153611. {&_16u1__p7_0,&_16u1__p7_1},
  153612. {&_16u1__p8_0,&_16u1__p8_1},
  153613. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153614. }
  153615. };
  153616. static static_bookblock _resbook_16u_2={
  153617. {
  153618. {0},
  153619. {0,0,&_16u2_p1_0},
  153620. {0,0,&_16u2_p2_0},
  153621. {0,0,&_16u2_p3_0},
  153622. {0,0,&_16u2_p4_0},
  153623. {&_16u2_p5_0,&_16u2_p5_1},
  153624. {&_16u2_p6_0,&_16u2_p6_1},
  153625. {&_16u2_p7_0,&_16u2_p7_1},
  153626. {&_16u2_p8_0,&_16u2_p8_1},
  153627. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153628. }
  153629. };
  153630. static vorbis_residue_template _res_16u_0[]={
  153631. {1,0, &_residue_44_low_un,
  153632. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153633. &_resbook_16u_0,&_resbook_16u_0},
  153634. };
  153635. static vorbis_residue_template _res_16u_1[]={
  153636. {1,0, &_residue_44_mid_un,
  153637. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153638. &_resbook_16u_1,&_resbook_16u_1},
  153639. {1,0, &_residue_44_mid_un,
  153640. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153641. &_resbook_16u_1,&_resbook_16u_1}
  153642. };
  153643. static vorbis_residue_template _res_16u_2[]={
  153644. {1,0, &_residue_44_hi_un,
  153645. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153646. &_resbook_16u_2,&_resbook_16u_2},
  153647. {1,0, &_residue_44_hi_un,
  153648. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153649. &_resbook_16u_2,&_resbook_16u_2}
  153650. };
  153651. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153652. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153653. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153654. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153655. };
  153656. /*** End of inlined file: residue_16.h ***/
  153657. static int blocksize_16_short[3]={
  153658. 1024,512,512
  153659. };
  153660. static int blocksize_16_long[3]={
  153661. 1024,1024,1024
  153662. };
  153663. static int _floor_mapping_16_short[3]={
  153664. 9,3,3
  153665. };
  153666. static int _floor_mapping_16[3]={
  153667. 9,9,9
  153668. };
  153669. static double rate_mapping_16[4]={
  153670. 12000.,20000.,44000.,86000.
  153671. };
  153672. static double rate_mapping_16_uncoupled[4]={
  153673. 16000.,28000.,64000.,100000.
  153674. };
  153675. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153676. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153677. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153678. ve_setup_data_template ve_setup_16_stereo={
  153679. 3,
  153680. rate_mapping_16,
  153681. quality_mapping_16,
  153682. 2,
  153683. 15000,
  153684. 19000,
  153685. blocksize_16_short,
  153686. blocksize_16_long,
  153687. _psy_tone_masteratt_16,
  153688. _psy_tone_0dB,
  153689. _psy_tone_suppress,
  153690. _vp_tonemask_adj_16,
  153691. _vp_tonemask_adj_16,
  153692. _vp_tonemask_adj_16,
  153693. _psy_noiseguards_8,
  153694. _psy_noisebias_16_impulse,
  153695. _psy_noisebias_16_short,
  153696. _psy_noisebias_16_short,
  153697. _psy_noisebias_16,
  153698. _psy_noise_suppress,
  153699. _psy_compand_8,
  153700. _psy_compand_16_mapping,
  153701. _psy_compand_16_mapping,
  153702. {_noise_start_16,_noise_start_16},
  153703. { _noise_part_16, _noise_part_16},
  153704. _noise_thresh_16,
  153705. _psy_ath_floater_16,
  153706. _psy_ath_abs_16,
  153707. _psy_lowpass_16,
  153708. _psy_global_44,
  153709. _global_mapping_16,
  153710. _psy_stereo_modes_16,
  153711. _floor_books,
  153712. _floor,
  153713. _floor_mapping_16_short,
  153714. _floor_mapping_16,
  153715. _mapres_template_16_stereo
  153716. };
  153717. ve_setup_data_template ve_setup_16_uncoupled={
  153718. 3,
  153719. rate_mapping_16_uncoupled,
  153720. quality_mapping_16,
  153721. -1,
  153722. 15000,
  153723. 19000,
  153724. blocksize_16_short,
  153725. blocksize_16_long,
  153726. _psy_tone_masteratt_16,
  153727. _psy_tone_0dB,
  153728. _psy_tone_suppress,
  153729. _vp_tonemask_adj_16,
  153730. _vp_tonemask_adj_16,
  153731. _vp_tonemask_adj_16,
  153732. _psy_noiseguards_8,
  153733. _psy_noisebias_16_impulse,
  153734. _psy_noisebias_16_short,
  153735. _psy_noisebias_16_short,
  153736. _psy_noisebias_16,
  153737. _psy_noise_suppress,
  153738. _psy_compand_8,
  153739. _psy_compand_16_mapping,
  153740. _psy_compand_16_mapping,
  153741. {_noise_start_16,_noise_start_16},
  153742. { _noise_part_16, _noise_part_16},
  153743. _noise_thresh_16,
  153744. _psy_ath_floater_16,
  153745. _psy_ath_abs_16,
  153746. _psy_lowpass_16,
  153747. _psy_global_44,
  153748. _global_mapping_16,
  153749. _psy_stereo_modes_16,
  153750. _floor_books,
  153751. _floor,
  153752. _floor_mapping_16_short,
  153753. _floor_mapping_16,
  153754. _mapres_template_16_uncoupled
  153755. };
  153756. /*** End of inlined file: setup_16.h ***/
  153757. /*** Start of inlined file: setup_22.h ***/
  153758. static double rate_mapping_22[4]={
  153759. 15000.,20000.,44000.,86000.
  153760. };
  153761. static double rate_mapping_22_uncoupled[4]={
  153762. 16000.,28000.,50000.,90000.
  153763. };
  153764. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153765. ve_setup_data_template ve_setup_22_stereo={
  153766. 3,
  153767. rate_mapping_22,
  153768. quality_mapping_16,
  153769. 2,
  153770. 19000,
  153771. 26000,
  153772. blocksize_16_short,
  153773. blocksize_16_long,
  153774. _psy_tone_masteratt_16,
  153775. _psy_tone_0dB,
  153776. _psy_tone_suppress,
  153777. _vp_tonemask_adj_16,
  153778. _vp_tonemask_adj_16,
  153779. _vp_tonemask_adj_16,
  153780. _psy_noiseguards_8,
  153781. _psy_noisebias_16_impulse,
  153782. _psy_noisebias_16_short,
  153783. _psy_noisebias_16_short,
  153784. _psy_noisebias_16,
  153785. _psy_noise_suppress,
  153786. _psy_compand_8,
  153787. _psy_compand_8_mapping,
  153788. _psy_compand_8_mapping,
  153789. {_noise_start_16,_noise_start_16},
  153790. { _noise_part_16, _noise_part_16},
  153791. _noise_thresh_16,
  153792. _psy_ath_floater_16,
  153793. _psy_ath_abs_16,
  153794. _psy_lowpass_22,
  153795. _psy_global_44,
  153796. _global_mapping_16,
  153797. _psy_stereo_modes_16,
  153798. _floor_books,
  153799. _floor,
  153800. _floor_mapping_16_short,
  153801. _floor_mapping_16,
  153802. _mapres_template_16_stereo
  153803. };
  153804. ve_setup_data_template ve_setup_22_uncoupled={
  153805. 3,
  153806. rate_mapping_22_uncoupled,
  153807. quality_mapping_16,
  153808. -1,
  153809. 19000,
  153810. 26000,
  153811. blocksize_16_short,
  153812. blocksize_16_long,
  153813. _psy_tone_masteratt_16,
  153814. _psy_tone_0dB,
  153815. _psy_tone_suppress,
  153816. _vp_tonemask_adj_16,
  153817. _vp_tonemask_adj_16,
  153818. _vp_tonemask_adj_16,
  153819. _psy_noiseguards_8,
  153820. _psy_noisebias_16_impulse,
  153821. _psy_noisebias_16_short,
  153822. _psy_noisebias_16_short,
  153823. _psy_noisebias_16,
  153824. _psy_noise_suppress,
  153825. _psy_compand_8,
  153826. _psy_compand_8_mapping,
  153827. _psy_compand_8_mapping,
  153828. {_noise_start_16,_noise_start_16},
  153829. { _noise_part_16, _noise_part_16},
  153830. _noise_thresh_16,
  153831. _psy_ath_floater_16,
  153832. _psy_ath_abs_16,
  153833. _psy_lowpass_22,
  153834. _psy_global_44,
  153835. _global_mapping_16,
  153836. _psy_stereo_modes_16,
  153837. _floor_books,
  153838. _floor,
  153839. _floor_mapping_16_short,
  153840. _floor_mapping_16,
  153841. _mapres_template_16_uncoupled
  153842. };
  153843. /*** End of inlined file: setup_22.h ***/
  153844. /*** Start of inlined file: setup_X.h ***/
  153845. static double rate_mapping_X[12]={
  153846. -1.,-1.,-1.,-1.,-1.,-1.,
  153847. -1.,-1.,-1.,-1.,-1.,-1.
  153848. };
  153849. ve_setup_data_template ve_setup_X_stereo={
  153850. 11,
  153851. rate_mapping_X,
  153852. quality_mapping_44,
  153853. 2,
  153854. 50000,
  153855. 200000,
  153856. blocksize_short_44,
  153857. blocksize_long_44,
  153858. _psy_tone_masteratt_44,
  153859. _psy_tone_0dB,
  153860. _psy_tone_suppress,
  153861. _vp_tonemask_adj_otherblock,
  153862. _vp_tonemask_adj_longblock,
  153863. _vp_tonemask_adj_otherblock,
  153864. _psy_noiseguards_44,
  153865. _psy_noisebias_impulse,
  153866. _psy_noisebias_padding,
  153867. _psy_noisebias_trans,
  153868. _psy_noisebias_long,
  153869. _psy_noise_suppress,
  153870. _psy_compand_44,
  153871. _psy_compand_short_mapping,
  153872. _psy_compand_long_mapping,
  153873. {_noise_start_short_44,_noise_start_long_44},
  153874. {_noise_part_short_44,_noise_part_long_44},
  153875. _noise_thresh_44,
  153876. _psy_ath_floater,
  153877. _psy_ath_abs,
  153878. _psy_lowpass_44,
  153879. _psy_global_44,
  153880. _global_mapping_44,
  153881. _psy_stereo_modes_44,
  153882. _floor_books,
  153883. _floor,
  153884. _floor_short_mapping_44,
  153885. _floor_long_mapping_44,
  153886. _mapres_template_44_stereo
  153887. };
  153888. ve_setup_data_template ve_setup_X_uncoupled={
  153889. 11,
  153890. rate_mapping_X,
  153891. quality_mapping_44,
  153892. -1,
  153893. 50000,
  153894. 200000,
  153895. blocksize_short_44,
  153896. blocksize_long_44,
  153897. _psy_tone_masteratt_44,
  153898. _psy_tone_0dB,
  153899. _psy_tone_suppress,
  153900. _vp_tonemask_adj_otherblock,
  153901. _vp_tonemask_adj_longblock,
  153902. _vp_tonemask_adj_otherblock,
  153903. _psy_noiseguards_44,
  153904. _psy_noisebias_impulse,
  153905. _psy_noisebias_padding,
  153906. _psy_noisebias_trans,
  153907. _psy_noisebias_long,
  153908. _psy_noise_suppress,
  153909. _psy_compand_44,
  153910. _psy_compand_short_mapping,
  153911. _psy_compand_long_mapping,
  153912. {_noise_start_short_44,_noise_start_long_44},
  153913. {_noise_part_short_44,_noise_part_long_44},
  153914. _noise_thresh_44,
  153915. _psy_ath_floater,
  153916. _psy_ath_abs,
  153917. _psy_lowpass_44,
  153918. _psy_global_44,
  153919. _global_mapping_44,
  153920. NULL,
  153921. _floor_books,
  153922. _floor,
  153923. _floor_short_mapping_44,
  153924. _floor_long_mapping_44,
  153925. _mapres_template_44_uncoupled
  153926. };
  153927. ve_setup_data_template ve_setup_XX_stereo={
  153928. 2,
  153929. rate_mapping_X,
  153930. quality_mapping_8,
  153931. 2,
  153932. 0,
  153933. 8000,
  153934. blocksize_8,
  153935. blocksize_8,
  153936. _psy_tone_masteratt_8,
  153937. _psy_tone_0dB,
  153938. _psy_tone_suppress,
  153939. _vp_tonemask_adj_8,
  153940. NULL,
  153941. _vp_tonemask_adj_8,
  153942. _psy_noiseguards_8,
  153943. _psy_noisebias_8,
  153944. _psy_noisebias_8,
  153945. NULL,
  153946. NULL,
  153947. _psy_noise_suppress,
  153948. _psy_compand_8,
  153949. _psy_compand_8_mapping,
  153950. NULL,
  153951. {_noise_start_8,_noise_start_8},
  153952. {_noise_part_8,_noise_part_8},
  153953. _noise_thresh_5only,
  153954. _psy_ath_floater_8,
  153955. _psy_ath_abs_8,
  153956. _psy_lowpass_8,
  153957. _psy_global_44,
  153958. _global_mapping_8,
  153959. _psy_stereo_modes_8,
  153960. _floor_books,
  153961. _floor,
  153962. _floor_mapping_8,
  153963. NULL,
  153964. _mapres_template_8_stereo
  153965. };
  153966. ve_setup_data_template ve_setup_XX_uncoupled={
  153967. 2,
  153968. rate_mapping_X,
  153969. quality_mapping_8,
  153970. -1,
  153971. 0,
  153972. 8000,
  153973. blocksize_8,
  153974. blocksize_8,
  153975. _psy_tone_masteratt_8,
  153976. _psy_tone_0dB,
  153977. _psy_tone_suppress,
  153978. _vp_tonemask_adj_8,
  153979. NULL,
  153980. _vp_tonemask_adj_8,
  153981. _psy_noiseguards_8,
  153982. _psy_noisebias_8,
  153983. _psy_noisebias_8,
  153984. NULL,
  153985. NULL,
  153986. _psy_noise_suppress,
  153987. _psy_compand_8,
  153988. _psy_compand_8_mapping,
  153989. NULL,
  153990. {_noise_start_8,_noise_start_8},
  153991. {_noise_part_8,_noise_part_8},
  153992. _noise_thresh_5only,
  153993. _psy_ath_floater_8,
  153994. _psy_ath_abs_8,
  153995. _psy_lowpass_8,
  153996. _psy_global_44,
  153997. _global_mapping_8,
  153998. _psy_stereo_modes_8,
  153999. _floor_books,
  154000. _floor,
  154001. _floor_mapping_8,
  154002. NULL,
  154003. _mapres_template_8_uncoupled
  154004. };
  154005. /*** End of inlined file: setup_X.h ***/
  154006. static ve_setup_data_template *setup_list[]={
  154007. &ve_setup_44_stereo,
  154008. &ve_setup_44_uncoupled,
  154009. &ve_setup_32_stereo,
  154010. &ve_setup_32_uncoupled,
  154011. &ve_setup_22_stereo,
  154012. &ve_setup_22_uncoupled,
  154013. &ve_setup_16_stereo,
  154014. &ve_setup_16_uncoupled,
  154015. &ve_setup_11_stereo,
  154016. &ve_setup_11_uncoupled,
  154017. &ve_setup_8_stereo,
  154018. &ve_setup_8_uncoupled,
  154019. &ve_setup_X_stereo,
  154020. &ve_setup_X_uncoupled,
  154021. &ve_setup_XX_stereo,
  154022. &ve_setup_XX_uncoupled,
  154023. 0
  154024. };
  154025. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154026. if(vi && vi->codec_setup){
  154027. vi->version=0;
  154028. vi->channels=ch;
  154029. vi->rate=rate;
  154030. return(0);
  154031. }
  154032. return(OV_EINVAL);
  154033. }
  154034. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154035. static_codebook ***books,
  154036. vorbis_info_floor1 *in,
  154037. int *x){
  154038. int i,k,is=s;
  154039. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154040. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154041. memcpy(f,in+x[is],sizeof(*f));
  154042. /* fill in the lowpass field, even if it's temporary */
  154043. f->n=ci->blocksizes[block]>>1;
  154044. /* books */
  154045. {
  154046. int partitions=f->partitions;
  154047. int maxclass=-1;
  154048. int maxbook=-1;
  154049. for(i=0;i<partitions;i++)
  154050. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154051. for(i=0;i<=maxclass;i++){
  154052. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154053. f->class_book[i]+=ci->books;
  154054. for(k=0;k<(1<<f->class_subs[i]);k++){
  154055. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154056. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154057. }
  154058. }
  154059. for(i=0;i<=maxbook;i++)
  154060. ci->book_param[ci->books++]=books[x[is]][i];
  154061. }
  154062. /* for now, we're only using floor 1 */
  154063. ci->floor_type[ci->floors]=1;
  154064. ci->floor_param[ci->floors]=f;
  154065. ci->floors++;
  154066. return;
  154067. }
  154068. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154069. vorbis_info_psy_global *in,
  154070. double *x){
  154071. int i,is=s;
  154072. double ds=s-is;
  154073. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154074. vorbis_info_psy_global *g=&ci->psy_g_param;
  154075. memcpy(g,in+(int)x[is],sizeof(*g));
  154076. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154077. is=(int)ds;
  154078. ds-=is;
  154079. if(ds==0 && is>0){
  154080. is--;
  154081. ds=1.;
  154082. }
  154083. /* interpolate the trigger threshholds */
  154084. for(i=0;i<4;i++){
  154085. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154086. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154087. }
  154088. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154089. return;
  154090. }
  154091. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154092. highlevel_encode_setup *hi,
  154093. adj_stereo *p){
  154094. float s=hi->stereo_point_setting;
  154095. int i,is=s;
  154096. double ds=s-is;
  154097. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154098. vorbis_info_psy_global *g=&ci->psy_g_param;
  154099. if(p){
  154100. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154101. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154102. if(hi->managed){
  154103. /* interpolate the kHz threshholds */
  154104. for(i=0;i<PACKETBLOBS;i++){
  154105. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154106. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154107. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154108. g->coupling_pkHz[i]=kHz;
  154109. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154110. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154111. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154112. }
  154113. }else{
  154114. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154115. for(i=0;i<PACKETBLOBS;i++){
  154116. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154117. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154118. g->coupling_pkHz[i]=kHz;
  154119. }
  154120. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154121. for(i=0;i<PACKETBLOBS;i++){
  154122. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154123. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154124. }
  154125. }
  154126. }else{
  154127. for(i=0;i<PACKETBLOBS;i++){
  154128. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154129. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154130. }
  154131. }
  154132. return;
  154133. }
  154134. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154135. int *nn_start,
  154136. int *nn_partition,
  154137. double *nn_thresh,
  154138. int block){
  154139. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154140. vorbis_info_psy *p=ci->psy_param[block];
  154141. highlevel_encode_setup *hi=&ci->hi;
  154142. int is=s;
  154143. if(block>=ci->psys)
  154144. ci->psys=block+1;
  154145. if(!p){
  154146. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154147. ci->psy_param[block]=p;
  154148. }
  154149. memcpy(p,&_psy_info_template,sizeof(*p));
  154150. p->blockflag=block>>1;
  154151. if(hi->noise_normalize_p){
  154152. p->normal_channel_p=1;
  154153. p->normal_point_p=1;
  154154. p->normal_start=nn_start[is];
  154155. p->normal_partition=nn_partition[is];
  154156. p->normal_thresh=nn_thresh[is];
  154157. }
  154158. return;
  154159. }
  154160. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154161. att3 *att,
  154162. int *max,
  154163. vp_adjblock *in){
  154164. int i,is=s;
  154165. double ds=s-is;
  154166. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154167. vorbis_info_psy *p=ci->psy_param[block];
  154168. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154169. filling the values in here */
  154170. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154171. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154172. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154173. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154174. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154175. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154176. for(i=0;i<P_BANDS;i++)
  154177. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154178. return;
  154179. }
  154180. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154181. compandblock *in, double *x){
  154182. int i,is=s;
  154183. double ds=s-is;
  154184. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154185. vorbis_info_psy *p=ci->psy_param[block];
  154186. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154187. is=(int)ds;
  154188. ds-=is;
  154189. if(ds==0 && is>0){
  154190. is--;
  154191. ds=1.;
  154192. }
  154193. /* interpolate the compander settings */
  154194. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154195. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154196. return;
  154197. }
  154198. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154199. int *suppress){
  154200. int is=s;
  154201. double ds=s-is;
  154202. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154203. vorbis_info_psy *p=ci->psy_param[block];
  154204. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154205. return;
  154206. }
  154207. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154208. int *suppress,
  154209. noise3 *in,
  154210. noiseguard *guard,
  154211. double userbias){
  154212. int i,is=s,j;
  154213. double ds=s-is;
  154214. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154215. vorbis_info_psy *p=ci->psy_param[block];
  154216. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154217. p->noisewindowlomin=guard[block].lo;
  154218. p->noisewindowhimin=guard[block].hi;
  154219. p->noisewindowfixed=guard[block].fixed;
  154220. for(j=0;j<P_NOISECURVES;j++)
  154221. for(i=0;i<P_BANDS;i++)
  154222. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154223. /* impulse blocks may take a user specified bias to boost the
  154224. nominal/high noise encoding depth */
  154225. for(j=0;j<P_NOISECURVES;j++){
  154226. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154227. for(i=0;i<P_BANDS;i++){
  154228. p->noiseoff[j][i]+=userbias;
  154229. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154230. }
  154231. }
  154232. return;
  154233. }
  154234. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154235. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154236. vorbis_info_psy *p=ci->psy_param[block];
  154237. p->ath_adjatt=ci->hi.ath_floating_dB;
  154238. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154239. return;
  154240. }
  154241. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154242. int i;
  154243. for(i=0;i<ci->books;i++)
  154244. if(ci->book_param[i]==book)return(i);
  154245. return(ci->books++);
  154246. }
  154247. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154248. int *shortb,int *longb){
  154249. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154250. int is=s;
  154251. int blockshort=shortb[is];
  154252. int blocklong=longb[is];
  154253. ci->blocksizes[0]=blockshort;
  154254. ci->blocksizes[1]=blocklong;
  154255. }
  154256. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154257. int number, int block,
  154258. vorbis_residue_template *res){
  154259. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154260. int i,n;
  154261. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154262. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154263. memcpy(r,res->res,sizeof(*r));
  154264. if(ci->residues<=number)ci->residues=number+1;
  154265. switch(ci->blocksizes[block]){
  154266. case 64:case 128:case 256:
  154267. r->grouping=16;
  154268. break;
  154269. default:
  154270. r->grouping=32;
  154271. break;
  154272. }
  154273. ci->residue_type[number]=res->res_type;
  154274. /* to be adjusted by lowpass/pointlimit later */
  154275. n=r->end=ci->blocksizes[block]>>1;
  154276. if(res->res_type==2)
  154277. n=r->end*=vi->channels;
  154278. /* fill in all the books */
  154279. {
  154280. int booklist=0,k;
  154281. if(ci->hi.managed){
  154282. for(i=0;i<r->partitions;i++)
  154283. for(k=0;k<3;k++)
  154284. if(res->books_base_managed->books[i][k])
  154285. r->secondstages[i]|=(1<<k);
  154286. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154287. ci->book_param[r->groupbook]=res->book_aux_managed;
  154288. for(i=0;i<r->partitions;i++){
  154289. for(k=0;k<3;k++){
  154290. if(res->books_base_managed->books[i][k]){
  154291. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154292. r->booklist[booklist++]=bookid;
  154293. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154294. }
  154295. }
  154296. }
  154297. }else{
  154298. for(i=0;i<r->partitions;i++)
  154299. for(k=0;k<3;k++)
  154300. if(res->books_base->books[i][k])
  154301. r->secondstages[i]|=(1<<k);
  154302. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154303. ci->book_param[r->groupbook]=res->book_aux;
  154304. for(i=0;i<r->partitions;i++){
  154305. for(k=0;k<3;k++){
  154306. if(res->books_base->books[i][k]){
  154307. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154308. r->booklist[booklist++]=bookid;
  154309. ci->book_param[bookid]=res->books_base->books[i][k];
  154310. }
  154311. }
  154312. }
  154313. }
  154314. }
  154315. /* lowpass setup/pointlimit */
  154316. {
  154317. double freq=ci->hi.lowpass_kHz*1000.;
  154318. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154319. double nyq=vi->rate/2.;
  154320. long blocksize=ci->blocksizes[block]>>1;
  154321. /* lowpass needs to be set in the floor and the residue. */
  154322. if(freq>nyq)freq=nyq;
  154323. /* in the floor, the granularity can be very fine; it doesn't alter
  154324. the encoding structure, only the samples used to fit the floor
  154325. approximation */
  154326. f->n=freq/nyq*blocksize;
  154327. /* this res may by limited by the maximum pointlimit of the mode,
  154328. not the lowpass. the floor is always lowpass limited. */
  154329. if(res->limit_type){
  154330. if(ci->hi.managed)
  154331. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154332. else
  154333. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154334. if(freq>nyq)freq=nyq;
  154335. }
  154336. /* in the residue, we're constrained, physically, by partition
  154337. boundaries. We still lowpass 'wherever', but we have to round up
  154338. here to next boundary, or the vorbis spec will round it *down* to
  154339. previous boundary in encode/decode */
  154340. if(ci->residue_type[block]==2)
  154341. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154342. r->grouping;
  154343. else
  154344. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154345. r->grouping;
  154346. }
  154347. }
  154348. /* we assume two maps in this encoder */
  154349. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154350. vorbis_mapping_template *maps){
  154351. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154352. int i,j,is=s,modes=2;
  154353. vorbis_info_mapping0 *map=maps[is].map;
  154354. vorbis_info_mode *mode=_mode_template;
  154355. vorbis_residue_template *res=maps[is].res;
  154356. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154357. for(i=0;i<modes;i++){
  154358. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154359. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154360. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154361. if(i>=ci->modes)ci->modes=i+1;
  154362. ci->map_type[i]=0;
  154363. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154364. if(i>=ci->maps)ci->maps=i+1;
  154365. for(j=0;j<map[i].submaps;j++)
  154366. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154367. ,res+map[i].residuesubmap[j]);
  154368. }
  154369. }
  154370. static double setting_to_approx_bitrate(vorbis_info *vi){
  154371. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154372. highlevel_encode_setup *hi=&ci->hi;
  154373. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154374. int is=hi->base_setting;
  154375. double ds=hi->base_setting-is;
  154376. int ch=vi->channels;
  154377. double *r=setup->rate_mapping;
  154378. if(r==NULL)
  154379. return(-1);
  154380. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154381. }
  154382. static void get_setup_template(vorbis_info *vi,
  154383. long ch,long srate,
  154384. double req,int q_or_bitrate){
  154385. int i=0,j;
  154386. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154387. highlevel_encode_setup *hi=&ci->hi;
  154388. if(q_or_bitrate)req/=ch;
  154389. while(setup_list[i]){
  154390. if(setup_list[i]->coupling_restriction==-1 ||
  154391. setup_list[i]->coupling_restriction==ch){
  154392. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154393. srate<=setup_list[i]->samplerate_max_restriction){
  154394. int mappings=setup_list[i]->mappings;
  154395. double *map=(q_or_bitrate?
  154396. setup_list[i]->rate_mapping:
  154397. setup_list[i]->quality_mapping);
  154398. /* the template matches. Does the requested quality mode
  154399. fall within this template's modes? */
  154400. if(req<map[0]){++i;continue;}
  154401. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154402. for(j=0;j<mappings;j++)
  154403. if(req>=map[j] && req<map[j+1])break;
  154404. /* an all-points match */
  154405. hi->setup=setup_list[i];
  154406. if(j==mappings)
  154407. hi->base_setting=j-.001;
  154408. else{
  154409. float low=map[j];
  154410. float high=map[j+1];
  154411. float del=(req-low)/(high-low);
  154412. hi->base_setting=j+del;
  154413. }
  154414. return;
  154415. }
  154416. }
  154417. i++;
  154418. }
  154419. hi->setup=NULL;
  154420. }
  154421. /* encoders will need to use vorbis_info_init beforehand and call
  154422. vorbis_info clear when all done */
  154423. /* two interfaces; this, more detailed one, and later a convenience
  154424. layer on top */
  154425. /* the final setup call */
  154426. int vorbis_encode_setup_init(vorbis_info *vi){
  154427. int i0=0,singleblock=0;
  154428. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154429. ve_setup_data_template *setup=NULL;
  154430. highlevel_encode_setup *hi=&ci->hi;
  154431. if(ci==NULL)return(OV_EINVAL);
  154432. if(!hi->impulse_block_p)i0=1;
  154433. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154434. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154435. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154436. /* again, bound this to avoid the app shooting itself int he foot
  154437. too badly */
  154438. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154439. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154440. /* get the appropriate setup template; matches the fetch in previous
  154441. stages */
  154442. setup=(ve_setup_data_template *)hi->setup;
  154443. if(setup==NULL)return(OV_EINVAL);
  154444. hi->set_in_stone=1;
  154445. /* choose block sizes from configured sizes as well as paying
  154446. attention to long_block_p and short_block_p. If the configured
  154447. short and long blocks are the same length, we set long_block_p
  154448. and unset short_block_p */
  154449. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154450. setup->blocksize_short,
  154451. setup->blocksize_long);
  154452. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154453. /* floor setup; choose proper floor params. Allocated on the floor
  154454. stack in order; if we alloc only long floor, it's 0 */
  154455. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154456. setup->floor_books,
  154457. setup->floor_params,
  154458. setup->floor_short_mapping);
  154459. if(!singleblock)
  154460. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154461. setup->floor_books,
  154462. setup->floor_params,
  154463. setup->floor_long_mapping);
  154464. /* setup of [mostly] short block detection and stereo*/
  154465. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154466. setup->global_params,
  154467. setup->global_mapping);
  154468. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154469. /* basic psych setup and noise normalization */
  154470. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154471. setup->psy_noise_normal_start[0],
  154472. setup->psy_noise_normal_partition[0],
  154473. setup->psy_noise_normal_thresh,
  154474. 0);
  154475. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154476. setup->psy_noise_normal_start[0],
  154477. setup->psy_noise_normal_partition[0],
  154478. setup->psy_noise_normal_thresh,
  154479. 1);
  154480. if(!singleblock){
  154481. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154482. setup->psy_noise_normal_start[1],
  154483. setup->psy_noise_normal_partition[1],
  154484. setup->psy_noise_normal_thresh,
  154485. 2);
  154486. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154487. setup->psy_noise_normal_start[1],
  154488. setup->psy_noise_normal_partition[1],
  154489. setup->psy_noise_normal_thresh,
  154490. 3);
  154491. }
  154492. /* tone masking setup */
  154493. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154494. setup->psy_tone_masteratt,
  154495. setup->psy_tone_0dB,
  154496. setup->psy_tone_adj_impulse);
  154497. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154498. setup->psy_tone_masteratt,
  154499. setup->psy_tone_0dB,
  154500. setup->psy_tone_adj_other);
  154501. if(!singleblock){
  154502. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154503. setup->psy_tone_masteratt,
  154504. setup->psy_tone_0dB,
  154505. setup->psy_tone_adj_other);
  154506. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154507. setup->psy_tone_masteratt,
  154508. setup->psy_tone_0dB,
  154509. setup->psy_tone_adj_long);
  154510. }
  154511. /* noise companding setup */
  154512. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154513. setup->psy_noise_compand,
  154514. setup->psy_noise_compand_short_mapping);
  154515. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154516. setup->psy_noise_compand,
  154517. setup->psy_noise_compand_short_mapping);
  154518. if(!singleblock){
  154519. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154520. setup->psy_noise_compand,
  154521. setup->psy_noise_compand_long_mapping);
  154522. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154523. setup->psy_noise_compand,
  154524. setup->psy_noise_compand_long_mapping);
  154525. }
  154526. /* peak guarding setup */
  154527. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154528. setup->psy_tone_dBsuppress);
  154529. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154530. setup->psy_tone_dBsuppress);
  154531. if(!singleblock){
  154532. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154533. setup->psy_tone_dBsuppress);
  154534. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154535. setup->psy_tone_dBsuppress);
  154536. }
  154537. /* noise bias setup */
  154538. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154539. setup->psy_noise_dBsuppress,
  154540. setup->psy_noise_bias_impulse,
  154541. setup->psy_noiseguards,
  154542. (i0==0?hi->impulse_noisetune:0.));
  154543. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154544. setup->psy_noise_dBsuppress,
  154545. setup->psy_noise_bias_padding,
  154546. setup->psy_noiseguards,0.);
  154547. if(!singleblock){
  154548. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154549. setup->psy_noise_dBsuppress,
  154550. setup->psy_noise_bias_trans,
  154551. setup->psy_noiseguards,0.);
  154552. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154553. setup->psy_noise_dBsuppress,
  154554. setup->psy_noise_bias_long,
  154555. setup->psy_noiseguards,0.);
  154556. }
  154557. vorbis_encode_ath_setup(vi,0);
  154558. vorbis_encode_ath_setup(vi,1);
  154559. if(!singleblock){
  154560. vorbis_encode_ath_setup(vi,2);
  154561. vorbis_encode_ath_setup(vi,3);
  154562. }
  154563. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154564. /* set bitrate readonlies and management */
  154565. if(hi->bitrate_av>0)
  154566. vi->bitrate_nominal=hi->bitrate_av;
  154567. else{
  154568. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154569. }
  154570. vi->bitrate_lower=hi->bitrate_min;
  154571. vi->bitrate_upper=hi->bitrate_max;
  154572. if(hi->bitrate_av)
  154573. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154574. else
  154575. vi->bitrate_window=0.;
  154576. if(hi->managed){
  154577. ci->bi.avg_rate=hi->bitrate_av;
  154578. ci->bi.min_rate=hi->bitrate_min;
  154579. ci->bi.max_rate=hi->bitrate_max;
  154580. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154581. ci->bi.reservoir_bias=
  154582. hi->bitrate_reservoir_bias;
  154583. ci->bi.slew_damp=hi->bitrate_av_damp;
  154584. }
  154585. return(0);
  154586. }
  154587. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154588. long channels,
  154589. long rate){
  154590. int ret=0,i,is;
  154591. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154592. highlevel_encode_setup *hi=&ci->hi;
  154593. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154594. double ds;
  154595. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154596. if(ret)return(ret);
  154597. is=hi->base_setting;
  154598. ds=hi->base_setting-is;
  154599. hi->short_setting=hi->base_setting;
  154600. hi->long_setting=hi->base_setting;
  154601. hi->managed=0;
  154602. hi->impulse_block_p=1;
  154603. hi->noise_normalize_p=1;
  154604. hi->stereo_point_setting=hi->base_setting;
  154605. hi->lowpass_kHz=
  154606. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154607. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154608. setup->psy_ath_float[is+1]*ds;
  154609. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154610. setup->psy_ath_abs[is+1]*ds;
  154611. hi->amplitude_track_dBpersec=-6.;
  154612. hi->trigger_setting=hi->base_setting;
  154613. for(i=0;i<4;i++){
  154614. hi->block[i].tone_mask_setting=hi->base_setting;
  154615. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154616. hi->block[i].noise_bias_setting=hi->base_setting;
  154617. hi->block[i].noise_compand_setting=hi->base_setting;
  154618. }
  154619. return(ret);
  154620. }
  154621. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154622. long channels,
  154623. long rate,
  154624. float quality){
  154625. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154626. highlevel_encode_setup *hi=&ci->hi;
  154627. quality+=.0000001;
  154628. if(quality>=1.)quality=.9999;
  154629. get_setup_template(vi,channels,rate,quality,0);
  154630. if(!hi->setup)return OV_EIMPL;
  154631. return vorbis_encode_setup_setting(vi,channels,rate);
  154632. }
  154633. int vorbis_encode_init_vbr(vorbis_info *vi,
  154634. long channels,
  154635. long rate,
  154636. float base_quality /* 0. to 1. */
  154637. ){
  154638. int ret=0;
  154639. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154640. if(ret){
  154641. vorbis_info_clear(vi);
  154642. return ret;
  154643. }
  154644. ret=vorbis_encode_setup_init(vi);
  154645. if(ret)
  154646. vorbis_info_clear(vi);
  154647. return(ret);
  154648. }
  154649. int vorbis_encode_setup_managed(vorbis_info *vi,
  154650. long channels,
  154651. long rate,
  154652. long max_bitrate,
  154653. long nominal_bitrate,
  154654. long min_bitrate){
  154655. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154656. highlevel_encode_setup *hi=&ci->hi;
  154657. double tnominal=nominal_bitrate;
  154658. int ret=0;
  154659. if(nominal_bitrate<=0.){
  154660. if(max_bitrate>0.){
  154661. if(min_bitrate>0.)
  154662. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154663. else
  154664. nominal_bitrate=max_bitrate*.875;
  154665. }else{
  154666. if(min_bitrate>0.){
  154667. nominal_bitrate=min_bitrate;
  154668. }else{
  154669. return(OV_EINVAL);
  154670. }
  154671. }
  154672. }
  154673. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154674. if(!hi->setup)return OV_EIMPL;
  154675. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154676. if(ret){
  154677. vorbis_info_clear(vi);
  154678. return ret;
  154679. }
  154680. /* initialize management with sane defaults */
  154681. hi->managed=1;
  154682. hi->bitrate_min=min_bitrate;
  154683. hi->bitrate_max=max_bitrate;
  154684. hi->bitrate_av=tnominal;
  154685. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154686. hi->bitrate_reservoir=nominal_bitrate*2;
  154687. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154688. return(ret);
  154689. }
  154690. int vorbis_encode_init(vorbis_info *vi,
  154691. long channels,
  154692. long rate,
  154693. long max_bitrate,
  154694. long nominal_bitrate,
  154695. long min_bitrate){
  154696. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154697. max_bitrate,
  154698. nominal_bitrate,
  154699. min_bitrate);
  154700. if(ret){
  154701. vorbis_info_clear(vi);
  154702. return(ret);
  154703. }
  154704. ret=vorbis_encode_setup_init(vi);
  154705. if(ret)
  154706. vorbis_info_clear(vi);
  154707. return(ret);
  154708. }
  154709. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154710. if(vi){
  154711. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154712. highlevel_encode_setup *hi=&ci->hi;
  154713. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154714. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154715. switch(number){
  154716. /* now deprecated *****************/
  154717. case OV_ECTL_RATEMANAGE_GET:
  154718. {
  154719. struct ovectl_ratemanage_arg *ai=
  154720. (struct ovectl_ratemanage_arg *)arg;
  154721. ai->management_active=hi->managed;
  154722. ai->bitrate_hard_window=ai->bitrate_av_window=
  154723. (double)hi->bitrate_reservoir/vi->rate;
  154724. ai->bitrate_av_window_center=1.;
  154725. ai->bitrate_hard_min=hi->bitrate_min;
  154726. ai->bitrate_hard_max=hi->bitrate_max;
  154727. ai->bitrate_av_lo=hi->bitrate_av;
  154728. ai->bitrate_av_hi=hi->bitrate_av;
  154729. }
  154730. return(0);
  154731. /* now deprecated *****************/
  154732. case OV_ECTL_RATEMANAGE_SET:
  154733. {
  154734. struct ovectl_ratemanage_arg *ai=
  154735. (struct ovectl_ratemanage_arg *)arg;
  154736. if(ai==NULL){
  154737. hi->managed=0;
  154738. }else{
  154739. hi->managed=ai->management_active;
  154740. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154741. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154742. }
  154743. }
  154744. return 0;
  154745. /* now deprecated *****************/
  154746. case OV_ECTL_RATEMANAGE_AVG:
  154747. {
  154748. struct ovectl_ratemanage_arg *ai=
  154749. (struct ovectl_ratemanage_arg *)arg;
  154750. if(ai==NULL){
  154751. hi->bitrate_av=0;
  154752. }else{
  154753. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154754. }
  154755. }
  154756. return(0);
  154757. /* now deprecated *****************/
  154758. case OV_ECTL_RATEMANAGE_HARD:
  154759. {
  154760. struct ovectl_ratemanage_arg *ai=
  154761. (struct ovectl_ratemanage_arg *)arg;
  154762. if(ai==NULL){
  154763. hi->bitrate_min=0;
  154764. hi->bitrate_max=0;
  154765. }else{
  154766. hi->bitrate_min=ai->bitrate_hard_min;
  154767. hi->bitrate_max=ai->bitrate_hard_max;
  154768. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154769. (hi->bitrate_max+hi->bitrate_min)*.5;
  154770. }
  154771. if(hi->bitrate_reservoir<128.)
  154772. hi->bitrate_reservoir=128.;
  154773. }
  154774. return(0);
  154775. /* replacement ratemanage interface */
  154776. case OV_ECTL_RATEMANAGE2_GET:
  154777. {
  154778. struct ovectl_ratemanage2_arg *ai=
  154779. (struct ovectl_ratemanage2_arg *)arg;
  154780. if(ai==NULL)return OV_EINVAL;
  154781. ai->management_active=hi->managed;
  154782. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154783. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154784. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154785. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154786. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154787. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154788. }
  154789. return (0);
  154790. case OV_ECTL_RATEMANAGE2_SET:
  154791. {
  154792. struct ovectl_ratemanage2_arg *ai=
  154793. (struct ovectl_ratemanage2_arg *)arg;
  154794. if(ai==NULL){
  154795. hi->managed=0;
  154796. }else{
  154797. /* sanity check; only catch invariant violations */
  154798. if(ai->bitrate_limit_min_kbps>0 &&
  154799. ai->bitrate_average_kbps>0 &&
  154800. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154801. return OV_EINVAL;
  154802. if(ai->bitrate_limit_max_kbps>0 &&
  154803. ai->bitrate_average_kbps>0 &&
  154804. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154805. return OV_EINVAL;
  154806. if(ai->bitrate_limit_min_kbps>0 &&
  154807. ai->bitrate_limit_max_kbps>0 &&
  154808. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154809. return OV_EINVAL;
  154810. if(ai->bitrate_average_damping <= 0.)
  154811. return OV_EINVAL;
  154812. if(ai->bitrate_limit_reservoir_bits < 0)
  154813. return OV_EINVAL;
  154814. if(ai->bitrate_limit_reservoir_bias < 0.)
  154815. return OV_EINVAL;
  154816. if(ai->bitrate_limit_reservoir_bias > 1.)
  154817. return OV_EINVAL;
  154818. hi->managed=ai->management_active;
  154819. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  154820. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  154821. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  154822. hi->bitrate_av_damp=ai->bitrate_average_damping;
  154823. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  154824. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  154825. }
  154826. }
  154827. return 0;
  154828. case OV_ECTL_LOWPASS_GET:
  154829. {
  154830. double *farg=(double *)arg;
  154831. *farg=hi->lowpass_kHz;
  154832. }
  154833. return(0);
  154834. case OV_ECTL_LOWPASS_SET:
  154835. {
  154836. double *farg=(double *)arg;
  154837. hi->lowpass_kHz=*farg;
  154838. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  154839. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  154840. }
  154841. return(0);
  154842. case OV_ECTL_IBLOCK_GET:
  154843. {
  154844. double *farg=(double *)arg;
  154845. *farg=hi->impulse_noisetune;
  154846. }
  154847. return(0);
  154848. case OV_ECTL_IBLOCK_SET:
  154849. {
  154850. double *farg=(double *)arg;
  154851. hi->impulse_noisetune=*farg;
  154852. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  154853. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  154854. }
  154855. return(0);
  154856. }
  154857. return(OV_EIMPL);
  154858. }
  154859. return(OV_EINVAL);
  154860. }
  154861. #endif
  154862. /*** End of inlined file: vorbisenc.c ***/
  154863. /*** Start of inlined file: vorbisfile.c ***/
  154864. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154865. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154866. // tasks..
  154867. #if JUCE_MSVC
  154868. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154869. #endif
  154870. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154871. #if JUCE_USE_OGGVORBIS
  154872. #include <stdlib.h>
  154873. #include <stdio.h>
  154874. #include <errno.h>
  154875. #include <string.h>
  154876. #include <math.h>
  154877. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  154878. one logical bitstream arranged end to end (the only form of Ogg
  154879. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  154880. multiplexing] is not allowed in Vorbis) */
  154881. /* A Vorbis file can be played beginning to end (streamed) without
  154882. worrying ahead of time about chaining (see decoder_example.c). If
  154883. we have the whole file, however, and want random access
  154884. (seeking/scrubbing) or desire to know the total length/time of a
  154885. file, we need to account for the possibility of chaining. */
  154886. /* We can handle things a number of ways; we can determine the entire
  154887. bitstream structure right off the bat, or find pieces on demand.
  154888. This example determines and caches structure for the entire
  154889. bitstream, but builds a virtual decoder on the fly when moving
  154890. between links in the chain. */
  154891. /* There are also different ways to implement seeking. Enough
  154892. information exists in an Ogg bitstream to seek to
  154893. sample-granularity positions in the output. Or, one can seek by
  154894. picking some portion of the stream roughly in the desired area if
  154895. we only want coarse navigation through the stream. */
  154896. /*************************************************************************
  154897. * Many, many internal helpers. The intention is not to be confusing;
  154898. * rampant duplication and monolithic function implementation would be
  154899. * harder to understand anyway. The high level functions are last. Begin
  154900. * grokking near the end of the file */
  154901. /* read a little more data from the file/pipe into the ogg_sync framer
  154902. */
  154903. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  154904. over 8k gets what they deserve */
  154905. static long _get_data(OggVorbis_File *vf){
  154906. errno=0;
  154907. if(vf->datasource){
  154908. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  154909. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  154910. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  154911. if(bytes==0 && errno)return(-1);
  154912. return(bytes);
  154913. }else
  154914. return(0);
  154915. }
  154916. /* save a tiny smidge of verbosity to make the code more readable */
  154917. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  154918. if(vf->datasource){
  154919. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  154920. vf->offset=offset;
  154921. ogg_sync_reset(&vf->oy);
  154922. }else{
  154923. /* shouldn't happen unless someone writes a broken callback */
  154924. return;
  154925. }
  154926. }
  154927. /* The read/seek functions track absolute position within the stream */
  154928. /* from the head of the stream, get the next page. boundary specifies
  154929. if the function is allowed to fetch more data from the stream (and
  154930. how much) or only use internally buffered data.
  154931. boundary: -1) unbounded search
  154932. 0) read no additional data; use cached only
  154933. n) search for a new page beginning for n bytes
  154934. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  154935. n) found a page at absolute offset n */
  154936. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  154937. ogg_int64_t boundary){
  154938. if(boundary>0)boundary+=vf->offset;
  154939. while(1){
  154940. long more;
  154941. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  154942. more=ogg_sync_pageseek(&vf->oy,og);
  154943. if(more<0){
  154944. /* skipped n bytes */
  154945. vf->offset-=more;
  154946. }else{
  154947. if(more==0){
  154948. /* send more paramedics */
  154949. if(!boundary)return(OV_FALSE);
  154950. {
  154951. long ret=_get_data(vf);
  154952. if(ret==0)return(OV_EOF);
  154953. if(ret<0)return(OV_EREAD);
  154954. }
  154955. }else{
  154956. /* got a page. Return the offset at the page beginning,
  154957. advance the internal offset past the page end */
  154958. ogg_int64_t ret=vf->offset;
  154959. vf->offset+=more;
  154960. return(ret);
  154961. }
  154962. }
  154963. }
  154964. }
  154965. /* find the latest page beginning before the current stream cursor
  154966. position. Much dirtier than the above as Ogg doesn't have any
  154967. backward search linkage. no 'readp' as it will certainly have to
  154968. read. */
  154969. /* returns offset or OV_EREAD, OV_FAULT */
  154970. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  154971. ogg_int64_t begin=vf->offset;
  154972. ogg_int64_t end=begin;
  154973. ogg_int64_t ret;
  154974. ogg_int64_t offset=-1;
  154975. while(offset==-1){
  154976. begin-=CHUNKSIZE;
  154977. if(begin<0)
  154978. begin=0;
  154979. _seek_helper(vf,begin);
  154980. while(vf->offset<end){
  154981. ret=_get_next_page(vf,og,end-vf->offset);
  154982. if(ret==OV_EREAD)return(OV_EREAD);
  154983. if(ret<0){
  154984. break;
  154985. }else{
  154986. offset=ret;
  154987. }
  154988. }
  154989. }
  154990. /* we have the offset. Actually snork and hold the page now */
  154991. _seek_helper(vf,offset);
  154992. ret=_get_next_page(vf,og,CHUNKSIZE);
  154993. if(ret<0)
  154994. /* this shouldn't be possible */
  154995. return(OV_EFAULT);
  154996. return(offset);
  154997. }
  154998. /* finds each bitstream link one at a time using a bisection search
  154999. (has to begin by knowing the offset of the lb's initial page).
  155000. Recurses for each link so it can alloc the link storage after
  155001. finding them all, then unroll and fill the cache at the same time */
  155002. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155003. ogg_int64_t begin,
  155004. ogg_int64_t searched,
  155005. ogg_int64_t end,
  155006. long currentno,
  155007. long m){
  155008. ogg_int64_t endsearched=end;
  155009. ogg_int64_t next=end;
  155010. ogg_page og;
  155011. ogg_int64_t ret;
  155012. /* the below guards against garbage seperating the last and
  155013. first pages of two links. */
  155014. while(searched<endsearched){
  155015. ogg_int64_t bisect;
  155016. if(endsearched-searched<CHUNKSIZE){
  155017. bisect=searched;
  155018. }else{
  155019. bisect=(searched+endsearched)/2;
  155020. }
  155021. _seek_helper(vf,bisect);
  155022. ret=_get_next_page(vf,&og,-1);
  155023. if(ret==OV_EREAD)return(OV_EREAD);
  155024. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155025. endsearched=bisect;
  155026. if(ret>=0)next=ret;
  155027. }else{
  155028. searched=ret+og.header_len+og.body_len;
  155029. }
  155030. }
  155031. _seek_helper(vf,next);
  155032. ret=_get_next_page(vf,&og,-1);
  155033. if(ret==OV_EREAD)return(OV_EREAD);
  155034. if(searched>=end || ret<0){
  155035. vf->links=m+1;
  155036. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155037. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155038. vf->offsets[m+1]=searched;
  155039. }else{
  155040. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155041. end,ogg_page_serialno(&og),m+1);
  155042. if(ret==OV_EREAD)return(OV_EREAD);
  155043. }
  155044. vf->offsets[m]=begin;
  155045. vf->serialnos[m]=currentno;
  155046. return(0);
  155047. }
  155048. /* uses the local ogg_stream storage in vf; this is important for
  155049. non-streaming input sources */
  155050. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155051. long *serialno,ogg_page *og_ptr){
  155052. ogg_page og;
  155053. ogg_packet op;
  155054. int i,ret;
  155055. if(!og_ptr){
  155056. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155057. if(llret==OV_EREAD)return(OV_EREAD);
  155058. if(llret<0)return OV_ENOTVORBIS;
  155059. og_ptr=&og;
  155060. }
  155061. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155062. if(serialno)*serialno=vf->os.serialno;
  155063. vf->ready_state=STREAMSET;
  155064. /* extract the initial header from the first page and verify that the
  155065. Ogg bitstream is in fact Vorbis data */
  155066. vorbis_info_init(vi);
  155067. vorbis_comment_init(vc);
  155068. i=0;
  155069. while(i<3){
  155070. ogg_stream_pagein(&vf->os,og_ptr);
  155071. while(i<3){
  155072. int result=ogg_stream_packetout(&vf->os,&op);
  155073. if(result==0)break;
  155074. if(result==-1){
  155075. ret=OV_EBADHEADER;
  155076. goto bail_header;
  155077. }
  155078. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155079. goto bail_header;
  155080. }
  155081. i++;
  155082. }
  155083. if(i<3)
  155084. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155085. ret=OV_EBADHEADER;
  155086. goto bail_header;
  155087. }
  155088. }
  155089. return 0;
  155090. bail_header:
  155091. vorbis_info_clear(vi);
  155092. vorbis_comment_clear(vc);
  155093. vf->ready_state=OPENED;
  155094. return ret;
  155095. }
  155096. /* last step of the OggVorbis_File initialization; get all the
  155097. vorbis_info structs and PCM positions. Only called by the seekable
  155098. initialization (local stream storage is hacked slightly; pay
  155099. attention to how that's done) */
  155100. /* this is void and does not propogate errors up because we want to be
  155101. able to open and use damaged bitstreams as well as we can. Just
  155102. watch out for missing information for links in the OggVorbis_File
  155103. struct */
  155104. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155105. ogg_page og;
  155106. int i;
  155107. ogg_int64_t ret;
  155108. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155109. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155110. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155111. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155112. for(i=0;i<vf->links;i++){
  155113. if(i==0){
  155114. /* we already grabbed the initial header earlier. Just set the offset */
  155115. vf->dataoffsets[i]=dataoffset;
  155116. _seek_helper(vf,dataoffset);
  155117. }else{
  155118. /* seek to the location of the initial header */
  155119. _seek_helper(vf,vf->offsets[i]);
  155120. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155121. vf->dataoffsets[i]=-1;
  155122. }else{
  155123. vf->dataoffsets[i]=vf->offset;
  155124. }
  155125. }
  155126. /* fetch beginning PCM offset */
  155127. if(vf->dataoffsets[i]!=-1){
  155128. ogg_int64_t accumulated=0;
  155129. long lastblock=-1;
  155130. int result;
  155131. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155132. while(1){
  155133. ogg_packet op;
  155134. ret=_get_next_page(vf,&og,-1);
  155135. if(ret<0)
  155136. /* this should not be possible unless the file is
  155137. truncated/mangled */
  155138. break;
  155139. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155140. break;
  155141. /* count blocksizes of all frames in the page */
  155142. ogg_stream_pagein(&vf->os,&og);
  155143. while((result=ogg_stream_packetout(&vf->os,&op))){
  155144. if(result>0){ /* ignore holes */
  155145. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155146. if(lastblock!=-1)
  155147. accumulated+=(lastblock+thisblock)>>2;
  155148. lastblock=thisblock;
  155149. }
  155150. }
  155151. if(ogg_page_granulepos(&og)!=-1){
  155152. /* pcm offset of last packet on the first audio page */
  155153. accumulated= ogg_page_granulepos(&og)-accumulated;
  155154. break;
  155155. }
  155156. }
  155157. /* less than zero? This is a stream with samples trimmed off
  155158. the beginning, a normal occurrence; set the offset to zero */
  155159. if(accumulated<0)accumulated=0;
  155160. vf->pcmlengths[i*2]=accumulated;
  155161. }
  155162. /* get the PCM length of this link. To do this,
  155163. get the last page of the stream */
  155164. {
  155165. ogg_int64_t end=vf->offsets[i+1];
  155166. _seek_helper(vf,end);
  155167. while(1){
  155168. ret=_get_prev_page(vf,&og);
  155169. if(ret<0){
  155170. /* this should not be possible */
  155171. vorbis_info_clear(vf->vi+i);
  155172. vorbis_comment_clear(vf->vc+i);
  155173. break;
  155174. }
  155175. if(ogg_page_granulepos(&og)!=-1){
  155176. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155177. break;
  155178. }
  155179. vf->offset=ret;
  155180. }
  155181. }
  155182. }
  155183. }
  155184. static int _make_decode_ready(OggVorbis_File *vf){
  155185. if(vf->ready_state>STREAMSET)return 0;
  155186. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155187. if(vf->seekable){
  155188. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155189. return OV_EBADLINK;
  155190. }else{
  155191. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155192. return OV_EBADLINK;
  155193. }
  155194. vorbis_block_init(&vf->vd,&vf->vb);
  155195. vf->ready_state=INITSET;
  155196. vf->bittrack=0.f;
  155197. vf->samptrack=0.f;
  155198. return 0;
  155199. }
  155200. static int _open_seekable2(OggVorbis_File *vf){
  155201. long serialno=vf->current_serialno;
  155202. ogg_int64_t dataoffset=vf->offset, end;
  155203. ogg_page og;
  155204. /* we're partially open and have a first link header state in
  155205. storage in vf */
  155206. /* we can seek, so set out learning all about this file */
  155207. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155208. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155209. /* We get the offset for the last page of the physical bitstream.
  155210. Most OggVorbis files will contain a single logical bitstream */
  155211. end=_get_prev_page(vf,&og);
  155212. if(end<0)return(end);
  155213. /* more than one logical bitstream? */
  155214. if(ogg_page_serialno(&og)!=serialno){
  155215. /* Chained bitstream. Bisect-search each logical bitstream
  155216. section. Do so based on serial number only */
  155217. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155218. }else{
  155219. /* Only one logical bitstream */
  155220. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155221. }
  155222. /* the initial header memory is referenced by vf after; don't free it */
  155223. _prefetch_all_headers(vf,dataoffset);
  155224. return(ov_raw_seek(vf,0));
  155225. }
  155226. /* clear out the current logical bitstream decoder */
  155227. static void _decode_clear(OggVorbis_File *vf){
  155228. vorbis_dsp_clear(&vf->vd);
  155229. vorbis_block_clear(&vf->vb);
  155230. vf->ready_state=OPENED;
  155231. }
  155232. /* fetch and process a packet. Handles the case where we're at a
  155233. bitstream boundary and dumps the decoding machine. If the decoding
  155234. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155235. date (seek and read both use this. seek uses a special hack with
  155236. readp).
  155237. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155238. 0) need more data (only if readp==0)
  155239. 1) got a packet
  155240. */
  155241. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155242. ogg_packet *op_in,
  155243. int readp,
  155244. int spanp){
  155245. ogg_page og;
  155246. /* handle one packet. Try to fetch it from current stream state */
  155247. /* extract packets from page */
  155248. while(1){
  155249. /* process a packet if we can. If the machine isn't loaded,
  155250. neither is a page */
  155251. if(vf->ready_state==INITSET){
  155252. while(1) {
  155253. ogg_packet op;
  155254. ogg_packet *op_ptr=(op_in?op_in:&op);
  155255. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155256. ogg_int64_t granulepos;
  155257. op_in=NULL;
  155258. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155259. if(result>0){
  155260. /* got a packet. process it */
  155261. granulepos=op_ptr->granulepos;
  155262. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155263. header handling. The
  155264. header packets aren't
  155265. audio, so if/when we
  155266. submit them,
  155267. vorbis_synthesis will
  155268. reject them */
  155269. /* suck in the synthesis data and track bitrate */
  155270. {
  155271. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155272. /* for proper use of libvorbis within libvorbisfile,
  155273. oldsamples will always be zero. */
  155274. if(oldsamples)return(OV_EFAULT);
  155275. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155276. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155277. vf->bittrack+=op_ptr->bytes*8;
  155278. }
  155279. /* update the pcm offset. */
  155280. if(granulepos!=-1 && !op_ptr->e_o_s){
  155281. int link=(vf->seekable?vf->current_link:0);
  155282. int i,samples;
  155283. /* this packet has a pcm_offset on it (the last packet
  155284. completed on a page carries the offset) After processing
  155285. (above), we know the pcm position of the *last* sample
  155286. ready to be returned. Find the offset of the *first*
  155287. As an aside, this trick is inaccurate if we begin
  155288. reading anew right at the last page; the end-of-stream
  155289. granulepos declares the last frame in the stream, and the
  155290. last packet of the last page may be a partial frame.
  155291. So, we need a previous granulepos from an in-sequence page
  155292. to have a reference point. Thus the !op_ptr->e_o_s clause
  155293. above */
  155294. if(vf->seekable && link>0)
  155295. granulepos-=vf->pcmlengths[link*2];
  155296. if(granulepos<0)granulepos=0; /* actually, this
  155297. shouldn't be possible
  155298. here unless the stream
  155299. is very broken */
  155300. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155301. granulepos-=samples;
  155302. for(i=0;i<link;i++)
  155303. granulepos+=vf->pcmlengths[i*2+1];
  155304. vf->pcm_offset=granulepos;
  155305. }
  155306. return(1);
  155307. }
  155308. }
  155309. else
  155310. break;
  155311. }
  155312. }
  155313. if(vf->ready_state>=OPENED){
  155314. ogg_int64_t ret;
  155315. if(!readp)return(0);
  155316. if((ret=_get_next_page(vf,&og,-1))<0){
  155317. return(OV_EOF); /* eof.
  155318. leave unitialized */
  155319. }
  155320. /* bitrate tracking; add the header's bytes here, the body bytes
  155321. are done by packet above */
  155322. vf->bittrack+=og.header_len*8;
  155323. /* has our decoding just traversed a bitstream boundary? */
  155324. if(vf->ready_state==INITSET){
  155325. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155326. if(!spanp)
  155327. return(OV_EOF);
  155328. _decode_clear(vf);
  155329. if(!vf->seekable){
  155330. vorbis_info_clear(vf->vi);
  155331. vorbis_comment_clear(vf->vc);
  155332. }
  155333. }
  155334. }
  155335. }
  155336. /* Do we need to load a new machine before submitting the page? */
  155337. /* This is different in the seekable and non-seekable cases.
  155338. In the seekable case, we already have all the header
  155339. information loaded and cached; we just initialize the machine
  155340. with it and continue on our merry way.
  155341. In the non-seekable (streaming) case, we'll only be at a
  155342. boundary if we just left the previous logical bitstream and
  155343. we're now nominally at the header of the next bitstream
  155344. */
  155345. if(vf->ready_state!=INITSET){
  155346. int link;
  155347. if(vf->ready_state<STREAMSET){
  155348. if(vf->seekable){
  155349. vf->current_serialno=ogg_page_serialno(&og);
  155350. /* match the serialno to bitstream section. We use this rather than
  155351. offset positions to avoid problems near logical bitstream
  155352. boundaries */
  155353. for(link=0;link<vf->links;link++)
  155354. if(vf->serialnos[link]==vf->current_serialno)break;
  155355. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155356. stream. error out,
  155357. leave machine
  155358. uninitialized */
  155359. vf->current_link=link;
  155360. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155361. vf->ready_state=STREAMSET;
  155362. }else{
  155363. /* we're streaming */
  155364. /* fetch the three header packets, build the info struct */
  155365. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155366. if(ret)return(ret);
  155367. vf->current_link++;
  155368. link=0;
  155369. }
  155370. }
  155371. {
  155372. int ret=_make_decode_ready(vf);
  155373. if(ret<0)return ret;
  155374. }
  155375. }
  155376. ogg_stream_pagein(&vf->os,&og);
  155377. }
  155378. }
  155379. /* if, eg, 64 bit stdio is configured by default, this will build with
  155380. fseek64 */
  155381. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155382. if(f==NULL)return(-1);
  155383. return fseek(f,off,whence);
  155384. }
  155385. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155386. long ibytes, ov_callbacks callbacks){
  155387. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155388. int ret;
  155389. memset(vf,0,sizeof(*vf));
  155390. vf->datasource=f;
  155391. vf->callbacks = callbacks;
  155392. /* init the framing state */
  155393. ogg_sync_init(&vf->oy);
  155394. /* perhaps some data was previously read into a buffer for testing
  155395. against other stream types. Allow initialization from this
  155396. previously read data (as we may be reading from a non-seekable
  155397. stream) */
  155398. if(initial){
  155399. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155400. memcpy(buffer,initial,ibytes);
  155401. ogg_sync_wrote(&vf->oy,ibytes);
  155402. }
  155403. /* can we seek? Stevens suggests the seek test was portable */
  155404. if(offsettest!=-1)vf->seekable=1;
  155405. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155406. entry for partial open */
  155407. vf->links=1;
  155408. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155409. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155410. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155411. /* Try to fetch the headers, maintaining all the storage */
  155412. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155413. vf->datasource=NULL;
  155414. ov_clear(vf);
  155415. }else
  155416. vf->ready_state=PARTOPEN;
  155417. return(ret);
  155418. }
  155419. static int _ov_open2(OggVorbis_File *vf){
  155420. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155421. vf->ready_state=OPENED;
  155422. if(vf->seekable){
  155423. int ret=_open_seekable2(vf);
  155424. if(ret){
  155425. vf->datasource=NULL;
  155426. ov_clear(vf);
  155427. }
  155428. return(ret);
  155429. }else
  155430. vf->ready_state=STREAMSET;
  155431. return 0;
  155432. }
  155433. /* clear out the OggVorbis_File struct */
  155434. int ov_clear(OggVorbis_File *vf){
  155435. if(vf){
  155436. vorbis_block_clear(&vf->vb);
  155437. vorbis_dsp_clear(&vf->vd);
  155438. ogg_stream_clear(&vf->os);
  155439. if(vf->vi && vf->links){
  155440. int i;
  155441. for(i=0;i<vf->links;i++){
  155442. vorbis_info_clear(vf->vi+i);
  155443. vorbis_comment_clear(vf->vc+i);
  155444. }
  155445. _ogg_free(vf->vi);
  155446. _ogg_free(vf->vc);
  155447. }
  155448. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155449. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155450. if(vf->serialnos)_ogg_free(vf->serialnos);
  155451. if(vf->offsets)_ogg_free(vf->offsets);
  155452. ogg_sync_clear(&vf->oy);
  155453. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155454. memset(vf,0,sizeof(*vf));
  155455. }
  155456. #ifdef DEBUG_LEAKS
  155457. _VDBG_dump();
  155458. #endif
  155459. return(0);
  155460. }
  155461. /* inspects the OggVorbis file and finds/documents all the logical
  155462. bitstreams contained in it. Tries to be tolerant of logical
  155463. bitstream sections that are truncated/woogie.
  155464. return: -1) error
  155465. 0) OK
  155466. */
  155467. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155468. ov_callbacks callbacks){
  155469. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155470. if(ret)return ret;
  155471. return _ov_open2(vf);
  155472. }
  155473. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155474. ov_callbacks callbacks = {
  155475. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155476. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155477. (int (*)(void *)) fclose,
  155478. (long (*)(void *)) ftell
  155479. };
  155480. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155481. }
  155482. /* cheap hack for game usage where downsampling is desirable; there's
  155483. no need for SRC as we can just do it cheaply in libvorbis. */
  155484. int ov_halfrate(OggVorbis_File *vf,int flag){
  155485. int i;
  155486. if(vf->vi==NULL)return OV_EINVAL;
  155487. if(!vf->seekable)return OV_EINVAL;
  155488. if(vf->ready_state>=STREAMSET)
  155489. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155490. will be able to swap this on the fly, but
  155491. for now dumping the decode machine is needed
  155492. to reinit the MDCT lookups. 1.1 libvorbis
  155493. is planned to be able to switch on the fly */
  155494. for(i=0;i<vf->links;i++){
  155495. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155496. ov_halfrate(vf,0);
  155497. return OV_EINVAL;
  155498. }
  155499. }
  155500. return 0;
  155501. }
  155502. int ov_halfrate_p(OggVorbis_File *vf){
  155503. if(vf->vi==NULL)return OV_EINVAL;
  155504. return vorbis_synthesis_halfrate_p(vf->vi);
  155505. }
  155506. /* Only partially open the vorbis file; test for Vorbisness, and load
  155507. the headers for the first chain. Do not seek (although test for
  155508. seekability). Use ov_test_open to finish opening the file, else
  155509. ov_clear to close/free it. Same return codes as open. */
  155510. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155511. ov_callbacks callbacks)
  155512. {
  155513. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155514. }
  155515. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155516. ov_callbacks callbacks = {
  155517. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155518. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155519. (int (*)(void *)) fclose,
  155520. (long (*)(void *)) ftell
  155521. };
  155522. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155523. }
  155524. int ov_test_open(OggVorbis_File *vf){
  155525. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155526. return _ov_open2(vf);
  155527. }
  155528. /* How many logical bitstreams in this physical bitstream? */
  155529. long ov_streams(OggVorbis_File *vf){
  155530. return vf->links;
  155531. }
  155532. /* Is the FILE * associated with vf seekable? */
  155533. long ov_seekable(OggVorbis_File *vf){
  155534. return vf->seekable;
  155535. }
  155536. /* returns the bitrate for a given logical bitstream or the entire
  155537. physical bitstream. If the file is open for random access, it will
  155538. find the *actual* average bitrate. If the file is streaming, it
  155539. returns the nominal bitrate (if set) else the average of the
  155540. upper/lower bounds (if set) else -1 (unset).
  155541. If you want the actual bitrate field settings, get them from the
  155542. vorbis_info structs */
  155543. long ov_bitrate(OggVorbis_File *vf,int i){
  155544. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155545. if(i>=vf->links)return(OV_EINVAL);
  155546. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155547. if(i<0){
  155548. ogg_int64_t bits=0;
  155549. int i;
  155550. float br;
  155551. for(i=0;i<vf->links;i++)
  155552. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155553. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155554. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155555. * so this is slightly transformed to make it work.
  155556. */
  155557. br = bits/ov_time_total(vf,-1);
  155558. return(rint(br));
  155559. }else{
  155560. if(vf->seekable){
  155561. /* return the actual bitrate */
  155562. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155563. }else{
  155564. /* return nominal if set */
  155565. if(vf->vi[i].bitrate_nominal>0){
  155566. return vf->vi[i].bitrate_nominal;
  155567. }else{
  155568. if(vf->vi[i].bitrate_upper>0){
  155569. if(vf->vi[i].bitrate_lower>0){
  155570. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155571. }else{
  155572. return vf->vi[i].bitrate_upper;
  155573. }
  155574. }
  155575. return(OV_FALSE);
  155576. }
  155577. }
  155578. }
  155579. }
  155580. /* returns the actual bitrate since last call. returns -1 if no
  155581. additional data to offer since last call (or at beginning of stream),
  155582. EINVAL if stream is only partially open
  155583. */
  155584. long ov_bitrate_instant(OggVorbis_File *vf){
  155585. int link=(vf->seekable?vf->current_link:0);
  155586. long ret;
  155587. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155588. if(vf->samptrack==0)return(OV_FALSE);
  155589. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155590. vf->bittrack=0.f;
  155591. vf->samptrack=0.f;
  155592. return(ret);
  155593. }
  155594. /* Guess */
  155595. long ov_serialnumber(OggVorbis_File *vf,int i){
  155596. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155597. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155598. if(i<0){
  155599. return(vf->current_serialno);
  155600. }else{
  155601. return(vf->serialnos[i]);
  155602. }
  155603. }
  155604. /* returns: total raw (compressed) length of content if i==-1
  155605. raw (compressed) length of that logical bitstream for i==0 to n
  155606. OV_EINVAL if the stream is not seekable (we can't know the length)
  155607. or if stream is only partially open
  155608. */
  155609. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155610. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155611. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155612. if(i<0){
  155613. ogg_int64_t acc=0;
  155614. int i;
  155615. for(i=0;i<vf->links;i++)
  155616. acc+=ov_raw_total(vf,i);
  155617. return(acc);
  155618. }else{
  155619. return(vf->offsets[i+1]-vf->offsets[i]);
  155620. }
  155621. }
  155622. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155623. (samples) of that logical bitstream for i==0 to n
  155624. OV_EINVAL if the stream is not seekable (we can't know the
  155625. length) or only partially open
  155626. */
  155627. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155628. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155629. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155630. if(i<0){
  155631. ogg_int64_t acc=0;
  155632. int i;
  155633. for(i=0;i<vf->links;i++)
  155634. acc+=ov_pcm_total(vf,i);
  155635. return(acc);
  155636. }else{
  155637. return(vf->pcmlengths[i*2+1]);
  155638. }
  155639. }
  155640. /* returns: total seconds of content if i==-1
  155641. seconds in that logical bitstream for i==0 to n
  155642. OV_EINVAL if the stream is not seekable (we can't know the
  155643. length) or only partially open
  155644. */
  155645. double ov_time_total(OggVorbis_File *vf,int i){
  155646. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155647. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155648. if(i<0){
  155649. double acc=0;
  155650. int i;
  155651. for(i=0;i<vf->links;i++)
  155652. acc+=ov_time_total(vf,i);
  155653. return(acc);
  155654. }else{
  155655. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155656. }
  155657. }
  155658. /* seek to an offset relative to the *compressed* data. This also
  155659. scans packets to update the PCM cursor. It will cross a logical
  155660. bitstream boundary, but only if it can't get any packets out of the
  155661. tail of the bitstream we seek to (so no surprises).
  155662. returns zero on success, nonzero on failure */
  155663. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155664. ogg_stream_state work_os;
  155665. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155666. if(!vf->seekable)
  155667. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155668. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155669. /* don't yet clear out decoding machine (if it's initialized), in
  155670. the case we're in the same link. Restart the decode lapping, and
  155671. let _fetch_and_process_packet deal with a potential bitstream
  155672. boundary */
  155673. vf->pcm_offset=-1;
  155674. ogg_stream_reset_serialno(&vf->os,
  155675. vf->current_serialno); /* must set serialno */
  155676. vorbis_synthesis_restart(&vf->vd);
  155677. _seek_helper(vf,pos);
  155678. /* we need to make sure the pcm_offset is set, but we don't want to
  155679. advance the raw cursor past good packets just to get to the first
  155680. with a granulepos. That's not equivalent behavior to beginning
  155681. decoding as immediately after the seek position as possible.
  155682. So, a hack. We use two stream states; a local scratch state and
  155683. the shared vf->os stream state. We use the local state to
  155684. scan, and the shared state as a buffer for later decode.
  155685. Unfortuantely, on the last page we still advance to last packet
  155686. because the granulepos on the last page is not necessarily on a
  155687. packet boundary, and we need to make sure the granpos is
  155688. correct.
  155689. */
  155690. {
  155691. ogg_page og;
  155692. ogg_packet op;
  155693. int lastblock=0;
  155694. int accblock=0;
  155695. int thisblock;
  155696. int eosflag;
  155697. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155698. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155699. return from not necessarily
  155700. starting from the beginning */
  155701. while(1){
  155702. if(vf->ready_state>=STREAMSET){
  155703. /* snarf/scan a packet if we can */
  155704. int result=ogg_stream_packetout(&work_os,&op);
  155705. if(result>0){
  155706. if(vf->vi[vf->current_link].codec_setup){
  155707. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155708. if(thisblock<0){
  155709. ogg_stream_packetout(&vf->os,NULL);
  155710. thisblock=0;
  155711. }else{
  155712. if(eosflag)
  155713. ogg_stream_packetout(&vf->os,NULL);
  155714. else
  155715. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155716. }
  155717. if(op.granulepos!=-1){
  155718. int i,link=vf->current_link;
  155719. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155720. if(granulepos<0)granulepos=0;
  155721. for(i=0;i<link;i++)
  155722. granulepos+=vf->pcmlengths[i*2+1];
  155723. vf->pcm_offset=granulepos-accblock;
  155724. break;
  155725. }
  155726. lastblock=thisblock;
  155727. continue;
  155728. }else
  155729. ogg_stream_packetout(&vf->os,NULL);
  155730. }
  155731. }
  155732. if(!lastblock){
  155733. if(_get_next_page(vf,&og,-1)<0){
  155734. vf->pcm_offset=ov_pcm_total(vf,-1);
  155735. break;
  155736. }
  155737. }else{
  155738. /* huh? Bogus stream with packets but no granulepos */
  155739. vf->pcm_offset=-1;
  155740. break;
  155741. }
  155742. /* has our decoding just traversed a bitstream boundary? */
  155743. if(vf->ready_state>=STREAMSET)
  155744. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155745. _decode_clear(vf); /* clear out stream state */
  155746. ogg_stream_clear(&work_os);
  155747. }
  155748. if(vf->ready_state<STREAMSET){
  155749. int link;
  155750. vf->current_serialno=ogg_page_serialno(&og);
  155751. for(link=0;link<vf->links;link++)
  155752. if(vf->serialnos[link]==vf->current_serialno)break;
  155753. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155754. error out, leave
  155755. machine uninitialized */
  155756. vf->current_link=link;
  155757. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155758. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155759. vf->ready_state=STREAMSET;
  155760. }
  155761. ogg_stream_pagein(&vf->os,&og);
  155762. ogg_stream_pagein(&work_os,&og);
  155763. eosflag=ogg_page_eos(&og);
  155764. }
  155765. }
  155766. ogg_stream_clear(&work_os);
  155767. vf->bittrack=0.f;
  155768. vf->samptrack=0.f;
  155769. return(0);
  155770. seek_error:
  155771. /* dump the machine so we're in a known state */
  155772. vf->pcm_offset=-1;
  155773. ogg_stream_clear(&work_os);
  155774. _decode_clear(vf);
  155775. return OV_EBADLINK;
  155776. }
  155777. /* Page granularity seek (faster than sample granularity because we
  155778. don't do the last bit of decode to find a specific sample).
  155779. Seek to the last [granule marked] page preceeding the specified pos
  155780. location, such that decoding past the returned point will quickly
  155781. arrive at the requested position. */
  155782. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155783. int link=-1;
  155784. ogg_int64_t result=0;
  155785. ogg_int64_t total=ov_pcm_total(vf,-1);
  155786. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155787. if(!vf->seekable)return(OV_ENOSEEK);
  155788. if(pos<0 || pos>total)return(OV_EINVAL);
  155789. /* which bitstream section does this pcm offset occur in? */
  155790. for(link=vf->links-1;link>=0;link--){
  155791. total-=vf->pcmlengths[link*2+1];
  155792. if(pos>=total)break;
  155793. }
  155794. /* search within the logical bitstream for the page with the highest
  155795. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155796. missing pages or incorrect frame number information in the
  155797. bitstream could make our task impossible. Account for that (it
  155798. would be an error condition) */
  155799. /* new search algorithm by HB (Nicholas Vinen) */
  155800. {
  155801. ogg_int64_t end=vf->offsets[link+1];
  155802. ogg_int64_t begin=vf->offsets[link];
  155803. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155804. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155805. ogg_int64_t target=pos-total+begintime;
  155806. ogg_int64_t best=begin;
  155807. ogg_page og;
  155808. while(begin<end){
  155809. ogg_int64_t bisect;
  155810. if(end-begin<CHUNKSIZE){
  155811. bisect=begin;
  155812. }else{
  155813. /* take a (pretty decent) guess. */
  155814. bisect=begin +
  155815. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  155816. if(bisect<=begin)
  155817. bisect=begin+1;
  155818. }
  155819. _seek_helper(vf,bisect);
  155820. while(begin<end){
  155821. result=_get_next_page(vf,&og,end-vf->offset);
  155822. if(result==OV_EREAD) goto seek_error;
  155823. if(result<0){
  155824. if(bisect<=begin+1)
  155825. end=begin; /* found it */
  155826. else{
  155827. if(bisect==0) goto seek_error;
  155828. bisect-=CHUNKSIZE;
  155829. if(bisect<=begin)bisect=begin+1;
  155830. _seek_helper(vf,bisect);
  155831. }
  155832. }else{
  155833. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  155834. if(granulepos==-1)continue;
  155835. if(granulepos<target){
  155836. best=result; /* raw offset of packet with granulepos */
  155837. begin=vf->offset; /* raw offset of next page */
  155838. begintime=granulepos;
  155839. if(target-begintime>44100)break;
  155840. bisect=begin; /* *not* begin + 1 */
  155841. }else{
  155842. if(bisect<=begin+1)
  155843. end=begin; /* found it */
  155844. else{
  155845. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  155846. end=result;
  155847. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  155848. if(bisect<=begin)bisect=begin+1;
  155849. _seek_helper(vf,bisect);
  155850. }else{
  155851. end=result;
  155852. endtime=granulepos;
  155853. break;
  155854. }
  155855. }
  155856. }
  155857. }
  155858. }
  155859. }
  155860. /* found our page. seek to it, update pcm offset. Easier case than
  155861. raw_seek, don't keep packets preceeding granulepos. */
  155862. {
  155863. ogg_page og;
  155864. ogg_packet op;
  155865. /* seek */
  155866. _seek_helper(vf,best);
  155867. vf->pcm_offset=-1;
  155868. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  155869. if(link!=vf->current_link){
  155870. /* Different link; dump entire decode machine */
  155871. _decode_clear(vf);
  155872. vf->current_link=link;
  155873. vf->current_serialno=ogg_page_serialno(&og);
  155874. vf->ready_state=STREAMSET;
  155875. }else{
  155876. vorbis_synthesis_restart(&vf->vd);
  155877. }
  155878. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155879. ogg_stream_pagein(&vf->os,&og);
  155880. /* pull out all but last packet; the one with granulepos */
  155881. while(1){
  155882. result=ogg_stream_packetpeek(&vf->os,&op);
  155883. if(result==0){
  155884. /* !!! the packet finishing this page originated on a
  155885. preceeding page. Keep fetching previous pages until we
  155886. get one with a granulepos or without the 'continued' flag
  155887. set. Then just use raw_seek for simplicity. */
  155888. _seek_helper(vf,best);
  155889. while(1){
  155890. result=_get_prev_page(vf,&og);
  155891. if(result<0) goto seek_error;
  155892. if(ogg_page_granulepos(&og)>-1 ||
  155893. !ogg_page_continued(&og)){
  155894. return ov_raw_seek(vf,result);
  155895. }
  155896. vf->offset=result;
  155897. }
  155898. }
  155899. if(result<0){
  155900. result = OV_EBADPACKET;
  155901. goto seek_error;
  155902. }
  155903. if(op.granulepos!=-1){
  155904. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155905. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155906. vf->pcm_offset+=total;
  155907. break;
  155908. }else
  155909. result=ogg_stream_packetout(&vf->os,NULL);
  155910. }
  155911. }
  155912. }
  155913. /* verify result */
  155914. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  155915. result=OV_EFAULT;
  155916. goto seek_error;
  155917. }
  155918. vf->bittrack=0.f;
  155919. vf->samptrack=0.f;
  155920. return(0);
  155921. seek_error:
  155922. /* dump machine so we're in a known state */
  155923. vf->pcm_offset=-1;
  155924. _decode_clear(vf);
  155925. return (int)result;
  155926. }
  155927. /* seek to a sample offset relative to the decompressed pcm stream
  155928. returns zero on success, nonzero on failure */
  155929. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155930. int thisblock,lastblock=0;
  155931. int ret=ov_pcm_seek_page(vf,pos);
  155932. if(ret<0)return(ret);
  155933. if((ret=_make_decode_ready(vf)))return ret;
  155934. /* discard leading packets we don't need for the lapping of the
  155935. position we want; don't decode them */
  155936. while(1){
  155937. ogg_packet op;
  155938. ogg_page og;
  155939. int ret=ogg_stream_packetpeek(&vf->os,&op);
  155940. if(ret>0){
  155941. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155942. if(thisblock<0){
  155943. ogg_stream_packetout(&vf->os,NULL);
  155944. continue; /* non audio packet */
  155945. }
  155946. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  155947. if(vf->pcm_offset+((thisblock+
  155948. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  155949. /* remove the packet from packet queue and track its granulepos */
  155950. ogg_stream_packetout(&vf->os,NULL);
  155951. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  155952. only tracking, no
  155953. pcm_decode */
  155954. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155955. /* end of logical stream case is hard, especially with exact
  155956. length positioning. */
  155957. if(op.granulepos>-1){
  155958. int i;
  155959. /* always believe the stream markers */
  155960. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155961. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155962. for(i=0;i<vf->current_link;i++)
  155963. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  155964. }
  155965. lastblock=thisblock;
  155966. }else{
  155967. if(ret<0 && ret!=OV_HOLE)break;
  155968. /* suck in a new page */
  155969. if(_get_next_page(vf,&og,-1)<0)break;
  155970. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  155971. if(vf->ready_state<STREAMSET){
  155972. int link;
  155973. vf->current_serialno=ogg_page_serialno(&og);
  155974. for(link=0;link<vf->links;link++)
  155975. if(vf->serialnos[link]==vf->current_serialno)break;
  155976. if(link==vf->links)return(OV_EBADLINK);
  155977. vf->current_link=link;
  155978. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155979. vf->ready_state=STREAMSET;
  155980. ret=_make_decode_ready(vf);
  155981. if(ret)return ret;
  155982. lastblock=0;
  155983. }
  155984. ogg_stream_pagein(&vf->os,&og);
  155985. }
  155986. }
  155987. vf->bittrack=0.f;
  155988. vf->samptrack=0.f;
  155989. /* discard samples until we reach the desired position. Crossing a
  155990. logical bitstream boundary with abandon is OK. */
  155991. while(vf->pcm_offset<pos){
  155992. ogg_int64_t target=pos-vf->pcm_offset;
  155993. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155994. if(samples>target)samples=target;
  155995. vorbis_synthesis_read(&vf->vd,samples);
  155996. vf->pcm_offset+=samples;
  155997. if(samples<target)
  155998. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  155999. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156000. }
  156001. return 0;
  156002. }
  156003. /* seek to a playback time relative to the decompressed pcm stream
  156004. returns zero on success, nonzero on failure */
  156005. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156006. /* translate time to PCM position and call ov_pcm_seek */
  156007. int link=-1;
  156008. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156009. double time_total=ov_time_total(vf,-1);
  156010. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156011. if(!vf->seekable)return(OV_ENOSEEK);
  156012. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156013. /* which bitstream section does this time offset occur in? */
  156014. for(link=vf->links-1;link>=0;link--){
  156015. pcm_total-=vf->pcmlengths[link*2+1];
  156016. time_total-=ov_time_total(vf,link);
  156017. if(seconds>=time_total)break;
  156018. }
  156019. /* enough information to convert time offset to pcm offset */
  156020. {
  156021. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156022. return(ov_pcm_seek(vf,target));
  156023. }
  156024. }
  156025. /* page-granularity version of ov_time_seek
  156026. returns zero on success, nonzero on failure */
  156027. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156028. /* translate time to PCM position and call ov_pcm_seek */
  156029. int link=-1;
  156030. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156031. double time_total=ov_time_total(vf,-1);
  156032. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156033. if(!vf->seekable)return(OV_ENOSEEK);
  156034. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156035. /* which bitstream section does this time offset occur in? */
  156036. for(link=vf->links-1;link>=0;link--){
  156037. pcm_total-=vf->pcmlengths[link*2+1];
  156038. time_total-=ov_time_total(vf,link);
  156039. if(seconds>=time_total)break;
  156040. }
  156041. /* enough information to convert time offset to pcm offset */
  156042. {
  156043. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156044. return(ov_pcm_seek_page(vf,target));
  156045. }
  156046. }
  156047. /* tell the current stream offset cursor. Note that seek followed by
  156048. tell will likely not give the set offset due to caching */
  156049. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156050. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156051. return(vf->offset);
  156052. }
  156053. /* return PCM offset (sample) of next PCM sample to be read */
  156054. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156055. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156056. return(vf->pcm_offset);
  156057. }
  156058. /* return time offset (seconds) of next PCM sample to be read */
  156059. double ov_time_tell(OggVorbis_File *vf){
  156060. int link=0;
  156061. ogg_int64_t pcm_total=0;
  156062. double time_total=0.f;
  156063. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156064. if(vf->seekable){
  156065. pcm_total=ov_pcm_total(vf,-1);
  156066. time_total=ov_time_total(vf,-1);
  156067. /* which bitstream section does this time offset occur in? */
  156068. for(link=vf->links-1;link>=0;link--){
  156069. pcm_total-=vf->pcmlengths[link*2+1];
  156070. time_total-=ov_time_total(vf,link);
  156071. if(vf->pcm_offset>=pcm_total)break;
  156072. }
  156073. }
  156074. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156075. }
  156076. /* link: -1) return the vorbis_info struct for the bitstream section
  156077. currently being decoded
  156078. 0-n) to request information for a specific bitstream section
  156079. In the case of a non-seekable bitstream, any call returns the
  156080. current bitstream. NULL in the case that the machine is not
  156081. initialized */
  156082. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156083. if(vf->seekable){
  156084. if(link<0)
  156085. if(vf->ready_state>=STREAMSET)
  156086. return vf->vi+vf->current_link;
  156087. else
  156088. return vf->vi;
  156089. else
  156090. if(link>=vf->links)
  156091. return NULL;
  156092. else
  156093. return vf->vi+link;
  156094. }else{
  156095. return vf->vi;
  156096. }
  156097. }
  156098. /* grr, strong typing, grr, no templates/inheritence, grr */
  156099. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156100. if(vf->seekable){
  156101. if(link<0)
  156102. if(vf->ready_state>=STREAMSET)
  156103. return vf->vc+vf->current_link;
  156104. else
  156105. return vf->vc;
  156106. else
  156107. if(link>=vf->links)
  156108. return NULL;
  156109. else
  156110. return vf->vc+link;
  156111. }else{
  156112. return vf->vc;
  156113. }
  156114. }
  156115. static int host_is_big_endian() {
  156116. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156117. unsigned char *bytewise = (unsigned char *)&pattern;
  156118. if (bytewise[0] == 0xfe) return 1;
  156119. return 0;
  156120. }
  156121. /* up to this point, everything could more or less hide the multiple
  156122. logical bitstream nature of chaining from the toplevel application
  156123. if the toplevel application didn't particularly care. However, at
  156124. the point that we actually read audio back, the multiple-section
  156125. nature must surface: Multiple bitstream sections do not necessarily
  156126. have to have the same number of channels or sampling rate.
  156127. ov_read returns the sequential logical bitstream number currently
  156128. being decoded along with the PCM data in order that the toplevel
  156129. application can take action on channel/sample rate changes. This
  156130. number will be incremented even for streamed (non-seekable) streams
  156131. (for seekable streams, it represents the actual logical bitstream
  156132. index within the physical bitstream. Note that the accessor
  156133. functions above are aware of this dichotomy).
  156134. input values: buffer) a buffer to hold packed PCM data for return
  156135. length) the byte length requested to be placed into buffer
  156136. bigendianp) should the data be packed LSB first (0) or
  156137. MSB first (1)
  156138. word) word size for output. currently 1 (byte) or
  156139. 2 (16 bit short)
  156140. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156141. 0) EOF
  156142. n) number of bytes of PCM actually returned. The
  156143. below works on a packet-by-packet basis, so the
  156144. return length is not related to the 'length' passed
  156145. in, just guaranteed to fit.
  156146. *section) set to the logical bitstream number */
  156147. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156148. int bigendianp,int word,int sgned,int *bitstream){
  156149. int i,j;
  156150. int host_endian = host_is_big_endian();
  156151. float **pcm;
  156152. long samples;
  156153. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156154. while(1){
  156155. if(vf->ready_state==INITSET){
  156156. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156157. if(samples)break;
  156158. }
  156159. /* suck in another packet */
  156160. {
  156161. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156162. if(ret==OV_EOF)
  156163. return(0);
  156164. if(ret<=0)
  156165. return(ret);
  156166. }
  156167. }
  156168. if(samples>0){
  156169. /* yay! proceed to pack data into the byte buffer */
  156170. long channels=ov_info(vf,-1)->channels;
  156171. long bytespersample=word * channels;
  156172. vorbis_fpu_control fpu;
  156173. (void) fpu; // (to avoid a warning about it being unused)
  156174. if(samples>length/bytespersample)samples=length/bytespersample;
  156175. if(samples <= 0)
  156176. return OV_EINVAL;
  156177. /* a tight loop to pack each size */
  156178. {
  156179. int val;
  156180. if(word==1){
  156181. int off=(sgned?0:128);
  156182. vorbis_fpu_setround(&fpu);
  156183. for(j=0;j<samples;j++)
  156184. for(i=0;i<channels;i++){
  156185. val=vorbis_ftoi(pcm[i][j]*128.f);
  156186. if(val>127)val=127;
  156187. else if(val<-128)val=-128;
  156188. *buffer++=val+off;
  156189. }
  156190. vorbis_fpu_restore(fpu);
  156191. }else{
  156192. int off=(sgned?0:32768);
  156193. if(host_endian==bigendianp){
  156194. if(sgned){
  156195. vorbis_fpu_setround(&fpu);
  156196. for(i=0;i<channels;i++) { /* It's faster in this order */
  156197. float *src=pcm[i];
  156198. short *dest=((short *)buffer)+i;
  156199. for(j=0;j<samples;j++) {
  156200. val=vorbis_ftoi(src[j]*32768.f);
  156201. if(val>32767)val=32767;
  156202. else if(val<-32768)val=-32768;
  156203. *dest=val;
  156204. dest+=channels;
  156205. }
  156206. }
  156207. vorbis_fpu_restore(fpu);
  156208. }else{
  156209. vorbis_fpu_setround(&fpu);
  156210. for(i=0;i<channels;i++) {
  156211. float *src=pcm[i];
  156212. short *dest=((short *)buffer)+i;
  156213. for(j=0;j<samples;j++) {
  156214. val=vorbis_ftoi(src[j]*32768.f);
  156215. if(val>32767)val=32767;
  156216. else if(val<-32768)val=-32768;
  156217. *dest=val+off;
  156218. dest+=channels;
  156219. }
  156220. }
  156221. vorbis_fpu_restore(fpu);
  156222. }
  156223. }else if(bigendianp){
  156224. vorbis_fpu_setround(&fpu);
  156225. for(j=0;j<samples;j++)
  156226. for(i=0;i<channels;i++){
  156227. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156228. if(val>32767)val=32767;
  156229. else if(val<-32768)val=-32768;
  156230. val+=off;
  156231. *buffer++=(val>>8);
  156232. *buffer++=(val&0xff);
  156233. }
  156234. vorbis_fpu_restore(fpu);
  156235. }else{
  156236. int val;
  156237. vorbis_fpu_setround(&fpu);
  156238. for(j=0;j<samples;j++)
  156239. for(i=0;i<channels;i++){
  156240. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156241. if(val>32767)val=32767;
  156242. else if(val<-32768)val=-32768;
  156243. val+=off;
  156244. *buffer++=(val&0xff);
  156245. *buffer++=(val>>8);
  156246. }
  156247. vorbis_fpu_restore(fpu);
  156248. }
  156249. }
  156250. }
  156251. vorbis_synthesis_read(&vf->vd,samples);
  156252. vf->pcm_offset+=samples;
  156253. if(bitstream)*bitstream=vf->current_link;
  156254. return(samples*bytespersample);
  156255. }else{
  156256. return(samples);
  156257. }
  156258. }
  156259. /* input values: pcm_channels) a float vector per channel of output
  156260. length) the sample length being read by the app
  156261. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156262. 0) EOF
  156263. n) number of samples of PCM actually returned. The
  156264. below works on a packet-by-packet basis, so the
  156265. return length is not related to the 'length' passed
  156266. in, just guaranteed to fit.
  156267. *section) set to the logical bitstream number */
  156268. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156269. int *bitstream){
  156270. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156271. while(1){
  156272. if(vf->ready_state==INITSET){
  156273. float **pcm;
  156274. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156275. if(samples){
  156276. if(pcm_channels)*pcm_channels=pcm;
  156277. if(samples>length)samples=length;
  156278. vorbis_synthesis_read(&vf->vd,samples);
  156279. vf->pcm_offset+=samples;
  156280. if(bitstream)*bitstream=vf->current_link;
  156281. return samples;
  156282. }
  156283. }
  156284. /* suck in another packet */
  156285. {
  156286. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156287. if(ret==OV_EOF)return(0);
  156288. if(ret<=0)return(ret);
  156289. }
  156290. }
  156291. }
  156292. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156293. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156294. ogg_int64_t off);
  156295. static void _ov_splice(float **pcm,float **lappcm,
  156296. int n1, int n2,
  156297. int ch1, int ch2,
  156298. float *w1, float *w2){
  156299. int i,j;
  156300. float *w=w1;
  156301. int n=n1;
  156302. if(n1>n2){
  156303. n=n2;
  156304. w=w2;
  156305. }
  156306. /* splice */
  156307. for(j=0;j<ch1 && j<ch2;j++){
  156308. float *s=lappcm[j];
  156309. float *d=pcm[j];
  156310. for(i=0;i<n;i++){
  156311. float wd=w[i]*w[i];
  156312. float ws=1.-wd;
  156313. d[i]=d[i]*wd + s[i]*ws;
  156314. }
  156315. }
  156316. /* window from zero */
  156317. for(;j<ch2;j++){
  156318. float *d=pcm[j];
  156319. for(i=0;i<n;i++){
  156320. float wd=w[i]*w[i];
  156321. d[i]=d[i]*wd;
  156322. }
  156323. }
  156324. }
  156325. /* make sure vf is INITSET */
  156326. static int _ov_initset(OggVorbis_File *vf){
  156327. while(1){
  156328. if(vf->ready_state==INITSET)break;
  156329. /* suck in another packet */
  156330. {
  156331. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156332. if(ret<0 && ret!=OV_HOLE)return(ret);
  156333. }
  156334. }
  156335. return 0;
  156336. }
  156337. /* make sure vf is INITSET and that we have a primed buffer; if
  156338. we're crosslapping at a stream section boundary, this also makes
  156339. sure we're sanity checking against the right stream information */
  156340. static int _ov_initprime(OggVorbis_File *vf){
  156341. vorbis_dsp_state *vd=&vf->vd;
  156342. while(1){
  156343. if(vf->ready_state==INITSET)
  156344. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156345. /* suck in another packet */
  156346. {
  156347. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156348. if(ret<0 && ret!=OV_HOLE)return(ret);
  156349. }
  156350. }
  156351. return 0;
  156352. }
  156353. /* grab enough data for lapping from vf; this may be in the form of
  156354. unreturned, already-decoded pcm, remaining PCM we will need to
  156355. decode, or synthetic postextrapolation from last packets. */
  156356. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156357. float **lappcm,int lapsize){
  156358. int lapcount=0,i;
  156359. float **pcm;
  156360. /* try first to decode the lapping data */
  156361. while(lapcount<lapsize){
  156362. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156363. if(samples){
  156364. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156365. for(i=0;i<vi->channels;i++)
  156366. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156367. lapcount+=samples;
  156368. vorbis_synthesis_read(vd,samples);
  156369. }else{
  156370. /* suck in another packet */
  156371. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156372. if(ret==OV_EOF)break;
  156373. }
  156374. }
  156375. if(lapcount<lapsize){
  156376. /* failed to get lapping data from normal decode; pry it from the
  156377. postextrapolation buffering, or the second half of the MDCT
  156378. from the last packet */
  156379. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156380. if(samples==0){
  156381. for(i=0;i<vi->channels;i++)
  156382. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156383. lapcount=lapsize;
  156384. }else{
  156385. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156386. for(i=0;i<vi->channels;i++)
  156387. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156388. lapcount+=samples;
  156389. }
  156390. }
  156391. }
  156392. /* this sets up crosslapping of a sample by using trailing data from
  156393. sample 1 and lapping it into the windowing buffer of sample 2 */
  156394. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156395. vorbis_info *vi1,*vi2;
  156396. float **lappcm;
  156397. float **pcm;
  156398. float *w1,*w2;
  156399. int n1,n2,i,ret,hs1,hs2;
  156400. if(vf1==vf2)return(0); /* degenerate case */
  156401. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156402. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156403. /* the relevant overlap buffers must be pre-checked and pre-primed
  156404. before looking at settings in the event that priming would cross
  156405. a bitstream boundary. So, do it now */
  156406. ret=_ov_initset(vf1);
  156407. if(ret)return(ret);
  156408. ret=_ov_initprime(vf2);
  156409. if(ret)return(ret);
  156410. vi1=ov_info(vf1,-1);
  156411. vi2=ov_info(vf2,-1);
  156412. hs1=ov_halfrate_p(vf1);
  156413. hs2=ov_halfrate_p(vf2);
  156414. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156415. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156416. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156417. w1=vorbis_window(&vf1->vd,0);
  156418. w2=vorbis_window(&vf2->vd,0);
  156419. for(i=0;i<vi1->channels;i++)
  156420. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156421. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156422. /* have a lapping buffer from vf1; now to splice it into the lapping
  156423. buffer of vf2 */
  156424. /* consolidate and expose the buffer. */
  156425. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156426. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156427. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156428. /* splice */
  156429. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156430. /* done */
  156431. return(0);
  156432. }
  156433. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156434. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156435. vorbis_info *vi;
  156436. float **lappcm;
  156437. float **pcm;
  156438. float *w1,*w2;
  156439. int n1,n2,ch1,ch2,hs;
  156440. int i,ret;
  156441. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156442. ret=_ov_initset(vf);
  156443. if(ret)return(ret);
  156444. vi=ov_info(vf,-1);
  156445. hs=ov_halfrate_p(vf);
  156446. ch1=vi->channels;
  156447. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156448. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156449. persistent; even if the decode state
  156450. from this link gets dumped, this
  156451. window array continues to exist */
  156452. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156453. for(i=0;i<ch1;i++)
  156454. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156455. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156456. /* have lapping data; seek and prime the buffer */
  156457. ret=localseek(vf,pos);
  156458. if(ret)return ret;
  156459. ret=_ov_initprime(vf);
  156460. if(ret)return(ret);
  156461. /* Guard against cross-link changes; they're perfectly legal */
  156462. vi=ov_info(vf,-1);
  156463. ch2=vi->channels;
  156464. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156465. w2=vorbis_window(&vf->vd,0);
  156466. /* consolidate and expose the buffer. */
  156467. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156468. /* splice */
  156469. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156470. /* done */
  156471. return(0);
  156472. }
  156473. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156474. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156475. }
  156476. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156477. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156478. }
  156479. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156480. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156481. }
  156482. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156483. int (*localseek)(OggVorbis_File *,double)){
  156484. vorbis_info *vi;
  156485. float **lappcm;
  156486. float **pcm;
  156487. float *w1,*w2;
  156488. int n1,n2,ch1,ch2,hs;
  156489. int i,ret;
  156490. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156491. ret=_ov_initset(vf);
  156492. if(ret)return(ret);
  156493. vi=ov_info(vf,-1);
  156494. hs=ov_halfrate_p(vf);
  156495. ch1=vi->channels;
  156496. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156497. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156498. persistent; even if the decode state
  156499. from this link gets dumped, this
  156500. window array continues to exist */
  156501. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156502. for(i=0;i<ch1;i++)
  156503. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156504. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156505. /* have lapping data; seek and prime the buffer */
  156506. ret=localseek(vf,pos);
  156507. if(ret)return ret;
  156508. ret=_ov_initprime(vf);
  156509. if(ret)return(ret);
  156510. /* Guard against cross-link changes; they're perfectly legal */
  156511. vi=ov_info(vf,-1);
  156512. ch2=vi->channels;
  156513. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156514. w2=vorbis_window(&vf->vd,0);
  156515. /* consolidate and expose the buffer. */
  156516. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156517. /* splice */
  156518. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156519. /* done */
  156520. return(0);
  156521. }
  156522. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156523. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156524. }
  156525. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156526. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156527. }
  156528. #endif
  156529. /*** End of inlined file: vorbisfile.c ***/
  156530. /*** Start of inlined file: window.c ***/
  156531. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156532. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156533. // tasks..
  156534. #if JUCE_MSVC
  156535. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156536. #endif
  156537. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156538. #if JUCE_USE_OGGVORBIS
  156539. #include <stdlib.h>
  156540. #include <math.h>
  156541. static float vwin64[32] = {
  156542. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156543. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156544. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156545. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156546. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156547. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156548. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156549. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156550. };
  156551. static float vwin128[64] = {
  156552. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156553. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156554. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156555. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156556. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156557. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156558. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156559. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156560. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156561. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156562. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156563. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156564. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156565. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156566. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156567. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156568. };
  156569. static float vwin256[128] = {
  156570. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156571. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156572. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156573. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156574. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156575. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156576. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156577. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156578. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156579. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156580. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156581. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156582. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156583. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156584. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156585. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156586. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156587. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156588. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156589. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156590. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156591. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156592. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156593. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156594. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156595. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156596. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156597. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156598. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156599. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156600. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156601. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156602. };
  156603. static float vwin512[256] = {
  156604. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156605. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156606. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156607. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156608. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156609. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156610. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156611. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156612. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156613. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156614. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156615. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156616. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156617. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156618. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156619. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156620. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156621. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156622. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156623. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156624. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156625. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156626. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156627. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156628. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156629. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156630. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156631. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156632. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156633. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156634. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156635. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156636. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156637. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156638. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156639. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156640. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156641. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156642. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156643. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156644. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156645. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156646. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156647. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156648. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156649. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156650. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156651. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156652. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156653. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156654. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156655. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156656. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156657. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156658. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156659. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156660. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156661. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156662. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156663. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156664. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156665. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156666. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156667. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156668. };
  156669. static float vwin1024[512] = {
  156670. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156671. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156672. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156673. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156674. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156675. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156676. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156677. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156678. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156679. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156680. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156681. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156682. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156683. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156684. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156685. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156686. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156687. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156688. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156689. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156690. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156691. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156692. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156693. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156694. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156695. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156696. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156697. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156698. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156699. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156700. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156701. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156702. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156703. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156704. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156705. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156706. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156707. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156708. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156709. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156710. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156711. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156712. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156713. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156714. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156715. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156716. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156717. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156718. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156719. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156720. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156721. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156722. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156723. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156724. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156725. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156726. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156727. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156728. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156729. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156730. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156731. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156732. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156733. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156734. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156735. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156736. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156737. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156738. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156739. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156740. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156741. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156742. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156743. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156744. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156745. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156746. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156747. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156748. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156749. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156750. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156751. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156752. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156753. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156754. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156755. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156756. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156757. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156758. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156759. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156760. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156761. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156762. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156763. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156764. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156765. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156766. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156767. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156768. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156769. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156770. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156771. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156772. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156773. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156774. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156775. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156776. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156777. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156778. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156779. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156780. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156781. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156782. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156783. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156784. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156785. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156786. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156787. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156788. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156789. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156790. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156791. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156792. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156793. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156794. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156795. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156796. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156797. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156798. };
  156799. static float vwin2048[1024] = {
  156800. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156801. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156802. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156803. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156804. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156805. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156806. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156807. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156808. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156809. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156810. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156811. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156812. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156813. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  156814. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  156815. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  156816. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  156817. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  156818. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  156819. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  156820. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  156821. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  156822. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  156823. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  156824. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  156825. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  156826. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  156827. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  156828. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  156829. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  156830. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  156831. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  156832. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  156833. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  156834. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  156835. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  156836. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  156837. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  156838. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  156839. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  156840. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  156841. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  156842. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  156843. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  156844. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  156845. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  156846. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  156847. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  156848. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  156849. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  156850. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  156851. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  156852. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  156853. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  156854. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  156855. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  156856. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  156857. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  156858. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  156859. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  156860. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  156861. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  156862. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  156863. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  156864. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  156865. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  156866. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  156867. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  156868. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  156869. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  156870. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  156871. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  156872. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  156873. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  156874. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  156875. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  156876. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  156877. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  156878. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  156879. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  156880. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  156881. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  156882. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  156883. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  156884. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  156885. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  156886. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  156887. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  156888. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  156889. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  156890. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  156891. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  156892. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  156893. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  156894. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  156895. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  156896. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  156897. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  156898. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  156899. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  156900. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  156901. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  156902. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  156903. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  156904. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  156905. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  156906. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  156907. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  156908. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  156909. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  156910. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  156911. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  156912. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  156913. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  156914. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  156915. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  156916. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  156917. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  156918. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  156919. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  156920. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  156921. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  156922. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  156923. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  156924. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  156925. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  156926. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  156927. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  156928. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  156929. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  156930. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  156931. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  156932. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  156933. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  156934. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  156935. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  156936. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  156937. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  156938. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  156939. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  156940. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  156941. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  156942. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  156943. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  156944. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  156945. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  156946. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  156947. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  156948. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  156949. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  156950. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  156951. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  156952. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  156953. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  156954. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  156955. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  156956. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  156957. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  156958. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  156959. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  156960. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  156961. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  156962. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  156963. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  156964. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  156965. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  156966. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  156967. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  156968. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  156969. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  156970. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  156971. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  156972. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  156973. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  156974. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  156975. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  156976. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  156977. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  156978. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  156979. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  156980. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  156981. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  156982. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  156983. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  156984. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  156985. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  156986. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  156987. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  156988. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  156989. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  156990. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  156991. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  156992. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  156993. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  156994. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  156995. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  156996. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  156997. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  156998. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  156999. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157000. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157001. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157002. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157003. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157004. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157005. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157006. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157007. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157008. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157009. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157010. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157011. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157012. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157013. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157014. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157015. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157016. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157017. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157018. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157019. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157020. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157021. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157022. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157023. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157024. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157025. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157026. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157027. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157028. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157029. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157030. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157031. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157032. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157033. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157034. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157035. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157036. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157037. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157038. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157039. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157040. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157041. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157042. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157043. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157044. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157045. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157046. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157047. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157048. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157049. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157050. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157051. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157052. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157053. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157054. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157055. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157056. };
  157057. static float vwin4096[2048] = {
  157058. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157059. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157060. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157061. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157062. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157063. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157064. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157065. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157066. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157067. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157068. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157069. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157070. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157071. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157072. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157073. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157074. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157075. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157076. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157077. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157078. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157079. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157080. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157081. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157082. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157083. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157084. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157085. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157086. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157087. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157088. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157089. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157090. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157091. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157092. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157093. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157094. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157095. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157096. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157097. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157098. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157099. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157100. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157101. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157102. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157103. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157104. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157105. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157106. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157107. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157108. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157109. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157110. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157111. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157112. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157113. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157114. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157115. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157116. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157117. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157118. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157119. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157120. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157121. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157122. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157123. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157124. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157125. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157126. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157127. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157128. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157129. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157130. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157131. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157132. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157133. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157134. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157135. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157136. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157137. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157138. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157139. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157140. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157141. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157142. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157143. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157144. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157145. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157146. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157147. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157148. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157149. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157150. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157151. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157152. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157153. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157154. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157155. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157156. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157157. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157158. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157159. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157160. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157161. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157162. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157163. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157164. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157165. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157166. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157167. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157168. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157169. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157170. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157171. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157172. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157173. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157174. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157175. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157176. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157177. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157178. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157179. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157180. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157181. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157182. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157183. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157184. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157185. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157186. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157187. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157188. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157189. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157190. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157191. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157192. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157193. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157194. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157195. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157196. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157197. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157198. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157199. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157200. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157201. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157202. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157203. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157204. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157205. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157206. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157207. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157208. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157209. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157210. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157211. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157212. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157213. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157214. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157215. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157216. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157217. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157218. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157219. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157220. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157221. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157222. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157223. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157224. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157225. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157226. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157227. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157228. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157229. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157230. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157231. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157232. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157233. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157234. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157235. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157236. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157237. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157238. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157239. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157240. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157241. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157242. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157243. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157244. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157245. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157246. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157247. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157248. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157249. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157250. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157251. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157252. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157253. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157254. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157255. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157256. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157257. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157258. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157259. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157260. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157261. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157262. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157263. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157264. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157265. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157266. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157267. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157268. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157269. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157270. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157271. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157272. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157273. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157274. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157275. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157276. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157277. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157278. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157279. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157280. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157281. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157282. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157283. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157284. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157285. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157286. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157287. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157288. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157289. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157290. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157291. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157292. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157293. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157294. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157295. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157296. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157297. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157298. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157299. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157300. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157301. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157302. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157303. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157304. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157305. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157306. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157307. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157308. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157309. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157310. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157311. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157312. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157313. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157314. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157315. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157316. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157317. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157318. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157319. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157320. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157321. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157322. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157323. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157324. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157325. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157326. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157327. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157328. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157329. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157330. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157331. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157332. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157333. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157334. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157335. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157336. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157337. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157338. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157339. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157340. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157341. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157342. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157343. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157344. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157345. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157346. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157347. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157348. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157349. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157350. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157351. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157352. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157353. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157354. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157355. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157356. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157357. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157358. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157359. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157360. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157361. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157362. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157363. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157364. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157365. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157366. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157367. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157368. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157369. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157370. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157371. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157372. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157373. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157374. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157375. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157376. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157377. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157378. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157379. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157380. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157381. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157382. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157383. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157384. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157385. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157386. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157387. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157388. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157389. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157390. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157391. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157392. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157393. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157394. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157395. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157396. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157397. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157398. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157399. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157400. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157401. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157402. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157403. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157404. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157405. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157406. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157407. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157408. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157409. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157410. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157411. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157412. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157413. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157414. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157415. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157416. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157417. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157418. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157419. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157420. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157421. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157422. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157423. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157424. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157425. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157426. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157427. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157428. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157429. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157430. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157431. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157432. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157433. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157434. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157435. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157436. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157437. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157438. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157439. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157440. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157441. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157442. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157443. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157444. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157445. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157446. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157447. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157448. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157449. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157450. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157451. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157452. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157453. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157454. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157455. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157456. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157457. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157458. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157459. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157460. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157461. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157462. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157463. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157464. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157465. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157466. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157467. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157468. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157469. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157470. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157471. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157472. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157473. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157474. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157475. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157476. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157477. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157478. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157479. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157480. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157481. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157482. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157483. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157484. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157485. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157486. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157487. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157488. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157489. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157490. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157491. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157492. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157493. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157494. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157495. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157496. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157497. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157498. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157499. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157500. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157501. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157502. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157503. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157504. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157505. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157506. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157507. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157508. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157509. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157510. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157511. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157512. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157513. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157514. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157515. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157516. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157517. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157518. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157519. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157520. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157521. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157522. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157523. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157524. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157525. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157526. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157527. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157528. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157529. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157530. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157531. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157532. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157533. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157534. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157535. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157536. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157537. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157538. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157539. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157540. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157541. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157542. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157543. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157544. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157545. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157546. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157547. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157548. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157549. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157550. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157551. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157552. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157553. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157554. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157555. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157556. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157557. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157558. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157559. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157560. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157561. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157562. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157563. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157564. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157565. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157566. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157567. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157568. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157569. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157570. };
  157571. static float vwin8192[4096] = {
  157572. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157573. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157574. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157575. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157576. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157577. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157578. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157579. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157580. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157581. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157582. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157583. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157584. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157585. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157586. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157587. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157588. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157589. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157590. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157591. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157592. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157593. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157594. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157595. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157596. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157597. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157598. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157599. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157600. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157601. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157602. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157603. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157604. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157605. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157606. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157607. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157608. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157609. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157610. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157611. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157612. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157613. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157614. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157615. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157616. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157617. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157618. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157619. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157620. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157621. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157622. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157623. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157624. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157625. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157626. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157627. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157628. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157629. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157630. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157631. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157632. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157633. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157634. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157635. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157636. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157637. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157638. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157639. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157640. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157641. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157642. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157643. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157644. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157645. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157646. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157647. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157648. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157649. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157650. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157651. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157652. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157653. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157654. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157655. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157656. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157657. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157658. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157659. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157660. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157661. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157662. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157663. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157664. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157665. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157666. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157667. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157668. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157669. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157670. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157671. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157672. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157673. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157674. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157675. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157676. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157677. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157678. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157679. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157680. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157681. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157682. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157683. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157684. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157685. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157686. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157687. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157688. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157689. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157690. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157691. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157692. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157693. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157694. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157695. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157696. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157697. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157698. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157699. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157700. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157701. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157702. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157703. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157704. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157705. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157706. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157707. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157708. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157709. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157710. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157711. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157712. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157713. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157714. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157715. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157716. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157717. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157718. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157719. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157720. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157721. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157722. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157723. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157724. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157725. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157726. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157727. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157728. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157729. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157730. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157731. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157732. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157733. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157734. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157735. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157736. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157737. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157738. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157739. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157740. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157741. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157742. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157743. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157744. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157745. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157746. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157747. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157748. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157749. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157750. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157751. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157752. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157753. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157754. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157755. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157756. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157757. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157758. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157759. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157760. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157761. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157762. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157763. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157764. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157765. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157766. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157767. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157768. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157769. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157770. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157771. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157772. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157773. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157774. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157775. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157776. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157777. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157778. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157779. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157780. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157781. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157782. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157783. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157784. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157785. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157786. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157787. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157788. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157789. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157790. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157791. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157792. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157793. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157794. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157795. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157796. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157797. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157798. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157799. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157800. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157801. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157802. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157803. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157804. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157805. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157806. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157807. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157808. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157809. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157810. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157811. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157812. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157813. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  157814. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  157815. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  157816. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  157817. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  157818. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  157819. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  157820. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  157821. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  157822. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  157823. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  157824. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  157825. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  157826. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  157827. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  157828. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  157829. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  157830. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  157831. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  157832. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  157833. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  157834. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  157835. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  157836. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  157837. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  157838. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  157839. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  157840. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  157841. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  157842. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  157843. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  157844. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  157845. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  157846. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  157847. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  157848. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  157849. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  157850. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  157851. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  157852. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  157853. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  157854. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  157855. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  157856. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  157857. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  157858. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  157859. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  157860. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  157861. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  157862. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  157863. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  157864. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  157865. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  157866. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  157867. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  157868. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  157869. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  157870. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  157871. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  157872. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  157873. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  157874. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  157875. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  157876. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  157877. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  157878. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  157879. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  157880. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  157881. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  157882. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  157883. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  157884. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  157885. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  157886. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  157887. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  157888. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  157889. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  157890. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  157891. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  157892. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  157893. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  157894. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  157895. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  157896. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  157897. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  157898. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  157899. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  157900. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  157901. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  157902. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  157903. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  157904. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  157905. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  157906. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  157907. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  157908. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  157909. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  157910. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  157911. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  157912. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  157913. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  157914. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  157915. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  157916. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  157917. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  157918. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  157919. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  157920. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  157921. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  157922. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  157923. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  157924. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  157925. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  157926. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  157927. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  157928. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  157929. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  157930. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  157931. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  157932. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  157933. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  157934. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  157935. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  157936. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  157937. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  157938. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  157939. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  157940. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  157941. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  157942. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  157943. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  157944. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  157945. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  157946. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  157947. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  157948. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  157949. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  157950. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  157951. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  157952. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  157953. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  157954. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  157955. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  157956. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  157957. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  157958. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  157959. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  157960. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  157961. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  157962. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  157963. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  157964. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  157965. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  157966. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  157967. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  157968. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  157969. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  157970. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  157971. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  157972. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  157973. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  157974. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  157975. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  157976. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  157977. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  157978. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  157979. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  157980. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  157981. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  157982. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  157983. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  157984. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  157985. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  157986. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  157987. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  157988. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  157989. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  157990. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  157991. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  157992. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  157993. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  157994. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  157995. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  157996. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  157997. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  157998. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  157999. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158000. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158001. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158002. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158003. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158004. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158005. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158006. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158007. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158008. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158009. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158010. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158011. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158012. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158013. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158014. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158015. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158016. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158017. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158018. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158019. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158020. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158021. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158022. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158023. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158024. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158025. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158026. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158027. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158028. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158029. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158030. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158031. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158032. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158033. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158034. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158035. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158036. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158037. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158038. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158039. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158040. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158041. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158042. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158043. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158044. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158045. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158046. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158047. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158048. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158049. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158050. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158051. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158052. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158053. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158054. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158055. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158056. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158057. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158058. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158059. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158060. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158061. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158062. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158063. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158064. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158065. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158066. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158067. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158068. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158069. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158070. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158071. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158072. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158073. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158074. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158075. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158076. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158077. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158078. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158079. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158080. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158081. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158082. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158083. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158084. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158085. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158086. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158087. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158088. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158089. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158090. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158091. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158092. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158093. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158094. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158095. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158096. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158097. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158098. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158099. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158100. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158101. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158102. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158103. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158104. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158105. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158106. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158107. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158108. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158109. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158110. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158111. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158112. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158113. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158114. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158115. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158116. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158117. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158118. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158119. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158120. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158121. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158122. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158123. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158124. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158125. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158126. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158127. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158128. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158129. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158130. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158131. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158132. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158133. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158134. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158135. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158136. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158137. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158138. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158139. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158140. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158141. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158142. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158143. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158144. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158145. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158146. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158147. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158148. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158149. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158150. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158151. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158152. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158153. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158154. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158155. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158156. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158157. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158158. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158159. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158160. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158161. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158162. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158163. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158164. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158165. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158166. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158167. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158168. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158169. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158170. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158171. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158172. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158173. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158174. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158175. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158176. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158177. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158178. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158179. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158180. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158181. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158182. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158183. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158184. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158185. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158186. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158187. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158188. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158189. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158190. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158191. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158192. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158193. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158194. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158195. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158196. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158197. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158198. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158199. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158200. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158201. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158202. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158203. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158204. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158205. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158206. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158207. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158208. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158209. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158210. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158211. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158212. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158213. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158214. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158215. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158216. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158217. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158218. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158219. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158220. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158221. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158222. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158223. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158224. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158225. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158226. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158227. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158228. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158229. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158230. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158231. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158232. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158233. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158234. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158235. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158236. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158237. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158238. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158239. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158240. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158241. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158242. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158243. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158244. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158245. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158246. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158247. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158248. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158249. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158250. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158251. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158252. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158253. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158254. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158255. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158256. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158257. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158258. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158259. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158260. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158261. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158262. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158263. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158264. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158265. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158266. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158267. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158268. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158269. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158270. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158271. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158272. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158273. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158274. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158275. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158276. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158277. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158278. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158279. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158280. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158281. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158282. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158283. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158284. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158285. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158286. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158287. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158288. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158289. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158290. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158291. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158292. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158293. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158294. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158295. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158296. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158297. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158298. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158299. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158300. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158301. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158302. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158303. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158304. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158305. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158306. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158307. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158308. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158309. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158310. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158311. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158312. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158313. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158314. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158315. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158316. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158317. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158318. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158319. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158320. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158321. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158322. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158323. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158324. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158325. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158326. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158327. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158328. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158329. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158330. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158331. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158332. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158333. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158334. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158335. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158336. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158337. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158338. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158339. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158340. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158341. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158342. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158343. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158344. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158345. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158346. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158347. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158348. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158349. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158350. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158351. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158352. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158353. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158354. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158355. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158356. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158357. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158358. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158359. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158360. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158361. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158362. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158363. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158364. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158365. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158366. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158367. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158368. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158369. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158370. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158371. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158372. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158373. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158374. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158375. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158376. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158377. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158378. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158379. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158380. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158381. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158382. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158383. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158384. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158385. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158386. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158387. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158388. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158389. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158390. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158391. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158392. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158393. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158394. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158395. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158396. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158397. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158398. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158399. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158400. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158401. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158402. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158403. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158404. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158405. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158406. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158407. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158408. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158409. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158410. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158411. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158412. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158413. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158414. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158415. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158416. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158417. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158418. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158419. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158420. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158421. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158422. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158423. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158424. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158425. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158426. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158427. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158428. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158429. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158430. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158431. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158432. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158433. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158434. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158435. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158436. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158437. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158438. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158439. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158440. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158441. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158442. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158443. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158444. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158445. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158446. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158447. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158448. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158449. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158450. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158451. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158452. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158453. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158454. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158455. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158456. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158457. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158458. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158459. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158460. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158461. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158462. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158463. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158464. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158465. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158466. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158467. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158468. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158469. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158470. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158471. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158472. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158473. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158474. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158475. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158476. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158477. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158478. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158479. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158480. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158481. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158482. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158483. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158484. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158485. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158486. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158487. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158488. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158489. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158490. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158491. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158492. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158493. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158494. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158495. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158496. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158497. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158498. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158499. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158500. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158501. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158502. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158503. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158504. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158505. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158506. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158507. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158508. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158509. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158510. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158511. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158512. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158513. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158514. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158515. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158516. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158517. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158518. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158519. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158520. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158521. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158522. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158523. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158524. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158525. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158526. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158527. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158528. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158529. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158530. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158531. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158532. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158533. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158534. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158535. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158536. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158537. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158538. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158539. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158540. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158541. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158542. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158543. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158544. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158545. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158546. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158547. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158548. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158549. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158550. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158551. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158552. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158553. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158554. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158555. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158556. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158557. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158558. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158559. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158560. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158561. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158562. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158563. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158564. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158565. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158566. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158567. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158568. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158569. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158570. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158571. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158572. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158573. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158574. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158575. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158576. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158577. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158578. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158579. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158580. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158581. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158582. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158583. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158584. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158585. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158586. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158587. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158588. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158589. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158590. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158591. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158592. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158593. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158594. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158595. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158596. };
  158597. static float *vwin[8] = {
  158598. vwin64,
  158599. vwin128,
  158600. vwin256,
  158601. vwin512,
  158602. vwin1024,
  158603. vwin2048,
  158604. vwin4096,
  158605. vwin8192,
  158606. };
  158607. float *_vorbis_window_get(int n){
  158608. return vwin[n];
  158609. }
  158610. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158611. int lW,int W,int nW){
  158612. lW=(W?lW:0);
  158613. nW=(W?nW:0);
  158614. {
  158615. float *windowLW=vwin[winno[lW]];
  158616. float *windowNW=vwin[winno[nW]];
  158617. long n=blocksizes[W];
  158618. long ln=blocksizes[lW];
  158619. long rn=blocksizes[nW];
  158620. long leftbegin=n/4-ln/4;
  158621. long leftend=leftbegin+ln/2;
  158622. long rightbegin=n/2+n/4-rn/4;
  158623. long rightend=rightbegin+rn/2;
  158624. int i,p;
  158625. for(i=0;i<leftbegin;i++)
  158626. d[i]=0.f;
  158627. for(p=0;i<leftend;i++,p++)
  158628. d[i]*=windowLW[p];
  158629. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158630. d[i]*=windowNW[p];
  158631. for(;i<n;i++)
  158632. d[i]=0.f;
  158633. }
  158634. }
  158635. #endif
  158636. /*** End of inlined file: window.c ***/
  158637. #else
  158638. #include <vorbis/vorbisenc.h>
  158639. #include <vorbis/codec.h>
  158640. #include <vorbis/vorbisfile.h>
  158641. #endif
  158642. }
  158643. #undef max
  158644. #undef min
  158645. BEGIN_JUCE_NAMESPACE
  158646. static const char* const oggFormatName = "Ogg-Vorbis file";
  158647. static const char* const oggExtensions[] = { ".ogg", 0 };
  158648. class OggReader : public AudioFormatReader
  158649. {
  158650. OggVorbisNamespace::OggVorbis_File ovFile;
  158651. OggVorbisNamespace::ov_callbacks callbacks;
  158652. AudioSampleBuffer reservoir;
  158653. int reservoirStart, samplesInReservoir;
  158654. public:
  158655. OggReader (InputStream* const inp)
  158656. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158657. reservoir (2, 4096),
  158658. reservoirStart (0),
  158659. samplesInReservoir (0)
  158660. {
  158661. using namespace OggVorbisNamespace;
  158662. sampleRate = 0;
  158663. usesFloatingPointData = true;
  158664. callbacks.read_func = &oggReadCallback;
  158665. callbacks.seek_func = &oggSeekCallback;
  158666. callbacks.close_func = &oggCloseCallback;
  158667. callbacks.tell_func = &oggTellCallback;
  158668. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158669. if (err == 0)
  158670. {
  158671. vorbis_info* info = ov_info (&ovFile, -1);
  158672. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158673. numChannels = info->channels;
  158674. bitsPerSample = 16;
  158675. sampleRate = info->rate;
  158676. reservoir.setSize (numChannels,
  158677. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158678. }
  158679. }
  158680. ~OggReader()
  158681. {
  158682. OggVorbisNamespace::ov_clear (&ovFile);
  158683. }
  158684. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158685. int64 startSampleInFile, int numSamples)
  158686. {
  158687. while (numSamples > 0)
  158688. {
  158689. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158690. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158691. {
  158692. // got a few samples overlapping, so use them before seeking..
  158693. const int numToUse = jmin (numSamples, numAvailable);
  158694. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158695. if (destSamples[i] != 0)
  158696. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158697. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158698. sizeof (float) * numToUse);
  158699. startSampleInFile += numToUse;
  158700. numSamples -= numToUse;
  158701. startOffsetInDestBuffer += numToUse;
  158702. if (numSamples == 0)
  158703. break;
  158704. }
  158705. if (startSampleInFile < reservoirStart
  158706. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158707. {
  158708. // buffer miss, so refill the reservoir
  158709. int bitStream = 0;
  158710. reservoirStart = jmax (0, (int) startSampleInFile);
  158711. samplesInReservoir = reservoir.getNumSamples();
  158712. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158713. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158714. int offset = 0;
  158715. int numToRead = samplesInReservoir;
  158716. while (numToRead > 0)
  158717. {
  158718. float** dataIn = 0;
  158719. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158720. if (samps <= 0)
  158721. break;
  158722. jassert (samps <= numToRead);
  158723. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158724. {
  158725. memcpy (reservoir.getSampleData (i, offset),
  158726. dataIn[i],
  158727. sizeof (float) * samps);
  158728. }
  158729. numToRead -= samps;
  158730. offset += samps;
  158731. }
  158732. if (numToRead > 0)
  158733. reservoir.clear (offset, numToRead);
  158734. }
  158735. }
  158736. if (numSamples > 0)
  158737. {
  158738. for (int i = numDestChannels; --i >= 0;)
  158739. if (destSamples[i] != 0)
  158740. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158741. sizeof (int) * numSamples);
  158742. }
  158743. return true;
  158744. }
  158745. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158746. {
  158747. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158748. }
  158749. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158750. {
  158751. InputStream* const in = static_cast <InputStream*> (datasource);
  158752. if (whence == SEEK_CUR)
  158753. offset += in->getPosition();
  158754. else if (whence == SEEK_END)
  158755. offset += in->getTotalLength();
  158756. in->setPosition (offset);
  158757. return 0;
  158758. }
  158759. static int oggCloseCallback (void*)
  158760. {
  158761. return 0;
  158762. }
  158763. static long oggTellCallback (void* datasource)
  158764. {
  158765. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158766. }
  158767. juce_UseDebuggingNewOperator
  158768. };
  158769. class OggWriter : public AudioFormatWriter
  158770. {
  158771. OggVorbisNamespace::ogg_stream_state os;
  158772. OggVorbisNamespace::ogg_page og;
  158773. OggVorbisNamespace::ogg_packet op;
  158774. OggVorbisNamespace::vorbis_info vi;
  158775. OggVorbisNamespace::vorbis_comment vc;
  158776. OggVorbisNamespace::vorbis_dsp_state vd;
  158777. OggVorbisNamespace::vorbis_block vb;
  158778. public:
  158779. bool ok;
  158780. OggWriter (OutputStream* const out,
  158781. const double sampleRate,
  158782. const int numChannels,
  158783. const int bitsPerSample,
  158784. const int qualityIndex)
  158785. : AudioFormatWriter (out, TRANS (oggFormatName),
  158786. sampleRate,
  158787. numChannels,
  158788. bitsPerSample)
  158789. {
  158790. using namespace OggVorbisNamespace;
  158791. ok = false;
  158792. vorbis_info_init (&vi);
  158793. if (vorbis_encode_init_vbr (&vi,
  158794. numChannels,
  158795. (int) sampleRate,
  158796. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158797. {
  158798. vorbis_comment_init (&vc);
  158799. if (JUCEApplication::getInstance() != 0)
  158800. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  158801. vorbis_analysis_init (&vd, &vi);
  158802. vorbis_block_init (&vd, &vb);
  158803. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158804. ogg_packet header;
  158805. ogg_packet header_comm;
  158806. ogg_packet header_code;
  158807. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158808. ogg_stream_packetin (&os, &header);
  158809. ogg_stream_packetin (&os, &header_comm);
  158810. ogg_stream_packetin (&os, &header_code);
  158811. for (;;)
  158812. {
  158813. if (ogg_stream_flush (&os, &og) == 0)
  158814. break;
  158815. output->write (og.header, og.header_len);
  158816. output->write (og.body, og.body_len);
  158817. }
  158818. ok = true;
  158819. }
  158820. }
  158821. ~OggWriter()
  158822. {
  158823. using namespace OggVorbisNamespace;
  158824. if (ok)
  158825. {
  158826. // write a zero-length packet to show ogg that we're finished..
  158827. write (0, 0);
  158828. ogg_stream_clear (&os);
  158829. vorbis_block_clear (&vb);
  158830. vorbis_dsp_clear (&vd);
  158831. vorbis_comment_clear (&vc);
  158832. vorbis_info_clear (&vi);
  158833. output->flush();
  158834. }
  158835. else
  158836. {
  158837. vorbis_info_clear (&vi);
  158838. output = 0; // to stop the base class deleting this, as it needs to be returned
  158839. // to the caller of createWriter()
  158840. }
  158841. }
  158842. bool write (const int** samplesToWrite, int numSamples)
  158843. {
  158844. using namespace OggVorbisNamespace;
  158845. if (! ok)
  158846. return false;
  158847. if (numSamples > 0)
  158848. {
  158849. const double gain = 1.0 / 0x80000000u;
  158850. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  158851. for (int i = numChannels; --i >= 0;)
  158852. {
  158853. float* const dst = vorbisBuffer[i];
  158854. const int* const src = samplesToWrite [i];
  158855. if (src != 0 && dst != 0)
  158856. {
  158857. for (int j = 0; j < numSamples; ++j)
  158858. dst[j] = (float) (src[j] * gain);
  158859. }
  158860. }
  158861. }
  158862. vorbis_analysis_wrote (&vd, numSamples);
  158863. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  158864. {
  158865. vorbis_analysis (&vb, 0);
  158866. vorbis_bitrate_addblock (&vb);
  158867. while (vorbis_bitrate_flushpacket (&vd, &op))
  158868. {
  158869. ogg_stream_packetin (&os, &op);
  158870. for (;;)
  158871. {
  158872. if (ogg_stream_pageout (&os, &og) == 0)
  158873. break;
  158874. output->write (og.header, og.header_len);
  158875. output->write (og.body, og.body_len);
  158876. if (ogg_page_eos (&og))
  158877. break;
  158878. }
  158879. }
  158880. }
  158881. return true;
  158882. }
  158883. juce_UseDebuggingNewOperator
  158884. };
  158885. OggVorbisAudioFormat::OggVorbisAudioFormat()
  158886. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  158887. {
  158888. }
  158889. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  158890. {
  158891. }
  158892. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  158893. {
  158894. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  158895. return Array <int> (rates);
  158896. }
  158897. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  158898. {
  158899. Array <int> depths;
  158900. depths.add (32);
  158901. return depths;
  158902. }
  158903. bool OggVorbisAudioFormat::canDoStereo()
  158904. {
  158905. return true;
  158906. }
  158907. bool OggVorbisAudioFormat::canDoMono()
  158908. {
  158909. return true;
  158910. }
  158911. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  158912. const bool deleteStreamIfOpeningFails)
  158913. {
  158914. ScopedPointer <OggReader> r (new OggReader (in));
  158915. if (r->sampleRate != 0)
  158916. return r.release();
  158917. if (! deleteStreamIfOpeningFails)
  158918. r->input = 0;
  158919. return 0;
  158920. }
  158921. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  158922. double sampleRate,
  158923. unsigned int numChannels,
  158924. int bitsPerSample,
  158925. const StringPairArray& /*metadataValues*/,
  158926. int qualityOptionIndex)
  158927. {
  158928. ScopedPointer <OggWriter> w (new OggWriter (out,
  158929. sampleRate,
  158930. numChannels,
  158931. bitsPerSample,
  158932. qualityOptionIndex));
  158933. return w->ok ? w.release() : 0;
  158934. }
  158935. bool OggVorbisAudioFormat::isCompressed()
  158936. {
  158937. return true;
  158938. }
  158939. const StringArray OggVorbisAudioFormat::getQualityOptions()
  158940. {
  158941. StringArray s;
  158942. s.add ("Low Quality");
  158943. s.add ("Medium Quality");
  158944. s.add ("High Quality");
  158945. return s;
  158946. }
  158947. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  158948. {
  158949. FileInputStream* const in = source.createInputStream();
  158950. if (in != 0)
  158951. {
  158952. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  158953. if (r != 0)
  158954. {
  158955. const int64 numSamps = r->lengthInSamples;
  158956. r = 0;
  158957. const int64 fileNumSamps = source.getSize() / 4;
  158958. const double ratio = numSamps / (double) fileNumSamps;
  158959. if (ratio > 12.0)
  158960. return 0;
  158961. else if (ratio > 6.0)
  158962. return 1;
  158963. else
  158964. return 2;
  158965. }
  158966. }
  158967. return 1;
  158968. }
  158969. END_JUCE_NAMESPACE
  158970. #endif
  158971. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  158972. #endif
  158973. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  158974. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  158975. #if JUCE_MSVC
  158976. #pragma warning (push)
  158977. #endif
  158978. namespace jpeglibNamespace
  158979. {
  158980. #if JUCE_INCLUDE_JPEGLIB_CODE
  158981. #if JUCE_MINGW
  158982. typedef unsigned char boolean;
  158983. #endif
  158984. extern "C"
  158985. {
  158986. #define JPEG_INTERNALS
  158987. #undef FAR
  158988. /*** Start of inlined file: jpeglib.h ***/
  158989. #ifndef JPEGLIB_H
  158990. #define JPEGLIB_H
  158991. /*
  158992. * First we include the configuration files that record how this
  158993. * installation of the JPEG library is set up. jconfig.h can be
  158994. * generated automatically for many systems. jmorecfg.h contains
  158995. * manual configuration options that most people need not worry about.
  158996. */
  158997. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  158998. /*** Start of inlined file: jconfig.h ***/
  158999. /* see jconfig.doc for explanations */
  159000. // disable all the warnings under MSVC
  159001. #ifdef _MSC_VER
  159002. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159003. #endif
  159004. #ifdef __BORLANDC__
  159005. #pragma warn -8057
  159006. #pragma warn -8019
  159007. #pragma warn -8004
  159008. #pragma warn -8008
  159009. #endif
  159010. #define HAVE_PROTOTYPES
  159011. #define HAVE_UNSIGNED_CHAR
  159012. #define HAVE_UNSIGNED_SHORT
  159013. /* #define void char */
  159014. /* #define const */
  159015. #undef CHAR_IS_UNSIGNED
  159016. #define HAVE_STDDEF_H
  159017. #define HAVE_STDLIB_H
  159018. #undef NEED_BSD_STRINGS
  159019. #undef NEED_SYS_TYPES_H
  159020. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159021. #undef NEED_SHORT_EXTERNAL_NAMES
  159022. #undef INCOMPLETE_TYPES_BROKEN
  159023. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159024. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159025. typedef unsigned char boolean;
  159026. #endif
  159027. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159028. #ifdef JPEG_INTERNALS
  159029. #undef RIGHT_SHIFT_IS_UNSIGNED
  159030. #endif /* JPEG_INTERNALS */
  159031. #ifdef JPEG_CJPEG_DJPEG
  159032. #define BMP_SUPPORTED /* BMP image file format */
  159033. #define GIF_SUPPORTED /* GIF image file format */
  159034. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159035. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159036. #define TARGA_SUPPORTED /* Targa image file format */
  159037. #define TWO_FILE_COMMANDLINE /* optional */
  159038. #define USE_SETMODE /* Microsoft has setmode() */
  159039. #undef NEED_SIGNAL_CATCHER
  159040. #undef DONT_USE_B_MODE
  159041. #undef PROGRESS_REPORT /* optional */
  159042. #endif /* JPEG_CJPEG_DJPEG */
  159043. /*** End of inlined file: jconfig.h ***/
  159044. /* widely used configuration options */
  159045. #endif
  159046. /*** Start of inlined file: jmorecfg.h ***/
  159047. /*
  159048. * Define BITS_IN_JSAMPLE as either
  159049. * 8 for 8-bit sample values (the usual setting)
  159050. * 12 for 12-bit sample values
  159051. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159052. * JPEG standard, and the IJG code does not support anything else!
  159053. * We do not support run-time selection of data precision, sorry.
  159054. */
  159055. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159056. /*
  159057. * Maximum number of components (color channels) allowed in JPEG image.
  159058. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159059. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159060. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159061. * really short on memory. (Each allowed component costs a hundred or so
  159062. * bytes of storage, whether actually used in an image or not.)
  159063. */
  159064. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159065. /*
  159066. * Basic data types.
  159067. * You may need to change these if you have a machine with unusual data
  159068. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159069. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159070. * but it had better be at least 16.
  159071. */
  159072. /* Representation of a single sample (pixel element value).
  159073. * We frequently allocate large arrays of these, so it's important to keep
  159074. * them small. But if you have memory to burn and access to char or short
  159075. * arrays is very slow on your hardware, you might want to change these.
  159076. */
  159077. #if BITS_IN_JSAMPLE == 8
  159078. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159079. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159080. */
  159081. #ifdef HAVE_UNSIGNED_CHAR
  159082. typedef unsigned char JSAMPLE;
  159083. #define GETJSAMPLE(value) ((int) (value))
  159084. #else /* not HAVE_UNSIGNED_CHAR */
  159085. typedef char JSAMPLE;
  159086. #ifdef CHAR_IS_UNSIGNED
  159087. #define GETJSAMPLE(value) ((int) (value))
  159088. #else
  159089. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159090. #endif /* CHAR_IS_UNSIGNED */
  159091. #endif /* HAVE_UNSIGNED_CHAR */
  159092. #define MAXJSAMPLE 255
  159093. #define CENTERJSAMPLE 128
  159094. #endif /* BITS_IN_JSAMPLE == 8 */
  159095. #if BITS_IN_JSAMPLE == 12
  159096. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159097. * On nearly all machines "short" will do nicely.
  159098. */
  159099. typedef short JSAMPLE;
  159100. #define GETJSAMPLE(value) ((int) (value))
  159101. #define MAXJSAMPLE 4095
  159102. #define CENTERJSAMPLE 2048
  159103. #endif /* BITS_IN_JSAMPLE == 12 */
  159104. /* Representation of a DCT frequency coefficient.
  159105. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159106. * Again, we allocate large arrays of these, but you can change to int
  159107. * if you have memory to burn and "short" is really slow.
  159108. */
  159109. typedef short JCOEF;
  159110. /* Compressed datastreams are represented as arrays of JOCTET.
  159111. * These must be EXACTLY 8 bits wide, at least once they are written to
  159112. * external storage. Note that when using the stdio data source/destination
  159113. * managers, this is also the data type passed to fread/fwrite.
  159114. */
  159115. #ifdef HAVE_UNSIGNED_CHAR
  159116. typedef unsigned char JOCTET;
  159117. #define GETJOCTET(value) (value)
  159118. #else /* not HAVE_UNSIGNED_CHAR */
  159119. typedef char JOCTET;
  159120. #ifdef CHAR_IS_UNSIGNED
  159121. #define GETJOCTET(value) (value)
  159122. #else
  159123. #define GETJOCTET(value) ((value) & 0xFF)
  159124. #endif /* CHAR_IS_UNSIGNED */
  159125. #endif /* HAVE_UNSIGNED_CHAR */
  159126. /* These typedefs are used for various table entries and so forth.
  159127. * They must be at least as wide as specified; but making them too big
  159128. * won't cost a huge amount of memory, so we don't provide special
  159129. * extraction code like we did for JSAMPLE. (In other words, these
  159130. * typedefs live at a different point on the speed/space tradeoff curve.)
  159131. */
  159132. /* UINT8 must hold at least the values 0..255. */
  159133. #ifdef HAVE_UNSIGNED_CHAR
  159134. typedef unsigned char UINT8;
  159135. #else /* not HAVE_UNSIGNED_CHAR */
  159136. #ifdef CHAR_IS_UNSIGNED
  159137. typedef char UINT8;
  159138. #else /* not CHAR_IS_UNSIGNED */
  159139. typedef short UINT8;
  159140. #endif /* CHAR_IS_UNSIGNED */
  159141. #endif /* HAVE_UNSIGNED_CHAR */
  159142. /* UINT16 must hold at least the values 0..65535. */
  159143. #ifdef HAVE_UNSIGNED_SHORT
  159144. typedef unsigned short UINT16;
  159145. #else /* not HAVE_UNSIGNED_SHORT */
  159146. typedef unsigned int UINT16;
  159147. #endif /* HAVE_UNSIGNED_SHORT */
  159148. /* INT16 must hold at least the values -32768..32767. */
  159149. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159150. typedef short INT16;
  159151. #endif
  159152. /* INT32 must hold at least signed 32-bit values. */
  159153. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159154. typedef long INT32;
  159155. #endif
  159156. /* Datatype used for image dimensions. The JPEG standard only supports
  159157. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159158. * "unsigned int" is sufficient on all machines. However, if you need to
  159159. * handle larger images and you don't mind deviating from the spec, you
  159160. * can change this datatype.
  159161. */
  159162. typedef unsigned int JDIMENSION;
  159163. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159164. /* These macros are used in all function definitions and extern declarations.
  159165. * You could modify them if you need to change function linkage conventions;
  159166. * in particular, you'll need to do that to make the library a Windows DLL.
  159167. * Another application is to make all functions global for use with debuggers
  159168. * or code profilers that require it.
  159169. */
  159170. /* a function called through method pointers: */
  159171. #define METHODDEF(type) static type
  159172. /* a function used only in its module: */
  159173. #define LOCAL(type) static type
  159174. /* a function referenced thru EXTERNs: */
  159175. #define GLOBAL(type) type
  159176. /* a reference to a GLOBAL function: */
  159177. #define EXTERN(type) extern type
  159178. /* This macro is used to declare a "method", that is, a function pointer.
  159179. * We want to supply prototype parameters if the compiler can cope.
  159180. * Note that the arglist parameter must be parenthesized!
  159181. * Again, you can customize this if you need special linkage keywords.
  159182. */
  159183. #ifdef HAVE_PROTOTYPES
  159184. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159185. #else
  159186. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159187. #endif
  159188. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159189. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159190. * by just saying "FAR *" where such a pointer is needed. In a few places
  159191. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159192. */
  159193. #ifdef NEED_FAR_POINTERS
  159194. #define FAR far
  159195. #else
  159196. #define FAR
  159197. #endif
  159198. /*
  159199. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159200. * in standard header files. Or you may have conflicts with application-
  159201. * specific header files that you want to include together with these files.
  159202. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159203. */
  159204. #ifndef HAVE_BOOLEAN
  159205. typedef int boolean;
  159206. #endif
  159207. #ifndef FALSE /* in case these macros already exist */
  159208. #define FALSE 0 /* values of boolean */
  159209. #endif
  159210. #ifndef TRUE
  159211. #define TRUE 1
  159212. #endif
  159213. /*
  159214. * The remaining options affect code selection within the JPEG library,
  159215. * but they don't need to be visible to most applications using the library.
  159216. * To minimize application namespace pollution, the symbols won't be
  159217. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159218. */
  159219. #ifdef JPEG_INTERNALS
  159220. #define JPEG_INTERNAL_OPTIONS
  159221. #endif
  159222. #ifdef JPEG_INTERNAL_OPTIONS
  159223. /*
  159224. * These defines indicate whether to include various optional functions.
  159225. * Undefining some of these symbols will produce a smaller but less capable
  159226. * library. Note that you can leave certain source files out of the
  159227. * compilation/linking process if you've #undef'd the corresponding symbols.
  159228. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159229. */
  159230. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159231. /* Capability options common to encoder and decoder: */
  159232. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159233. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159234. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159235. /* Encoder capability options: */
  159236. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159237. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159238. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159239. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159240. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159241. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159242. * precision, so jchuff.c normally uses entropy optimization to compute
  159243. * usable tables for higher precision. If you don't want to do optimization,
  159244. * you'll have to supply different default Huffman tables.
  159245. * The exact same statements apply for progressive JPEG: the default tables
  159246. * don't work for progressive mode. (This may get fixed, however.)
  159247. */
  159248. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159249. /* Decoder capability options: */
  159250. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159251. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159252. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159253. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159254. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159255. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159256. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159257. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159258. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159259. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159260. /* more capability options later, no doubt */
  159261. /*
  159262. * Ordering of RGB data in scanlines passed to or from the application.
  159263. * If your application wants to deal with data in the order B,G,R, just
  159264. * change these macros. You can also deal with formats such as R,G,B,X
  159265. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159266. * the offsets will also change the order in which colormap data is organized.
  159267. * RESTRICTIONS:
  159268. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159269. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159270. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159271. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159272. * is not 3 (they don't understand about dummy color components!). So you
  159273. * can't use color quantization if you change that value.
  159274. */
  159275. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159276. #define RGB_GREEN 1 /* Offset of Green */
  159277. #define RGB_BLUE 2 /* Offset of Blue */
  159278. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159279. /* Definitions for speed-related optimizations. */
  159280. /* If your compiler supports inline functions, define INLINE
  159281. * as the inline keyword; otherwise define it as empty.
  159282. */
  159283. #ifndef INLINE
  159284. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159285. #define INLINE __inline__
  159286. #endif
  159287. #ifndef INLINE
  159288. #define INLINE /* default is to define it as empty */
  159289. #endif
  159290. #endif
  159291. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159292. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159293. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159294. */
  159295. #ifndef MULTIPLIER
  159296. #define MULTIPLIER int /* type for fastest integer multiply */
  159297. #endif
  159298. /* FAST_FLOAT should be either float or double, whichever is done faster
  159299. * by your compiler. (Note that this type is only used in the floating point
  159300. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159301. * Typically, float is faster in ANSI C compilers, while double is faster in
  159302. * pre-ANSI compilers (because they insist on converting to double anyway).
  159303. * The code below therefore chooses float if we have ANSI-style prototypes.
  159304. */
  159305. #ifndef FAST_FLOAT
  159306. #ifdef HAVE_PROTOTYPES
  159307. #define FAST_FLOAT float
  159308. #else
  159309. #define FAST_FLOAT double
  159310. #endif
  159311. #endif
  159312. #endif /* JPEG_INTERNAL_OPTIONS */
  159313. /*** End of inlined file: jmorecfg.h ***/
  159314. /* seldom changed options */
  159315. /* Version ID for the JPEG library.
  159316. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159317. */
  159318. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159319. /* Various constants determining the sizes of things.
  159320. * All of these are specified by the JPEG standard, so don't change them
  159321. * if you want to be compatible.
  159322. */
  159323. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159324. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159325. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159326. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159327. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159328. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159329. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159330. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159331. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159332. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159333. * to handle it. We even let you do this from the jconfig.h file. However,
  159334. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159335. * sometimes emits noncompliant files doesn't mean you should too.
  159336. */
  159337. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159338. #ifndef D_MAX_BLOCKS_IN_MCU
  159339. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159340. #endif
  159341. /* Data structures for images (arrays of samples and of DCT coefficients).
  159342. * On 80x86 machines, the image arrays are too big for near pointers,
  159343. * but the pointer arrays can fit in near memory.
  159344. */
  159345. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159346. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159347. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159348. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159349. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159350. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159351. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159352. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159353. /* Types for JPEG compression parameters and working tables. */
  159354. /* DCT coefficient quantization tables. */
  159355. typedef struct {
  159356. /* This array gives the coefficient quantizers in natural array order
  159357. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159358. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159359. */
  159360. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159361. /* This field is used only during compression. It's initialized FALSE when
  159362. * the table is created, and set TRUE when it's been output to the file.
  159363. * You could suppress output of a table by setting this to TRUE.
  159364. * (See jpeg_suppress_tables for an example.)
  159365. */
  159366. boolean sent_table; /* TRUE when table has been output */
  159367. } JQUANT_TBL;
  159368. /* Huffman coding tables. */
  159369. typedef struct {
  159370. /* These two fields directly represent the contents of a JPEG DHT marker */
  159371. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159372. /* length k bits; bits[0] is unused */
  159373. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159374. /* This field is used only during compression. It's initialized FALSE when
  159375. * the table is created, and set TRUE when it's been output to the file.
  159376. * You could suppress output of a table by setting this to TRUE.
  159377. * (See jpeg_suppress_tables for an example.)
  159378. */
  159379. boolean sent_table; /* TRUE when table has been output */
  159380. } JHUFF_TBL;
  159381. /* Basic info about one component (color channel). */
  159382. typedef struct {
  159383. /* These values are fixed over the whole image. */
  159384. /* For compression, they must be supplied by parameter setup; */
  159385. /* for decompression, they are read from the SOF marker. */
  159386. int component_id; /* identifier for this component (0..255) */
  159387. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159388. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159389. int v_samp_factor; /* vertical sampling factor (1..4) */
  159390. int quant_tbl_no; /* quantization table selector (0..3) */
  159391. /* These values may vary between scans. */
  159392. /* For compression, they must be supplied by parameter setup; */
  159393. /* for decompression, they are read from the SOS marker. */
  159394. /* The decompressor output side may not use these variables. */
  159395. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159396. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159397. /* Remaining fields should be treated as private by applications. */
  159398. /* These values are computed during compression or decompression startup: */
  159399. /* Component's size in DCT blocks.
  159400. * Any dummy blocks added to complete an MCU are not counted; therefore
  159401. * these values do not depend on whether a scan is interleaved or not.
  159402. */
  159403. JDIMENSION width_in_blocks;
  159404. JDIMENSION height_in_blocks;
  159405. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159406. * For decompression this is the size of the output from one DCT block,
  159407. * reflecting any scaling we choose to apply during the IDCT step.
  159408. * Values of 1,2,4,8 are likely to be supported. Note that different
  159409. * components may receive different IDCT scalings.
  159410. */
  159411. int DCT_scaled_size;
  159412. /* The downsampled dimensions are the component's actual, unpadded number
  159413. * of samples at the main buffer (preprocessing/compression interface), thus
  159414. * downsampled_width = ceil(image_width * Hi/Hmax)
  159415. * and similarly for height. For decompression, IDCT scaling is included, so
  159416. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159417. */
  159418. JDIMENSION downsampled_width; /* actual width in samples */
  159419. JDIMENSION downsampled_height; /* actual height in samples */
  159420. /* This flag is used only for decompression. In cases where some of the
  159421. * components will be ignored (eg grayscale output from YCbCr image),
  159422. * we can skip most computations for the unused components.
  159423. */
  159424. boolean component_needed; /* do we need the value of this component? */
  159425. /* These values are computed before starting a scan of the component. */
  159426. /* The decompressor output side may not use these variables. */
  159427. int MCU_width; /* number of blocks per MCU, horizontally */
  159428. int MCU_height; /* number of blocks per MCU, vertically */
  159429. int MCU_blocks; /* MCU_width * MCU_height */
  159430. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159431. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159432. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159433. /* Saved quantization table for component; NULL if none yet saved.
  159434. * See jdinput.c comments about the need for this information.
  159435. * This field is currently used only for decompression.
  159436. */
  159437. JQUANT_TBL * quant_table;
  159438. /* Private per-component storage for DCT or IDCT subsystem. */
  159439. void * dct_table;
  159440. } jpeg_component_info;
  159441. /* The script for encoding a multiple-scan file is an array of these: */
  159442. typedef struct {
  159443. int comps_in_scan; /* number of components encoded in this scan */
  159444. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159445. int Ss, Se; /* progressive JPEG spectral selection parms */
  159446. int Ah, Al; /* progressive JPEG successive approx. parms */
  159447. } jpeg_scan_info;
  159448. /* The decompressor can save APPn and COM markers in a list of these: */
  159449. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159450. struct jpeg_marker_struct {
  159451. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159452. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159453. unsigned int original_length; /* # bytes of data in the file */
  159454. unsigned int data_length; /* # bytes of data saved at data[] */
  159455. JOCTET FAR * data; /* the data contained in the marker */
  159456. /* the marker length word is not counted in data_length or original_length */
  159457. };
  159458. /* Known color spaces. */
  159459. typedef enum {
  159460. JCS_UNKNOWN, /* error/unspecified */
  159461. JCS_GRAYSCALE, /* monochrome */
  159462. JCS_RGB, /* red/green/blue */
  159463. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159464. JCS_CMYK, /* C/M/Y/K */
  159465. JCS_YCCK /* Y/Cb/Cr/K */
  159466. } J_COLOR_SPACE;
  159467. /* DCT/IDCT algorithm options. */
  159468. typedef enum {
  159469. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159470. JDCT_IFAST, /* faster, less accurate integer method */
  159471. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159472. } J_DCT_METHOD;
  159473. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159474. #define JDCT_DEFAULT JDCT_ISLOW
  159475. #endif
  159476. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159477. #define JDCT_FASTEST JDCT_IFAST
  159478. #endif
  159479. /* Dithering options for decompression. */
  159480. typedef enum {
  159481. JDITHER_NONE, /* no dithering */
  159482. JDITHER_ORDERED, /* simple ordered dither */
  159483. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159484. } J_DITHER_MODE;
  159485. /* Common fields between JPEG compression and decompression master structs. */
  159486. #define jpeg_common_fields \
  159487. struct jpeg_error_mgr * err; /* Error handler module */\
  159488. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159489. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159490. void * client_data; /* Available for use by application */\
  159491. boolean is_decompressor; /* So common code can tell which is which */\
  159492. int global_state /* For checking call sequence validity */
  159493. /* Routines that are to be used by both halves of the library are declared
  159494. * to receive a pointer to this structure. There are no actual instances of
  159495. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159496. */
  159497. struct jpeg_common_struct {
  159498. jpeg_common_fields; /* Fields common to both master struct types */
  159499. /* Additional fields follow in an actual jpeg_compress_struct or
  159500. * jpeg_decompress_struct. All three structs must agree on these
  159501. * initial fields! (This would be a lot cleaner in C++.)
  159502. */
  159503. };
  159504. typedef struct jpeg_common_struct * j_common_ptr;
  159505. typedef struct jpeg_compress_struct * j_compress_ptr;
  159506. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159507. /* Master record for a compression instance */
  159508. struct jpeg_compress_struct {
  159509. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159510. /* Destination for compressed data */
  159511. struct jpeg_destination_mgr * dest;
  159512. /* Description of source image --- these fields must be filled in by
  159513. * outer application before starting compression. in_color_space must
  159514. * be correct before you can even call jpeg_set_defaults().
  159515. */
  159516. JDIMENSION image_width; /* input image width */
  159517. JDIMENSION image_height; /* input image height */
  159518. int input_components; /* # of color components in input image */
  159519. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159520. double input_gamma; /* image gamma of input image */
  159521. /* Compression parameters --- these fields must be set before calling
  159522. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159523. * initialize everything to reasonable defaults, then changing anything
  159524. * the application specifically wants to change. That way you won't get
  159525. * burnt when new parameters are added. Also note that there are several
  159526. * helper routines to simplify changing parameters.
  159527. */
  159528. int data_precision; /* bits of precision in image data */
  159529. int num_components; /* # of color components in JPEG image */
  159530. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159531. jpeg_component_info * comp_info;
  159532. /* comp_info[i] describes component that appears i'th in SOF */
  159533. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159534. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159535. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159536. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159537. /* ptrs to Huffman coding tables, or NULL if not defined */
  159538. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159539. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159540. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159541. int num_scans; /* # of entries in scan_info array */
  159542. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159543. /* The default value of scan_info is NULL, which causes a single-scan
  159544. * sequential JPEG file to be emitted. To create a multi-scan file,
  159545. * set num_scans and scan_info to point to an array of scan definitions.
  159546. */
  159547. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159548. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159549. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159550. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159551. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159552. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159553. /* The restart interval can be specified in absolute MCUs by setting
  159554. * restart_interval, or in MCU rows by setting restart_in_rows
  159555. * (in which case the correct restart_interval will be figured
  159556. * for each scan).
  159557. */
  159558. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159559. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159560. /* Parameters controlling emission of special markers. */
  159561. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159562. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159563. UINT8 JFIF_minor_version;
  159564. /* These three values are not used by the JPEG code, merely copied */
  159565. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159566. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159567. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159568. UINT8 density_unit; /* JFIF code for pixel size units */
  159569. UINT16 X_density; /* Horizontal pixel density */
  159570. UINT16 Y_density; /* Vertical pixel density */
  159571. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159572. /* State variable: index of next scanline to be written to
  159573. * jpeg_write_scanlines(). Application may use this to control its
  159574. * processing loop, e.g., "while (next_scanline < image_height)".
  159575. */
  159576. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159577. /* Remaining fields are known throughout compressor, but generally
  159578. * should not be touched by a surrounding application.
  159579. */
  159580. /*
  159581. * These fields are computed during compression startup
  159582. */
  159583. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159584. int max_h_samp_factor; /* largest h_samp_factor */
  159585. int max_v_samp_factor; /* largest v_samp_factor */
  159586. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159587. /* The coefficient controller receives data in units of MCU rows as defined
  159588. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159589. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159590. * "iMCU" (interleaved MCU) row.
  159591. */
  159592. /*
  159593. * These fields are valid during any one scan.
  159594. * They describe the components and MCUs actually appearing in the scan.
  159595. */
  159596. int comps_in_scan; /* # of JPEG components in this scan */
  159597. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159598. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159599. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159600. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159601. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159602. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159603. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159604. /* i'th block in an MCU */
  159605. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159606. /*
  159607. * Links to compression subobjects (methods and private variables of modules)
  159608. */
  159609. struct jpeg_comp_master * master;
  159610. struct jpeg_c_main_controller * main;
  159611. struct jpeg_c_prep_controller * prep;
  159612. struct jpeg_c_coef_controller * coef;
  159613. struct jpeg_marker_writer * marker;
  159614. struct jpeg_color_converter * cconvert;
  159615. struct jpeg_downsampler * downsample;
  159616. struct jpeg_forward_dct * fdct;
  159617. struct jpeg_entropy_encoder * entropy;
  159618. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159619. int script_space_size;
  159620. };
  159621. /* Master record for a decompression instance */
  159622. struct jpeg_decompress_struct {
  159623. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159624. /* Source of compressed data */
  159625. struct jpeg_source_mgr * src;
  159626. /* Basic description of image --- filled in by jpeg_read_header(). */
  159627. /* Application may inspect these values to decide how to process image. */
  159628. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159629. JDIMENSION image_height; /* nominal image height */
  159630. int num_components; /* # of color components in JPEG image */
  159631. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159632. /* Decompression processing parameters --- these fields must be set before
  159633. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159634. * them to default values.
  159635. */
  159636. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159637. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159638. double output_gamma; /* image gamma wanted in output */
  159639. boolean buffered_image; /* TRUE=multiple output passes */
  159640. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159641. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159642. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159643. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159644. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159645. /* the following are ignored if not quantize_colors: */
  159646. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159647. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159648. int desired_number_of_colors; /* max # colors to use in created colormap */
  159649. /* these are significant only in buffered-image mode: */
  159650. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159651. boolean enable_external_quant;/* enable future use of external colormap */
  159652. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159653. /* Description of actual output image that will be returned to application.
  159654. * These fields are computed by jpeg_start_decompress().
  159655. * You can also use jpeg_calc_output_dimensions() to determine these values
  159656. * in advance of calling jpeg_start_decompress().
  159657. */
  159658. JDIMENSION output_width; /* scaled image width */
  159659. JDIMENSION output_height; /* scaled image height */
  159660. int out_color_components; /* # of color components in out_color_space */
  159661. int output_components; /* # of color components returned */
  159662. /* output_components is 1 (a colormap index) when quantizing colors;
  159663. * otherwise it equals out_color_components.
  159664. */
  159665. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159666. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159667. * high, space and time will be wasted due to unnecessary data copying.
  159668. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159669. */
  159670. /* When quantizing colors, the output colormap is described by these fields.
  159671. * The application can supply a colormap by setting colormap non-NULL before
  159672. * calling jpeg_start_decompress; otherwise a colormap is created during
  159673. * jpeg_start_decompress or jpeg_start_output.
  159674. * The map has out_color_components rows and actual_number_of_colors columns.
  159675. */
  159676. int actual_number_of_colors; /* number of entries in use */
  159677. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159678. /* State variables: these variables indicate the progress of decompression.
  159679. * The application may examine these but must not modify them.
  159680. */
  159681. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159682. * Application may use this to control its processing loop, e.g.,
  159683. * "while (output_scanline < output_height)".
  159684. */
  159685. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159686. /* Current input scan number and number of iMCU rows completed in scan.
  159687. * These indicate the progress of the decompressor input side.
  159688. */
  159689. int input_scan_number; /* Number of SOS markers seen so far */
  159690. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159691. /* The "output scan number" is the notional scan being displayed by the
  159692. * output side. The decompressor will not allow output scan/row number
  159693. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159694. */
  159695. int output_scan_number; /* Nominal scan number being displayed */
  159696. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159697. /* Current progression status. coef_bits[c][i] indicates the precision
  159698. * with which component c's DCT coefficient i (in zigzag order) is known.
  159699. * It is -1 when no data has yet been received, otherwise it is the point
  159700. * transform (shift) value for the most recent scan of the coefficient
  159701. * (thus, 0 at completion of the progression).
  159702. * This pointer is NULL when reading a non-progressive file.
  159703. */
  159704. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159705. /* Internal JPEG parameters --- the application usually need not look at
  159706. * these fields. Note that the decompressor output side may not use
  159707. * any parameters that can change between scans.
  159708. */
  159709. /* Quantization and Huffman tables are carried forward across input
  159710. * datastreams when processing abbreviated JPEG datastreams.
  159711. */
  159712. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159713. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159714. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159715. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159716. /* ptrs to Huffman coding tables, or NULL if not defined */
  159717. /* These parameters are never carried across datastreams, since they
  159718. * are given in SOF/SOS markers or defined to be reset by SOI.
  159719. */
  159720. int data_precision; /* bits of precision in image data */
  159721. jpeg_component_info * comp_info;
  159722. /* comp_info[i] describes component that appears i'th in SOF */
  159723. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159724. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159725. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159726. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159727. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159728. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159729. /* These fields record data obtained from optional markers recognized by
  159730. * the JPEG library.
  159731. */
  159732. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159733. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159734. UINT8 JFIF_major_version; /* JFIF version number */
  159735. UINT8 JFIF_minor_version;
  159736. UINT8 density_unit; /* JFIF code for pixel size units */
  159737. UINT16 X_density; /* Horizontal pixel density */
  159738. UINT16 Y_density; /* Vertical pixel density */
  159739. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159740. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159741. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159742. /* Aside from the specific data retained from APPn markers known to the
  159743. * library, the uninterpreted contents of any or all APPn and COM markers
  159744. * can be saved in a list for examination by the application.
  159745. */
  159746. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159747. /* Remaining fields are known throughout decompressor, but generally
  159748. * should not be touched by a surrounding application.
  159749. */
  159750. /*
  159751. * These fields are computed during decompression startup
  159752. */
  159753. int max_h_samp_factor; /* largest h_samp_factor */
  159754. int max_v_samp_factor; /* largest v_samp_factor */
  159755. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159756. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159757. /* The coefficient controller's input and output progress is measured in
  159758. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159759. * in fully interleaved JPEG scans, but are used whether the scan is
  159760. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159761. * rows of each component. Therefore, the IDCT output contains
  159762. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159763. */
  159764. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159765. /*
  159766. * These fields are valid during any one scan.
  159767. * They describe the components and MCUs actually appearing in the scan.
  159768. * Note that the decompressor output side must not use these fields.
  159769. */
  159770. int comps_in_scan; /* # of JPEG components in this scan */
  159771. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159772. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159773. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159774. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159775. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159776. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159777. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159778. /* i'th block in an MCU */
  159779. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159780. /* This field is shared between entropy decoder and marker parser.
  159781. * It is either zero or the code of a JPEG marker that has been
  159782. * read from the data source, but has not yet been processed.
  159783. */
  159784. int unread_marker;
  159785. /*
  159786. * Links to decompression subobjects (methods, private variables of modules)
  159787. */
  159788. struct jpeg_decomp_master * master;
  159789. struct jpeg_d_main_controller * main;
  159790. struct jpeg_d_coef_controller * coef;
  159791. struct jpeg_d_post_controller * post;
  159792. struct jpeg_input_controller * inputctl;
  159793. struct jpeg_marker_reader * marker;
  159794. struct jpeg_entropy_decoder * entropy;
  159795. struct jpeg_inverse_dct * idct;
  159796. struct jpeg_upsampler * upsample;
  159797. struct jpeg_color_deconverter * cconvert;
  159798. struct jpeg_color_quantizer * cquantize;
  159799. };
  159800. /* "Object" declarations for JPEG modules that may be supplied or called
  159801. * directly by the surrounding application.
  159802. * As with all objects in the JPEG library, these structs only define the
  159803. * publicly visible methods and state variables of a module. Additional
  159804. * private fields may exist after the public ones.
  159805. */
  159806. /* Error handler object */
  159807. struct jpeg_error_mgr {
  159808. /* Error exit handler: does not return to caller */
  159809. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159810. /* Conditionally emit a trace or warning message */
  159811. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159812. /* Routine that actually outputs a trace or error message */
  159813. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159814. /* Format a message string for the most recent JPEG error or message */
  159815. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159816. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159817. /* Reset error state variables at start of a new image */
  159818. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159819. /* The message ID code and any parameters are saved here.
  159820. * A message can have one string parameter or up to 8 int parameters.
  159821. */
  159822. int msg_code;
  159823. #define JMSG_STR_PARM_MAX 80
  159824. union {
  159825. int i[8];
  159826. char s[JMSG_STR_PARM_MAX];
  159827. } msg_parm;
  159828. /* Standard state variables for error facility */
  159829. int trace_level; /* max msg_level that will be displayed */
  159830. /* For recoverable corrupt-data errors, we emit a warning message,
  159831. * but keep going unless emit_message chooses to abort. emit_message
  159832. * should count warnings in num_warnings. The surrounding application
  159833. * can check for bad data by seeing if num_warnings is nonzero at the
  159834. * end of processing.
  159835. */
  159836. long num_warnings; /* number of corrupt-data warnings */
  159837. /* These fields point to the table(s) of error message strings.
  159838. * An application can change the table pointer to switch to a different
  159839. * message list (typically, to change the language in which errors are
  159840. * reported). Some applications may wish to add additional error codes
  159841. * that will be handled by the JPEG library error mechanism; the second
  159842. * table pointer is used for this purpose.
  159843. *
  159844. * First table includes all errors generated by JPEG library itself.
  159845. * Error code 0 is reserved for a "no such error string" message.
  159846. */
  159847. const char * const * jpeg_message_table; /* Library errors */
  159848. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  159849. /* Second table can be added by application (see cjpeg/djpeg for example).
  159850. * It contains strings numbered first_addon_message..last_addon_message.
  159851. */
  159852. const char * const * addon_message_table; /* Non-library errors */
  159853. int first_addon_message; /* code for first string in addon table */
  159854. int last_addon_message; /* code for last string in addon table */
  159855. };
  159856. /* Progress monitor object */
  159857. struct jpeg_progress_mgr {
  159858. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  159859. long pass_counter; /* work units completed in this pass */
  159860. long pass_limit; /* total number of work units in this pass */
  159861. int completed_passes; /* passes completed so far */
  159862. int total_passes; /* total number of passes expected */
  159863. };
  159864. /* Data destination object for compression */
  159865. struct jpeg_destination_mgr {
  159866. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159867. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159868. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  159869. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  159870. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  159871. };
  159872. /* Data source object for decompression */
  159873. struct jpeg_source_mgr {
  159874. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  159875. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  159876. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  159877. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  159878. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  159879. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  159880. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  159881. };
  159882. /* Memory manager object.
  159883. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  159884. * and "really big" objects (virtual arrays with backing store if needed).
  159885. * The memory manager does not allow individual objects to be freed; rather,
  159886. * each created object is assigned to a pool, and whole pools can be freed
  159887. * at once. This is faster and more convenient than remembering exactly what
  159888. * to free, especially where malloc()/free() are not too speedy.
  159889. * NB: alloc routines never return NULL. They exit to error_exit if not
  159890. * successful.
  159891. */
  159892. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  159893. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  159894. #define JPOOL_NUMPOOLS 2
  159895. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  159896. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  159897. struct jpeg_memory_mgr {
  159898. /* Method pointers */
  159899. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  159900. size_t sizeofobject));
  159901. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  159902. size_t sizeofobject));
  159903. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  159904. JDIMENSION samplesperrow,
  159905. JDIMENSION numrows));
  159906. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  159907. JDIMENSION blocksperrow,
  159908. JDIMENSION numrows));
  159909. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  159910. int pool_id,
  159911. boolean pre_zero,
  159912. JDIMENSION samplesperrow,
  159913. JDIMENSION numrows,
  159914. JDIMENSION maxaccess));
  159915. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  159916. int pool_id,
  159917. boolean pre_zero,
  159918. JDIMENSION blocksperrow,
  159919. JDIMENSION numrows,
  159920. JDIMENSION maxaccess));
  159921. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  159922. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  159923. jvirt_sarray_ptr ptr,
  159924. JDIMENSION start_row,
  159925. JDIMENSION num_rows,
  159926. boolean writable));
  159927. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  159928. jvirt_barray_ptr ptr,
  159929. JDIMENSION start_row,
  159930. JDIMENSION num_rows,
  159931. boolean writable));
  159932. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  159933. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  159934. /* Limit on memory allocation for this JPEG object. (Note that this is
  159935. * merely advisory, not a guaranteed maximum; it only affects the space
  159936. * used for virtual-array buffers.) May be changed by outer application
  159937. * after creating the JPEG object.
  159938. */
  159939. long max_memory_to_use;
  159940. /* Maximum allocation request accepted by alloc_large. */
  159941. long max_alloc_chunk;
  159942. };
  159943. /* Routine signature for application-supplied marker processing methods.
  159944. * Need not pass marker code since it is stored in cinfo->unread_marker.
  159945. */
  159946. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  159947. /* Declarations for routines called by application.
  159948. * The JPP macro hides prototype parameters from compilers that can't cope.
  159949. * Note JPP requires double parentheses.
  159950. */
  159951. #ifdef HAVE_PROTOTYPES
  159952. #define JPP(arglist) arglist
  159953. #else
  159954. #define JPP(arglist) ()
  159955. #endif
  159956. /* Short forms of external names for systems with brain-damaged linkers.
  159957. * We shorten external names to be unique in the first six letters, which
  159958. * is good enough for all known systems.
  159959. * (If your compiler itself needs names to be unique in less than 15
  159960. * characters, you are out of luck. Get a better compiler.)
  159961. */
  159962. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159963. #define jpeg_std_error jStdError
  159964. #define jpeg_CreateCompress jCreaCompress
  159965. #define jpeg_CreateDecompress jCreaDecompress
  159966. #define jpeg_destroy_compress jDestCompress
  159967. #define jpeg_destroy_decompress jDestDecompress
  159968. #define jpeg_stdio_dest jStdDest
  159969. #define jpeg_stdio_src jStdSrc
  159970. #define jpeg_set_defaults jSetDefaults
  159971. #define jpeg_set_colorspace jSetColorspace
  159972. #define jpeg_default_colorspace jDefColorspace
  159973. #define jpeg_set_quality jSetQuality
  159974. #define jpeg_set_linear_quality jSetLQuality
  159975. #define jpeg_add_quant_table jAddQuantTable
  159976. #define jpeg_quality_scaling jQualityScaling
  159977. #define jpeg_simple_progression jSimProgress
  159978. #define jpeg_suppress_tables jSuppressTables
  159979. #define jpeg_alloc_quant_table jAlcQTable
  159980. #define jpeg_alloc_huff_table jAlcHTable
  159981. #define jpeg_start_compress jStrtCompress
  159982. #define jpeg_write_scanlines jWrtScanlines
  159983. #define jpeg_finish_compress jFinCompress
  159984. #define jpeg_write_raw_data jWrtRawData
  159985. #define jpeg_write_marker jWrtMarker
  159986. #define jpeg_write_m_header jWrtMHeader
  159987. #define jpeg_write_m_byte jWrtMByte
  159988. #define jpeg_write_tables jWrtTables
  159989. #define jpeg_read_header jReadHeader
  159990. #define jpeg_start_decompress jStrtDecompress
  159991. #define jpeg_read_scanlines jReadScanlines
  159992. #define jpeg_finish_decompress jFinDecompress
  159993. #define jpeg_read_raw_data jReadRawData
  159994. #define jpeg_has_multiple_scans jHasMultScn
  159995. #define jpeg_start_output jStrtOutput
  159996. #define jpeg_finish_output jFinOutput
  159997. #define jpeg_input_complete jInComplete
  159998. #define jpeg_new_colormap jNewCMap
  159999. #define jpeg_consume_input jConsumeInput
  160000. #define jpeg_calc_output_dimensions jCalcDimensions
  160001. #define jpeg_save_markers jSaveMarkers
  160002. #define jpeg_set_marker_processor jSetMarker
  160003. #define jpeg_read_coefficients jReadCoefs
  160004. #define jpeg_write_coefficients jWrtCoefs
  160005. #define jpeg_copy_critical_parameters jCopyCrit
  160006. #define jpeg_abort_compress jAbrtCompress
  160007. #define jpeg_abort_decompress jAbrtDecompress
  160008. #define jpeg_abort jAbort
  160009. #define jpeg_destroy jDestroy
  160010. #define jpeg_resync_to_restart jResyncRestart
  160011. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160012. /* Default error-management setup */
  160013. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160014. JPP((struct jpeg_error_mgr * err));
  160015. /* Initialization of JPEG compression objects.
  160016. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160017. * names that applications should call. These expand to calls on
  160018. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160019. * passed for version mismatch checking.
  160020. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160021. */
  160022. #define jpeg_create_compress(cinfo) \
  160023. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160024. (size_t) sizeof(struct jpeg_compress_struct))
  160025. #define jpeg_create_decompress(cinfo) \
  160026. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160027. (size_t) sizeof(struct jpeg_decompress_struct))
  160028. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160029. int version, size_t structsize));
  160030. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160031. int version, size_t structsize));
  160032. /* Destruction of JPEG compression objects */
  160033. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160034. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160035. /* Standard data source and destination managers: stdio streams. */
  160036. /* Caller is responsible for opening the file before and closing after. */
  160037. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160038. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160039. /* Default parameter setup for compression */
  160040. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160041. /* Compression parameter setup aids */
  160042. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160043. J_COLOR_SPACE colorspace));
  160044. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160045. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160046. boolean force_baseline));
  160047. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160048. int scale_factor,
  160049. boolean force_baseline));
  160050. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160051. const unsigned int *basic_table,
  160052. int scale_factor,
  160053. boolean force_baseline));
  160054. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160055. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160056. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160057. boolean suppress));
  160058. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160059. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160060. /* Main entry points for compression */
  160061. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160062. boolean write_all_tables));
  160063. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160064. JSAMPARRAY scanlines,
  160065. JDIMENSION num_lines));
  160066. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160067. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160068. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160069. JSAMPIMAGE data,
  160070. JDIMENSION num_lines));
  160071. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160072. EXTERN(void) jpeg_write_marker
  160073. JPP((j_compress_ptr cinfo, int marker,
  160074. const JOCTET * dataptr, unsigned int datalen));
  160075. /* Same, but piecemeal. */
  160076. EXTERN(void) jpeg_write_m_header
  160077. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160078. EXTERN(void) jpeg_write_m_byte
  160079. JPP((j_compress_ptr cinfo, int val));
  160080. /* Alternate compression function: just write an abbreviated table file */
  160081. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160082. /* Decompression startup: read start of JPEG datastream to see what's there */
  160083. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160084. boolean require_image));
  160085. /* Return value is one of: */
  160086. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160087. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160088. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160089. /* If you pass require_image = TRUE (normal case), you need not check for
  160090. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160091. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160092. * give a suspension return (the stdio source module doesn't).
  160093. */
  160094. /* Main entry points for decompression */
  160095. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160096. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160097. JSAMPARRAY scanlines,
  160098. JDIMENSION max_lines));
  160099. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160100. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160101. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160102. JSAMPIMAGE data,
  160103. JDIMENSION max_lines));
  160104. /* Additional entry points for buffered-image mode. */
  160105. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160106. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160107. int scan_number));
  160108. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160109. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160110. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160111. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160112. /* Return value is one of: */
  160113. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160114. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160115. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160116. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160117. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160118. /* Precalculate output dimensions for current decompression parameters. */
  160119. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160120. /* Control saving of COM and APPn markers into marker_list. */
  160121. EXTERN(void) jpeg_save_markers
  160122. JPP((j_decompress_ptr cinfo, int marker_code,
  160123. unsigned int length_limit));
  160124. /* Install a special processing method for COM or APPn markers. */
  160125. EXTERN(void) jpeg_set_marker_processor
  160126. JPP((j_decompress_ptr cinfo, int marker_code,
  160127. jpeg_marker_parser_method routine));
  160128. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160129. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160130. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160131. jvirt_barray_ptr * coef_arrays));
  160132. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160133. j_compress_ptr dstinfo));
  160134. /* If you choose to abort compression or decompression before completing
  160135. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160136. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160137. * if you're done with the JPEG object, but if you want to clean it up and
  160138. * reuse it, call this:
  160139. */
  160140. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160141. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160142. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160143. * flavor of JPEG object. These may be more convenient in some places.
  160144. */
  160145. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160146. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160147. /* Default restart-marker-resync procedure for use by data source modules */
  160148. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160149. int desired));
  160150. /* These marker codes are exported since applications and data source modules
  160151. * are likely to want to use them.
  160152. */
  160153. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160154. #define JPEG_EOI 0xD9 /* EOI marker code */
  160155. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160156. #define JPEG_COM 0xFE /* COM marker code */
  160157. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160158. * for structure definitions that are never filled in, keep it quiet by
  160159. * supplying dummy definitions for the various substructures.
  160160. */
  160161. #ifdef INCOMPLETE_TYPES_BROKEN
  160162. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160163. struct jvirt_sarray_control { long dummy; };
  160164. struct jvirt_barray_control { long dummy; };
  160165. struct jpeg_comp_master { long dummy; };
  160166. struct jpeg_c_main_controller { long dummy; };
  160167. struct jpeg_c_prep_controller { long dummy; };
  160168. struct jpeg_c_coef_controller { long dummy; };
  160169. struct jpeg_marker_writer { long dummy; };
  160170. struct jpeg_color_converter { long dummy; };
  160171. struct jpeg_downsampler { long dummy; };
  160172. struct jpeg_forward_dct { long dummy; };
  160173. struct jpeg_entropy_encoder { long dummy; };
  160174. struct jpeg_decomp_master { long dummy; };
  160175. struct jpeg_d_main_controller { long dummy; };
  160176. struct jpeg_d_coef_controller { long dummy; };
  160177. struct jpeg_d_post_controller { long dummy; };
  160178. struct jpeg_input_controller { long dummy; };
  160179. struct jpeg_marker_reader { long dummy; };
  160180. struct jpeg_entropy_decoder { long dummy; };
  160181. struct jpeg_inverse_dct { long dummy; };
  160182. struct jpeg_upsampler { long dummy; };
  160183. struct jpeg_color_deconverter { long dummy; };
  160184. struct jpeg_color_quantizer { long dummy; };
  160185. #endif /* JPEG_INTERNALS */
  160186. #endif /* INCOMPLETE_TYPES_BROKEN */
  160187. /*
  160188. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160189. * The internal structure declarations are read only when that is true.
  160190. * Applications using the library should not include jpegint.h, but may wish
  160191. * to include jerror.h.
  160192. */
  160193. #ifdef JPEG_INTERNALS
  160194. /*** Start of inlined file: jpegint.h ***/
  160195. /* Declarations for both compression & decompression */
  160196. typedef enum { /* Operating modes for buffer controllers */
  160197. JBUF_PASS_THRU, /* Plain stripwise operation */
  160198. /* Remaining modes require a full-image buffer to have been created */
  160199. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160200. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160201. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160202. } J_BUF_MODE;
  160203. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160204. #define CSTATE_START 100 /* after create_compress */
  160205. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160206. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160207. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160208. #define DSTATE_START 200 /* after create_decompress */
  160209. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160210. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160211. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160212. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160213. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160214. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160215. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160216. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160217. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160218. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160219. /* Declarations for compression modules */
  160220. /* Master control module */
  160221. struct jpeg_comp_master {
  160222. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160223. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160224. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160225. /* State variables made visible to other modules */
  160226. boolean call_pass_startup; /* True if pass_startup must be called */
  160227. boolean is_last_pass; /* True during last pass */
  160228. };
  160229. /* Main buffer control (downsampled-data buffer) */
  160230. struct jpeg_c_main_controller {
  160231. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160232. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160233. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160234. JDIMENSION in_rows_avail));
  160235. };
  160236. /* Compression preprocessing (downsampling input buffer control) */
  160237. struct jpeg_c_prep_controller {
  160238. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160239. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160240. JSAMPARRAY input_buf,
  160241. JDIMENSION *in_row_ctr,
  160242. JDIMENSION in_rows_avail,
  160243. JSAMPIMAGE output_buf,
  160244. JDIMENSION *out_row_group_ctr,
  160245. JDIMENSION out_row_groups_avail));
  160246. };
  160247. /* Coefficient buffer control */
  160248. struct jpeg_c_coef_controller {
  160249. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160250. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160251. JSAMPIMAGE input_buf));
  160252. };
  160253. /* Colorspace conversion */
  160254. struct jpeg_color_converter {
  160255. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160256. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160257. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160258. JDIMENSION output_row, int num_rows));
  160259. };
  160260. /* Downsampling */
  160261. struct jpeg_downsampler {
  160262. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160263. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160264. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160265. JSAMPIMAGE output_buf,
  160266. JDIMENSION out_row_group_index));
  160267. boolean need_context_rows; /* TRUE if need rows above & below */
  160268. };
  160269. /* Forward DCT (also controls coefficient quantization) */
  160270. struct jpeg_forward_dct {
  160271. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160272. /* perhaps this should be an array??? */
  160273. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160274. jpeg_component_info * compptr,
  160275. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160276. JDIMENSION start_row, JDIMENSION start_col,
  160277. JDIMENSION num_blocks));
  160278. };
  160279. /* Entropy encoding */
  160280. struct jpeg_entropy_encoder {
  160281. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160282. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160283. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160284. };
  160285. /* Marker writing */
  160286. struct jpeg_marker_writer {
  160287. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160288. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160289. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160290. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160291. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160292. /* These routines are exported to allow insertion of extra markers */
  160293. /* Probably only COM and APPn markers should be written this way */
  160294. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160295. unsigned int datalen));
  160296. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160297. };
  160298. /* Declarations for decompression modules */
  160299. /* Master control module */
  160300. struct jpeg_decomp_master {
  160301. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160302. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160303. /* State variables made visible to other modules */
  160304. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160305. };
  160306. /* Input control module */
  160307. struct jpeg_input_controller {
  160308. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160309. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160310. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160311. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160312. /* State variables made visible to other modules */
  160313. boolean has_multiple_scans; /* True if file has multiple scans */
  160314. boolean eoi_reached; /* True when EOI has been consumed */
  160315. };
  160316. /* Main buffer control (downsampled-data buffer) */
  160317. struct jpeg_d_main_controller {
  160318. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160319. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160320. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160321. JDIMENSION out_rows_avail));
  160322. };
  160323. /* Coefficient buffer control */
  160324. struct jpeg_d_coef_controller {
  160325. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160326. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160327. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160328. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160329. JSAMPIMAGE output_buf));
  160330. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160331. jvirt_barray_ptr *coef_arrays;
  160332. };
  160333. /* Decompression postprocessing (color quantization buffer control) */
  160334. struct jpeg_d_post_controller {
  160335. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160336. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160337. JSAMPIMAGE input_buf,
  160338. JDIMENSION *in_row_group_ctr,
  160339. JDIMENSION in_row_groups_avail,
  160340. JSAMPARRAY output_buf,
  160341. JDIMENSION *out_row_ctr,
  160342. JDIMENSION out_rows_avail));
  160343. };
  160344. /* Marker reading & parsing */
  160345. struct jpeg_marker_reader {
  160346. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160347. /* Read markers until SOS or EOI.
  160348. * Returns same codes as are defined for jpeg_consume_input:
  160349. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160350. */
  160351. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160352. /* Read a restart marker --- exported for use by entropy decoder only */
  160353. jpeg_marker_parser_method read_restart_marker;
  160354. /* State of marker reader --- nominally internal, but applications
  160355. * supplying COM or APPn handlers might like to know the state.
  160356. */
  160357. boolean saw_SOI; /* found SOI? */
  160358. boolean saw_SOF; /* found SOF? */
  160359. int next_restart_num; /* next restart number expected (0-7) */
  160360. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160361. };
  160362. /* Entropy decoding */
  160363. struct jpeg_entropy_decoder {
  160364. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160365. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160366. JBLOCKROW *MCU_data));
  160367. /* This is here to share code between baseline and progressive decoders; */
  160368. /* other modules probably should not use it */
  160369. boolean insufficient_data; /* set TRUE after emitting warning */
  160370. };
  160371. /* Inverse DCT (also performs dequantization) */
  160372. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160373. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160374. JCOEFPTR coef_block,
  160375. JSAMPARRAY output_buf, JDIMENSION output_col));
  160376. struct jpeg_inverse_dct {
  160377. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160378. /* It is useful to allow each component to have a separate IDCT method. */
  160379. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160380. };
  160381. /* Upsampling (note that upsampler must also call color converter) */
  160382. struct jpeg_upsampler {
  160383. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160384. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160385. JSAMPIMAGE input_buf,
  160386. JDIMENSION *in_row_group_ctr,
  160387. JDIMENSION in_row_groups_avail,
  160388. JSAMPARRAY output_buf,
  160389. JDIMENSION *out_row_ctr,
  160390. JDIMENSION out_rows_avail));
  160391. boolean need_context_rows; /* TRUE if need rows above & below */
  160392. };
  160393. /* Colorspace conversion */
  160394. struct jpeg_color_deconverter {
  160395. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160396. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160397. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160398. JSAMPARRAY output_buf, int num_rows));
  160399. };
  160400. /* Color quantization or color precision reduction */
  160401. struct jpeg_color_quantizer {
  160402. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160403. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160404. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160405. int num_rows));
  160406. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160407. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160408. };
  160409. /* Miscellaneous useful macros */
  160410. #undef MAX
  160411. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160412. #undef MIN
  160413. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160414. /* We assume that right shift corresponds to signed division by 2 with
  160415. * rounding towards minus infinity. This is correct for typical "arithmetic
  160416. * shift" instructions that shift in copies of the sign bit. But some
  160417. * C compilers implement >> with an unsigned shift. For these machines you
  160418. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160419. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160420. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160421. * included in the variables of any routine using RIGHT_SHIFT.
  160422. */
  160423. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160424. #define SHIFT_TEMPS INT32 shift_temp;
  160425. #define RIGHT_SHIFT(x,shft) \
  160426. ((shift_temp = (x)) < 0 ? \
  160427. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160428. (shift_temp >> (shft)))
  160429. #else
  160430. #define SHIFT_TEMPS
  160431. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160432. #endif
  160433. /* Short forms of external names for systems with brain-damaged linkers. */
  160434. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160435. #define jinit_compress_master jICompress
  160436. #define jinit_c_master_control jICMaster
  160437. #define jinit_c_main_controller jICMainC
  160438. #define jinit_c_prep_controller jICPrepC
  160439. #define jinit_c_coef_controller jICCoefC
  160440. #define jinit_color_converter jICColor
  160441. #define jinit_downsampler jIDownsampler
  160442. #define jinit_forward_dct jIFDCT
  160443. #define jinit_huff_encoder jIHEncoder
  160444. #define jinit_phuff_encoder jIPHEncoder
  160445. #define jinit_marker_writer jIMWriter
  160446. #define jinit_master_decompress jIDMaster
  160447. #define jinit_d_main_controller jIDMainC
  160448. #define jinit_d_coef_controller jIDCoefC
  160449. #define jinit_d_post_controller jIDPostC
  160450. #define jinit_input_controller jIInCtlr
  160451. #define jinit_marker_reader jIMReader
  160452. #define jinit_huff_decoder jIHDecoder
  160453. #define jinit_phuff_decoder jIPHDecoder
  160454. #define jinit_inverse_dct jIIDCT
  160455. #define jinit_upsampler jIUpsampler
  160456. #define jinit_color_deconverter jIDColor
  160457. #define jinit_1pass_quantizer jI1Quant
  160458. #define jinit_2pass_quantizer jI2Quant
  160459. #define jinit_merged_upsampler jIMUpsampler
  160460. #define jinit_memory_mgr jIMemMgr
  160461. #define jdiv_round_up jDivRound
  160462. #define jround_up jRound
  160463. #define jcopy_sample_rows jCopySamples
  160464. #define jcopy_block_row jCopyBlocks
  160465. #define jzero_far jZeroFar
  160466. #define jpeg_zigzag_order jZIGTable
  160467. #define jpeg_natural_order jZAGTable
  160468. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160469. /* Compression module initialization routines */
  160470. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160471. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160472. boolean transcode_only));
  160473. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160474. boolean need_full_buffer));
  160475. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160476. boolean need_full_buffer));
  160477. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160478. boolean need_full_buffer));
  160479. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160480. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160481. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160482. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160483. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160484. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160485. /* Decompression module initialization routines */
  160486. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160487. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160488. boolean need_full_buffer));
  160489. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160490. boolean need_full_buffer));
  160491. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160492. boolean need_full_buffer));
  160493. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160494. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160495. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160496. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160497. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160498. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160499. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160500. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160501. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160502. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160503. /* Memory manager initialization */
  160504. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160505. /* Utility routines in jutils.c */
  160506. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160507. EXTERN(long) jround_up JPP((long a, long b));
  160508. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160509. JSAMPARRAY output_array, int dest_row,
  160510. int num_rows, JDIMENSION num_cols));
  160511. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160512. JDIMENSION num_blocks));
  160513. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160514. /* Constant tables in jutils.c */
  160515. #if 0 /* This table is not actually needed in v6a */
  160516. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160517. #endif
  160518. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160519. /* Suppress undefined-structure complaints if necessary. */
  160520. #ifdef INCOMPLETE_TYPES_BROKEN
  160521. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160522. struct jvirt_sarray_control { long dummy; };
  160523. struct jvirt_barray_control { long dummy; };
  160524. #endif
  160525. #endif /* INCOMPLETE_TYPES_BROKEN */
  160526. /*** End of inlined file: jpegint.h ***/
  160527. /* fetch private declarations */
  160528. /*** Start of inlined file: jerror.h ***/
  160529. /*
  160530. * To define the enum list of message codes, include this file without
  160531. * defining macro JMESSAGE. To create a message string table, include it
  160532. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160533. */
  160534. #ifndef JMESSAGE
  160535. #ifndef JERROR_H
  160536. /* First time through, define the enum list */
  160537. #define JMAKE_ENUM_LIST
  160538. #else
  160539. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160540. #define JMESSAGE(code,string)
  160541. #endif /* JERROR_H */
  160542. #endif /* JMESSAGE */
  160543. #ifdef JMAKE_ENUM_LIST
  160544. typedef enum {
  160545. #define JMESSAGE(code,string) code ,
  160546. #endif /* JMAKE_ENUM_LIST */
  160547. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160548. /* For maintenance convenience, list is alphabetical by message code name */
  160549. JMESSAGE(JERR_ARITH_NOTIMPL,
  160550. "Sorry, there are legal restrictions on arithmetic coding")
  160551. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160552. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160553. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160554. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160555. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160556. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160557. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160558. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160559. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160560. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160561. JMESSAGE(JERR_BAD_LIB_VERSION,
  160562. "Wrong JPEG library version: library is %d, caller expects %d")
  160563. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160564. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160565. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160566. JMESSAGE(JERR_BAD_PROGRESSION,
  160567. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160568. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160569. "Invalid progressive parameters at scan script entry %d")
  160570. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160571. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160572. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160573. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160574. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160575. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160576. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160577. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160578. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160579. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160580. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160581. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160582. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160583. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160584. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160585. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160586. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160587. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160588. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160589. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160590. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160591. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160592. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160593. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160594. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160595. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160596. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160597. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160598. "Cannot transcode due to multiple use of quantization table %d")
  160599. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160600. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160601. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160602. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160603. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160604. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160605. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160606. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160607. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160608. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160609. JMESSAGE(JERR_QUANT_COMPONENTS,
  160610. "Cannot quantize more than %d color components")
  160611. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160612. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160613. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160614. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160615. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160616. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160617. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160618. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160619. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160620. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160621. JMESSAGE(JERR_TFILE_WRITE,
  160622. "Write failed on temporary file --- out of disk space?")
  160623. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160624. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160625. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160626. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160627. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160628. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160629. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160630. JMESSAGE(JMSG_VERSION, JVERSION)
  160631. JMESSAGE(JTRC_16BIT_TABLES,
  160632. "Caution: quantization tables are too coarse for baseline JPEG")
  160633. JMESSAGE(JTRC_ADOBE,
  160634. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160635. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160636. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160637. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160638. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160639. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160640. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160641. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160642. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160643. JMESSAGE(JTRC_EOI, "End Of Image")
  160644. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160645. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160646. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160647. "Warning: thumbnail image size does not match data length %u")
  160648. JMESSAGE(JTRC_JFIF_EXTENSION,
  160649. "JFIF extension marker: type 0x%02x, length %u")
  160650. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160651. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160652. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160653. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160654. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160655. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160656. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160657. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160658. JMESSAGE(JTRC_RST, "RST%d")
  160659. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160660. "Smoothing not supported with nonstandard sampling ratios")
  160661. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160662. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160663. JMESSAGE(JTRC_SOI, "Start of Image")
  160664. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160665. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160666. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160667. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160668. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160669. JMESSAGE(JTRC_THUMB_JPEG,
  160670. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160671. JMESSAGE(JTRC_THUMB_PALETTE,
  160672. "JFIF extension marker: palette thumbnail image, length %u")
  160673. JMESSAGE(JTRC_THUMB_RGB,
  160674. "JFIF extension marker: RGB thumbnail image, length %u")
  160675. JMESSAGE(JTRC_UNKNOWN_IDS,
  160676. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160677. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160678. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160679. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160680. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160681. "Inconsistent progression sequence for component %d coefficient %d")
  160682. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160683. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160684. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160685. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160686. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160687. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160688. JMESSAGE(JWRN_MUST_RESYNC,
  160689. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160690. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160691. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160692. #ifdef JMAKE_ENUM_LIST
  160693. JMSG_LASTMSGCODE
  160694. } J_MESSAGE_CODE;
  160695. #undef JMAKE_ENUM_LIST
  160696. #endif /* JMAKE_ENUM_LIST */
  160697. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160698. #undef JMESSAGE
  160699. #ifndef JERROR_H
  160700. #define JERROR_H
  160701. /* Macros to simplify using the error and trace message stuff */
  160702. /* The first parameter is either type of cinfo pointer */
  160703. /* Fatal errors (print message and exit) */
  160704. #define ERREXIT(cinfo,code) \
  160705. ((cinfo)->err->msg_code = (code), \
  160706. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160707. #define ERREXIT1(cinfo,code,p1) \
  160708. ((cinfo)->err->msg_code = (code), \
  160709. (cinfo)->err->msg_parm.i[0] = (p1), \
  160710. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160711. #define ERREXIT2(cinfo,code,p1,p2) \
  160712. ((cinfo)->err->msg_code = (code), \
  160713. (cinfo)->err->msg_parm.i[0] = (p1), \
  160714. (cinfo)->err->msg_parm.i[1] = (p2), \
  160715. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160716. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160717. ((cinfo)->err->msg_code = (code), \
  160718. (cinfo)->err->msg_parm.i[0] = (p1), \
  160719. (cinfo)->err->msg_parm.i[1] = (p2), \
  160720. (cinfo)->err->msg_parm.i[2] = (p3), \
  160721. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160722. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160723. ((cinfo)->err->msg_code = (code), \
  160724. (cinfo)->err->msg_parm.i[0] = (p1), \
  160725. (cinfo)->err->msg_parm.i[1] = (p2), \
  160726. (cinfo)->err->msg_parm.i[2] = (p3), \
  160727. (cinfo)->err->msg_parm.i[3] = (p4), \
  160728. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160729. #define ERREXITS(cinfo,code,str) \
  160730. ((cinfo)->err->msg_code = (code), \
  160731. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160732. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160733. #define MAKESTMT(stuff) do { stuff } while (0)
  160734. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160735. #define WARNMS(cinfo,code) \
  160736. ((cinfo)->err->msg_code = (code), \
  160737. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160738. #define WARNMS1(cinfo,code,p1) \
  160739. ((cinfo)->err->msg_code = (code), \
  160740. (cinfo)->err->msg_parm.i[0] = (p1), \
  160741. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160742. #define WARNMS2(cinfo,code,p1,p2) \
  160743. ((cinfo)->err->msg_code = (code), \
  160744. (cinfo)->err->msg_parm.i[0] = (p1), \
  160745. (cinfo)->err->msg_parm.i[1] = (p2), \
  160746. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160747. /* Informational/debugging messages */
  160748. #define TRACEMS(cinfo,lvl,code) \
  160749. ((cinfo)->err->msg_code = (code), \
  160750. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160751. #define TRACEMS1(cinfo,lvl,code,p1) \
  160752. ((cinfo)->err->msg_code = (code), \
  160753. (cinfo)->err->msg_parm.i[0] = (p1), \
  160754. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160755. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160756. ((cinfo)->err->msg_code = (code), \
  160757. (cinfo)->err->msg_parm.i[0] = (p1), \
  160758. (cinfo)->err->msg_parm.i[1] = (p2), \
  160759. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160760. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160761. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160762. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160763. (cinfo)->err->msg_code = (code); \
  160764. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160765. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160766. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160767. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160768. (cinfo)->err->msg_code = (code); \
  160769. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160770. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160771. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160772. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160773. _mp[4] = (p5); \
  160774. (cinfo)->err->msg_code = (code); \
  160775. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160776. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160777. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160778. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160779. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160780. (cinfo)->err->msg_code = (code); \
  160781. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160782. #define TRACEMSS(cinfo,lvl,code,str) \
  160783. ((cinfo)->err->msg_code = (code), \
  160784. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160785. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160786. #endif /* JERROR_H */
  160787. /*** End of inlined file: jerror.h ***/
  160788. /* fetch error codes too */
  160789. #endif
  160790. #endif /* JPEGLIB_H */
  160791. /*** End of inlined file: jpeglib.h ***/
  160792. /*** Start of inlined file: jcapimin.c ***/
  160793. #define JPEG_INTERNALS
  160794. /*** Start of inlined file: jinclude.h ***/
  160795. /* Include auto-config file to find out which system include files we need. */
  160796. #ifndef __jinclude_h__
  160797. #define __jinclude_h__
  160798. /*** Start of inlined file: jconfig.h ***/
  160799. /* see jconfig.doc for explanations */
  160800. // disable all the warnings under MSVC
  160801. #ifdef _MSC_VER
  160802. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160803. #endif
  160804. #ifdef __BORLANDC__
  160805. #pragma warn -8057
  160806. #pragma warn -8019
  160807. #pragma warn -8004
  160808. #pragma warn -8008
  160809. #endif
  160810. #define HAVE_PROTOTYPES
  160811. #define HAVE_UNSIGNED_CHAR
  160812. #define HAVE_UNSIGNED_SHORT
  160813. /* #define void char */
  160814. /* #define const */
  160815. #undef CHAR_IS_UNSIGNED
  160816. #define HAVE_STDDEF_H
  160817. #define HAVE_STDLIB_H
  160818. #undef NEED_BSD_STRINGS
  160819. #undef NEED_SYS_TYPES_H
  160820. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160821. #undef NEED_SHORT_EXTERNAL_NAMES
  160822. #undef INCOMPLETE_TYPES_BROKEN
  160823. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160824. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160825. typedef unsigned char boolean;
  160826. #endif
  160827. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160828. #ifdef JPEG_INTERNALS
  160829. #undef RIGHT_SHIFT_IS_UNSIGNED
  160830. #endif /* JPEG_INTERNALS */
  160831. #ifdef JPEG_CJPEG_DJPEG
  160832. #define BMP_SUPPORTED /* BMP image file format */
  160833. #define GIF_SUPPORTED /* GIF image file format */
  160834. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160835. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160836. #define TARGA_SUPPORTED /* Targa image file format */
  160837. #define TWO_FILE_COMMANDLINE /* optional */
  160838. #define USE_SETMODE /* Microsoft has setmode() */
  160839. #undef NEED_SIGNAL_CATCHER
  160840. #undef DONT_USE_B_MODE
  160841. #undef PROGRESS_REPORT /* optional */
  160842. #endif /* JPEG_CJPEG_DJPEG */
  160843. /*** End of inlined file: jconfig.h ***/
  160844. /* auto configuration options */
  160845. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  160846. /*
  160847. * We need the NULL macro and size_t typedef.
  160848. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  160849. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  160850. * pull in <sys/types.h> as well.
  160851. * Note that the core JPEG library does not require <stdio.h>;
  160852. * only the default error handler and data source/destination modules do.
  160853. * But we must pull it in because of the references to FILE in jpeglib.h.
  160854. * You can remove those references if you want to compile without <stdio.h>.
  160855. */
  160856. #ifdef HAVE_STDDEF_H
  160857. #include <stddef.h>
  160858. #endif
  160859. #ifdef HAVE_STDLIB_H
  160860. #include <stdlib.h>
  160861. #endif
  160862. #ifdef NEED_SYS_TYPES_H
  160863. #include <sys/types.h>
  160864. #endif
  160865. #include <stdio.h>
  160866. /*
  160867. * We need memory copying and zeroing functions, plus strncpy().
  160868. * ANSI and System V implementations declare these in <string.h>.
  160869. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  160870. * Some systems may declare memset and memcpy in <memory.h>.
  160871. *
  160872. * NOTE: we assume the size parameters to these functions are of type size_t.
  160873. * Change the casts in these macros if not!
  160874. */
  160875. #ifdef NEED_BSD_STRINGS
  160876. #include <strings.h>
  160877. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  160878. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  160879. #else /* not BSD, assume ANSI/SysV string lib */
  160880. #include <string.h>
  160881. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  160882. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  160883. #endif
  160884. /*
  160885. * In ANSI C, and indeed any rational implementation, size_t is also the
  160886. * type returned by sizeof(). However, it seems there are some irrational
  160887. * implementations out there, in which sizeof() returns an int even though
  160888. * size_t is defined as long or unsigned long. To ensure consistent results
  160889. * we always use this SIZEOF() macro in place of using sizeof() directly.
  160890. */
  160891. #define SIZEOF(object) ((size_t) sizeof(object))
  160892. /*
  160893. * The modules that use fread() and fwrite() always invoke them through
  160894. * these macros. On some systems you may need to twiddle the argument casts.
  160895. * CAUTION: argument order is different from underlying functions!
  160896. */
  160897. #define JFREAD(file,buf,sizeofbuf) \
  160898. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160899. #define JFWRITE(file,buf,sizeofbuf) \
  160900. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160901. typedef enum { /* JPEG marker codes */
  160902. M_SOF0 = 0xc0,
  160903. M_SOF1 = 0xc1,
  160904. M_SOF2 = 0xc2,
  160905. M_SOF3 = 0xc3,
  160906. M_SOF5 = 0xc5,
  160907. M_SOF6 = 0xc6,
  160908. M_SOF7 = 0xc7,
  160909. M_JPG = 0xc8,
  160910. M_SOF9 = 0xc9,
  160911. M_SOF10 = 0xca,
  160912. M_SOF11 = 0xcb,
  160913. M_SOF13 = 0xcd,
  160914. M_SOF14 = 0xce,
  160915. M_SOF15 = 0xcf,
  160916. M_DHT = 0xc4,
  160917. M_DAC = 0xcc,
  160918. M_RST0 = 0xd0,
  160919. M_RST1 = 0xd1,
  160920. M_RST2 = 0xd2,
  160921. M_RST3 = 0xd3,
  160922. M_RST4 = 0xd4,
  160923. M_RST5 = 0xd5,
  160924. M_RST6 = 0xd6,
  160925. M_RST7 = 0xd7,
  160926. M_SOI = 0xd8,
  160927. M_EOI = 0xd9,
  160928. M_SOS = 0xda,
  160929. M_DQT = 0xdb,
  160930. M_DNL = 0xdc,
  160931. M_DRI = 0xdd,
  160932. M_DHP = 0xde,
  160933. M_EXP = 0xdf,
  160934. M_APP0 = 0xe0,
  160935. M_APP1 = 0xe1,
  160936. M_APP2 = 0xe2,
  160937. M_APP3 = 0xe3,
  160938. M_APP4 = 0xe4,
  160939. M_APP5 = 0xe5,
  160940. M_APP6 = 0xe6,
  160941. M_APP7 = 0xe7,
  160942. M_APP8 = 0xe8,
  160943. M_APP9 = 0xe9,
  160944. M_APP10 = 0xea,
  160945. M_APP11 = 0xeb,
  160946. M_APP12 = 0xec,
  160947. M_APP13 = 0xed,
  160948. M_APP14 = 0xee,
  160949. M_APP15 = 0xef,
  160950. M_JPG0 = 0xf0,
  160951. M_JPG13 = 0xfd,
  160952. M_COM = 0xfe,
  160953. M_TEM = 0x01,
  160954. M_ERROR = 0x100
  160955. } JPEG_MARKER;
  160956. /*
  160957. * Figure F.12: extend sign bit.
  160958. * On some machines, a shift and add will be faster than a table lookup.
  160959. */
  160960. #ifdef AVOID_TABLES
  160961. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  160962. #else
  160963. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  160964. static const int extend_test[16] = /* entry n is 2**(n-1) */
  160965. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  160966. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  160967. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  160968. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  160969. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  160970. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  160971. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  160972. #endif /* AVOID_TABLES */
  160973. #endif
  160974. /*** End of inlined file: jinclude.h ***/
  160975. /*
  160976. * Initialization of a JPEG compression object.
  160977. * The error manager must already be set up (in case memory manager fails).
  160978. */
  160979. GLOBAL(void)
  160980. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  160981. {
  160982. int i;
  160983. /* Guard against version mismatches between library and caller. */
  160984. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  160985. if (version != JPEG_LIB_VERSION)
  160986. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  160987. if (structsize != SIZEOF(struct jpeg_compress_struct))
  160988. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  160989. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  160990. /* For debugging purposes, we zero the whole master structure.
  160991. * But the application has already set the err pointer, and may have set
  160992. * client_data, so we have to save and restore those fields.
  160993. * Note: if application hasn't set client_data, tools like Purify may
  160994. * complain here.
  160995. */
  160996. {
  160997. struct jpeg_error_mgr * err = cinfo->err;
  160998. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  160999. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161000. cinfo->err = err;
  161001. cinfo->client_data = client_data;
  161002. }
  161003. cinfo->is_decompressor = FALSE;
  161004. /* Initialize a memory manager instance for this object */
  161005. jinit_memory_mgr((j_common_ptr) cinfo);
  161006. /* Zero out pointers to permanent structures. */
  161007. cinfo->progress = NULL;
  161008. cinfo->dest = NULL;
  161009. cinfo->comp_info = NULL;
  161010. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161011. cinfo->quant_tbl_ptrs[i] = NULL;
  161012. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161013. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161014. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161015. }
  161016. cinfo->script_space = NULL;
  161017. cinfo->input_gamma = 1.0; /* in case application forgets */
  161018. /* OK, I'm ready */
  161019. cinfo->global_state = CSTATE_START;
  161020. }
  161021. /*
  161022. * Destruction of a JPEG compression object
  161023. */
  161024. GLOBAL(void)
  161025. jpeg_destroy_compress (j_compress_ptr cinfo)
  161026. {
  161027. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161028. }
  161029. /*
  161030. * Abort processing of a JPEG compression operation,
  161031. * but don't destroy the object itself.
  161032. */
  161033. GLOBAL(void)
  161034. jpeg_abort_compress (j_compress_ptr cinfo)
  161035. {
  161036. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161037. }
  161038. /*
  161039. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161040. * Marks all currently defined tables as already written (if suppress)
  161041. * or not written (if !suppress). This will control whether they get emitted
  161042. * by a subsequent jpeg_start_compress call.
  161043. *
  161044. * This routine is exported for use by applications that want to produce
  161045. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161046. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161047. * jcparam.o would be linked whether the application used it or not.
  161048. */
  161049. GLOBAL(void)
  161050. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161051. {
  161052. int i;
  161053. JQUANT_TBL * qtbl;
  161054. JHUFF_TBL * htbl;
  161055. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161056. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161057. qtbl->sent_table = suppress;
  161058. }
  161059. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161060. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161061. htbl->sent_table = suppress;
  161062. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161063. htbl->sent_table = suppress;
  161064. }
  161065. }
  161066. /*
  161067. * Finish JPEG compression.
  161068. *
  161069. * If a multipass operating mode was selected, this may do a great deal of
  161070. * work including most of the actual output.
  161071. */
  161072. GLOBAL(void)
  161073. jpeg_finish_compress (j_compress_ptr cinfo)
  161074. {
  161075. JDIMENSION iMCU_row;
  161076. if (cinfo->global_state == CSTATE_SCANNING ||
  161077. cinfo->global_state == CSTATE_RAW_OK) {
  161078. /* Terminate first pass */
  161079. if (cinfo->next_scanline < cinfo->image_height)
  161080. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161081. (*cinfo->master->finish_pass) (cinfo);
  161082. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161083. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161084. /* Perform any remaining passes */
  161085. while (! cinfo->master->is_last_pass) {
  161086. (*cinfo->master->prepare_for_pass) (cinfo);
  161087. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161088. if (cinfo->progress != NULL) {
  161089. cinfo->progress->pass_counter = (long) iMCU_row;
  161090. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161091. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161092. }
  161093. /* We bypass the main controller and invoke coef controller directly;
  161094. * all work is being done from the coefficient buffer.
  161095. */
  161096. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161097. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161098. }
  161099. (*cinfo->master->finish_pass) (cinfo);
  161100. }
  161101. /* Write EOI, do final cleanup */
  161102. (*cinfo->marker->write_file_trailer) (cinfo);
  161103. (*cinfo->dest->term_destination) (cinfo);
  161104. /* We can use jpeg_abort to release memory and reset global_state */
  161105. jpeg_abort((j_common_ptr) cinfo);
  161106. }
  161107. /*
  161108. * Write a special marker.
  161109. * This is only recommended for writing COM or APPn markers.
  161110. * Must be called after jpeg_start_compress() and before
  161111. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161112. */
  161113. GLOBAL(void)
  161114. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161115. const JOCTET *dataptr, unsigned int datalen)
  161116. {
  161117. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161118. if (cinfo->next_scanline != 0 ||
  161119. (cinfo->global_state != CSTATE_SCANNING &&
  161120. cinfo->global_state != CSTATE_RAW_OK &&
  161121. cinfo->global_state != CSTATE_WRCOEFS))
  161122. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161123. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161124. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161125. while (datalen--) {
  161126. (*write_marker_byte) (cinfo, *dataptr);
  161127. dataptr++;
  161128. }
  161129. }
  161130. /* Same, but piecemeal. */
  161131. GLOBAL(void)
  161132. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161133. {
  161134. if (cinfo->next_scanline != 0 ||
  161135. (cinfo->global_state != CSTATE_SCANNING &&
  161136. cinfo->global_state != CSTATE_RAW_OK &&
  161137. cinfo->global_state != CSTATE_WRCOEFS))
  161138. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161139. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161140. }
  161141. GLOBAL(void)
  161142. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161143. {
  161144. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161145. }
  161146. /*
  161147. * Alternate compression function: just write an abbreviated table file.
  161148. * Before calling this, all parameters and a data destination must be set up.
  161149. *
  161150. * To produce a pair of files containing abbreviated tables and abbreviated
  161151. * image data, one would proceed as follows:
  161152. *
  161153. * initialize JPEG object
  161154. * set JPEG parameters
  161155. * set destination to table file
  161156. * jpeg_write_tables(cinfo);
  161157. * set destination to image file
  161158. * jpeg_start_compress(cinfo, FALSE);
  161159. * write data...
  161160. * jpeg_finish_compress(cinfo);
  161161. *
  161162. * jpeg_write_tables has the side effect of marking all tables written
  161163. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161164. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161165. */
  161166. GLOBAL(void)
  161167. jpeg_write_tables (j_compress_ptr cinfo)
  161168. {
  161169. if (cinfo->global_state != CSTATE_START)
  161170. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161171. /* (Re)initialize error mgr and destination modules */
  161172. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161173. (*cinfo->dest->init_destination) (cinfo);
  161174. /* Initialize the marker writer ... bit of a crock to do it here. */
  161175. jinit_marker_writer(cinfo);
  161176. /* Write them tables! */
  161177. (*cinfo->marker->write_tables_only) (cinfo);
  161178. /* And clean up. */
  161179. (*cinfo->dest->term_destination) (cinfo);
  161180. /*
  161181. * In library releases up through v6a, we called jpeg_abort() here to free
  161182. * any working memory allocated by the destination manager and marker
  161183. * writer. Some applications had a problem with that: they allocated space
  161184. * of their own from the library memory manager, and didn't want it to go
  161185. * away during write_tables. So now we do nothing. This will cause a
  161186. * memory leak if an app calls write_tables repeatedly without doing a full
  161187. * compression cycle or otherwise resetting the JPEG object. However, that
  161188. * seems less bad than unexpectedly freeing memory in the normal case.
  161189. * An app that prefers the old behavior can call jpeg_abort for itself after
  161190. * each call to jpeg_write_tables().
  161191. */
  161192. }
  161193. /*** End of inlined file: jcapimin.c ***/
  161194. /*** Start of inlined file: jcapistd.c ***/
  161195. #define JPEG_INTERNALS
  161196. /*
  161197. * Compression initialization.
  161198. * Before calling this, all parameters and a data destination must be set up.
  161199. *
  161200. * We require a write_all_tables parameter as a failsafe check when writing
  161201. * multiple datastreams from the same compression object. Since prior runs
  161202. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161203. * would emit an abbreviated stream (no tables) by default. This may be what
  161204. * is wanted, but for safety's sake it should not be the default behavior:
  161205. * programmers should have to make a deliberate choice to emit abbreviated
  161206. * images. Therefore the documentation and examples should encourage people
  161207. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161208. * wrong thing.
  161209. */
  161210. GLOBAL(void)
  161211. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161212. {
  161213. if (cinfo->global_state != CSTATE_START)
  161214. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161215. if (write_all_tables)
  161216. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161217. /* (Re)initialize error mgr and destination modules */
  161218. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161219. (*cinfo->dest->init_destination) (cinfo);
  161220. /* Perform master selection of active modules */
  161221. jinit_compress_master(cinfo);
  161222. /* Set up for the first pass */
  161223. (*cinfo->master->prepare_for_pass) (cinfo);
  161224. /* Ready for application to drive first pass through jpeg_write_scanlines
  161225. * or jpeg_write_raw_data.
  161226. */
  161227. cinfo->next_scanline = 0;
  161228. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161229. }
  161230. /*
  161231. * Write some scanlines of data to the JPEG compressor.
  161232. *
  161233. * The return value will be the number of lines actually written.
  161234. * This should be less than the supplied num_lines only in case that
  161235. * the data destination module has requested suspension of the compressor,
  161236. * or if more than image_height scanlines are passed in.
  161237. *
  161238. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161239. * this likely signals an application programmer error. However,
  161240. * excess scanlines passed in the last valid call are *silently* ignored,
  161241. * so that the application need not adjust num_lines for end-of-image
  161242. * when using a multiple-scanline buffer.
  161243. */
  161244. GLOBAL(JDIMENSION)
  161245. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161246. JDIMENSION num_lines)
  161247. {
  161248. JDIMENSION row_ctr, rows_left;
  161249. if (cinfo->global_state != CSTATE_SCANNING)
  161250. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161251. if (cinfo->next_scanline >= cinfo->image_height)
  161252. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161253. /* Call progress monitor hook if present */
  161254. if (cinfo->progress != NULL) {
  161255. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161256. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161257. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161258. }
  161259. /* Give master control module another chance if this is first call to
  161260. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161261. * delayed so that application can write COM, etc, markers between
  161262. * jpeg_start_compress and jpeg_write_scanlines.
  161263. */
  161264. if (cinfo->master->call_pass_startup)
  161265. (*cinfo->master->pass_startup) (cinfo);
  161266. /* Ignore any extra scanlines at bottom of image. */
  161267. rows_left = cinfo->image_height - cinfo->next_scanline;
  161268. if (num_lines > rows_left)
  161269. num_lines = rows_left;
  161270. row_ctr = 0;
  161271. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161272. cinfo->next_scanline += row_ctr;
  161273. return row_ctr;
  161274. }
  161275. /*
  161276. * Alternate entry point to write raw data.
  161277. * Processes exactly one iMCU row per call, unless suspended.
  161278. */
  161279. GLOBAL(JDIMENSION)
  161280. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161281. JDIMENSION num_lines)
  161282. {
  161283. JDIMENSION lines_per_iMCU_row;
  161284. if (cinfo->global_state != CSTATE_RAW_OK)
  161285. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161286. if (cinfo->next_scanline >= cinfo->image_height) {
  161287. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161288. return 0;
  161289. }
  161290. /* Call progress monitor hook if present */
  161291. if (cinfo->progress != NULL) {
  161292. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161293. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161294. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161295. }
  161296. /* Give master control module another chance if this is first call to
  161297. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161298. * delayed so that application can write COM, etc, markers between
  161299. * jpeg_start_compress and jpeg_write_raw_data.
  161300. */
  161301. if (cinfo->master->call_pass_startup)
  161302. (*cinfo->master->pass_startup) (cinfo);
  161303. /* Verify that at least one iMCU row has been passed. */
  161304. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161305. if (num_lines < lines_per_iMCU_row)
  161306. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161307. /* Directly compress the row. */
  161308. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161309. /* If compressor did not consume the whole row, suspend processing. */
  161310. return 0;
  161311. }
  161312. /* OK, we processed one iMCU row. */
  161313. cinfo->next_scanline += lines_per_iMCU_row;
  161314. return lines_per_iMCU_row;
  161315. }
  161316. /*** End of inlined file: jcapistd.c ***/
  161317. /*** Start of inlined file: jccoefct.c ***/
  161318. #define JPEG_INTERNALS
  161319. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161320. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161321. * step is run during the first pass, and subsequent passes need only read
  161322. * the buffered coefficients.
  161323. */
  161324. #ifdef ENTROPY_OPT_SUPPORTED
  161325. #define FULL_COEF_BUFFER_SUPPORTED
  161326. #else
  161327. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161328. #define FULL_COEF_BUFFER_SUPPORTED
  161329. #endif
  161330. #endif
  161331. /* Private buffer controller object */
  161332. typedef struct {
  161333. struct jpeg_c_coef_controller pub; /* public fields */
  161334. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161335. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161336. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161337. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161338. /* For single-pass compression, it's sufficient to buffer just one MCU
  161339. * (although this may prove a bit slow in practice). We allocate a
  161340. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161341. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161342. * it's not really very big; this is to keep the module interfaces unchanged
  161343. * when a large coefficient buffer is necessary.)
  161344. * In multi-pass modes, this array points to the current MCU's blocks
  161345. * within the virtual arrays.
  161346. */
  161347. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161348. /* In multi-pass modes, we need a virtual block array for each component. */
  161349. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161350. } my_coef_controller;
  161351. typedef my_coef_controller * my_coef_ptr;
  161352. /* Forward declarations */
  161353. METHODDEF(boolean) compress_data
  161354. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161355. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161356. METHODDEF(boolean) compress_first_pass
  161357. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161358. METHODDEF(boolean) compress_output
  161359. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161360. #endif
  161361. LOCAL(void)
  161362. start_iMCU_row (j_compress_ptr cinfo)
  161363. /* Reset within-iMCU-row counters for a new row */
  161364. {
  161365. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161366. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161367. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161368. * But at the bottom of the image, process only what's left.
  161369. */
  161370. if (cinfo->comps_in_scan > 1) {
  161371. coef->MCU_rows_per_iMCU_row = 1;
  161372. } else {
  161373. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161374. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161375. else
  161376. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161377. }
  161378. coef->mcu_ctr = 0;
  161379. coef->MCU_vert_offset = 0;
  161380. }
  161381. /*
  161382. * Initialize for a processing pass.
  161383. */
  161384. METHODDEF(void)
  161385. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161386. {
  161387. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161388. coef->iMCU_row_num = 0;
  161389. start_iMCU_row(cinfo);
  161390. switch (pass_mode) {
  161391. case JBUF_PASS_THRU:
  161392. if (coef->whole_image[0] != NULL)
  161393. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161394. coef->pub.compress_data = compress_data;
  161395. break;
  161396. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161397. case JBUF_SAVE_AND_PASS:
  161398. if (coef->whole_image[0] == NULL)
  161399. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161400. coef->pub.compress_data = compress_first_pass;
  161401. break;
  161402. case JBUF_CRANK_DEST:
  161403. if (coef->whole_image[0] == NULL)
  161404. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161405. coef->pub.compress_data = compress_output;
  161406. break;
  161407. #endif
  161408. default:
  161409. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161410. break;
  161411. }
  161412. }
  161413. /*
  161414. * Process some data in the single-pass case.
  161415. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161416. * per call, ie, v_samp_factor block rows for each component in the image.
  161417. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161418. *
  161419. * NB: input_buf contains a plane for each component in image,
  161420. * which we index according to the component's SOF position.
  161421. */
  161422. METHODDEF(boolean)
  161423. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161424. {
  161425. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161426. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161427. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161428. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161429. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161430. JDIMENSION ypos, xpos;
  161431. jpeg_component_info *compptr;
  161432. /* Loop to write as much as one whole iMCU row */
  161433. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161434. yoffset++) {
  161435. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161436. MCU_col_num++) {
  161437. /* Determine where data comes from in input_buf and do the DCT thing.
  161438. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161439. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161440. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161441. * specially. The data in them does not matter for image reconstruction,
  161442. * so we fill them with values that will encode to the smallest amount of
  161443. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161444. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161445. */
  161446. blkn = 0;
  161447. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161448. compptr = cinfo->cur_comp_info[ci];
  161449. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161450. : compptr->last_col_width;
  161451. xpos = MCU_col_num * compptr->MCU_sample_width;
  161452. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161453. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161454. if (coef->iMCU_row_num < last_iMCU_row ||
  161455. yoffset+yindex < compptr->last_row_height) {
  161456. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161457. input_buf[compptr->component_index],
  161458. coef->MCU_buffer[blkn],
  161459. ypos, xpos, (JDIMENSION) blockcnt);
  161460. if (blockcnt < compptr->MCU_width) {
  161461. /* Create some dummy blocks at the right edge of the image. */
  161462. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161463. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161464. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161465. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161466. }
  161467. }
  161468. } else {
  161469. /* Create a row of dummy blocks at the bottom of the image. */
  161470. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161471. compptr->MCU_width * SIZEOF(JBLOCK));
  161472. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161473. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161474. }
  161475. }
  161476. blkn += compptr->MCU_width;
  161477. ypos += DCTSIZE;
  161478. }
  161479. }
  161480. /* Try to write the MCU. In event of a suspension failure, we will
  161481. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161482. */
  161483. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161484. /* Suspension forced; update state counters and exit */
  161485. coef->MCU_vert_offset = yoffset;
  161486. coef->mcu_ctr = MCU_col_num;
  161487. return FALSE;
  161488. }
  161489. }
  161490. /* Completed an MCU row, but perhaps not an iMCU row */
  161491. coef->mcu_ctr = 0;
  161492. }
  161493. /* Completed the iMCU row, advance counters for next one */
  161494. coef->iMCU_row_num++;
  161495. start_iMCU_row(cinfo);
  161496. return TRUE;
  161497. }
  161498. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161499. /*
  161500. * Process some data in the first pass of a multi-pass case.
  161501. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161502. * per call, ie, v_samp_factor block rows for each component in the image.
  161503. * This amount of data is read from the source buffer, DCT'd and quantized,
  161504. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161505. * as needed at the right and lower edges. (The dummy blocks are constructed
  161506. * in the virtual arrays, which have been padded appropriately.) This makes
  161507. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161508. *
  161509. * We must also emit the data to the entropy encoder. This is conveniently
  161510. * done by calling compress_output() after we've loaded the current strip
  161511. * of the virtual arrays.
  161512. *
  161513. * NB: input_buf contains a plane for each component in image. All
  161514. * components are DCT'd and loaded into the virtual arrays in this pass.
  161515. * However, it may be that only a subset of the components are emitted to
  161516. * the entropy encoder during this first pass; be careful about looking
  161517. * at the scan-dependent variables (MCU dimensions, etc).
  161518. */
  161519. METHODDEF(boolean)
  161520. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161521. {
  161522. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161523. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161524. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161525. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161526. JCOEF lastDC;
  161527. jpeg_component_info *compptr;
  161528. JBLOCKARRAY buffer;
  161529. JBLOCKROW thisblockrow, lastblockrow;
  161530. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161531. ci++, compptr++) {
  161532. /* Align the virtual buffer for this component. */
  161533. buffer = (*cinfo->mem->access_virt_barray)
  161534. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161535. coef->iMCU_row_num * compptr->v_samp_factor,
  161536. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161537. /* Count non-dummy DCT block rows in this iMCU row. */
  161538. if (coef->iMCU_row_num < last_iMCU_row)
  161539. block_rows = compptr->v_samp_factor;
  161540. else {
  161541. /* NB: can't use last_row_height here, since may not be set! */
  161542. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161543. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161544. }
  161545. blocks_across = compptr->width_in_blocks;
  161546. h_samp_factor = compptr->h_samp_factor;
  161547. /* Count number of dummy blocks to be added at the right margin. */
  161548. ndummy = (int) (blocks_across % h_samp_factor);
  161549. if (ndummy > 0)
  161550. ndummy = h_samp_factor - ndummy;
  161551. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161552. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161553. */
  161554. for (block_row = 0; block_row < block_rows; block_row++) {
  161555. thisblockrow = buffer[block_row];
  161556. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161557. input_buf[ci], thisblockrow,
  161558. (JDIMENSION) (block_row * DCTSIZE),
  161559. (JDIMENSION) 0, blocks_across);
  161560. if (ndummy > 0) {
  161561. /* Create dummy blocks at the right edge of the image. */
  161562. thisblockrow += blocks_across; /* => first dummy block */
  161563. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161564. lastDC = thisblockrow[-1][0];
  161565. for (bi = 0; bi < ndummy; bi++) {
  161566. thisblockrow[bi][0] = lastDC;
  161567. }
  161568. }
  161569. }
  161570. /* If at end of image, create dummy block rows as needed.
  161571. * The tricky part here is that within each MCU, we want the DC values
  161572. * of the dummy blocks to match the last real block's DC value.
  161573. * This squeezes a few more bytes out of the resulting file...
  161574. */
  161575. if (coef->iMCU_row_num == last_iMCU_row) {
  161576. blocks_across += ndummy; /* include lower right corner */
  161577. MCUs_across = blocks_across / h_samp_factor;
  161578. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161579. block_row++) {
  161580. thisblockrow = buffer[block_row];
  161581. lastblockrow = buffer[block_row-1];
  161582. jzero_far((void FAR *) thisblockrow,
  161583. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161584. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161585. lastDC = lastblockrow[h_samp_factor-1][0];
  161586. for (bi = 0; bi < h_samp_factor; bi++) {
  161587. thisblockrow[bi][0] = lastDC;
  161588. }
  161589. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161590. lastblockrow += h_samp_factor;
  161591. }
  161592. }
  161593. }
  161594. }
  161595. /* NB: compress_output will increment iMCU_row_num if successful.
  161596. * A suspension return will result in redoing all the work above next time.
  161597. */
  161598. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161599. return compress_output(cinfo, input_buf);
  161600. }
  161601. /*
  161602. * Process some data in subsequent passes of a multi-pass case.
  161603. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161604. * per call, ie, v_samp_factor block rows for each component in the scan.
  161605. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161606. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161607. *
  161608. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161609. */
  161610. METHODDEF(boolean)
  161611. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161612. {
  161613. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161614. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161615. int blkn, ci, xindex, yindex, yoffset;
  161616. JDIMENSION start_col;
  161617. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161618. JBLOCKROW buffer_ptr;
  161619. jpeg_component_info *compptr;
  161620. /* Align the virtual buffers for the components used in this scan.
  161621. * NB: during first pass, this is safe only because the buffers will
  161622. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161623. */
  161624. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161625. compptr = cinfo->cur_comp_info[ci];
  161626. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161627. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161628. coef->iMCU_row_num * compptr->v_samp_factor,
  161629. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161630. }
  161631. /* Loop to process one whole iMCU row */
  161632. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161633. yoffset++) {
  161634. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161635. MCU_col_num++) {
  161636. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161637. blkn = 0; /* index of current DCT block within MCU */
  161638. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161639. compptr = cinfo->cur_comp_info[ci];
  161640. start_col = MCU_col_num * compptr->MCU_width;
  161641. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161642. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161643. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161644. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161645. }
  161646. }
  161647. }
  161648. /* Try to write the MCU. */
  161649. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161650. /* Suspension forced; update state counters and exit */
  161651. coef->MCU_vert_offset = yoffset;
  161652. coef->mcu_ctr = MCU_col_num;
  161653. return FALSE;
  161654. }
  161655. }
  161656. /* Completed an MCU row, but perhaps not an iMCU row */
  161657. coef->mcu_ctr = 0;
  161658. }
  161659. /* Completed the iMCU row, advance counters for next one */
  161660. coef->iMCU_row_num++;
  161661. start_iMCU_row(cinfo);
  161662. return TRUE;
  161663. }
  161664. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161665. /*
  161666. * Initialize coefficient buffer controller.
  161667. */
  161668. GLOBAL(void)
  161669. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161670. {
  161671. my_coef_ptr coef;
  161672. coef = (my_coef_ptr)
  161673. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161674. SIZEOF(my_coef_controller));
  161675. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161676. coef->pub.start_pass = start_pass_coef;
  161677. /* Create the coefficient buffer. */
  161678. if (need_full_buffer) {
  161679. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161680. /* Allocate a full-image virtual array for each component, */
  161681. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161682. int ci;
  161683. jpeg_component_info *compptr;
  161684. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161685. ci++, compptr++) {
  161686. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161687. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161688. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161689. (long) compptr->h_samp_factor),
  161690. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161691. (long) compptr->v_samp_factor),
  161692. (JDIMENSION) compptr->v_samp_factor);
  161693. }
  161694. #else
  161695. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161696. #endif
  161697. } else {
  161698. /* We only need a single-MCU buffer. */
  161699. JBLOCKROW buffer;
  161700. int i;
  161701. buffer = (JBLOCKROW)
  161702. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161703. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161704. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161705. coef->MCU_buffer[i] = buffer + i;
  161706. }
  161707. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161708. }
  161709. }
  161710. /*** End of inlined file: jccoefct.c ***/
  161711. /*** Start of inlined file: jccolor.c ***/
  161712. #define JPEG_INTERNALS
  161713. /* Private subobject */
  161714. typedef struct {
  161715. struct jpeg_color_converter pub; /* public fields */
  161716. /* Private state for RGB->YCC conversion */
  161717. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161718. } my_color_converter;
  161719. typedef my_color_converter * my_cconvert_ptr;
  161720. /**************** RGB -> YCbCr conversion: most common case **************/
  161721. /*
  161722. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161723. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161724. * The conversion equations to be implemented are therefore
  161725. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161726. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161727. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161728. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161729. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161730. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161731. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161732. * were not represented exactly. Now we sacrifice exact representation of
  161733. * maximum red and maximum blue in order to get exact grayscales.
  161734. *
  161735. * To avoid floating-point arithmetic, we represent the fractional constants
  161736. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161737. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161738. *
  161739. * For even more speed, we avoid doing any multiplications in the inner loop
  161740. * by precalculating the constants times R,G,B for all possible values.
  161741. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161742. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161743. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161744. * colorspace anyway.
  161745. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161746. * in the tables to save adding them separately in the inner loop.
  161747. */
  161748. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161749. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161750. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161751. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161752. /* We allocate one big table and divide it up into eight parts, instead of
  161753. * doing eight alloc_small requests. This lets us use a single table base
  161754. * address, which can be held in a register in the inner loops on many
  161755. * machines (more than can hold all eight addresses, anyway).
  161756. */
  161757. #define R_Y_OFF 0 /* offset to R => Y section */
  161758. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161759. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161760. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161761. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161762. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161763. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161764. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161765. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161766. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161767. /*
  161768. * Initialize for RGB->YCC colorspace conversion.
  161769. */
  161770. METHODDEF(void)
  161771. rgb_ycc_start (j_compress_ptr cinfo)
  161772. {
  161773. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161774. INT32 * rgb_ycc_tab;
  161775. INT32 i;
  161776. /* Allocate and fill in the conversion tables. */
  161777. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161778. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161779. (TABLE_SIZE * SIZEOF(INT32)));
  161780. for (i = 0; i <= MAXJSAMPLE; i++) {
  161781. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161782. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161783. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161784. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161785. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161786. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161787. * This ensures that the maximum output will round to MAXJSAMPLE
  161788. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161789. */
  161790. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161791. /* B=>Cb and R=>Cr tables are the same
  161792. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161793. */
  161794. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161795. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161796. }
  161797. }
  161798. /*
  161799. * Convert some rows of samples to the JPEG colorspace.
  161800. *
  161801. * Note that we change from the application's interleaved-pixel format
  161802. * to our internal noninterleaved, one-plane-per-component format.
  161803. * The input buffer is therefore three times as wide as the output buffer.
  161804. *
  161805. * A starting row offset is provided only for the output buffer. The caller
  161806. * can easily adjust the passed input_buf value to accommodate any row
  161807. * offset required on that side.
  161808. */
  161809. METHODDEF(void)
  161810. rgb_ycc_convert (j_compress_ptr cinfo,
  161811. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161812. JDIMENSION output_row, int num_rows)
  161813. {
  161814. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161815. register int r, g, b;
  161816. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161817. register JSAMPROW inptr;
  161818. register JSAMPROW outptr0, outptr1, outptr2;
  161819. register JDIMENSION col;
  161820. JDIMENSION num_cols = cinfo->image_width;
  161821. while (--num_rows >= 0) {
  161822. inptr = *input_buf++;
  161823. outptr0 = output_buf[0][output_row];
  161824. outptr1 = output_buf[1][output_row];
  161825. outptr2 = output_buf[2][output_row];
  161826. output_row++;
  161827. for (col = 0; col < num_cols; col++) {
  161828. r = GETJSAMPLE(inptr[RGB_RED]);
  161829. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161830. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161831. inptr += RGB_PIXELSIZE;
  161832. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161833. * must be too; we do not need an explicit range-limiting operation.
  161834. * Hence the value being shifted is never negative, and we don't
  161835. * need the general RIGHT_SHIFT macro.
  161836. */
  161837. /* Y */
  161838. outptr0[col] = (JSAMPLE)
  161839. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161840. >> SCALEBITS);
  161841. /* Cb */
  161842. outptr1[col] = (JSAMPLE)
  161843. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161844. >> SCALEBITS);
  161845. /* Cr */
  161846. outptr2[col] = (JSAMPLE)
  161847. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161848. >> SCALEBITS);
  161849. }
  161850. }
  161851. }
  161852. /**************** Cases other than RGB -> YCbCr **************/
  161853. /*
  161854. * Convert some rows of samples to the JPEG colorspace.
  161855. * This version handles RGB->grayscale conversion, which is the same
  161856. * as the RGB->Y portion of RGB->YCbCr.
  161857. * We assume rgb_ycc_start has been called (we only use the Y tables).
  161858. */
  161859. METHODDEF(void)
  161860. rgb_gray_convert (j_compress_ptr cinfo,
  161861. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161862. JDIMENSION output_row, int num_rows)
  161863. {
  161864. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161865. register int r, g, b;
  161866. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161867. register JSAMPROW inptr;
  161868. register JSAMPROW outptr;
  161869. register JDIMENSION col;
  161870. JDIMENSION num_cols = cinfo->image_width;
  161871. while (--num_rows >= 0) {
  161872. inptr = *input_buf++;
  161873. outptr = output_buf[0][output_row];
  161874. output_row++;
  161875. for (col = 0; col < num_cols; col++) {
  161876. r = GETJSAMPLE(inptr[RGB_RED]);
  161877. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161878. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161879. inptr += RGB_PIXELSIZE;
  161880. /* Y */
  161881. outptr[col] = (JSAMPLE)
  161882. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161883. >> SCALEBITS);
  161884. }
  161885. }
  161886. }
  161887. /*
  161888. * Convert some rows of samples to the JPEG colorspace.
  161889. * This version handles Adobe-style CMYK->YCCK conversion,
  161890. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  161891. * conversion as above, while passing K (black) unchanged.
  161892. * We assume rgb_ycc_start has been called.
  161893. */
  161894. METHODDEF(void)
  161895. cmyk_ycck_convert (j_compress_ptr cinfo,
  161896. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161897. JDIMENSION output_row, int num_rows)
  161898. {
  161899. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161900. register int r, g, b;
  161901. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161902. register JSAMPROW inptr;
  161903. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  161904. register JDIMENSION col;
  161905. JDIMENSION num_cols = cinfo->image_width;
  161906. while (--num_rows >= 0) {
  161907. inptr = *input_buf++;
  161908. outptr0 = output_buf[0][output_row];
  161909. outptr1 = output_buf[1][output_row];
  161910. outptr2 = output_buf[2][output_row];
  161911. outptr3 = output_buf[3][output_row];
  161912. output_row++;
  161913. for (col = 0; col < num_cols; col++) {
  161914. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  161915. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  161916. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  161917. /* K passes through as-is */
  161918. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  161919. inptr += 4;
  161920. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161921. * must be too; we do not need an explicit range-limiting operation.
  161922. * Hence the value being shifted is never negative, and we don't
  161923. * need the general RIGHT_SHIFT macro.
  161924. */
  161925. /* Y */
  161926. outptr0[col] = (JSAMPLE)
  161927. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161928. >> SCALEBITS);
  161929. /* Cb */
  161930. outptr1[col] = (JSAMPLE)
  161931. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161932. >> SCALEBITS);
  161933. /* Cr */
  161934. outptr2[col] = (JSAMPLE)
  161935. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161936. >> SCALEBITS);
  161937. }
  161938. }
  161939. }
  161940. /*
  161941. * Convert some rows of samples to the JPEG colorspace.
  161942. * This version handles grayscale output with no conversion.
  161943. * The source can be either plain grayscale or YCbCr (since Y == gray).
  161944. */
  161945. METHODDEF(void)
  161946. grayscale_convert (j_compress_ptr cinfo,
  161947. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161948. JDIMENSION output_row, int num_rows)
  161949. {
  161950. register JSAMPROW inptr;
  161951. register JSAMPROW outptr;
  161952. register JDIMENSION col;
  161953. JDIMENSION num_cols = cinfo->image_width;
  161954. int instride = cinfo->input_components;
  161955. while (--num_rows >= 0) {
  161956. inptr = *input_buf++;
  161957. outptr = output_buf[0][output_row];
  161958. output_row++;
  161959. for (col = 0; col < num_cols; col++) {
  161960. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  161961. inptr += instride;
  161962. }
  161963. }
  161964. }
  161965. /*
  161966. * Convert some rows of samples to the JPEG colorspace.
  161967. * This version handles multi-component colorspaces without conversion.
  161968. * We assume input_components == num_components.
  161969. */
  161970. METHODDEF(void)
  161971. null_convert (j_compress_ptr cinfo,
  161972. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161973. JDIMENSION output_row, int num_rows)
  161974. {
  161975. register JSAMPROW inptr;
  161976. register JSAMPROW outptr;
  161977. register JDIMENSION col;
  161978. register int ci;
  161979. int nc = cinfo->num_components;
  161980. JDIMENSION num_cols = cinfo->image_width;
  161981. while (--num_rows >= 0) {
  161982. /* It seems fastest to make a separate pass for each component. */
  161983. for (ci = 0; ci < nc; ci++) {
  161984. inptr = *input_buf;
  161985. outptr = output_buf[ci][output_row];
  161986. for (col = 0; col < num_cols; col++) {
  161987. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  161988. inptr += nc;
  161989. }
  161990. }
  161991. input_buf++;
  161992. output_row++;
  161993. }
  161994. }
  161995. /*
  161996. * Empty method for start_pass.
  161997. */
  161998. METHODDEF(void)
  161999. null_method (j_compress_ptr)
  162000. {
  162001. /* no work needed */
  162002. }
  162003. /*
  162004. * Module initialization routine for input colorspace conversion.
  162005. */
  162006. GLOBAL(void)
  162007. jinit_color_converter (j_compress_ptr cinfo)
  162008. {
  162009. my_cconvert_ptr cconvert;
  162010. cconvert = (my_cconvert_ptr)
  162011. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162012. SIZEOF(my_color_converter));
  162013. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162014. /* set start_pass to null method until we find out differently */
  162015. cconvert->pub.start_pass = null_method;
  162016. /* Make sure input_components agrees with in_color_space */
  162017. switch (cinfo->in_color_space) {
  162018. case JCS_GRAYSCALE:
  162019. if (cinfo->input_components != 1)
  162020. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162021. break;
  162022. case JCS_RGB:
  162023. #if RGB_PIXELSIZE != 3
  162024. if (cinfo->input_components != RGB_PIXELSIZE)
  162025. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162026. break;
  162027. #endif /* else share code with YCbCr */
  162028. case JCS_YCbCr:
  162029. if (cinfo->input_components != 3)
  162030. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162031. break;
  162032. case JCS_CMYK:
  162033. case JCS_YCCK:
  162034. if (cinfo->input_components != 4)
  162035. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162036. break;
  162037. default: /* JCS_UNKNOWN can be anything */
  162038. if (cinfo->input_components < 1)
  162039. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162040. break;
  162041. }
  162042. /* Check num_components, set conversion method based on requested space */
  162043. switch (cinfo->jpeg_color_space) {
  162044. case JCS_GRAYSCALE:
  162045. if (cinfo->num_components != 1)
  162046. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162047. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162048. cconvert->pub.color_convert = grayscale_convert;
  162049. else if (cinfo->in_color_space == JCS_RGB) {
  162050. cconvert->pub.start_pass = rgb_ycc_start;
  162051. cconvert->pub.color_convert = rgb_gray_convert;
  162052. } else if (cinfo->in_color_space == JCS_YCbCr)
  162053. cconvert->pub.color_convert = grayscale_convert;
  162054. else
  162055. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162056. break;
  162057. case JCS_RGB:
  162058. if (cinfo->num_components != 3)
  162059. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162060. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162061. cconvert->pub.color_convert = null_convert;
  162062. else
  162063. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162064. break;
  162065. case JCS_YCbCr:
  162066. if (cinfo->num_components != 3)
  162067. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162068. if (cinfo->in_color_space == JCS_RGB) {
  162069. cconvert->pub.start_pass = rgb_ycc_start;
  162070. cconvert->pub.color_convert = rgb_ycc_convert;
  162071. } else if (cinfo->in_color_space == JCS_YCbCr)
  162072. cconvert->pub.color_convert = null_convert;
  162073. else
  162074. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162075. break;
  162076. case JCS_CMYK:
  162077. if (cinfo->num_components != 4)
  162078. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162079. if (cinfo->in_color_space == JCS_CMYK)
  162080. cconvert->pub.color_convert = null_convert;
  162081. else
  162082. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162083. break;
  162084. case JCS_YCCK:
  162085. if (cinfo->num_components != 4)
  162086. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162087. if (cinfo->in_color_space == JCS_CMYK) {
  162088. cconvert->pub.start_pass = rgb_ycc_start;
  162089. cconvert->pub.color_convert = cmyk_ycck_convert;
  162090. } else if (cinfo->in_color_space == JCS_YCCK)
  162091. cconvert->pub.color_convert = null_convert;
  162092. else
  162093. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162094. break;
  162095. default: /* allow null conversion of JCS_UNKNOWN */
  162096. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162097. cinfo->num_components != cinfo->input_components)
  162098. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162099. cconvert->pub.color_convert = null_convert;
  162100. break;
  162101. }
  162102. }
  162103. /*** End of inlined file: jccolor.c ***/
  162104. #undef FIX
  162105. /*** Start of inlined file: jcdctmgr.c ***/
  162106. #define JPEG_INTERNALS
  162107. /*** Start of inlined file: jdct.h ***/
  162108. /*
  162109. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162110. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162111. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162112. * implementations use an array of type FAST_FLOAT, instead.)
  162113. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162114. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162115. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162116. * convention improves accuracy in integer implementations and saves some
  162117. * work in floating-point ones.
  162118. * Quantization of the output coefficients is done by jcdctmgr.c.
  162119. */
  162120. #ifndef __jdct_h__
  162121. #define __jdct_h__
  162122. #if BITS_IN_JSAMPLE == 8
  162123. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162124. #else
  162125. typedef INT32 DCTELEM; /* must have 32 bits */
  162126. #endif
  162127. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162128. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162129. /*
  162130. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162131. * to an output sample array. The routine must dequantize the input data as
  162132. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162133. * pointed to by compptr->dct_table. The output data is to be placed into the
  162134. * sample array starting at a specified column. (Any row offset needed will
  162135. * be applied to the array pointer before it is passed to the IDCT code.)
  162136. * Note that the number of samples emitted by the IDCT routine is
  162137. * DCT_scaled_size * DCT_scaled_size.
  162138. */
  162139. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162140. /*
  162141. * Each IDCT routine has its own ideas about the best dct_table element type.
  162142. */
  162143. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162144. #if BITS_IN_JSAMPLE == 8
  162145. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162146. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162147. #else
  162148. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162149. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162150. #endif
  162151. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162152. /*
  162153. * Each IDCT routine is responsible for range-limiting its results and
  162154. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162155. * be quite far out of range if the input data is corrupt, so a bulletproof
  162156. * range-limiting step is required. We use a mask-and-table-lookup method
  162157. * to do the combined operations quickly. See the comments with
  162158. * prepare_range_limit_table (in jdmaster.c) for more info.
  162159. */
  162160. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162161. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162162. /* Short forms of external names for systems with brain-damaged linkers. */
  162163. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162164. #define jpeg_fdct_islow jFDislow
  162165. #define jpeg_fdct_ifast jFDifast
  162166. #define jpeg_fdct_float jFDfloat
  162167. #define jpeg_idct_islow jRDislow
  162168. #define jpeg_idct_ifast jRDifast
  162169. #define jpeg_idct_float jRDfloat
  162170. #define jpeg_idct_4x4 jRD4x4
  162171. #define jpeg_idct_2x2 jRD2x2
  162172. #define jpeg_idct_1x1 jRD1x1
  162173. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162174. /* Extern declarations for the forward and inverse DCT routines. */
  162175. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162176. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162177. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162178. EXTERN(void) jpeg_idct_islow
  162179. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162180. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162181. EXTERN(void) jpeg_idct_ifast
  162182. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162183. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162184. EXTERN(void) jpeg_idct_float
  162185. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162186. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162187. EXTERN(void) jpeg_idct_4x4
  162188. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162189. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162190. EXTERN(void) jpeg_idct_2x2
  162191. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162192. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162193. EXTERN(void) jpeg_idct_1x1
  162194. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162195. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162196. /*
  162197. * Macros for handling fixed-point arithmetic; these are used by many
  162198. * but not all of the DCT/IDCT modules.
  162199. *
  162200. * All values are expected to be of type INT32.
  162201. * Fractional constants are scaled left by CONST_BITS bits.
  162202. * CONST_BITS is defined within each module using these macros,
  162203. * and may differ from one module to the next.
  162204. */
  162205. #define ONE ((INT32) 1)
  162206. #define CONST_SCALE (ONE << CONST_BITS)
  162207. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162208. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162209. * thus causing a lot of useless floating-point operations at run time.
  162210. */
  162211. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162212. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162213. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162214. * the fudge factor is correct for either sign of X.
  162215. */
  162216. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162217. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162218. * This macro is used only when the two inputs will actually be no more than
  162219. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162220. * full 32x32 multiply. This provides a useful speedup on many machines.
  162221. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162222. * in C, but some C compilers will do the right thing if you provide the
  162223. * correct combination of casts.
  162224. */
  162225. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162226. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162227. #endif
  162228. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162229. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162230. #endif
  162231. #ifndef MULTIPLY16C16 /* default definition */
  162232. #define MULTIPLY16C16(var,const) ((var) * (const))
  162233. #endif
  162234. /* Same except both inputs are variables. */
  162235. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162236. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162237. #endif
  162238. #ifndef MULTIPLY16V16 /* default definition */
  162239. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162240. #endif
  162241. #endif
  162242. /*** End of inlined file: jdct.h ***/
  162243. /* Private declarations for DCT subsystem */
  162244. /* Private subobject for this module */
  162245. typedef struct {
  162246. struct jpeg_forward_dct pub; /* public fields */
  162247. /* Pointer to the DCT routine actually in use */
  162248. forward_DCT_method_ptr do_dct;
  162249. /* The actual post-DCT divisors --- not identical to the quant table
  162250. * entries, because of scaling (especially for an unnormalized DCT).
  162251. * Each table is given in normal array order.
  162252. */
  162253. DCTELEM * divisors[NUM_QUANT_TBLS];
  162254. #ifdef DCT_FLOAT_SUPPORTED
  162255. /* Same as above for the floating-point case. */
  162256. float_DCT_method_ptr do_float_dct;
  162257. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162258. #endif
  162259. } my_fdct_controller;
  162260. typedef my_fdct_controller * my_fdct_ptr;
  162261. /*
  162262. * Initialize for a processing pass.
  162263. * Verify that all referenced Q-tables are present, and set up
  162264. * the divisor table for each one.
  162265. * In the current implementation, DCT of all components is done during
  162266. * the first pass, even if only some components will be output in the
  162267. * first scan. Hence all components should be examined here.
  162268. */
  162269. METHODDEF(void)
  162270. start_pass_fdctmgr (j_compress_ptr cinfo)
  162271. {
  162272. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162273. int ci, qtblno, i;
  162274. jpeg_component_info *compptr;
  162275. JQUANT_TBL * qtbl;
  162276. DCTELEM * dtbl;
  162277. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162278. ci++, compptr++) {
  162279. qtblno = compptr->quant_tbl_no;
  162280. /* Make sure specified quantization table is present */
  162281. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162282. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162283. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162284. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162285. /* Compute divisors for this quant table */
  162286. /* We may do this more than once for same table, but it's not a big deal */
  162287. switch (cinfo->dct_method) {
  162288. #ifdef DCT_ISLOW_SUPPORTED
  162289. case JDCT_ISLOW:
  162290. /* For LL&M IDCT method, divisors are equal to raw quantization
  162291. * coefficients multiplied by 8 (to counteract scaling).
  162292. */
  162293. if (fdct->divisors[qtblno] == NULL) {
  162294. fdct->divisors[qtblno] = (DCTELEM *)
  162295. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162296. DCTSIZE2 * SIZEOF(DCTELEM));
  162297. }
  162298. dtbl = fdct->divisors[qtblno];
  162299. for (i = 0; i < DCTSIZE2; i++) {
  162300. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162301. }
  162302. break;
  162303. #endif
  162304. #ifdef DCT_IFAST_SUPPORTED
  162305. case JDCT_IFAST:
  162306. {
  162307. /* For AA&N IDCT method, divisors are equal to quantization
  162308. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162309. * scalefactor[0] = 1
  162310. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162311. * We apply a further scale factor of 8.
  162312. */
  162313. #define CONST_BITS 14
  162314. static const INT16 aanscales[DCTSIZE2] = {
  162315. /* precomputed values scaled up by 14 bits */
  162316. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162317. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162318. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162319. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162320. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162321. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162322. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162323. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162324. };
  162325. SHIFT_TEMPS
  162326. if (fdct->divisors[qtblno] == NULL) {
  162327. fdct->divisors[qtblno] = (DCTELEM *)
  162328. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162329. DCTSIZE2 * SIZEOF(DCTELEM));
  162330. }
  162331. dtbl = fdct->divisors[qtblno];
  162332. for (i = 0; i < DCTSIZE2; i++) {
  162333. dtbl[i] = (DCTELEM)
  162334. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162335. (INT32) aanscales[i]),
  162336. CONST_BITS-3);
  162337. }
  162338. }
  162339. break;
  162340. #endif
  162341. #ifdef DCT_FLOAT_SUPPORTED
  162342. case JDCT_FLOAT:
  162343. {
  162344. /* For float AA&N IDCT method, divisors are equal to quantization
  162345. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162346. * scalefactor[0] = 1
  162347. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162348. * We apply a further scale factor of 8.
  162349. * What's actually stored is 1/divisor so that the inner loop can
  162350. * use a multiplication rather than a division.
  162351. */
  162352. FAST_FLOAT * fdtbl;
  162353. int row, col;
  162354. static const double aanscalefactor[DCTSIZE] = {
  162355. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162356. 1.0, 0.785694958, 0.541196100, 0.275899379
  162357. };
  162358. if (fdct->float_divisors[qtblno] == NULL) {
  162359. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162360. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162361. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162362. }
  162363. fdtbl = fdct->float_divisors[qtblno];
  162364. i = 0;
  162365. for (row = 0; row < DCTSIZE; row++) {
  162366. for (col = 0; col < DCTSIZE; col++) {
  162367. fdtbl[i] = (FAST_FLOAT)
  162368. (1.0 / (((double) qtbl->quantval[i] *
  162369. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162370. i++;
  162371. }
  162372. }
  162373. }
  162374. break;
  162375. #endif
  162376. default:
  162377. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162378. break;
  162379. }
  162380. }
  162381. }
  162382. /*
  162383. * Perform forward DCT on one or more blocks of a component.
  162384. *
  162385. * The input samples are taken from the sample_data[] array starting at
  162386. * position start_row/start_col, and moving to the right for any additional
  162387. * blocks. The quantized coefficients are returned in coef_blocks[].
  162388. */
  162389. METHODDEF(void)
  162390. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162391. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162392. JDIMENSION start_row, JDIMENSION start_col,
  162393. JDIMENSION num_blocks)
  162394. /* This version is used for integer DCT implementations. */
  162395. {
  162396. /* This routine is heavily used, so it's worth coding it tightly. */
  162397. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162398. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162399. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162400. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162401. JDIMENSION bi;
  162402. sample_data += start_row; /* fold in the vertical offset once */
  162403. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162404. /* Load data into workspace, applying unsigned->signed conversion */
  162405. { register DCTELEM *workspaceptr;
  162406. register JSAMPROW elemptr;
  162407. register int elemr;
  162408. workspaceptr = workspace;
  162409. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162410. elemptr = sample_data[elemr] + start_col;
  162411. #if DCTSIZE == 8 /* unroll the inner loop */
  162412. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162413. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162414. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162415. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162416. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162417. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162418. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162419. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162420. #else
  162421. { register int elemc;
  162422. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162423. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162424. }
  162425. }
  162426. #endif
  162427. }
  162428. }
  162429. /* Perform the DCT */
  162430. (*do_dct) (workspace);
  162431. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162432. { register DCTELEM temp, qval;
  162433. register int i;
  162434. register JCOEFPTR output_ptr = coef_blocks[bi];
  162435. for (i = 0; i < DCTSIZE2; i++) {
  162436. qval = divisors[i];
  162437. temp = workspace[i];
  162438. /* Divide the coefficient value by qval, ensuring proper rounding.
  162439. * Since C does not specify the direction of rounding for negative
  162440. * quotients, we have to force the dividend positive for portability.
  162441. *
  162442. * In most files, at least half of the output values will be zero
  162443. * (at default quantization settings, more like three-quarters...)
  162444. * so we should ensure that this case is fast. On many machines,
  162445. * a comparison is enough cheaper than a divide to make a special test
  162446. * a win. Since both inputs will be nonnegative, we need only test
  162447. * for a < b to discover whether a/b is 0.
  162448. * If your machine's division is fast enough, define FAST_DIVIDE.
  162449. */
  162450. #ifdef FAST_DIVIDE
  162451. #define DIVIDE_BY(a,b) a /= b
  162452. #else
  162453. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162454. #endif
  162455. if (temp < 0) {
  162456. temp = -temp;
  162457. temp += qval>>1; /* for rounding */
  162458. DIVIDE_BY(temp, qval);
  162459. temp = -temp;
  162460. } else {
  162461. temp += qval>>1; /* for rounding */
  162462. DIVIDE_BY(temp, qval);
  162463. }
  162464. output_ptr[i] = (JCOEF) temp;
  162465. }
  162466. }
  162467. }
  162468. }
  162469. #ifdef DCT_FLOAT_SUPPORTED
  162470. METHODDEF(void)
  162471. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162472. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162473. JDIMENSION start_row, JDIMENSION start_col,
  162474. JDIMENSION num_blocks)
  162475. /* This version is used for floating-point DCT implementations. */
  162476. {
  162477. /* This routine is heavily used, so it's worth coding it tightly. */
  162478. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162479. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162480. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162481. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162482. JDIMENSION bi;
  162483. sample_data += start_row; /* fold in the vertical offset once */
  162484. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162485. /* Load data into workspace, applying unsigned->signed conversion */
  162486. { register FAST_FLOAT *workspaceptr;
  162487. register JSAMPROW elemptr;
  162488. register int elemr;
  162489. workspaceptr = workspace;
  162490. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162491. elemptr = sample_data[elemr] + start_col;
  162492. #if DCTSIZE == 8 /* unroll the inner loop */
  162493. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162494. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162495. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162496. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162497. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162498. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162499. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162500. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162501. #else
  162502. { register int elemc;
  162503. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162504. *workspaceptr++ = (FAST_FLOAT)
  162505. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162506. }
  162507. }
  162508. #endif
  162509. }
  162510. }
  162511. /* Perform the DCT */
  162512. (*do_dct) (workspace);
  162513. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162514. { register FAST_FLOAT temp;
  162515. register int i;
  162516. register JCOEFPTR output_ptr = coef_blocks[bi];
  162517. for (i = 0; i < DCTSIZE2; i++) {
  162518. /* Apply the quantization and scaling factor */
  162519. temp = workspace[i] * divisors[i];
  162520. /* Round to nearest integer.
  162521. * Since C does not specify the direction of rounding for negative
  162522. * quotients, we have to force the dividend positive for portability.
  162523. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162524. * code should work for either 16-bit or 32-bit ints.
  162525. */
  162526. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162527. }
  162528. }
  162529. }
  162530. }
  162531. #endif /* DCT_FLOAT_SUPPORTED */
  162532. /*
  162533. * Initialize FDCT manager.
  162534. */
  162535. GLOBAL(void)
  162536. jinit_forward_dct (j_compress_ptr cinfo)
  162537. {
  162538. my_fdct_ptr fdct;
  162539. int i;
  162540. fdct = (my_fdct_ptr)
  162541. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162542. SIZEOF(my_fdct_controller));
  162543. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162544. fdct->pub.start_pass = start_pass_fdctmgr;
  162545. switch (cinfo->dct_method) {
  162546. #ifdef DCT_ISLOW_SUPPORTED
  162547. case JDCT_ISLOW:
  162548. fdct->pub.forward_DCT = forward_DCT;
  162549. fdct->do_dct = jpeg_fdct_islow;
  162550. break;
  162551. #endif
  162552. #ifdef DCT_IFAST_SUPPORTED
  162553. case JDCT_IFAST:
  162554. fdct->pub.forward_DCT = forward_DCT;
  162555. fdct->do_dct = jpeg_fdct_ifast;
  162556. break;
  162557. #endif
  162558. #ifdef DCT_FLOAT_SUPPORTED
  162559. case JDCT_FLOAT:
  162560. fdct->pub.forward_DCT = forward_DCT_float;
  162561. fdct->do_float_dct = jpeg_fdct_float;
  162562. break;
  162563. #endif
  162564. default:
  162565. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162566. break;
  162567. }
  162568. /* Mark divisor tables unallocated */
  162569. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162570. fdct->divisors[i] = NULL;
  162571. #ifdef DCT_FLOAT_SUPPORTED
  162572. fdct->float_divisors[i] = NULL;
  162573. #endif
  162574. }
  162575. }
  162576. /*** End of inlined file: jcdctmgr.c ***/
  162577. #undef CONST_BITS
  162578. /*** Start of inlined file: jchuff.c ***/
  162579. #define JPEG_INTERNALS
  162580. /*** Start of inlined file: jchuff.h ***/
  162581. /* The legal range of a DCT coefficient is
  162582. * -1024 .. +1023 for 8-bit data;
  162583. * -16384 .. +16383 for 12-bit data.
  162584. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162585. */
  162586. #ifndef _jchuff_h_
  162587. #define _jchuff_h_
  162588. #if BITS_IN_JSAMPLE == 8
  162589. #define MAX_COEF_BITS 10
  162590. #else
  162591. #define MAX_COEF_BITS 14
  162592. #endif
  162593. /* Derived data constructed for each Huffman table */
  162594. typedef struct {
  162595. unsigned int ehufco[256]; /* code for each symbol */
  162596. char ehufsi[256]; /* length of code for each symbol */
  162597. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162598. } c_derived_tbl;
  162599. /* Short forms of external names for systems with brain-damaged linkers. */
  162600. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162601. #define jpeg_make_c_derived_tbl jMkCDerived
  162602. #define jpeg_gen_optimal_table jGenOptTbl
  162603. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162604. /* Expand a Huffman table definition into the derived format */
  162605. EXTERN(void) jpeg_make_c_derived_tbl
  162606. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162607. c_derived_tbl ** pdtbl));
  162608. /* Generate an optimal table definition given the specified counts */
  162609. EXTERN(void) jpeg_gen_optimal_table
  162610. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162611. #endif
  162612. /*** End of inlined file: jchuff.h ***/
  162613. /* Declarations shared with jcphuff.c */
  162614. /* Expanded entropy encoder object for Huffman encoding.
  162615. *
  162616. * The savable_state subrecord contains fields that change within an MCU,
  162617. * but must not be updated permanently until we complete the MCU.
  162618. */
  162619. typedef struct {
  162620. INT32 put_buffer; /* current bit-accumulation buffer */
  162621. int put_bits; /* # of bits now in it */
  162622. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162623. } savable_state;
  162624. /* This macro is to work around compilers with missing or broken
  162625. * structure assignment. You'll need to fix this code if you have
  162626. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162627. */
  162628. #ifndef NO_STRUCT_ASSIGN
  162629. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162630. #else
  162631. #if MAX_COMPS_IN_SCAN == 4
  162632. #define ASSIGN_STATE(dest,src) \
  162633. ((dest).put_buffer = (src).put_buffer, \
  162634. (dest).put_bits = (src).put_bits, \
  162635. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162636. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162637. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162638. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162639. #endif
  162640. #endif
  162641. typedef struct {
  162642. struct jpeg_entropy_encoder pub; /* public fields */
  162643. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162644. /* These fields are NOT loaded into local working state. */
  162645. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162646. int next_restart_num; /* next restart number to write (0-7) */
  162647. /* Pointers to derived tables (these workspaces have image lifespan) */
  162648. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162649. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162650. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162651. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162652. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162653. #endif
  162654. } huff_entropy_encoder;
  162655. typedef huff_entropy_encoder * huff_entropy_ptr;
  162656. /* Working state while writing an MCU.
  162657. * This struct contains all the fields that are needed by subroutines.
  162658. */
  162659. typedef struct {
  162660. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162661. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162662. savable_state cur; /* Current bit buffer & DC state */
  162663. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162664. } working_state;
  162665. /* Forward declarations */
  162666. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162667. JBLOCKROW *MCU_data));
  162668. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162669. #ifdef ENTROPY_OPT_SUPPORTED
  162670. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162671. JBLOCKROW *MCU_data));
  162672. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162673. #endif
  162674. /*
  162675. * Initialize for a Huffman-compressed scan.
  162676. * If gather_statistics is TRUE, we do not output anything during the scan,
  162677. * just count the Huffman symbols used and generate Huffman code tables.
  162678. */
  162679. METHODDEF(void)
  162680. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162681. {
  162682. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162683. int ci, dctbl, actbl;
  162684. jpeg_component_info * compptr;
  162685. if (gather_statistics) {
  162686. #ifdef ENTROPY_OPT_SUPPORTED
  162687. entropy->pub.encode_mcu = encode_mcu_gather;
  162688. entropy->pub.finish_pass = finish_pass_gather;
  162689. #else
  162690. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162691. #endif
  162692. } else {
  162693. entropy->pub.encode_mcu = encode_mcu_huff;
  162694. entropy->pub.finish_pass = finish_pass_huff;
  162695. }
  162696. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162697. compptr = cinfo->cur_comp_info[ci];
  162698. dctbl = compptr->dc_tbl_no;
  162699. actbl = compptr->ac_tbl_no;
  162700. if (gather_statistics) {
  162701. #ifdef ENTROPY_OPT_SUPPORTED
  162702. /* Check for invalid table indexes */
  162703. /* (make_c_derived_tbl does this in the other path) */
  162704. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162705. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162706. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162707. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162708. /* Allocate and zero the statistics tables */
  162709. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162710. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162711. entropy->dc_count_ptrs[dctbl] = (long *)
  162712. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162713. 257 * SIZEOF(long));
  162714. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162715. if (entropy->ac_count_ptrs[actbl] == NULL)
  162716. entropy->ac_count_ptrs[actbl] = (long *)
  162717. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162718. 257 * SIZEOF(long));
  162719. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162720. #endif
  162721. } else {
  162722. /* Compute derived values for Huffman tables */
  162723. /* We may do this more than once for a table, but it's not expensive */
  162724. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162725. & entropy->dc_derived_tbls[dctbl]);
  162726. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162727. & entropy->ac_derived_tbls[actbl]);
  162728. }
  162729. /* Initialize DC predictions to 0 */
  162730. entropy->saved.last_dc_val[ci] = 0;
  162731. }
  162732. /* Initialize bit buffer to empty */
  162733. entropy->saved.put_buffer = 0;
  162734. entropy->saved.put_bits = 0;
  162735. /* Initialize restart stuff */
  162736. entropy->restarts_to_go = cinfo->restart_interval;
  162737. entropy->next_restart_num = 0;
  162738. }
  162739. /*
  162740. * Compute the derived values for a Huffman table.
  162741. * This routine also performs some validation checks on the table.
  162742. *
  162743. * Note this is also used by jcphuff.c.
  162744. */
  162745. GLOBAL(void)
  162746. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162747. c_derived_tbl ** pdtbl)
  162748. {
  162749. JHUFF_TBL *htbl;
  162750. c_derived_tbl *dtbl;
  162751. int p, i, l, lastp, si, maxsymbol;
  162752. char huffsize[257];
  162753. unsigned int huffcode[257];
  162754. unsigned int code;
  162755. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162756. * paralleling the order of the symbols themselves in htbl->huffval[].
  162757. */
  162758. /* Find the input Huffman table */
  162759. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162760. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162761. htbl =
  162762. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162763. if (htbl == NULL)
  162764. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162765. /* Allocate a workspace if we haven't already done so. */
  162766. if (*pdtbl == NULL)
  162767. *pdtbl = (c_derived_tbl *)
  162768. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162769. SIZEOF(c_derived_tbl));
  162770. dtbl = *pdtbl;
  162771. /* Figure C.1: make table of Huffman code length for each symbol */
  162772. p = 0;
  162773. for (l = 1; l <= 16; l++) {
  162774. i = (int) htbl->bits[l];
  162775. if (i < 0 || p + i > 256) /* protect against table overrun */
  162776. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162777. while (i--)
  162778. huffsize[p++] = (char) l;
  162779. }
  162780. huffsize[p] = 0;
  162781. lastp = p;
  162782. /* Figure C.2: generate the codes themselves */
  162783. /* We also validate that the counts represent a legal Huffman code tree. */
  162784. code = 0;
  162785. si = huffsize[0];
  162786. p = 0;
  162787. while (huffsize[p]) {
  162788. while (((int) huffsize[p]) == si) {
  162789. huffcode[p++] = code;
  162790. code++;
  162791. }
  162792. /* code is now 1 more than the last code used for codelength si; but
  162793. * it must still fit in si bits, since no code is allowed to be all ones.
  162794. */
  162795. if (((INT32) code) >= (((INT32) 1) << si))
  162796. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162797. code <<= 1;
  162798. si++;
  162799. }
  162800. /* Figure C.3: generate encoding tables */
  162801. /* These are code and size indexed by symbol value */
  162802. /* Set all codeless symbols to have code length 0;
  162803. * this lets us detect duplicate VAL entries here, and later
  162804. * allows emit_bits to detect any attempt to emit such symbols.
  162805. */
  162806. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162807. /* This is also a convenient place to check for out-of-range
  162808. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162809. * but only 0..15 for DC. (We could constrain them further
  162810. * based on data depth and mode, but this seems enough.)
  162811. */
  162812. maxsymbol = isDC ? 15 : 255;
  162813. for (p = 0; p < lastp; p++) {
  162814. i = htbl->huffval[p];
  162815. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162816. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162817. dtbl->ehufco[i] = huffcode[p];
  162818. dtbl->ehufsi[i] = huffsize[p];
  162819. }
  162820. }
  162821. /* Outputting bytes to the file */
  162822. /* Emit a byte, taking 'action' if must suspend. */
  162823. #define emit_byte(state,val,action) \
  162824. { *(state)->next_output_byte++ = (JOCTET) (val); \
  162825. if (--(state)->free_in_buffer == 0) \
  162826. if (! dump_buffer(state)) \
  162827. { action; } }
  162828. LOCAL(boolean)
  162829. dump_buffer (working_state * state)
  162830. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  162831. {
  162832. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  162833. if (! (*dest->empty_output_buffer) (state->cinfo))
  162834. return FALSE;
  162835. /* After a successful buffer dump, must reset buffer pointers */
  162836. state->next_output_byte = dest->next_output_byte;
  162837. state->free_in_buffer = dest->free_in_buffer;
  162838. return TRUE;
  162839. }
  162840. /* Outputting bits to the file */
  162841. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162842. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162843. * in one call, and we never retain more than 7 bits in put_buffer
  162844. * between calls, so 24 bits are sufficient.
  162845. */
  162846. INLINE
  162847. LOCAL(boolean)
  162848. emit_bits (working_state * state, unsigned int code, int size)
  162849. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  162850. {
  162851. /* This routine is heavily used, so it's worth coding tightly. */
  162852. register INT32 put_buffer = (INT32) code;
  162853. register int put_bits = state->cur.put_bits;
  162854. /* if size is 0, caller used an invalid Huffman table entry */
  162855. if (size == 0)
  162856. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  162857. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162858. put_bits += size; /* new number of bits in buffer */
  162859. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162860. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  162861. while (put_bits >= 8) {
  162862. int c = (int) ((put_buffer >> 16) & 0xFF);
  162863. emit_byte(state, c, return FALSE);
  162864. if (c == 0xFF) { /* need to stuff a zero byte? */
  162865. emit_byte(state, 0, return FALSE);
  162866. }
  162867. put_buffer <<= 8;
  162868. put_bits -= 8;
  162869. }
  162870. state->cur.put_buffer = put_buffer; /* update state variables */
  162871. state->cur.put_bits = put_bits;
  162872. return TRUE;
  162873. }
  162874. LOCAL(boolean)
  162875. flush_bits (working_state * state)
  162876. {
  162877. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  162878. return FALSE;
  162879. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  162880. state->cur.put_bits = 0;
  162881. return TRUE;
  162882. }
  162883. /* Encode a single block's worth of coefficients */
  162884. LOCAL(boolean)
  162885. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  162886. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  162887. {
  162888. register int temp, temp2;
  162889. register int nbits;
  162890. register int k, r, i;
  162891. /* Encode the DC coefficient difference per section F.1.2.1 */
  162892. temp = temp2 = block[0] - last_dc_val;
  162893. if (temp < 0) {
  162894. temp = -temp; /* temp is abs value of input */
  162895. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162896. /* This code assumes we are on a two's complement machine */
  162897. temp2--;
  162898. }
  162899. /* Find the number of bits needed for the magnitude of the coefficient */
  162900. nbits = 0;
  162901. while (temp) {
  162902. nbits++;
  162903. temp >>= 1;
  162904. }
  162905. /* Check for out-of-range coefficient values.
  162906. * Since we're encoding a difference, the range limit is twice as much.
  162907. */
  162908. if (nbits > MAX_COEF_BITS+1)
  162909. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162910. /* Emit the Huffman-coded symbol for the number of bits */
  162911. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  162912. return FALSE;
  162913. /* Emit that number of bits of the value, if positive, */
  162914. /* or the complement of its magnitude, if negative. */
  162915. if (nbits) /* emit_bits rejects calls with size 0 */
  162916. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162917. return FALSE;
  162918. /* Encode the AC coefficients per section F.1.2.2 */
  162919. r = 0; /* r = run length of zeros */
  162920. for (k = 1; k < DCTSIZE2; k++) {
  162921. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162922. r++;
  162923. } else {
  162924. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162925. while (r > 15) {
  162926. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  162927. return FALSE;
  162928. r -= 16;
  162929. }
  162930. temp2 = temp;
  162931. if (temp < 0) {
  162932. temp = -temp; /* temp is abs value of input */
  162933. /* This code assumes we are on a two's complement machine */
  162934. temp2--;
  162935. }
  162936. /* Find the number of bits needed for the magnitude of the coefficient */
  162937. nbits = 1; /* there must be at least one 1 bit */
  162938. while ((temp >>= 1))
  162939. nbits++;
  162940. /* Check for out-of-range coefficient values */
  162941. if (nbits > MAX_COEF_BITS)
  162942. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162943. /* Emit Huffman symbol for run length / number of bits */
  162944. i = (r << 4) + nbits;
  162945. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  162946. return FALSE;
  162947. /* Emit that number of bits of the value, if positive, */
  162948. /* or the complement of its magnitude, if negative. */
  162949. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162950. return FALSE;
  162951. r = 0;
  162952. }
  162953. }
  162954. /* If the last coef(s) were zero, emit an end-of-block code */
  162955. if (r > 0)
  162956. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  162957. return FALSE;
  162958. return TRUE;
  162959. }
  162960. /*
  162961. * Emit a restart marker & resynchronize predictions.
  162962. */
  162963. LOCAL(boolean)
  162964. emit_restart (working_state * state, int restart_num)
  162965. {
  162966. int ci;
  162967. if (! flush_bits(state))
  162968. return FALSE;
  162969. emit_byte(state, 0xFF, return FALSE);
  162970. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  162971. /* Re-initialize DC predictions to 0 */
  162972. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  162973. state->cur.last_dc_val[ci] = 0;
  162974. /* The restart counter is not updated until we successfully write the MCU. */
  162975. return TRUE;
  162976. }
  162977. /*
  162978. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  162979. */
  162980. METHODDEF(boolean)
  162981. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162982. {
  162983. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162984. working_state state;
  162985. int blkn, ci;
  162986. jpeg_component_info * compptr;
  162987. /* Load up working state */
  162988. state.next_output_byte = cinfo->dest->next_output_byte;
  162989. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162990. ASSIGN_STATE(state.cur, entropy->saved);
  162991. state.cinfo = cinfo;
  162992. /* Emit restart marker if needed */
  162993. if (cinfo->restart_interval) {
  162994. if (entropy->restarts_to_go == 0)
  162995. if (! emit_restart(&state, entropy->next_restart_num))
  162996. return FALSE;
  162997. }
  162998. /* Encode the MCU data blocks */
  162999. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163000. ci = cinfo->MCU_membership[blkn];
  163001. compptr = cinfo->cur_comp_info[ci];
  163002. if (! encode_one_block(&state,
  163003. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163004. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163005. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163006. return FALSE;
  163007. /* Update last_dc_val */
  163008. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163009. }
  163010. /* Completed MCU, so update state */
  163011. cinfo->dest->next_output_byte = state.next_output_byte;
  163012. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163013. ASSIGN_STATE(entropy->saved, state.cur);
  163014. /* Update restart-interval state too */
  163015. if (cinfo->restart_interval) {
  163016. if (entropy->restarts_to_go == 0) {
  163017. entropy->restarts_to_go = cinfo->restart_interval;
  163018. entropy->next_restart_num++;
  163019. entropy->next_restart_num &= 7;
  163020. }
  163021. entropy->restarts_to_go--;
  163022. }
  163023. return TRUE;
  163024. }
  163025. /*
  163026. * Finish up at the end of a Huffman-compressed scan.
  163027. */
  163028. METHODDEF(void)
  163029. finish_pass_huff (j_compress_ptr cinfo)
  163030. {
  163031. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163032. working_state state;
  163033. /* Load up working state ... flush_bits needs it */
  163034. state.next_output_byte = cinfo->dest->next_output_byte;
  163035. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163036. ASSIGN_STATE(state.cur, entropy->saved);
  163037. state.cinfo = cinfo;
  163038. /* Flush out the last data */
  163039. if (! flush_bits(&state))
  163040. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163041. /* Update state */
  163042. cinfo->dest->next_output_byte = state.next_output_byte;
  163043. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163044. ASSIGN_STATE(entropy->saved, state.cur);
  163045. }
  163046. /*
  163047. * Huffman coding optimization.
  163048. *
  163049. * We first scan the supplied data and count the number of uses of each symbol
  163050. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163051. * Then we build a Huffman coding tree for the observed counts.
  163052. * Symbols which are not needed at all for the particular image are not
  163053. * assigned any code, which saves space in the DHT marker as well as in
  163054. * the compressed data.
  163055. */
  163056. #ifdef ENTROPY_OPT_SUPPORTED
  163057. /* Process a single block's worth of coefficients */
  163058. LOCAL(void)
  163059. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163060. long dc_counts[], long ac_counts[])
  163061. {
  163062. register int temp;
  163063. register int nbits;
  163064. register int k, r;
  163065. /* Encode the DC coefficient difference per section F.1.2.1 */
  163066. temp = block[0] - last_dc_val;
  163067. if (temp < 0)
  163068. temp = -temp;
  163069. /* Find the number of bits needed for the magnitude of the coefficient */
  163070. nbits = 0;
  163071. while (temp) {
  163072. nbits++;
  163073. temp >>= 1;
  163074. }
  163075. /* Check for out-of-range coefficient values.
  163076. * Since we're encoding a difference, the range limit is twice as much.
  163077. */
  163078. if (nbits > MAX_COEF_BITS+1)
  163079. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163080. /* Count the Huffman symbol for the number of bits */
  163081. dc_counts[nbits]++;
  163082. /* Encode the AC coefficients per section F.1.2.2 */
  163083. r = 0; /* r = run length of zeros */
  163084. for (k = 1; k < DCTSIZE2; k++) {
  163085. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163086. r++;
  163087. } else {
  163088. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163089. while (r > 15) {
  163090. ac_counts[0xF0]++;
  163091. r -= 16;
  163092. }
  163093. /* Find the number of bits needed for the magnitude of the coefficient */
  163094. if (temp < 0)
  163095. temp = -temp;
  163096. /* Find the number of bits needed for the magnitude of the coefficient */
  163097. nbits = 1; /* there must be at least one 1 bit */
  163098. while ((temp >>= 1))
  163099. nbits++;
  163100. /* Check for out-of-range coefficient values */
  163101. if (nbits > MAX_COEF_BITS)
  163102. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163103. /* Count Huffman symbol for run length / number of bits */
  163104. ac_counts[(r << 4) + nbits]++;
  163105. r = 0;
  163106. }
  163107. }
  163108. /* If the last coef(s) were zero, emit an end-of-block code */
  163109. if (r > 0)
  163110. ac_counts[0]++;
  163111. }
  163112. /*
  163113. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163114. * No data is actually output, so no suspension return is possible.
  163115. */
  163116. METHODDEF(boolean)
  163117. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163118. {
  163119. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163120. int blkn, ci;
  163121. jpeg_component_info * compptr;
  163122. /* Take care of restart intervals if needed */
  163123. if (cinfo->restart_interval) {
  163124. if (entropy->restarts_to_go == 0) {
  163125. /* Re-initialize DC predictions to 0 */
  163126. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163127. entropy->saved.last_dc_val[ci] = 0;
  163128. /* Update restart state */
  163129. entropy->restarts_to_go = cinfo->restart_interval;
  163130. }
  163131. entropy->restarts_to_go--;
  163132. }
  163133. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163134. ci = cinfo->MCU_membership[blkn];
  163135. compptr = cinfo->cur_comp_info[ci];
  163136. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163137. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163138. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163139. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163140. }
  163141. return TRUE;
  163142. }
  163143. /*
  163144. * Generate the best Huffman code table for the given counts, fill htbl.
  163145. * Note this is also used by jcphuff.c.
  163146. *
  163147. * The JPEG standard requires that no symbol be assigned a codeword of all
  163148. * one bits (so that padding bits added at the end of a compressed segment
  163149. * can't look like a valid code). Because of the canonical ordering of
  163150. * codewords, this just means that there must be an unused slot in the
  163151. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163152. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163153. * with count 1. In theory that's not optimal; giving it count zero but
  163154. * including it in the symbol set anyway should give a better Huffman code.
  163155. * But the theoretically better code actually seems to come out worse in
  163156. * practice, because it produces more all-ones bytes (which incur stuffed
  163157. * zero bytes in the final file). In any case the difference is tiny.
  163158. *
  163159. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163160. * If some symbols have a very small but nonzero probability, the Huffman tree
  163161. * must be adjusted to meet the code length restriction. We currently use
  163162. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163163. * optimal; it may not choose the best possible limited-length code. But
  163164. * typically only very-low-frequency symbols will be given less-than-optimal
  163165. * lengths, so the code is almost optimal. Experimental comparisons against
  163166. * an optimal limited-length-code algorithm indicate that the difference is
  163167. * microscopic --- usually less than a hundredth of a percent of total size.
  163168. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163169. */
  163170. GLOBAL(void)
  163171. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163172. {
  163173. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163174. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163175. int codesize[257]; /* codesize[k] = code length of symbol k */
  163176. int others[257]; /* next symbol in current branch of tree */
  163177. int c1, c2;
  163178. int p, i, j;
  163179. long v;
  163180. /* This algorithm is explained in section K.2 of the JPEG standard */
  163181. MEMZERO(bits, SIZEOF(bits));
  163182. MEMZERO(codesize, SIZEOF(codesize));
  163183. for (i = 0; i < 257; i++)
  163184. others[i] = -1; /* init links to empty */
  163185. freq[256] = 1; /* make sure 256 has a nonzero count */
  163186. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163187. * that no real symbol is given code-value of all ones, because 256
  163188. * will be placed last in the largest codeword category.
  163189. */
  163190. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163191. for (;;) {
  163192. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163193. /* In case of ties, take the larger symbol number */
  163194. c1 = -1;
  163195. v = 1000000000L;
  163196. for (i = 0; i <= 256; i++) {
  163197. if (freq[i] && freq[i] <= v) {
  163198. v = freq[i];
  163199. c1 = i;
  163200. }
  163201. }
  163202. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163203. /* In case of ties, take the larger symbol number */
  163204. c2 = -1;
  163205. v = 1000000000L;
  163206. for (i = 0; i <= 256; i++) {
  163207. if (freq[i] && freq[i] <= v && i != c1) {
  163208. v = freq[i];
  163209. c2 = i;
  163210. }
  163211. }
  163212. /* Done if we've merged everything into one frequency */
  163213. if (c2 < 0)
  163214. break;
  163215. /* Else merge the two counts/trees */
  163216. freq[c1] += freq[c2];
  163217. freq[c2] = 0;
  163218. /* Increment the codesize of everything in c1's tree branch */
  163219. codesize[c1]++;
  163220. while (others[c1] >= 0) {
  163221. c1 = others[c1];
  163222. codesize[c1]++;
  163223. }
  163224. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163225. /* Increment the codesize of everything in c2's tree branch */
  163226. codesize[c2]++;
  163227. while (others[c2] >= 0) {
  163228. c2 = others[c2];
  163229. codesize[c2]++;
  163230. }
  163231. }
  163232. /* Now count the number of symbols of each code length */
  163233. for (i = 0; i <= 256; i++) {
  163234. if (codesize[i]) {
  163235. /* The JPEG standard seems to think that this can't happen, */
  163236. /* but I'm paranoid... */
  163237. if (codesize[i] > MAX_CLEN)
  163238. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163239. bits[codesize[i]]++;
  163240. }
  163241. }
  163242. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163243. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163244. * Here is what the JPEG spec says about how this next bit works:
  163245. * Since symbols are paired for the longest Huffman code, the symbols are
  163246. * removed from this length category two at a time. The prefix for the pair
  163247. * (which is one bit shorter) is allocated to one of the pair; then,
  163248. * skipping the BITS entry for that prefix length, a code word from the next
  163249. * shortest nonzero BITS entry is converted into a prefix for two code words
  163250. * one bit longer.
  163251. */
  163252. for (i = MAX_CLEN; i > 16; i--) {
  163253. while (bits[i] > 0) {
  163254. j = i - 2; /* find length of new prefix to be used */
  163255. while (bits[j] == 0)
  163256. j--;
  163257. bits[i] -= 2; /* remove two symbols */
  163258. bits[i-1]++; /* one goes in this length */
  163259. bits[j+1] += 2; /* two new symbols in this length */
  163260. bits[j]--; /* symbol of this length is now a prefix */
  163261. }
  163262. }
  163263. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163264. while (bits[i] == 0) /* find largest codelength still in use */
  163265. i--;
  163266. bits[i]--;
  163267. /* Return final symbol counts (only for lengths 0..16) */
  163268. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163269. /* Return a list of the symbols sorted by code length */
  163270. /* It's not real clear to me why we don't need to consider the codelength
  163271. * changes made above, but the JPEG spec seems to think this works.
  163272. */
  163273. p = 0;
  163274. for (i = 1; i <= MAX_CLEN; i++) {
  163275. for (j = 0; j <= 255; j++) {
  163276. if (codesize[j] == i) {
  163277. htbl->huffval[p] = (UINT8) j;
  163278. p++;
  163279. }
  163280. }
  163281. }
  163282. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163283. htbl->sent_table = FALSE;
  163284. }
  163285. /*
  163286. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163287. */
  163288. METHODDEF(void)
  163289. finish_pass_gather (j_compress_ptr cinfo)
  163290. {
  163291. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163292. int ci, dctbl, actbl;
  163293. jpeg_component_info * compptr;
  163294. JHUFF_TBL **htblptr;
  163295. boolean did_dc[NUM_HUFF_TBLS];
  163296. boolean did_ac[NUM_HUFF_TBLS];
  163297. /* It's important not to apply jpeg_gen_optimal_table more than once
  163298. * per table, because it clobbers the input frequency counts!
  163299. */
  163300. MEMZERO(did_dc, SIZEOF(did_dc));
  163301. MEMZERO(did_ac, SIZEOF(did_ac));
  163302. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163303. compptr = cinfo->cur_comp_info[ci];
  163304. dctbl = compptr->dc_tbl_no;
  163305. actbl = compptr->ac_tbl_no;
  163306. if (! did_dc[dctbl]) {
  163307. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163308. if (*htblptr == NULL)
  163309. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163310. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163311. did_dc[dctbl] = TRUE;
  163312. }
  163313. if (! did_ac[actbl]) {
  163314. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163315. if (*htblptr == NULL)
  163316. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163317. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163318. did_ac[actbl] = TRUE;
  163319. }
  163320. }
  163321. }
  163322. #endif /* ENTROPY_OPT_SUPPORTED */
  163323. /*
  163324. * Module initialization routine for Huffman entropy encoding.
  163325. */
  163326. GLOBAL(void)
  163327. jinit_huff_encoder (j_compress_ptr cinfo)
  163328. {
  163329. huff_entropy_ptr entropy;
  163330. int i;
  163331. entropy = (huff_entropy_ptr)
  163332. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163333. SIZEOF(huff_entropy_encoder));
  163334. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163335. entropy->pub.start_pass = start_pass_huff;
  163336. /* Mark tables unallocated */
  163337. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163338. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163339. #ifdef ENTROPY_OPT_SUPPORTED
  163340. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163341. #endif
  163342. }
  163343. }
  163344. /*** End of inlined file: jchuff.c ***/
  163345. #undef emit_byte
  163346. /*** Start of inlined file: jcinit.c ***/
  163347. #define JPEG_INTERNALS
  163348. /*
  163349. * Master selection of compression modules.
  163350. * This is done once at the start of processing an image. We determine
  163351. * which modules will be used and give them appropriate initialization calls.
  163352. */
  163353. GLOBAL(void)
  163354. jinit_compress_master (j_compress_ptr cinfo)
  163355. {
  163356. /* Initialize master control (includes parameter checking/processing) */
  163357. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163358. /* Preprocessing */
  163359. if (! cinfo->raw_data_in) {
  163360. jinit_color_converter(cinfo);
  163361. jinit_downsampler(cinfo);
  163362. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163363. }
  163364. /* Forward DCT */
  163365. jinit_forward_dct(cinfo);
  163366. /* Entropy encoding: either Huffman or arithmetic coding. */
  163367. if (cinfo->arith_code) {
  163368. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163369. } else {
  163370. if (cinfo->progressive_mode) {
  163371. #ifdef C_PROGRESSIVE_SUPPORTED
  163372. jinit_phuff_encoder(cinfo);
  163373. #else
  163374. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163375. #endif
  163376. } else
  163377. jinit_huff_encoder(cinfo);
  163378. }
  163379. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163380. jinit_c_coef_controller(cinfo,
  163381. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163382. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163383. jinit_marker_writer(cinfo);
  163384. /* We can now tell the memory manager to allocate virtual arrays. */
  163385. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163386. /* Write the datastream header (SOI) immediately.
  163387. * Frame and scan headers are postponed till later.
  163388. * This lets application insert special markers after the SOI.
  163389. */
  163390. (*cinfo->marker->write_file_header) (cinfo);
  163391. }
  163392. /*** End of inlined file: jcinit.c ***/
  163393. /*** Start of inlined file: jcmainct.c ***/
  163394. #define JPEG_INTERNALS
  163395. /* Note: currently, there is no operating mode in which a full-image buffer
  163396. * is needed at this step. If there were, that mode could not be used with
  163397. * "raw data" input, since this module is bypassed in that case. However,
  163398. * we've left the code here for possible use in special applications.
  163399. */
  163400. #undef FULL_MAIN_BUFFER_SUPPORTED
  163401. /* Private buffer controller object */
  163402. typedef struct {
  163403. struct jpeg_c_main_controller pub; /* public fields */
  163404. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163405. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163406. boolean suspended; /* remember if we suspended output */
  163407. J_BUF_MODE pass_mode; /* current operating mode */
  163408. /* If using just a strip buffer, this points to the entire set of buffers
  163409. * (we allocate one for each component). In the full-image case, this
  163410. * points to the currently accessible strips of the virtual arrays.
  163411. */
  163412. JSAMPARRAY buffer[MAX_COMPONENTS];
  163413. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163414. /* If using full-image storage, this array holds pointers to virtual-array
  163415. * control blocks for each component. Unused if not full-image storage.
  163416. */
  163417. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163418. #endif
  163419. } my_main_controller;
  163420. typedef my_main_controller * my_main_ptr;
  163421. /* Forward declarations */
  163422. METHODDEF(void) process_data_simple_main
  163423. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163424. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163425. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163426. METHODDEF(void) process_data_buffer_main
  163427. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163428. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163429. #endif
  163430. /*
  163431. * Initialize for a processing pass.
  163432. */
  163433. METHODDEF(void)
  163434. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163435. {
  163436. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163437. /* Do nothing in raw-data mode. */
  163438. if (cinfo->raw_data_in)
  163439. return;
  163440. main_->cur_iMCU_row = 0; /* initialize counters */
  163441. main_->rowgroup_ctr = 0;
  163442. main_->suspended = FALSE;
  163443. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163444. switch (pass_mode) {
  163445. case JBUF_PASS_THRU:
  163446. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163447. if (main_->whole_image[0] != NULL)
  163448. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163449. #endif
  163450. main_->pub.process_data = process_data_simple_main;
  163451. break;
  163452. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163453. case JBUF_SAVE_SOURCE:
  163454. case JBUF_CRANK_DEST:
  163455. case JBUF_SAVE_AND_PASS:
  163456. if (main_->whole_image[0] == NULL)
  163457. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163458. main_->pub.process_data = process_data_buffer_main;
  163459. break;
  163460. #endif
  163461. default:
  163462. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163463. break;
  163464. }
  163465. }
  163466. /*
  163467. * Process some data.
  163468. * This routine handles the simple pass-through mode,
  163469. * where we have only a strip buffer.
  163470. */
  163471. METHODDEF(void)
  163472. process_data_simple_main (j_compress_ptr cinfo,
  163473. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163474. JDIMENSION in_rows_avail)
  163475. {
  163476. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163477. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163478. /* Read input data if we haven't filled the main buffer yet */
  163479. if (main_->rowgroup_ctr < DCTSIZE)
  163480. (*cinfo->prep->pre_process_data) (cinfo,
  163481. input_buf, in_row_ctr, in_rows_avail,
  163482. main_->buffer, &main_->rowgroup_ctr,
  163483. (JDIMENSION) DCTSIZE);
  163484. /* If we don't have a full iMCU row buffered, return to application for
  163485. * more data. Note that preprocessor will always pad to fill the iMCU row
  163486. * at the bottom of the image.
  163487. */
  163488. if (main_->rowgroup_ctr != DCTSIZE)
  163489. return;
  163490. /* Send the completed row to the compressor */
  163491. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163492. /* If compressor did not consume the whole row, then we must need to
  163493. * suspend processing and return to the application. In this situation
  163494. * we pretend we didn't yet consume the last input row; otherwise, if
  163495. * it happened to be the last row of the image, the application would
  163496. * think we were done.
  163497. */
  163498. if (! main_->suspended) {
  163499. (*in_row_ctr)--;
  163500. main_->suspended = TRUE;
  163501. }
  163502. return;
  163503. }
  163504. /* We did finish the row. Undo our little suspension hack if a previous
  163505. * call suspended; then mark the main buffer empty.
  163506. */
  163507. if (main_->suspended) {
  163508. (*in_row_ctr)++;
  163509. main_->suspended = FALSE;
  163510. }
  163511. main_->rowgroup_ctr = 0;
  163512. main_->cur_iMCU_row++;
  163513. }
  163514. }
  163515. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163516. /*
  163517. * Process some data.
  163518. * This routine handles all of the modes that use a full-size buffer.
  163519. */
  163520. METHODDEF(void)
  163521. process_data_buffer_main (j_compress_ptr cinfo,
  163522. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163523. JDIMENSION in_rows_avail)
  163524. {
  163525. my_main_ptr main = (my_main_ptr) cinfo->main;
  163526. int ci;
  163527. jpeg_component_info *compptr;
  163528. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163529. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163530. /* Realign the virtual buffers if at the start of an iMCU row. */
  163531. if (main->rowgroup_ctr == 0) {
  163532. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163533. ci++, compptr++) {
  163534. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163535. ((j_common_ptr) cinfo, main->whole_image[ci],
  163536. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163537. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163538. }
  163539. /* In a read pass, pretend we just read some source data. */
  163540. if (! writing) {
  163541. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163542. main->rowgroup_ctr = DCTSIZE;
  163543. }
  163544. }
  163545. /* If a write pass, read input data until the current iMCU row is full. */
  163546. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163547. if (writing) {
  163548. (*cinfo->prep->pre_process_data) (cinfo,
  163549. input_buf, in_row_ctr, in_rows_avail,
  163550. main->buffer, &main->rowgroup_ctr,
  163551. (JDIMENSION) DCTSIZE);
  163552. /* Return to application if we need more data to fill the iMCU row. */
  163553. if (main->rowgroup_ctr < DCTSIZE)
  163554. return;
  163555. }
  163556. /* Emit data, unless this is a sink-only pass. */
  163557. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163558. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163559. /* If compressor did not consume the whole row, then we must need to
  163560. * suspend processing and return to the application. In this situation
  163561. * we pretend we didn't yet consume the last input row; otherwise, if
  163562. * it happened to be the last row of the image, the application would
  163563. * think we were done.
  163564. */
  163565. if (! main->suspended) {
  163566. (*in_row_ctr)--;
  163567. main->suspended = TRUE;
  163568. }
  163569. return;
  163570. }
  163571. /* We did finish the row. Undo our little suspension hack if a previous
  163572. * call suspended; then mark the main buffer empty.
  163573. */
  163574. if (main->suspended) {
  163575. (*in_row_ctr)++;
  163576. main->suspended = FALSE;
  163577. }
  163578. }
  163579. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163580. main->rowgroup_ctr = 0;
  163581. main->cur_iMCU_row++;
  163582. }
  163583. }
  163584. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163585. /*
  163586. * Initialize main buffer controller.
  163587. */
  163588. GLOBAL(void)
  163589. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163590. {
  163591. my_main_ptr main_;
  163592. int ci;
  163593. jpeg_component_info *compptr;
  163594. main_ = (my_main_ptr)
  163595. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163596. SIZEOF(my_main_controller));
  163597. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163598. main_->pub.start_pass = start_pass_main;
  163599. /* We don't need to create a buffer in raw-data mode. */
  163600. if (cinfo->raw_data_in)
  163601. return;
  163602. /* Create the buffer. It holds downsampled data, so each component
  163603. * may be of a different size.
  163604. */
  163605. if (need_full_buffer) {
  163606. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163607. /* Allocate a full-image virtual array for each component */
  163608. /* Note we pad the bottom to a multiple of the iMCU height */
  163609. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163610. ci++, compptr++) {
  163611. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163612. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163613. compptr->width_in_blocks * DCTSIZE,
  163614. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163615. (long) compptr->v_samp_factor) * DCTSIZE,
  163616. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163617. }
  163618. #else
  163619. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163620. #endif
  163621. } else {
  163622. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163623. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163624. #endif
  163625. /* Allocate a strip buffer for each component */
  163626. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163627. ci++, compptr++) {
  163628. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163629. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163630. compptr->width_in_blocks * DCTSIZE,
  163631. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163632. }
  163633. }
  163634. }
  163635. /*** End of inlined file: jcmainct.c ***/
  163636. /*** Start of inlined file: jcmarker.c ***/
  163637. #define JPEG_INTERNALS
  163638. /* Private state */
  163639. typedef struct {
  163640. struct jpeg_marker_writer pub; /* public fields */
  163641. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163642. } my_marker_writer;
  163643. typedef my_marker_writer * my_marker_ptr;
  163644. /*
  163645. * Basic output routines.
  163646. *
  163647. * Note that we do not support suspension while writing a marker.
  163648. * Therefore, an application using suspension must ensure that there is
  163649. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163650. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163651. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163652. * modes are not supported at all with suspension, so those two are the only
  163653. * points where markers will be written.
  163654. */
  163655. LOCAL(void)
  163656. emit_byte (j_compress_ptr cinfo, int val)
  163657. /* Emit a byte */
  163658. {
  163659. struct jpeg_destination_mgr * dest = cinfo->dest;
  163660. *(dest->next_output_byte)++ = (JOCTET) val;
  163661. if (--dest->free_in_buffer == 0) {
  163662. if (! (*dest->empty_output_buffer) (cinfo))
  163663. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163664. }
  163665. }
  163666. LOCAL(void)
  163667. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163668. /* Emit a marker code */
  163669. {
  163670. emit_byte(cinfo, 0xFF);
  163671. emit_byte(cinfo, (int) mark);
  163672. }
  163673. LOCAL(void)
  163674. emit_2bytes (j_compress_ptr cinfo, int value)
  163675. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163676. {
  163677. emit_byte(cinfo, (value >> 8) & 0xFF);
  163678. emit_byte(cinfo, value & 0xFF);
  163679. }
  163680. /*
  163681. * Routines to write specific marker types.
  163682. */
  163683. LOCAL(int)
  163684. emit_dqt (j_compress_ptr cinfo, int index)
  163685. /* Emit a DQT marker */
  163686. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163687. {
  163688. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163689. int prec;
  163690. int i;
  163691. if (qtbl == NULL)
  163692. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163693. prec = 0;
  163694. for (i = 0; i < DCTSIZE2; i++) {
  163695. if (qtbl->quantval[i] > 255)
  163696. prec = 1;
  163697. }
  163698. if (! qtbl->sent_table) {
  163699. emit_marker(cinfo, M_DQT);
  163700. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163701. emit_byte(cinfo, index + (prec<<4));
  163702. for (i = 0; i < DCTSIZE2; i++) {
  163703. /* The table entries must be emitted in zigzag order. */
  163704. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163705. if (prec)
  163706. emit_byte(cinfo, (int) (qval >> 8));
  163707. emit_byte(cinfo, (int) (qval & 0xFF));
  163708. }
  163709. qtbl->sent_table = TRUE;
  163710. }
  163711. return prec;
  163712. }
  163713. LOCAL(void)
  163714. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163715. /* Emit a DHT marker */
  163716. {
  163717. JHUFF_TBL * htbl;
  163718. int length, i;
  163719. if (is_ac) {
  163720. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163721. index += 0x10; /* output index has AC bit set */
  163722. } else {
  163723. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163724. }
  163725. if (htbl == NULL)
  163726. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163727. if (! htbl->sent_table) {
  163728. emit_marker(cinfo, M_DHT);
  163729. length = 0;
  163730. for (i = 1; i <= 16; i++)
  163731. length += htbl->bits[i];
  163732. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163733. emit_byte(cinfo, index);
  163734. for (i = 1; i <= 16; i++)
  163735. emit_byte(cinfo, htbl->bits[i]);
  163736. for (i = 0; i < length; i++)
  163737. emit_byte(cinfo, htbl->huffval[i]);
  163738. htbl->sent_table = TRUE;
  163739. }
  163740. }
  163741. LOCAL(void)
  163742. emit_dac (j_compress_ptr)
  163743. /* Emit a DAC marker */
  163744. /* Since the useful info is so small, we want to emit all the tables in */
  163745. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163746. {
  163747. #ifdef C_ARITH_CODING_SUPPORTED
  163748. char dc_in_use[NUM_ARITH_TBLS];
  163749. char ac_in_use[NUM_ARITH_TBLS];
  163750. int length, i;
  163751. jpeg_component_info *compptr;
  163752. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163753. dc_in_use[i] = ac_in_use[i] = 0;
  163754. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163755. compptr = cinfo->cur_comp_info[i];
  163756. dc_in_use[compptr->dc_tbl_no] = 1;
  163757. ac_in_use[compptr->ac_tbl_no] = 1;
  163758. }
  163759. length = 0;
  163760. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163761. length += dc_in_use[i] + ac_in_use[i];
  163762. emit_marker(cinfo, M_DAC);
  163763. emit_2bytes(cinfo, length*2 + 2);
  163764. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163765. if (dc_in_use[i]) {
  163766. emit_byte(cinfo, i);
  163767. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163768. }
  163769. if (ac_in_use[i]) {
  163770. emit_byte(cinfo, i + 0x10);
  163771. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163772. }
  163773. }
  163774. #endif /* C_ARITH_CODING_SUPPORTED */
  163775. }
  163776. LOCAL(void)
  163777. emit_dri (j_compress_ptr cinfo)
  163778. /* Emit a DRI marker */
  163779. {
  163780. emit_marker(cinfo, M_DRI);
  163781. emit_2bytes(cinfo, 4); /* fixed length */
  163782. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163783. }
  163784. LOCAL(void)
  163785. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163786. /* Emit a SOF marker */
  163787. {
  163788. int ci;
  163789. jpeg_component_info *compptr;
  163790. emit_marker(cinfo, code);
  163791. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163792. /* Make sure image isn't bigger than SOF field can handle */
  163793. if ((long) cinfo->image_height > 65535L ||
  163794. (long) cinfo->image_width > 65535L)
  163795. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163796. emit_byte(cinfo, cinfo->data_precision);
  163797. emit_2bytes(cinfo, (int) cinfo->image_height);
  163798. emit_2bytes(cinfo, (int) cinfo->image_width);
  163799. emit_byte(cinfo, cinfo->num_components);
  163800. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163801. ci++, compptr++) {
  163802. emit_byte(cinfo, compptr->component_id);
  163803. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163804. emit_byte(cinfo, compptr->quant_tbl_no);
  163805. }
  163806. }
  163807. LOCAL(void)
  163808. emit_sos (j_compress_ptr cinfo)
  163809. /* Emit a SOS marker */
  163810. {
  163811. int i, td, ta;
  163812. jpeg_component_info *compptr;
  163813. emit_marker(cinfo, M_SOS);
  163814. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163815. emit_byte(cinfo, cinfo->comps_in_scan);
  163816. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163817. compptr = cinfo->cur_comp_info[i];
  163818. emit_byte(cinfo, compptr->component_id);
  163819. td = compptr->dc_tbl_no;
  163820. ta = compptr->ac_tbl_no;
  163821. if (cinfo->progressive_mode) {
  163822. /* Progressive mode: only DC or only AC tables are used in one scan;
  163823. * furthermore, Huffman coding of DC refinement uses no table at all.
  163824. * We emit 0 for unused field(s); this is recommended by the P&M text
  163825. * but does not seem to be specified in the standard.
  163826. */
  163827. if (cinfo->Ss == 0) {
  163828. ta = 0; /* DC scan */
  163829. if (cinfo->Ah != 0 && !cinfo->arith_code)
  163830. td = 0; /* no DC table either */
  163831. } else {
  163832. td = 0; /* AC scan */
  163833. }
  163834. }
  163835. emit_byte(cinfo, (td << 4) + ta);
  163836. }
  163837. emit_byte(cinfo, cinfo->Ss);
  163838. emit_byte(cinfo, cinfo->Se);
  163839. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  163840. }
  163841. LOCAL(void)
  163842. emit_jfif_app0 (j_compress_ptr cinfo)
  163843. /* Emit a JFIF-compliant APP0 marker */
  163844. {
  163845. /*
  163846. * Length of APP0 block (2 bytes)
  163847. * Block ID (4 bytes - ASCII "JFIF")
  163848. * Zero byte (1 byte to terminate the ID string)
  163849. * Version Major, Minor (2 bytes - major first)
  163850. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  163851. * Xdpu (2 bytes - dots per unit horizontal)
  163852. * Ydpu (2 bytes - dots per unit vertical)
  163853. * Thumbnail X size (1 byte)
  163854. * Thumbnail Y size (1 byte)
  163855. */
  163856. emit_marker(cinfo, M_APP0);
  163857. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  163858. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  163859. emit_byte(cinfo, 0x46);
  163860. emit_byte(cinfo, 0x49);
  163861. emit_byte(cinfo, 0x46);
  163862. emit_byte(cinfo, 0);
  163863. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  163864. emit_byte(cinfo, cinfo->JFIF_minor_version);
  163865. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  163866. emit_2bytes(cinfo, (int) cinfo->X_density);
  163867. emit_2bytes(cinfo, (int) cinfo->Y_density);
  163868. emit_byte(cinfo, 0); /* No thumbnail image */
  163869. emit_byte(cinfo, 0);
  163870. }
  163871. LOCAL(void)
  163872. emit_adobe_app14 (j_compress_ptr cinfo)
  163873. /* Emit an Adobe APP14 marker */
  163874. {
  163875. /*
  163876. * Length of APP14 block (2 bytes)
  163877. * Block ID (5 bytes - ASCII "Adobe")
  163878. * Version Number (2 bytes - currently 100)
  163879. * Flags0 (2 bytes - currently 0)
  163880. * Flags1 (2 bytes - currently 0)
  163881. * Color transform (1 byte)
  163882. *
  163883. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  163884. * now in circulation seem to use Version = 100, so that's what we write.
  163885. *
  163886. * We write the color transform byte as 1 if the JPEG color space is
  163887. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  163888. * whether the encoder performed a transformation, which is pretty useless.
  163889. */
  163890. emit_marker(cinfo, M_APP14);
  163891. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  163892. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  163893. emit_byte(cinfo, 0x64);
  163894. emit_byte(cinfo, 0x6F);
  163895. emit_byte(cinfo, 0x62);
  163896. emit_byte(cinfo, 0x65);
  163897. emit_2bytes(cinfo, 100); /* Version */
  163898. emit_2bytes(cinfo, 0); /* Flags0 */
  163899. emit_2bytes(cinfo, 0); /* Flags1 */
  163900. switch (cinfo->jpeg_color_space) {
  163901. case JCS_YCbCr:
  163902. emit_byte(cinfo, 1); /* Color transform = 1 */
  163903. break;
  163904. case JCS_YCCK:
  163905. emit_byte(cinfo, 2); /* Color transform = 2 */
  163906. break;
  163907. default:
  163908. emit_byte(cinfo, 0); /* Color transform = 0 */
  163909. break;
  163910. }
  163911. }
  163912. /*
  163913. * These routines allow writing an arbitrary marker with parameters.
  163914. * The only intended use is to emit COM or APPn markers after calling
  163915. * write_file_header and before calling write_frame_header.
  163916. * Other uses are not guaranteed to produce desirable results.
  163917. * Counting the parameter bytes properly is the caller's responsibility.
  163918. */
  163919. METHODDEF(void)
  163920. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  163921. /* Emit an arbitrary marker header */
  163922. {
  163923. if (datalen > (unsigned int) 65533) /* safety check */
  163924. ERREXIT(cinfo, JERR_BAD_LENGTH);
  163925. emit_marker(cinfo, (JPEG_MARKER) marker);
  163926. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  163927. }
  163928. METHODDEF(void)
  163929. write_marker_byte (j_compress_ptr cinfo, int val)
  163930. /* Emit one byte of marker parameters following write_marker_header */
  163931. {
  163932. emit_byte(cinfo, val);
  163933. }
  163934. /*
  163935. * Write datastream header.
  163936. * This consists of an SOI and optional APPn markers.
  163937. * We recommend use of the JFIF marker, but not the Adobe marker,
  163938. * when using YCbCr or grayscale data. The JFIF marker should NOT
  163939. * be used for any other JPEG colorspace. The Adobe marker is helpful
  163940. * to distinguish RGB, CMYK, and YCCK colorspaces.
  163941. * Note that an application can write additional header markers after
  163942. * jpeg_start_compress returns.
  163943. */
  163944. METHODDEF(void)
  163945. write_file_header (j_compress_ptr cinfo)
  163946. {
  163947. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163948. emit_marker(cinfo, M_SOI); /* first the SOI */
  163949. /* SOI is defined to reset restart interval to 0 */
  163950. marker->last_restart_interval = 0;
  163951. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  163952. emit_jfif_app0(cinfo);
  163953. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  163954. emit_adobe_app14(cinfo);
  163955. }
  163956. /*
  163957. * Write frame header.
  163958. * This consists of DQT and SOFn markers.
  163959. * Note that we do not emit the SOF until we have emitted the DQT(s).
  163960. * This avoids compatibility problems with incorrect implementations that
  163961. * try to error-check the quant table numbers as soon as they see the SOF.
  163962. */
  163963. METHODDEF(void)
  163964. write_frame_header (j_compress_ptr cinfo)
  163965. {
  163966. int ci, prec;
  163967. boolean is_baseline;
  163968. jpeg_component_info *compptr;
  163969. /* Emit DQT for each quantization table.
  163970. * Note that emit_dqt() suppresses any duplicate tables.
  163971. */
  163972. prec = 0;
  163973. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163974. ci++, compptr++) {
  163975. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  163976. }
  163977. /* now prec is nonzero iff there are any 16-bit quant tables. */
  163978. /* Check for a non-baseline specification.
  163979. * Note we assume that Huffman table numbers won't be changed later.
  163980. */
  163981. if (cinfo->arith_code || cinfo->progressive_mode ||
  163982. cinfo->data_precision != 8) {
  163983. is_baseline = FALSE;
  163984. } else {
  163985. is_baseline = TRUE;
  163986. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163987. ci++, compptr++) {
  163988. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  163989. is_baseline = FALSE;
  163990. }
  163991. if (prec && is_baseline) {
  163992. is_baseline = FALSE;
  163993. /* If it's baseline except for quantizer size, warn the user */
  163994. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  163995. }
  163996. }
  163997. /* Emit the proper SOF marker */
  163998. if (cinfo->arith_code) {
  163999. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164000. } else {
  164001. if (cinfo->progressive_mode)
  164002. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164003. else if (is_baseline)
  164004. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164005. else
  164006. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164007. }
  164008. }
  164009. /*
  164010. * Write scan header.
  164011. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164012. * Compressed data will be written following the SOS.
  164013. */
  164014. METHODDEF(void)
  164015. write_scan_header (j_compress_ptr cinfo)
  164016. {
  164017. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164018. int i;
  164019. jpeg_component_info *compptr;
  164020. if (cinfo->arith_code) {
  164021. /* Emit arith conditioning info. We may have some duplication
  164022. * if the file has multiple scans, but it's so small it's hardly
  164023. * worth worrying about.
  164024. */
  164025. emit_dac(cinfo);
  164026. } else {
  164027. /* Emit Huffman tables.
  164028. * Note that emit_dht() suppresses any duplicate tables.
  164029. */
  164030. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164031. compptr = cinfo->cur_comp_info[i];
  164032. if (cinfo->progressive_mode) {
  164033. /* Progressive mode: only DC or only AC tables are used in one scan */
  164034. if (cinfo->Ss == 0) {
  164035. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164036. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164037. } else {
  164038. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164039. }
  164040. } else {
  164041. /* Sequential mode: need both DC and AC tables */
  164042. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164043. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164044. }
  164045. }
  164046. }
  164047. /* Emit DRI if required --- note that DRI value could change for each scan.
  164048. * We avoid wasting space with unnecessary DRIs, however.
  164049. */
  164050. if (cinfo->restart_interval != marker->last_restart_interval) {
  164051. emit_dri(cinfo);
  164052. marker->last_restart_interval = cinfo->restart_interval;
  164053. }
  164054. emit_sos(cinfo);
  164055. }
  164056. /*
  164057. * Write datastream trailer.
  164058. */
  164059. METHODDEF(void)
  164060. write_file_trailer (j_compress_ptr cinfo)
  164061. {
  164062. emit_marker(cinfo, M_EOI);
  164063. }
  164064. /*
  164065. * Write an abbreviated table-specification datastream.
  164066. * This consists of SOI, DQT and DHT tables, and EOI.
  164067. * Any table that is defined and not marked sent_table = TRUE will be
  164068. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164069. */
  164070. METHODDEF(void)
  164071. write_tables_only (j_compress_ptr cinfo)
  164072. {
  164073. int i;
  164074. emit_marker(cinfo, M_SOI);
  164075. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164076. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164077. (void) emit_dqt(cinfo, i);
  164078. }
  164079. if (! cinfo->arith_code) {
  164080. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164081. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164082. emit_dht(cinfo, i, FALSE);
  164083. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164084. emit_dht(cinfo, i, TRUE);
  164085. }
  164086. }
  164087. emit_marker(cinfo, M_EOI);
  164088. }
  164089. /*
  164090. * Initialize the marker writer module.
  164091. */
  164092. GLOBAL(void)
  164093. jinit_marker_writer (j_compress_ptr cinfo)
  164094. {
  164095. my_marker_ptr marker;
  164096. /* Create the subobject */
  164097. marker = (my_marker_ptr)
  164098. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164099. SIZEOF(my_marker_writer));
  164100. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164101. /* Initialize method pointers */
  164102. marker->pub.write_file_header = write_file_header;
  164103. marker->pub.write_frame_header = write_frame_header;
  164104. marker->pub.write_scan_header = write_scan_header;
  164105. marker->pub.write_file_trailer = write_file_trailer;
  164106. marker->pub.write_tables_only = write_tables_only;
  164107. marker->pub.write_marker_header = write_marker_header;
  164108. marker->pub.write_marker_byte = write_marker_byte;
  164109. /* Initialize private state */
  164110. marker->last_restart_interval = 0;
  164111. }
  164112. /*** End of inlined file: jcmarker.c ***/
  164113. /*** Start of inlined file: jcmaster.c ***/
  164114. #define JPEG_INTERNALS
  164115. /* Private state */
  164116. typedef enum {
  164117. main_pass, /* input data, also do first output step */
  164118. huff_opt_pass, /* Huffman code optimization pass */
  164119. output_pass /* data output pass */
  164120. } c_pass_type;
  164121. typedef struct {
  164122. struct jpeg_comp_master pub; /* public fields */
  164123. c_pass_type pass_type; /* the type of the current pass */
  164124. int pass_number; /* # of passes completed */
  164125. int total_passes; /* total # of passes needed */
  164126. int scan_number; /* current index in scan_info[] */
  164127. } my_comp_master;
  164128. typedef my_comp_master * my_master_ptr;
  164129. /*
  164130. * Support routines that do various essential calculations.
  164131. */
  164132. LOCAL(void)
  164133. initial_setup (j_compress_ptr cinfo)
  164134. /* Do computations that are needed before master selection phase */
  164135. {
  164136. int ci;
  164137. jpeg_component_info *compptr;
  164138. long samplesperrow;
  164139. JDIMENSION jd_samplesperrow;
  164140. /* Sanity check on image dimensions */
  164141. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164142. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164143. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164144. /* Make sure image isn't bigger than I can handle */
  164145. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164146. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164147. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164148. /* Width of an input scanline must be representable as JDIMENSION. */
  164149. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164150. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164151. if ((long) jd_samplesperrow != samplesperrow)
  164152. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164153. /* For now, precision must match compiled-in value... */
  164154. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164155. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164156. /* Check that number of components won't exceed internal array sizes */
  164157. if (cinfo->num_components > MAX_COMPONENTS)
  164158. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164159. MAX_COMPONENTS);
  164160. /* Compute maximum sampling factors; check factor validity */
  164161. cinfo->max_h_samp_factor = 1;
  164162. cinfo->max_v_samp_factor = 1;
  164163. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164164. ci++, compptr++) {
  164165. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164166. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164167. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164168. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164169. compptr->h_samp_factor);
  164170. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164171. compptr->v_samp_factor);
  164172. }
  164173. /* Compute dimensions of components */
  164174. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164175. ci++, compptr++) {
  164176. /* Fill in the correct component_index value; don't rely on application */
  164177. compptr->component_index = ci;
  164178. /* For compression, we never do DCT scaling. */
  164179. compptr->DCT_scaled_size = DCTSIZE;
  164180. /* Size in DCT blocks */
  164181. compptr->width_in_blocks = (JDIMENSION)
  164182. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164183. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164184. compptr->height_in_blocks = (JDIMENSION)
  164185. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164186. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164187. /* Size in samples */
  164188. compptr->downsampled_width = (JDIMENSION)
  164189. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164190. (long) cinfo->max_h_samp_factor);
  164191. compptr->downsampled_height = (JDIMENSION)
  164192. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164193. (long) cinfo->max_v_samp_factor);
  164194. /* Mark component needed (this flag isn't actually used for compression) */
  164195. compptr->component_needed = TRUE;
  164196. }
  164197. /* Compute number of fully interleaved MCU rows (number of times that
  164198. * main controller will call coefficient controller).
  164199. */
  164200. cinfo->total_iMCU_rows = (JDIMENSION)
  164201. jdiv_round_up((long) cinfo->image_height,
  164202. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164203. }
  164204. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164205. LOCAL(void)
  164206. validate_script (j_compress_ptr cinfo)
  164207. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164208. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164209. */
  164210. {
  164211. const jpeg_scan_info * scanptr;
  164212. int scanno, ncomps, ci, coefi, thisi;
  164213. int Ss, Se, Ah, Al;
  164214. boolean component_sent[MAX_COMPONENTS];
  164215. #ifdef C_PROGRESSIVE_SUPPORTED
  164216. int * last_bitpos_ptr;
  164217. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164218. /* -1 until that coefficient has been seen; then last Al for it */
  164219. #endif
  164220. if (cinfo->num_scans <= 0)
  164221. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164222. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164223. * for progressive JPEG, no scan can have this.
  164224. */
  164225. scanptr = cinfo->scan_info;
  164226. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164227. #ifdef C_PROGRESSIVE_SUPPORTED
  164228. cinfo->progressive_mode = TRUE;
  164229. last_bitpos_ptr = & last_bitpos[0][0];
  164230. for (ci = 0; ci < cinfo->num_components; ci++)
  164231. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164232. *last_bitpos_ptr++ = -1;
  164233. #else
  164234. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164235. #endif
  164236. } else {
  164237. cinfo->progressive_mode = FALSE;
  164238. for (ci = 0; ci < cinfo->num_components; ci++)
  164239. component_sent[ci] = FALSE;
  164240. }
  164241. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164242. /* Validate component indexes */
  164243. ncomps = scanptr->comps_in_scan;
  164244. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164245. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164246. for (ci = 0; ci < ncomps; ci++) {
  164247. thisi = scanptr->component_index[ci];
  164248. if (thisi < 0 || thisi >= cinfo->num_components)
  164249. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164250. /* Components must appear in SOF order within each scan */
  164251. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164252. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164253. }
  164254. /* Validate progression parameters */
  164255. Ss = scanptr->Ss;
  164256. Se = scanptr->Se;
  164257. Ah = scanptr->Ah;
  164258. Al = scanptr->Al;
  164259. if (cinfo->progressive_mode) {
  164260. #ifdef C_PROGRESSIVE_SUPPORTED
  164261. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164262. * seems wrong: the upper bound ought to depend on data precision.
  164263. * Perhaps they really meant 0..N+1 for N-bit precision.
  164264. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164265. * out-of-range reconstructed DC values during the first DC scan,
  164266. * which might cause problems for some decoders.
  164267. */
  164268. #if BITS_IN_JSAMPLE == 8
  164269. #define MAX_AH_AL 10
  164270. #else
  164271. #define MAX_AH_AL 13
  164272. #endif
  164273. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164274. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164275. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164276. if (Ss == 0) {
  164277. if (Se != 0) /* DC and AC together not OK */
  164278. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164279. } else {
  164280. if (ncomps != 1) /* AC scans must be for only one component */
  164281. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164282. }
  164283. for (ci = 0; ci < ncomps; ci++) {
  164284. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164285. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164286. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164287. for (coefi = Ss; coefi <= Se; coefi++) {
  164288. if (last_bitpos_ptr[coefi] < 0) {
  164289. /* first scan of this coefficient */
  164290. if (Ah != 0)
  164291. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164292. } else {
  164293. /* not first scan */
  164294. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164295. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164296. }
  164297. last_bitpos_ptr[coefi] = Al;
  164298. }
  164299. }
  164300. #endif
  164301. } else {
  164302. /* For sequential JPEG, all progression parameters must be these: */
  164303. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164304. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164305. /* Make sure components are not sent twice */
  164306. for (ci = 0; ci < ncomps; ci++) {
  164307. thisi = scanptr->component_index[ci];
  164308. if (component_sent[thisi])
  164309. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164310. component_sent[thisi] = TRUE;
  164311. }
  164312. }
  164313. }
  164314. /* Now verify that everything got sent. */
  164315. if (cinfo->progressive_mode) {
  164316. #ifdef C_PROGRESSIVE_SUPPORTED
  164317. /* For progressive mode, we only check that at least some DC data
  164318. * got sent for each component; the spec does not require that all bits
  164319. * of all coefficients be transmitted. Would it be wiser to enforce
  164320. * transmission of all coefficient bits??
  164321. */
  164322. for (ci = 0; ci < cinfo->num_components; ci++) {
  164323. if (last_bitpos[ci][0] < 0)
  164324. ERREXIT(cinfo, JERR_MISSING_DATA);
  164325. }
  164326. #endif
  164327. } else {
  164328. for (ci = 0; ci < cinfo->num_components; ci++) {
  164329. if (! component_sent[ci])
  164330. ERREXIT(cinfo, JERR_MISSING_DATA);
  164331. }
  164332. }
  164333. }
  164334. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164335. LOCAL(void)
  164336. select_scan_parameters (j_compress_ptr cinfo)
  164337. /* Set up the scan parameters for the current scan */
  164338. {
  164339. int ci;
  164340. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164341. if (cinfo->scan_info != NULL) {
  164342. /* Prepare for current scan --- the script is already validated */
  164343. my_master_ptr master = (my_master_ptr) cinfo->master;
  164344. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164345. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164346. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164347. cinfo->cur_comp_info[ci] =
  164348. &cinfo->comp_info[scanptr->component_index[ci]];
  164349. }
  164350. cinfo->Ss = scanptr->Ss;
  164351. cinfo->Se = scanptr->Se;
  164352. cinfo->Ah = scanptr->Ah;
  164353. cinfo->Al = scanptr->Al;
  164354. }
  164355. else
  164356. #endif
  164357. {
  164358. /* Prepare for single sequential-JPEG scan containing all components */
  164359. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164360. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164361. MAX_COMPS_IN_SCAN);
  164362. cinfo->comps_in_scan = cinfo->num_components;
  164363. for (ci = 0; ci < cinfo->num_components; ci++) {
  164364. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164365. }
  164366. cinfo->Ss = 0;
  164367. cinfo->Se = DCTSIZE2-1;
  164368. cinfo->Ah = 0;
  164369. cinfo->Al = 0;
  164370. }
  164371. }
  164372. LOCAL(void)
  164373. per_scan_setup (j_compress_ptr cinfo)
  164374. /* Do computations that are needed before processing a JPEG scan */
  164375. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164376. {
  164377. int ci, mcublks, tmp;
  164378. jpeg_component_info *compptr;
  164379. if (cinfo->comps_in_scan == 1) {
  164380. /* Noninterleaved (single-component) scan */
  164381. compptr = cinfo->cur_comp_info[0];
  164382. /* Overall image size in MCUs */
  164383. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164384. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164385. /* For noninterleaved scan, always one block per MCU */
  164386. compptr->MCU_width = 1;
  164387. compptr->MCU_height = 1;
  164388. compptr->MCU_blocks = 1;
  164389. compptr->MCU_sample_width = DCTSIZE;
  164390. compptr->last_col_width = 1;
  164391. /* For noninterleaved scans, it is convenient to define last_row_height
  164392. * as the number of block rows present in the last iMCU row.
  164393. */
  164394. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164395. if (tmp == 0) tmp = compptr->v_samp_factor;
  164396. compptr->last_row_height = tmp;
  164397. /* Prepare array describing MCU composition */
  164398. cinfo->blocks_in_MCU = 1;
  164399. cinfo->MCU_membership[0] = 0;
  164400. } else {
  164401. /* Interleaved (multi-component) scan */
  164402. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164403. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164404. MAX_COMPS_IN_SCAN);
  164405. /* Overall image size in MCUs */
  164406. cinfo->MCUs_per_row = (JDIMENSION)
  164407. jdiv_round_up((long) cinfo->image_width,
  164408. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164409. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164410. jdiv_round_up((long) cinfo->image_height,
  164411. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164412. cinfo->blocks_in_MCU = 0;
  164413. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164414. compptr = cinfo->cur_comp_info[ci];
  164415. /* Sampling factors give # of blocks of component in each MCU */
  164416. compptr->MCU_width = compptr->h_samp_factor;
  164417. compptr->MCU_height = compptr->v_samp_factor;
  164418. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164419. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164420. /* Figure number of non-dummy blocks in last MCU column & row */
  164421. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164422. if (tmp == 0) tmp = compptr->MCU_width;
  164423. compptr->last_col_width = tmp;
  164424. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164425. if (tmp == 0) tmp = compptr->MCU_height;
  164426. compptr->last_row_height = tmp;
  164427. /* Prepare array describing MCU composition */
  164428. mcublks = compptr->MCU_blocks;
  164429. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164430. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164431. while (mcublks-- > 0) {
  164432. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164433. }
  164434. }
  164435. }
  164436. /* Convert restart specified in rows to actual MCU count. */
  164437. /* Note that count must fit in 16 bits, so we provide limiting. */
  164438. if (cinfo->restart_in_rows > 0) {
  164439. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164440. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164441. }
  164442. }
  164443. /*
  164444. * Per-pass setup.
  164445. * This is called at the beginning of each pass. We determine which modules
  164446. * will be active during this pass and give them appropriate start_pass calls.
  164447. * We also set is_last_pass to indicate whether any more passes will be
  164448. * required.
  164449. */
  164450. METHODDEF(void)
  164451. prepare_for_pass (j_compress_ptr cinfo)
  164452. {
  164453. my_master_ptr master = (my_master_ptr) cinfo->master;
  164454. switch (master->pass_type) {
  164455. case main_pass:
  164456. /* Initial pass: will collect input data, and do either Huffman
  164457. * optimization or data output for the first scan.
  164458. */
  164459. select_scan_parameters(cinfo);
  164460. per_scan_setup(cinfo);
  164461. if (! cinfo->raw_data_in) {
  164462. (*cinfo->cconvert->start_pass) (cinfo);
  164463. (*cinfo->downsample->start_pass) (cinfo);
  164464. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164465. }
  164466. (*cinfo->fdct->start_pass) (cinfo);
  164467. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164468. (*cinfo->coef->start_pass) (cinfo,
  164469. (master->total_passes > 1 ?
  164470. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164471. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164472. if (cinfo->optimize_coding) {
  164473. /* No immediate data output; postpone writing frame/scan headers */
  164474. master->pub.call_pass_startup = FALSE;
  164475. } else {
  164476. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164477. master->pub.call_pass_startup = TRUE;
  164478. }
  164479. break;
  164480. #ifdef ENTROPY_OPT_SUPPORTED
  164481. case huff_opt_pass:
  164482. /* Do Huffman optimization for a scan after the first one. */
  164483. select_scan_parameters(cinfo);
  164484. per_scan_setup(cinfo);
  164485. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164486. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164487. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164488. master->pub.call_pass_startup = FALSE;
  164489. break;
  164490. }
  164491. /* Special case: Huffman DC refinement scans need no Huffman table
  164492. * and therefore we can skip the optimization pass for them.
  164493. */
  164494. master->pass_type = output_pass;
  164495. master->pass_number++;
  164496. /*FALLTHROUGH*/
  164497. #endif
  164498. case output_pass:
  164499. /* Do a data-output pass. */
  164500. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164501. if (! cinfo->optimize_coding) {
  164502. select_scan_parameters(cinfo);
  164503. per_scan_setup(cinfo);
  164504. }
  164505. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164506. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164507. /* We emit frame/scan headers now */
  164508. if (master->scan_number == 0)
  164509. (*cinfo->marker->write_frame_header) (cinfo);
  164510. (*cinfo->marker->write_scan_header) (cinfo);
  164511. master->pub.call_pass_startup = FALSE;
  164512. break;
  164513. default:
  164514. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164515. }
  164516. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164517. /* Set up progress monitor's pass info if present */
  164518. if (cinfo->progress != NULL) {
  164519. cinfo->progress->completed_passes = master->pass_number;
  164520. cinfo->progress->total_passes = master->total_passes;
  164521. }
  164522. }
  164523. /*
  164524. * Special start-of-pass hook.
  164525. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164526. * In single-pass processing, we need this hook because we don't want to
  164527. * write frame/scan headers during jpeg_start_compress; we want to let the
  164528. * application write COM markers etc. between jpeg_start_compress and the
  164529. * jpeg_write_scanlines loop.
  164530. * In multi-pass processing, this routine is not used.
  164531. */
  164532. METHODDEF(void)
  164533. pass_startup (j_compress_ptr cinfo)
  164534. {
  164535. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164536. (*cinfo->marker->write_frame_header) (cinfo);
  164537. (*cinfo->marker->write_scan_header) (cinfo);
  164538. }
  164539. /*
  164540. * Finish up at end of pass.
  164541. */
  164542. METHODDEF(void)
  164543. finish_pass_master (j_compress_ptr cinfo)
  164544. {
  164545. my_master_ptr master = (my_master_ptr) cinfo->master;
  164546. /* The entropy coder always needs an end-of-pass call,
  164547. * either to analyze statistics or to flush its output buffer.
  164548. */
  164549. (*cinfo->entropy->finish_pass) (cinfo);
  164550. /* Update state for next pass */
  164551. switch (master->pass_type) {
  164552. case main_pass:
  164553. /* next pass is either output of scan 0 (after optimization)
  164554. * or output of scan 1 (if no optimization).
  164555. */
  164556. master->pass_type = output_pass;
  164557. if (! cinfo->optimize_coding)
  164558. master->scan_number++;
  164559. break;
  164560. case huff_opt_pass:
  164561. /* next pass is always output of current scan */
  164562. master->pass_type = output_pass;
  164563. break;
  164564. case output_pass:
  164565. /* next pass is either optimization or output of next scan */
  164566. if (cinfo->optimize_coding)
  164567. master->pass_type = huff_opt_pass;
  164568. master->scan_number++;
  164569. break;
  164570. }
  164571. master->pass_number++;
  164572. }
  164573. /*
  164574. * Initialize master compression control.
  164575. */
  164576. GLOBAL(void)
  164577. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164578. {
  164579. my_master_ptr master;
  164580. master = (my_master_ptr)
  164581. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164582. SIZEOF(my_comp_master));
  164583. cinfo->master = (struct jpeg_comp_master *) master;
  164584. master->pub.prepare_for_pass = prepare_for_pass;
  164585. master->pub.pass_startup = pass_startup;
  164586. master->pub.finish_pass = finish_pass_master;
  164587. master->pub.is_last_pass = FALSE;
  164588. /* Validate parameters, determine derived values */
  164589. initial_setup(cinfo);
  164590. if (cinfo->scan_info != NULL) {
  164591. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164592. validate_script(cinfo);
  164593. #else
  164594. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164595. #endif
  164596. } else {
  164597. cinfo->progressive_mode = FALSE;
  164598. cinfo->num_scans = 1;
  164599. }
  164600. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164601. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164602. /* Initialize my private state */
  164603. if (transcode_only) {
  164604. /* no main pass in transcoding */
  164605. if (cinfo->optimize_coding)
  164606. master->pass_type = huff_opt_pass;
  164607. else
  164608. master->pass_type = output_pass;
  164609. } else {
  164610. /* for normal compression, first pass is always this type: */
  164611. master->pass_type = main_pass;
  164612. }
  164613. master->scan_number = 0;
  164614. master->pass_number = 0;
  164615. if (cinfo->optimize_coding)
  164616. master->total_passes = cinfo->num_scans * 2;
  164617. else
  164618. master->total_passes = cinfo->num_scans;
  164619. }
  164620. /*** End of inlined file: jcmaster.c ***/
  164621. /*** Start of inlined file: jcomapi.c ***/
  164622. #define JPEG_INTERNALS
  164623. /*
  164624. * Abort processing of a JPEG compression or decompression operation,
  164625. * but don't destroy the object itself.
  164626. *
  164627. * For this, we merely clean up all the nonpermanent memory pools.
  164628. * Note that temp files (virtual arrays) are not allowed to belong to
  164629. * the permanent pool, so we will be able to close all temp files here.
  164630. * Closing a data source or destination, if necessary, is the application's
  164631. * responsibility.
  164632. */
  164633. GLOBAL(void)
  164634. jpeg_abort (j_common_ptr cinfo)
  164635. {
  164636. int pool;
  164637. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164638. if (cinfo->mem == NULL)
  164639. return;
  164640. /* Releasing pools in reverse order might help avoid fragmentation
  164641. * with some (brain-damaged) malloc libraries.
  164642. */
  164643. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164644. (*cinfo->mem->free_pool) (cinfo, pool);
  164645. }
  164646. /* Reset overall state for possible reuse of object */
  164647. if (cinfo->is_decompressor) {
  164648. cinfo->global_state = DSTATE_START;
  164649. /* Try to keep application from accessing now-deleted marker list.
  164650. * A bit kludgy to do it here, but this is the most central place.
  164651. */
  164652. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164653. } else {
  164654. cinfo->global_state = CSTATE_START;
  164655. }
  164656. }
  164657. /*
  164658. * Destruction of a JPEG object.
  164659. *
  164660. * Everything gets deallocated except the master jpeg_compress_struct itself
  164661. * and the error manager struct. Both of these are supplied by the application
  164662. * and must be freed, if necessary, by the application. (Often they are on
  164663. * the stack and so don't need to be freed anyway.)
  164664. * Closing a data source or destination, if necessary, is the application's
  164665. * responsibility.
  164666. */
  164667. GLOBAL(void)
  164668. jpeg_destroy (j_common_ptr cinfo)
  164669. {
  164670. /* We need only tell the memory manager to release everything. */
  164671. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164672. if (cinfo->mem != NULL)
  164673. (*cinfo->mem->self_destruct) (cinfo);
  164674. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164675. cinfo->global_state = 0; /* mark it destroyed */
  164676. }
  164677. /*
  164678. * Convenience routines for allocating quantization and Huffman tables.
  164679. * (Would jutils.c be a more reasonable place to put these?)
  164680. */
  164681. GLOBAL(JQUANT_TBL *)
  164682. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164683. {
  164684. JQUANT_TBL *tbl;
  164685. tbl = (JQUANT_TBL *)
  164686. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164687. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164688. return tbl;
  164689. }
  164690. GLOBAL(JHUFF_TBL *)
  164691. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164692. {
  164693. JHUFF_TBL *tbl;
  164694. tbl = (JHUFF_TBL *)
  164695. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164696. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164697. return tbl;
  164698. }
  164699. /*** End of inlined file: jcomapi.c ***/
  164700. /*** Start of inlined file: jcparam.c ***/
  164701. #define JPEG_INTERNALS
  164702. /*
  164703. * Quantization table setup routines
  164704. */
  164705. GLOBAL(void)
  164706. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164707. const unsigned int *basic_table,
  164708. int scale_factor, boolean force_baseline)
  164709. /* Define a quantization table equal to the basic_table times
  164710. * a scale factor (given as a percentage).
  164711. * If force_baseline is TRUE, the computed quantization table entries
  164712. * are limited to 1..255 for JPEG baseline compatibility.
  164713. */
  164714. {
  164715. JQUANT_TBL ** qtblptr;
  164716. int i;
  164717. long temp;
  164718. /* Safety check to ensure start_compress not called yet. */
  164719. if (cinfo->global_state != CSTATE_START)
  164720. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164721. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164722. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164723. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164724. if (*qtblptr == NULL)
  164725. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164726. for (i = 0; i < DCTSIZE2; i++) {
  164727. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164728. /* limit the values to the valid range */
  164729. if (temp <= 0L) temp = 1L;
  164730. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164731. if (force_baseline && temp > 255L)
  164732. temp = 255L; /* limit to baseline range if requested */
  164733. (*qtblptr)->quantval[i] = (UINT16) temp;
  164734. }
  164735. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164736. (*qtblptr)->sent_table = FALSE;
  164737. }
  164738. GLOBAL(void)
  164739. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164740. boolean force_baseline)
  164741. /* Set or change the 'quality' (quantization) setting, using default tables
  164742. * and a straight percentage-scaling quality scale. In most cases it's better
  164743. * to use jpeg_set_quality (below); this entry point is provided for
  164744. * applications that insist on a linear percentage scaling.
  164745. */
  164746. {
  164747. /* These are the sample quantization tables given in JPEG spec section K.1.
  164748. * The spec says that the values given produce "good" quality, and
  164749. * when divided by 2, "very good" quality.
  164750. */
  164751. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164752. 16, 11, 10, 16, 24, 40, 51, 61,
  164753. 12, 12, 14, 19, 26, 58, 60, 55,
  164754. 14, 13, 16, 24, 40, 57, 69, 56,
  164755. 14, 17, 22, 29, 51, 87, 80, 62,
  164756. 18, 22, 37, 56, 68, 109, 103, 77,
  164757. 24, 35, 55, 64, 81, 104, 113, 92,
  164758. 49, 64, 78, 87, 103, 121, 120, 101,
  164759. 72, 92, 95, 98, 112, 100, 103, 99
  164760. };
  164761. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164762. 17, 18, 24, 47, 99, 99, 99, 99,
  164763. 18, 21, 26, 66, 99, 99, 99, 99,
  164764. 24, 26, 56, 99, 99, 99, 99, 99,
  164765. 47, 66, 99, 99, 99, 99, 99, 99,
  164766. 99, 99, 99, 99, 99, 99, 99, 99,
  164767. 99, 99, 99, 99, 99, 99, 99, 99,
  164768. 99, 99, 99, 99, 99, 99, 99, 99,
  164769. 99, 99, 99, 99, 99, 99, 99, 99
  164770. };
  164771. /* Set up two quantization tables using the specified scaling */
  164772. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164773. scale_factor, force_baseline);
  164774. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164775. scale_factor, force_baseline);
  164776. }
  164777. GLOBAL(int)
  164778. jpeg_quality_scaling (int quality)
  164779. /* Convert a user-specified quality rating to a percentage scaling factor
  164780. * for an underlying quantization table, using our recommended scaling curve.
  164781. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164782. */
  164783. {
  164784. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164785. if (quality <= 0) quality = 1;
  164786. if (quality > 100) quality = 100;
  164787. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164788. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164789. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164790. * to make all the table entries 1 (hence, minimum quantization loss).
  164791. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164792. */
  164793. if (quality < 50)
  164794. quality = 5000 / quality;
  164795. else
  164796. quality = 200 - quality*2;
  164797. return quality;
  164798. }
  164799. GLOBAL(void)
  164800. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164801. /* Set or change the 'quality' (quantization) setting, using default tables.
  164802. * This is the standard quality-adjusting entry point for typical user
  164803. * interfaces; only those who want detailed control over quantization tables
  164804. * would use the preceding three routines directly.
  164805. */
  164806. {
  164807. /* Convert user 0-100 rating to percentage scaling */
  164808. quality = jpeg_quality_scaling(quality);
  164809. /* Set up standard quality tables */
  164810. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164811. }
  164812. /*
  164813. * Huffman table setup routines
  164814. */
  164815. LOCAL(void)
  164816. add_huff_table (j_compress_ptr cinfo,
  164817. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164818. /* Define a Huffman table */
  164819. {
  164820. int nsymbols, len;
  164821. if (*htblptr == NULL)
  164822. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164823. /* Copy the number-of-symbols-of-each-code-length counts */
  164824. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164825. /* Validate the counts. We do this here mainly so we can copy the right
  164826. * number of symbols from the val[] array, without risking marching off
  164827. * the end of memory. jchuff.c will do a more thorough test later.
  164828. */
  164829. nsymbols = 0;
  164830. for (len = 1; len <= 16; len++)
  164831. nsymbols += bits[len];
  164832. if (nsymbols < 1 || nsymbols > 256)
  164833. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164834. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  164835. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164836. (*htblptr)->sent_table = FALSE;
  164837. }
  164838. LOCAL(void)
  164839. std_huff_tables (j_compress_ptr cinfo)
  164840. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  164841. /* IMPORTANT: these are only valid for 8-bit data precision! */
  164842. {
  164843. static const UINT8 bits_dc_luminance[17] =
  164844. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  164845. static const UINT8 val_dc_luminance[] =
  164846. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164847. static const UINT8 bits_dc_chrominance[17] =
  164848. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  164849. static const UINT8 val_dc_chrominance[] =
  164850. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164851. static const UINT8 bits_ac_luminance[17] =
  164852. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  164853. static const UINT8 val_ac_luminance[] =
  164854. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  164855. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  164856. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  164857. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  164858. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  164859. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  164860. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  164861. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  164862. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  164863. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  164864. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  164865. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  164866. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  164867. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  164868. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  164869. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  164870. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  164871. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  164872. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  164873. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164874. 0xf9, 0xfa };
  164875. static const UINT8 bits_ac_chrominance[17] =
  164876. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  164877. static const UINT8 val_ac_chrominance[] =
  164878. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  164879. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  164880. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  164881. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  164882. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  164883. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  164884. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  164885. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  164886. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  164887. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  164888. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  164889. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  164890. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  164891. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  164892. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  164893. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  164894. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  164895. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  164896. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  164897. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164898. 0xf9, 0xfa };
  164899. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  164900. bits_dc_luminance, val_dc_luminance);
  164901. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  164902. bits_ac_luminance, val_ac_luminance);
  164903. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  164904. bits_dc_chrominance, val_dc_chrominance);
  164905. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  164906. bits_ac_chrominance, val_ac_chrominance);
  164907. }
  164908. /*
  164909. * Default parameter setup for compression.
  164910. *
  164911. * Applications that don't choose to use this routine must do their
  164912. * own setup of all these parameters. Alternately, you can call this
  164913. * to establish defaults and then alter parameters selectively. This
  164914. * is the recommended approach since, if we add any new parameters,
  164915. * your code will still work (they'll be set to reasonable defaults).
  164916. */
  164917. GLOBAL(void)
  164918. jpeg_set_defaults (j_compress_ptr cinfo)
  164919. {
  164920. int i;
  164921. /* Safety check to ensure start_compress not called yet. */
  164922. if (cinfo->global_state != CSTATE_START)
  164923. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164924. /* Allocate comp_info array large enough for maximum component count.
  164925. * Array is made permanent in case application wants to compress
  164926. * multiple images at same param settings.
  164927. */
  164928. if (cinfo->comp_info == NULL)
  164929. cinfo->comp_info = (jpeg_component_info *)
  164930. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164931. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  164932. /* Initialize everything not dependent on the color space */
  164933. cinfo->data_precision = BITS_IN_JSAMPLE;
  164934. /* Set up two quantization tables using default quality of 75 */
  164935. jpeg_set_quality(cinfo, 75, TRUE);
  164936. /* Set up two Huffman tables */
  164937. std_huff_tables(cinfo);
  164938. /* Initialize default arithmetic coding conditioning */
  164939. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164940. cinfo->arith_dc_L[i] = 0;
  164941. cinfo->arith_dc_U[i] = 1;
  164942. cinfo->arith_ac_K[i] = 5;
  164943. }
  164944. /* Default is no multiple-scan output */
  164945. cinfo->scan_info = NULL;
  164946. cinfo->num_scans = 0;
  164947. /* Expect normal source image, not raw downsampled data */
  164948. cinfo->raw_data_in = FALSE;
  164949. /* Use Huffman coding, not arithmetic coding, by default */
  164950. cinfo->arith_code = FALSE;
  164951. /* By default, don't do extra passes to optimize entropy coding */
  164952. cinfo->optimize_coding = FALSE;
  164953. /* The standard Huffman tables are only valid for 8-bit data precision.
  164954. * If the precision is higher, force optimization on so that usable
  164955. * tables will be computed. This test can be removed if default tables
  164956. * are supplied that are valid for the desired precision.
  164957. */
  164958. if (cinfo->data_precision > 8)
  164959. cinfo->optimize_coding = TRUE;
  164960. /* By default, use the simpler non-cosited sampling alignment */
  164961. cinfo->CCIR601_sampling = FALSE;
  164962. /* No input smoothing */
  164963. cinfo->smoothing_factor = 0;
  164964. /* DCT algorithm preference */
  164965. cinfo->dct_method = JDCT_DEFAULT;
  164966. /* No restart markers */
  164967. cinfo->restart_interval = 0;
  164968. cinfo->restart_in_rows = 0;
  164969. /* Fill in default JFIF marker parameters. Note that whether the marker
  164970. * will actually be written is determined by jpeg_set_colorspace.
  164971. *
  164972. * By default, the library emits JFIF version code 1.01.
  164973. * An application that wants to emit JFIF 1.02 extension markers should set
  164974. * JFIF_minor_version to 2. We could probably get away with just defaulting
  164975. * to 1.02, but there may still be some decoders in use that will complain
  164976. * about that; saying 1.01 should minimize compatibility problems.
  164977. */
  164978. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  164979. cinfo->JFIF_minor_version = 1;
  164980. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  164981. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  164982. cinfo->Y_density = 1;
  164983. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  164984. jpeg_default_colorspace(cinfo);
  164985. }
  164986. /*
  164987. * Select an appropriate JPEG colorspace for in_color_space.
  164988. */
  164989. GLOBAL(void)
  164990. jpeg_default_colorspace (j_compress_ptr cinfo)
  164991. {
  164992. switch (cinfo->in_color_space) {
  164993. case JCS_GRAYSCALE:
  164994. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  164995. break;
  164996. case JCS_RGB:
  164997. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164998. break;
  164999. case JCS_YCbCr:
  165000. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165001. break;
  165002. case JCS_CMYK:
  165003. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165004. break;
  165005. case JCS_YCCK:
  165006. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165007. break;
  165008. case JCS_UNKNOWN:
  165009. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165010. break;
  165011. default:
  165012. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165013. }
  165014. }
  165015. /*
  165016. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165017. */
  165018. GLOBAL(void)
  165019. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165020. {
  165021. jpeg_component_info * compptr;
  165022. int ci;
  165023. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165024. (compptr = &cinfo->comp_info[index], \
  165025. compptr->component_id = (id), \
  165026. compptr->h_samp_factor = (hsamp), \
  165027. compptr->v_samp_factor = (vsamp), \
  165028. compptr->quant_tbl_no = (quant), \
  165029. compptr->dc_tbl_no = (dctbl), \
  165030. compptr->ac_tbl_no = (actbl) )
  165031. /* Safety check to ensure start_compress not called yet. */
  165032. if (cinfo->global_state != CSTATE_START)
  165033. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165034. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165035. * tables 1 for chrominance components.
  165036. */
  165037. cinfo->jpeg_color_space = colorspace;
  165038. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165039. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165040. switch (colorspace) {
  165041. case JCS_GRAYSCALE:
  165042. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165043. cinfo->num_components = 1;
  165044. /* JFIF specifies component ID 1 */
  165045. SET_COMP(0, 1, 1,1, 0, 0,0);
  165046. break;
  165047. case JCS_RGB:
  165048. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165049. cinfo->num_components = 3;
  165050. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165051. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165052. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165053. break;
  165054. case JCS_YCbCr:
  165055. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165056. cinfo->num_components = 3;
  165057. /* JFIF specifies component IDs 1,2,3 */
  165058. /* We default to 2x2 subsamples of chrominance */
  165059. SET_COMP(0, 1, 2,2, 0, 0,0);
  165060. SET_COMP(1, 2, 1,1, 1, 1,1);
  165061. SET_COMP(2, 3, 1,1, 1, 1,1);
  165062. break;
  165063. case JCS_CMYK:
  165064. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165065. cinfo->num_components = 4;
  165066. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165067. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165068. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165069. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165070. break;
  165071. case JCS_YCCK:
  165072. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165073. cinfo->num_components = 4;
  165074. SET_COMP(0, 1, 2,2, 0, 0,0);
  165075. SET_COMP(1, 2, 1,1, 1, 1,1);
  165076. SET_COMP(2, 3, 1,1, 1, 1,1);
  165077. SET_COMP(3, 4, 2,2, 0, 0,0);
  165078. break;
  165079. case JCS_UNKNOWN:
  165080. cinfo->num_components = cinfo->input_components;
  165081. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165082. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165083. MAX_COMPONENTS);
  165084. for (ci = 0; ci < cinfo->num_components; ci++) {
  165085. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165086. }
  165087. break;
  165088. default:
  165089. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165090. }
  165091. }
  165092. #ifdef C_PROGRESSIVE_SUPPORTED
  165093. LOCAL(jpeg_scan_info *)
  165094. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165095. int Ss, int Se, int Ah, int Al)
  165096. /* Support routine: generate one scan for specified component */
  165097. {
  165098. scanptr->comps_in_scan = 1;
  165099. scanptr->component_index[0] = ci;
  165100. scanptr->Ss = Ss;
  165101. scanptr->Se = Se;
  165102. scanptr->Ah = Ah;
  165103. scanptr->Al = Al;
  165104. scanptr++;
  165105. return scanptr;
  165106. }
  165107. LOCAL(jpeg_scan_info *)
  165108. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165109. int Ss, int Se, int Ah, int Al)
  165110. /* Support routine: generate one scan for each component */
  165111. {
  165112. int ci;
  165113. for (ci = 0; ci < ncomps; ci++) {
  165114. scanptr->comps_in_scan = 1;
  165115. scanptr->component_index[0] = ci;
  165116. scanptr->Ss = Ss;
  165117. scanptr->Se = Se;
  165118. scanptr->Ah = Ah;
  165119. scanptr->Al = Al;
  165120. scanptr++;
  165121. }
  165122. return scanptr;
  165123. }
  165124. LOCAL(jpeg_scan_info *)
  165125. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165126. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165127. {
  165128. int ci;
  165129. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165130. /* Single interleaved DC scan */
  165131. scanptr->comps_in_scan = ncomps;
  165132. for (ci = 0; ci < ncomps; ci++)
  165133. scanptr->component_index[ci] = ci;
  165134. scanptr->Ss = scanptr->Se = 0;
  165135. scanptr->Ah = Ah;
  165136. scanptr->Al = Al;
  165137. scanptr++;
  165138. } else {
  165139. /* Noninterleaved DC scan for each component */
  165140. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165141. }
  165142. return scanptr;
  165143. }
  165144. /*
  165145. * Create a recommended progressive-JPEG script.
  165146. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165147. */
  165148. GLOBAL(void)
  165149. jpeg_simple_progression (j_compress_ptr cinfo)
  165150. {
  165151. int ncomps = cinfo->num_components;
  165152. int nscans;
  165153. jpeg_scan_info * scanptr;
  165154. /* Safety check to ensure start_compress not called yet. */
  165155. if (cinfo->global_state != CSTATE_START)
  165156. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165157. /* Figure space needed for script. Calculation must match code below! */
  165158. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165159. /* Custom script for YCbCr color images. */
  165160. nscans = 10;
  165161. } else {
  165162. /* All-purpose script for other color spaces. */
  165163. if (ncomps > MAX_COMPS_IN_SCAN)
  165164. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165165. else
  165166. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165167. }
  165168. /* Allocate space for script.
  165169. * We need to put it in the permanent pool in case the application performs
  165170. * multiple compressions without changing the settings. To avoid a memory
  165171. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165172. * object, we try to re-use previously allocated space, and we allocate
  165173. * enough space to handle YCbCr even if initially asked for grayscale.
  165174. */
  165175. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165176. cinfo->script_space_size = MAX(nscans, 10);
  165177. cinfo->script_space = (jpeg_scan_info *)
  165178. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165179. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165180. }
  165181. scanptr = cinfo->script_space;
  165182. cinfo->scan_info = scanptr;
  165183. cinfo->num_scans = nscans;
  165184. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165185. /* Custom script for YCbCr color images. */
  165186. /* Initial DC scan */
  165187. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165188. /* Initial AC scan: get some luma data out in a hurry */
  165189. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165190. /* Chroma data is too small to be worth expending many scans on */
  165191. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165192. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165193. /* Complete spectral selection for luma AC */
  165194. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165195. /* Refine next bit of luma AC */
  165196. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165197. /* Finish DC successive approximation */
  165198. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165199. /* Finish AC successive approximation */
  165200. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165201. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165202. /* Luma bottom bit comes last since it's usually largest scan */
  165203. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165204. } else {
  165205. /* All-purpose script for other color spaces. */
  165206. /* Successive approximation first pass */
  165207. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165208. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165209. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165210. /* Successive approximation second pass */
  165211. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165212. /* Successive approximation final pass */
  165213. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165214. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165215. }
  165216. }
  165217. #endif /* C_PROGRESSIVE_SUPPORTED */
  165218. /*** End of inlined file: jcparam.c ***/
  165219. /*** Start of inlined file: jcphuff.c ***/
  165220. #define JPEG_INTERNALS
  165221. #ifdef C_PROGRESSIVE_SUPPORTED
  165222. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165223. typedef struct {
  165224. struct jpeg_entropy_encoder pub; /* public fields */
  165225. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165226. boolean gather_statistics;
  165227. /* Bit-level coding status.
  165228. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165229. */
  165230. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165231. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165232. INT32 put_buffer; /* current bit-accumulation buffer */
  165233. int put_bits; /* # of bits now in it */
  165234. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165235. /* Coding status for DC components */
  165236. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165237. /* Coding status for AC components */
  165238. int ac_tbl_no; /* the table number of the single component */
  165239. unsigned int EOBRUN; /* run length of EOBs */
  165240. unsigned int BE; /* # of buffered correction bits before MCU */
  165241. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165242. /* packing correction bits tightly would save some space but cost time... */
  165243. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165244. int next_restart_num; /* next restart number to write (0-7) */
  165245. /* Pointers to derived tables (these workspaces have image lifespan).
  165246. * Since any one scan codes only DC or only AC, we only need one set
  165247. * of tables, not one for DC and one for AC.
  165248. */
  165249. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165250. /* Statistics tables for optimization; again, one set is enough */
  165251. long * count_ptrs[NUM_HUFF_TBLS];
  165252. } phuff_entropy_encoder;
  165253. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165254. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165255. * buffer can hold. Larger sizes may slightly improve compression, but
  165256. * 1000 is already well into the realm of overkill.
  165257. * The minimum safe size is 64 bits.
  165258. */
  165259. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165260. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165261. * We assume that int right shift is unsigned if INT32 right shift is,
  165262. * which should be safe.
  165263. */
  165264. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165265. #define ISHIFT_TEMPS int ishift_temp;
  165266. #define IRIGHT_SHIFT(x,shft) \
  165267. ((ishift_temp = (x)) < 0 ? \
  165268. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165269. (ishift_temp >> (shft)))
  165270. #else
  165271. #define ISHIFT_TEMPS
  165272. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165273. #endif
  165274. /* Forward declarations */
  165275. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165276. JBLOCKROW *MCU_data));
  165277. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165278. JBLOCKROW *MCU_data));
  165279. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165280. JBLOCKROW *MCU_data));
  165281. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165282. JBLOCKROW *MCU_data));
  165283. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165284. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165285. /*
  165286. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165287. */
  165288. METHODDEF(void)
  165289. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165290. {
  165291. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165292. boolean is_DC_band;
  165293. int ci, tbl;
  165294. jpeg_component_info * compptr;
  165295. entropy->cinfo = cinfo;
  165296. entropy->gather_statistics = gather_statistics;
  165297. is_DC_band = (cinfo->Ss == 0);
  165298. /* We assume jcmaster.c already validated the scan parameters. */
  165299. /* Select execution routines */
  165300. if (cinfo->Ah == 0) {
  165301. if (is_DC_band)
  165302. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165303. else
  165304. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165305. } else {
  165306. if (is_DC_band)
  165307. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165308. else {
  165309. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165310. /* AC refinement needs a correction bit buffer */
  165311. if (entropy->bit_buffer == NULL)
  165312. entropy->bit_buffer = (char *)
  165313. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165314. MAX_CORR_BITS * SIZEOF(char));
  165315. }
  165316. }
  165317. if (gather_statistics)
  165318. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165319. else
  165320. entropy->pub.finish_pass = finish_pass_phuff;
  165321. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165322. * for AC coefficients.
  165323. */
  165324. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165325. compptr = cinfo->cur_comp_info[ci];
  165326. /* Initialize DC predictions to 0 */
  165327. entropy->last_dc_val[ci] = 0;
  165328. /* Get table index */
  165329. if (is_DC_band) {
  165330. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165331. continue;
  165332. tbl = compptr->dc_tbl_no;
  165333. } else {
  165334. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165335. }
  165336. if (gather_statistics) {
  165337. /* Check for invalid table index */
  165338. /* (make_c_derived_tbl does this in the other path) */
  165339. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165340. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165341. /* Allocate and zero the statistics tables */
  165342. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165343. if (entropy->count_ptrs[tbl] == NULL)
  165344. entropy->count_ptrs[tbl] = (long *)
  165345. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165346. 257 * SIZEOF(long));
  165347. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165348. } else {
  165349. /* Compute derived values for Huffman table */
  165350. /* We may do this more than once for a table, but it's not expensive */
  165351. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165352. & entropy->derived_tbls[tbl]);
  165353. }
  165354. }
  165355. /* Initialize AC stuff */
  165356. entropy->EOBRUN = 0;
  165357. entropy->BE = 0;
  165358. /* Initialize bit buffer to empty */
  165359. entropy->put_buffer = 0;
  165360. entropy->put_bits = 0;
  165361. /* Initialize restart stuff */
  165362. entropy->restarts_to_go = cinfo->restart_interval;
  165363. entropy->next_restart_num = 0;
  165364. }
  165365. /* Outputting bytes to the file.
  165366. * NB: these must be called only when actually outputting,
  165367. * that is, entropy->gather_statistics == FALSE.
  165368. */
  165369. /* Emit a byte */
  165370. #define emit_byte(entropy,val) \
  165371. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165372. if (--(entropy)->free_in_buffer == 0) \
  165373. dump_buffer_p(entropy); }
  165374. LOCAL(void)
  165375. dump_buffer_p (phuff_entropy_ptr entropy)
  165376. /* Empty the output buffer; we do not support suspension in this module. */
  165377. {
  165378. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165379. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165380. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165381. /* After a successful buffer dump, must reset buffer pointers */
  165382. entropy->next_output_byte = dest->next_output_byte;
  165383. entropy->free_in_buffer = dest->free_in_buffer;
  165384. }
  165385. /* Outputting bits to the file */
  165386. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165387. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165388. * in one call, and we never retain more than 7 bits in put_buffer
  165389. * between calls, so 24 bits are sufficient.
  165390. */
  165391. INLINE
  165392. LOCAL(void)
  165393. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165394. /* Emit some bits, unless we are in gather mode */
  165395. {
  165396. /* This routine is heavily used, so it's worth coding tightly. */
  165397. register INT32 put_buffer = (INT32) code;
  165398. register int put_bits = entropy->put_bits;
  165399. /* if size is 0, caller used an invalid Huffman table entry */
  165400. if (size == 0)
  165401. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165402. if (entropy->gather_statistics)
  165403. return; /* do nothing if we're only getting stats */
  165404. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165405. put_bits += size; /* new number of bits in buffer */
  165406. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165407. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165408. while (put_bits >= 8) {
  165409. int c = (int) ((put_buffer >> 16) & 0xFF);
  165410. emit_byte(entropy, c);
  165411. if (c == 0xFF) { /* need to stuff a zero byte? */
  165412. emit_byte(entropy, 0);
  165413. }
  165414. put_buffer <<= 8;
  165415. put_bits -= 8;
  165416. }
  165417. entropy->put_buffer = put_buffer; /* update variables */
  165418. entropy->put_bits = put_bits;
  165419. }
  165420. LOCAL(void)
  165421. flush_bits_p (phuff_entropy_ptr entropy)
  165422. {
  165423. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165424. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165425. entropy->put_bits = 0;
  165426. }
  165427. /*
  165428. * Emit (or just count) a Huffman symbol.
  165429. */
  165430. INLINE
  165431. LOCAL(void)
  165432. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165433. {
  165434. if (entropy->gather_statistics)
  165435. entropy->count_ptrs[tbl_no][symbol]++;
  165436. else {
  165437. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165438. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165439. }
  165440. }
  165441. /*
  165442. * Emit bits from a correction bit buffer.
  165443. */
  165444. LOCAL(void)
  165445. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165446. unsigned int nbits)
  165447. {
  165448. if (entropy->gather_statistics)
  165449. return; /* no real work */
  165450. while (nbits > 0) {
  165451. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165452. bufstart++;
  165453. nbits--;
  165454. }
  165455. }
  165456. /*
  165457. * Emit any pending EOBRUN symbol.
  165458. */
  165459. LOCAL(void)
  165460. emit_eobrun (phuff_entropy_ptr entropy)
  165461. {
  165462. register int temp, nbits;
  165463. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165464. temp = entropy->EOBRUN;
  165465. nbits = 0;
  165466. while ((temp >>= 1))
  165467. nbits++;
  165468. /* safety check: shouldn't happen given limited correction-bit buffer */
  165469. if (nbits > 14)
  165470. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165471. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165472. if (nbits)
  165473. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165474. entropy->EOBRUN = 0;
  165475. /* Emit any buffered correction bits */
  165476. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165477. entropy->BE = 0;
  165478. }
  165479. }
  165480. /*
  165481. * Emit a restart marker & resynchronize predictions.
  165482. */
  165483. LOCAL(void)
  165484. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165485. {
  165486. int ci;
  165487. emit_eobrun(entropy);
  165488. if (! entropy->gather_statistics) {
  165489. flush_bits_p(entropy);
  165490. emit_byte(entropy, 0xFF);
  165491. emit_byte(entropy, JPEG_RST0 + restart_num);
  165492. }
  165493. if (entropy->cinfo->Ss == 0) {
  165494. /* Re-initialize DC predictions to 0 */
  165495. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165496. entropy->last_dc_val[ci] = 0;
  165497. } else {
  165498. /* Re-initialize all AC-related fields to 0 */
  165499. entropy->EOBRUN = 0;
  165500. entropy->BE = 0;
  165501. }
  165502. }
  165503. /*
  165504. * MCU encoding for DC initial scan (either spectral selection,
  165505. * or first pass of successive approximation).
  165506. */
  165507. METHODDEF(boolean)
  165508. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165509. {
  165510. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165511. register int temp, temp2;
  165512. register int nbits;
  165513. int blkn, ci;
  165514. int Al = cinfo->Al;
  165515. JBLOCKROW block;
  165516. jpeg_component_info * compptr;
  165517. ISHIFT_TEMPS
  165518. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165519. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165520. /* Emit restart marker if needed */
  165521. if (cinfo->restart_interval)
  165522. if (entropy->restarts_to_go == 0)
  165523. emit_restart_p(entropy, entropy->next_restart_num);
  165524. /* Encode the MCU data blocks */
  165525. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165526. block = MCU_data[blkn];
  165527. ci = cinfo->MCU_membership[blkn];
  165528. compptr = cinfo->cur_comp_info[ci];
  165529. /* Compute the DC value after the required point transform by Al.
  165530. * This is simply an arithmetic right shift.
  165531. */
  165532. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165533. /* DC differences are figured on the point-transformed values. */
  165534. temp = temp2 - entropy->last_dc_val[ci];
  165535. entropy->last_dc_val[ci] = temp2;
  165536. /* Encode the DC coefficient difference per section G.1.2.1 */
  165537. temp2 = temp;
  165538. if (temp < 0) {
  165539. temp = -temp; /* temp is abs value of input */
  165540. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165541. /* This code assumes we are on a two's complement machine */
  165542. temp2--;
  165543. }
  165544. /* Find the number of bits needed for the magnitude of the coefficient */
  165545. nbits = 0;
  165546. while (temp) {
  165547. nbits++;
  165548. temp >>= 1;
  165549. }
  165550. /* Check for out-of-range coefficient values.
  165551. * Since we're encoding a difference, the range limit is twice as much.
  165552. */
  165553. if (nbits > MAX_COEF_BITS+1)
  165554. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165555. /* Count/emit the Huffman-coded symbol for the number of bits */
  165556. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165557. /* Emit that number of bits of the value, if positive, */
  165558. /* or the complement of its magnitude, if negative. */
  165559. if (nbits) /* emit_bits rejects calls with size 0 */
  165560. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165561. }
  165562. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165563. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165564. /* Update restart-interval state too */
  165565. if (cinfo->restart_interval) {
  165566. if (entropy->restarts_to_go == 0) {
  165567. entropy->restarts_to_go = cinfo->restart_interval;
  165568. entropy->next_restart_num++;
  165569. entropy->next_restart_num &= 7;
  165570. }
  165571. entropy->restarts_to_go--;
  165572. }
  165573. return TRUE;
  165574. }
  165575. /*
  165576. * MCU encoding for AC initial scan (either spectral selection,
  165577. * or first pass of successive approximation).
  165578. */
  165579. METHODDEF(boolean)
  165580. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165581. {
  165582. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165583. register int temp, temp2;
  165584. register int nbits;
  165585. register int r, k;
  165586. int Se = cinfo->Se;
  165587. int Al = cinfo->Al;
  165588. JBLOCKROW block;
  165589. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165590. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165591. /* Emit restart marker if needed */
  165592. if (cinfo->restart_interval)
  165593. if (entropy->restarts_to_go == 0)
  165594. emit_restart_p(entropy, entropy->next_restart_num);
  165595. /* Encode the MCU data block */
  165596. block = MCU_data[0];
  165597. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165598. r = 0; /* r = run length of zeros */
  165599. for (k = cinfo->Ss; k <= Se; k++) {
  165600. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165601. r++;
  165602. continue;
  165603. }
  165604. /* We must apply the point transform by Al. For AC coefficients this
  165605. * is an integer division with rounding towards 0. To do this portably
  165606. * in C, we shift after obtaining the absolute value; so the code is
  165607. * interwoven with finding the abs value (temp) and output bits (temp2).
  165608. */
  165609. if (temp < 0) {
  165610. temp = -temp; /* temp is abs value of input */
  165611. temp >>= Al; /* apply the point transform */
  165612. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165613. temp2 = ~temp;
  165614. } else {
  165615. temp >>= Al; /* apply the point transform */
  165616. temp2 = temp;
  165617. }
  165618. /* Watch out for case that nonzero coef is zero after point transform */
  165619. if (temp == 0) {
  165620. r++;
  165621. continue;
  165622. }
  165623. /* Emit any pending EOBRUN */
  165624. if (entropy->EOBRUN > 0)
  165625. emit_eobrun(entropy);
  165626. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165627. while (r > 15) {
  165628. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165629. r -= 16;
  165630. }
  165631. /* Find the number of bits needed for the magnitude of the coefficient */
  165632. nbits = 1; /* there must be at least one 1 bit */
  165633. while ((temp >>= 1))
  165634. nbits++;
  165635. /* Check for out-of-range coefficient values */
  165636. if (nbits > MAX_COEF_BITS)
  165637. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165638. /* Count/emit Huffman symbol for run length / number of bits */
  165639. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165640. /* Emit that number of bits of the value, if positive, */
  165641. /* or the complement of its magnitude, if negative. */
  165642. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165643. r = 0; /* reset zero run length */
  165644. }
  165645. if (r > 0) { /* If there are trailing zeroes, */
  165646. entropy->EOBRUN++; /* count an EOB */
  165647. if (entropy->EOBRUN == 0x7FFF)
  165648. emit_eobrun(entropy); /* force it out to avoid overflow */
  165649. }
  165650. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165651. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165652. /* Update restart-interval state too */
  165653. if (cinfo->restart_interval) {
  165654. if (entropy->restarts_to_go == 0) {
  165655. entropy->restarts_to_go = cinfo->restart_interval;
  165656. entropy->next_restart_num++;
  165657. entropy->next_restart_num &= 7;
  165658. }
  165659. entropy->restarts_to_go--;
  165660. }
  165661. return TRUE;
  165662. }
  165663. /*
  165664. * MCU encoding for DC successive approximation refinement scan.
  165665. * Note: we assume such scans can be multi-component, although the spec
  165666. * is not very clear on the point.
  165667. */
  165668. METHODDEF(boolean)
  165669. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165670. {
  165671. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165672. register int temp;
  165673. int blkn;
  165674. int Al = cinfo->Al;
  165675. JBLOCKROW block;
  165676. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165677. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165678. /* Emit restart marker if needed */
  165679. if (cinfo->restart_interval)
  165680. if (entropy->restarts_to_go == 0)
  165681. emit_restart_p(entropy, entropy->next_restart_num);
  165682. /* Encode the MCU data blocks */
  165683. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165684. block = MCU_data[blkn];
  165685. /* We simply emit the Al'th bit of the DC coefficient value. */
  165686. temp = (*block)[0];
  165687. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165688. }
  165689. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165690. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165691. /* Update restart-interval state too */
  165692. if (cinfo->restart_interval) {
  165693. if (entropy->restarts_to_go == 0) {
  165694. entropy->restarts_to_go = cinfo->restart_interval;
  165695. entropy->next_restart_num++;
  165696. entropy->next_restart_num &= 7;
  165697. }
  165698. entropy->restarts_to_go--;
  165699. }
  165700. return TRUE;
  165701. }
  165702. /*
  165703. * MCU encoding for AC successive approximation refinement scan.
  165704. */
  165705. METHODDEF(boolean)
  165706. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165707. {
  165708. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165709. register int temp;
  165710. register int r, k;
  165711. int EOB;
  165712. char *BR_buffer;
  165713. unsigned int BR;
  165714. int Se = cinfo->Se;
  165715. int Al = cinfo->Al;
  165716. JBLOCKROW block;
  165717. int absvalues[DCTSIZE2];
  165718. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165719. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165720. /* Emit restart marker if needed */
  165721. if (cinfo->restart_interval)
  165722. if (entropy->restarts_to_go == 0)
  165723. emit_restart_p(entropy, entropy->next_restart_num);
  165724. /* Encode the MCU data block */
  165725. block = MCU_data[0];
  165726. /* It is convenient to make a pre-pass to determine the transformed
  165727. * coefficients' absolute values and the EOB position.
  165728. */
  165729. EOB = 0;
  165730. for (k = cinfo->Ss; k <= Se; k++) {
  165731. temp = (*block)[jpeg_natural_order[k]];
  165732. /* We must apply the point transform by Al. For AC coefficients this
  165733. * is an integer division with rounding towards 0. To do this portably
  165734. * in C, we shift after obtaining the absolute value.
  165735. */
  165736. if (temp < 0)
  165737. temp = -temp; /* temp is abs value of input */
  165738. temp >>= Al; /* apply the point transform */
  165739. absvalues[k] = temp; /* save abs value for main pass */
  165740. if (temp == 1)
  165741. EOB = k; /* EOB = index of last newly-nonzero coef */
  165742. }
  165743. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165744. r = 0; /* r = run length of zeros */
  165745. BR = 0; /* BR = count of buffered bits added now */
  165746. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165747. for (k = cinfo->Ss; k <= Se; k++) {
  165748. if ((temp = absvalues[k]) == 0) {
  165749. r++;
  165750. continue;
  165751. }
  165752. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165753. while (r > 15 && k <= EOB) {
  165754. /* emit any pending EOBRUN and the BE correction bits */
  165755. emit_eobrun(entropy);
  165756. /* Emit ZRL */
  165757. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165758. r -= 16;
  165759. /* Emit buffered correction bits that must be associated with ZRL */
  165760. emit_buffered_bits(entropy, BR_buffer, BR);
  165761. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165762. BR = 0;
  165763. }
  165764. /* If the coef was previously nonzero, it only needs a correction bit.
  165765. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165766. * that we also need to test r > 15. But if r > 15, we can only get here
  165767. * if k > EOB, which implies that this coefficient is not 1.
  165768. */
  165769. if (temp > 1) {
  165770. /* The correction bit is the next bit of the absolute value. */
  165771. BR_buffer[BR++] = (char) (temp & 1);
  165772. continue;
  165773. }
  165774. /* Emit any pending EOBRUN and the BE correction bits */
  165775. emit_eobrun(entropy);
  165776. /* Count/emit Huffman symbol for run length / number of bits */
  165777. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165778. /* Emit output bit for newly-nonzero coef */
  165779. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165780. emit_bits_p(entropy, (unsigned int) temp, 1);
  165781. /* Emit buffered correction bits that must be associated with this code */
  165782. emit_buffered_bits(entropy, BR_buffer, BR);
  165783. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165784. BR = 0;
  165785. r = 0; /* reset zero run length */
  165786. }
  165787. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165788. entropy->EOBRUN++; /* count an EOB */
  165789. entropy->BE += BR; /* concat my correction bits to older ones */
  165790. /* We force out the EOB if we risk either:
  165791. * 1. overflow of the EOB counter;
  165792. * 2. overflow of the correction bit buffer during the next MCU.
  165793. */
  165794. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165795. emit_eobrun(entropy);
  165796. }
  165797. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165798. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165799. /* Update restart-interval state too */
  165800. if (cinfo->restart_interval) {
  165801. if (entropy->restarts_to_go == 0) {
  165802. entropy->restarts_to_go = cinfo->restart_interval;
  165803. entropy->next_restart_num++;
  165804. entropy->next_restart_num &= 7;
  165805. }
  165806. entropy->restarts_to_go--;
  165807. }
  165808. return TRUE;
  165809. }
  165810. /*
  165811. * Finish up at the end of a Huffman-compressed progressive scan.
  165812. */
  165813. METHODDEF(void)
  165814. finish_pass_phuff (j_compress_ptr cinfo)
  165815. {
  165816. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165817. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165818. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165819. /* Flush out any buffered data */
  165820. emit_eobrun(entropy);
  165821. flush_bits_p(entropy);
  165822. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165823. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165824. }
  165825. /*
  165826. * Finish up a statistics-gathering pass and create the new Huffman tables.
  165827. */
  165828. METHODDEF(void)
  165829. finish_pass_gather_phuff (j_compress_ptr cinfo)
  165830. {
  165831. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165832. boolean is_DC_band;
  165833. int ci, tbl;
  165834. jpeg_component_info * compptr;
  165835. JHUFF_TBL **htblptr;
  165836. boolean did[NUM_HUFF_TBLS];
  165837. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  165838. emit_eobrun(entropy);
  165839. is_DC_band = (cinfo->Ss == 0);
  165840. /* It's important not to apply jpeg_gen_optimal_table more than once
  165841. * per table, because it clobbers the input frequency counts!
  165842. */
  165843. MEMZERO(did, SIZEOF(did));
  165844. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165845. compptr = cinfo->cur_comp_info[ci];
  165846. if (is_DC_band) {
  165847. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165848. continue;
  165849. tbl = compptr->dc_tbl_no;
  165850. } else {
  165851. tbl = compptr->ac_tbl_no;
  165852. }
  165853. if (! did[tbl]) {
  165854. if (is_DC_band)
  165855. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  165856. else
  165857. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  165858. if (*htblptr == NULL)
  165859. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165860. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  165861. did[tbl] = TRUE;
  165862. }
  165863. }
  165864. }
  165865. /*
  165866. * Module initialization routine for progressive Huffman entropy encoding.
  165867. */
  165868. GLOBAL(void)
  165869. jinit_phuff_encoder (j_compress_ptr cinfo)
  165870. {
  165871. phuff_entropy_ptr entropy;
  165872. int i;
  165873. entropy = (phuff_entropy_ptr)
  165874. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165875. SIZEOF(phuff_entropy_encoder));
  165876. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  165877. entropy->pub.start_pass = start_pass_phuff;
  165878. /* Mark tables unallocated */
  165879. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165880. entropy->derived_tbls[i] = NULL;
  165881. entropy->count_ptrs[i] = NULL;
  165882. }
  165883. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  165884. }
  165885. #endif /* C_PROGRESSIVE_SUPPORTED */
  165886. /*** End of inlined file: jcphuff.c ***/
  165887. /*** Start of inlined file: jcprepct.c ***/
  165888. #define JPEG_INTERNALS
  165889. /* At present, jcsample.c can request context rows only for smoothing.
  165890. * In the future, we might also need context rows for CCIR601 sampling
  165891. * or other more-complex downsampling procedures. The code to support
  165892. * context rows should be compiled only if needed.
  165893. */
  165894. #ifdef INPUT_SMOOTHING_SUPPORTED
  165895. #define CONTEXT_ROWS_SUPPORTED
  165896. #endif
  165897. /*
  165898. * For the simple (no-context-row) case, we just need to buffer one
  165899. * row group's worth of pixels for the downsampling step. At the bottom of
  165900. * the image, we pad to a full row group by replicating the last pixel row.
  165901. * The downsampler's last output row is then replicated if needed to pad
  165902. * out to a full iMCU row.
  165903. *
  165904. * When providing context rows, we must buffer three row groups' worth of
  165905. * pixels. Three row groups are physically allocated, but the row pointer
  165906. * arrays are made five row groups high, with the extra pointers above and
  165907. * below "wrapping around" to point to the last and first real row groups.
  165908. * This allows the downsampler to access the proper context rows.
  165909. * At the top and bottom of the image, we create dummy context rows by
  165910. * copying the first or last real pixel row. This copying could be avoided
  165911. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  165912. * trouble on the compression side.
  165913. */
  165914. /* Private buffer controller object */
  165915. typedef struct {
  165916. struct jpeg_c_prep_controller pub; /* public fields */
  165917. /* Downsampling input buffer. This buffer holds color-converted data
  165918. * until we have enough to do a downsample step.
  165919. */
  165920. JSAMPARRAY color_buf[MAX_COMPONENTS];
  165921. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  165922. int next_buf_row; /* index of next row to store in color_buf */
  165923. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  165924. int this_row_group; /* starting row index of group to process */
  165925. int next_buf_stop; /* downsample when we reach this index */
  165926. #endif
  165927. } my_prep_controller;
  165928. typedef my_prep_controller * my_prep_ptr;
  165929. /*
  165930. * Initialize for a processing pass.
  165931. */
  165932. METHODDEF(void)
  165933. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165934. {
  165935. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165936. if (pass_mode != JBUF_PASS_THRU)
  165937. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165938. /* Initialize total-height counter for detecting bottom of image */
  165939. prep->rows_to_go = cinfo->image_height;
  165940. /* Mark the conversion buffer empty */
  165941. prep->next_buf_row = 0;
  165942. #ifdef CONTEXT_ROWS_SUPPORTED
  165943. /* Preset additional state variables for context mode.
  165944. * These aren't used in non-context mode, so we needn't test which mode.
  165945. */
  165946. prep->this_row_group = 0;
  165947. /* Set next_buf_stop to stop after two row groups have been read in. */
  165948. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  165949. #endif
  165950. }
  165951. /*
  165952. * Expand an image vertically from height input_rows to height output_rows,
  165953. * by duplicating the bottom row.
  165954. */
  165955. LOCAL(void)
  165956. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  165957. int input_rows, int output_rows)
  165958. {
  165959. register int row;
  165960. for (row = input_rows; row < output_rows; row++) {
  165961. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  165962. 1, num_cols);
  165963. }
  165964. }
  165965. /*
  165966. * Process some data in the simple no-context case.
  165967. *
  165968. * Preprocessor output data is counted in "row groups". A row group
  165969. * is defined to be v_samp_factor sample rows of each component.
  165970. * Downsampling will produce this much data from each max_v_samp_factor
  165971. * input rows.
  165972. */
  165973. METHODDEF(void)
  165974. pre_process_data (j_compress_ptr cinfo,
  165975. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165976. JDIMENSION in_rows_avail,
  165977. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165978. JDIMENSION out_row_groups_avail)
  165979. {
  165980. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165981. int numrows, ci;
  165982. JDIMENSION inrows;
  165983. jpeg_component_info * compptr;
  165984. while (*in_row_ctr < in_rows_avail &&
  165985. *out_row_group_ctr < out_row_groups_avail) {
  165986. /* Do color conversion to fill the conversion buffer. */
  165987. inrows = in_rows_avail - *in_row_ctr;
  165988. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  165989. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165990. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165991. prep->color_buf,
  165992. (JDIMENSION) prep->next_buf_row,
  165993. numrows);
  165994. *in_row_ctr += numrows;
  165995. prep->next_buf_row += numrows;
  165996. prep->rows_to_go -= numrows;
  165997. /* If at bottom of image, pad to fill the conversion buffer. */
  165998. if (prep->rows_to_go == 0 &&
  165999. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166000. for (ci = 0; ci < cinfo->num_components; ci++) {
  166001. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166002. prep->next_buf_row, cinfo->max_v_samp_factor);
  166003. }
  166004. prep->next_buf_row = cinfo->max_v_samp_factor;
  166005. }
  166006. /* If we've filled the conversion buffer, empty it. */
  166007. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166008. (*cinfo->downsample->downsample) (cinfo,
  166009. prep->color_buf, (JDIMENSION) 0,
  166010. output_buf, *out_row_group_ctr);
  166011. prep->next_buf_row = 0;
  166012. (*out_row_group_ctr)++;
  166013. }
  166014. /* If at bottom of image, pad the output to a full iMCU height.
  166015. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166016. */
  166017. if (prep->rows_to_go == 0 &&
  166018. *out_row_group_ctr < out_row_groups_avail) {
  166019. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166020. ci++, compptr++) {
  166021. expand_bottom_edge(output_buf[ci],
  166022. compptr->width_in_blocks * DCTSIZE,
  166023. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166024. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166025. }
  166026. *out_row_group_ctr = out_row_groups_avail;
  166027. break; /* can exit outer loop without test */
  166028. }
  166029. }
  166030. }
  166031. #ifdef CONTEXT_ROWS_SUPPORTED
  166032. /*
  166033. * Process some data in the context case.
  166034. */
  166035. METHODDEF(void)
  166036. pre_process_context (j_compress_ptr cinfo,
  166037. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166038. JDIMENSION in_rows_avail,
  166039. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166040. JDIMENSION out_row_groups_avail)
  166041. {
  166042. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166043. int numrows, ci;
  166044. int buf_height = cinfo->max_v_samp_factor * 3;
  166045. JDIMENSION inrows;
  166046. while (*out_row_group_ctr < out_row_groups_avail) {
  166047. if (*in_row_ctr < in_rows_avail) {
  166048. /* Do color conversion to fill the conversion buffer. */
  166049. inrows = in_rows_avail - *in_row_ctr;
  166050. numrows = prep->next_buf_stop - prep->next_buf_row;
  166051. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166052. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166053. prep->color_buf,
  166054. (JDIMENSION) prep->next_buf_row,
  166055. numrows);
  166056. /* Pad at top of image, if first time through */
  166057. if (prep->rows_to_go == cinfo->image_height) {
  166058. for (ci = 0; ci < cinfo->num_components; ci++) {
  166059. int row;
  166060. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166061. jcopy_sample_rows(prep->color_buf[ci], 0,
  166062. prep->color_buf[ci], -row,
  166063. 1, cinfo->image_width);
  166064. }
  166065. }
  166066. }
  166067. *in_row_ctr += numrows;
  166068. prep->next_buf_row += numrows;
  166069. prep->rows_to_go -= numrows;
  166070. } else {
  166071. /* Return for more data, unless we are at the bottom of the image. */
  166072. if (prep->rows_to_go != 0)
  166073. break;
  166074. /* When at bottom of image, pad to fill the conversion buffer. */
  166075. if (prep->next_buf_row < prep->next_buf_stop) {
  166076. for (ci = 0; ci < cinfo->num_components; ci++) {
  166077. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166078. prep->next_buf_row, prep->next_buf_stop);
  166079. }
  166080. prep->next_buf_row = prep->next_buf_stop;
  166081. }
  166082. }
  166083. /* If we've gotten enough data, downsample a row group. */
  166084. if (prep->next_buf_row == prep->next_buf_stop) {
  166085. (*cinfo->downsample->downsample) (cinfo,
  166086. prep->color_buf,
  166087. (JDIMENSION) prep->this_row_group,
  166088. output_buf, *out_row_group_ctr);
  166089. (*out_row_group_ctr)++;
  166090. /* Advance pointers with wraparound as necessary. */
  166091. prep->this_row_group += cinfo->max_v_samp_factor;
  166092. if (prep->this_row_group >= buf_height)
  166093. prep->this_row_group = 0;
  166094. if (prep->next_buf_row >= buf_height)
  166095. prep->next_buf_row = 0;
  166096. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166097. }
  166098. }
  166099. }
  166100. /*
  166101. * Create the wrapped-around downsampling input buffer needed for context mode.
  166102. */
  166103. LOCAL(void)
  166104. create_context_buffer (j_compress_ptr cinfo)
  166105. {
  166106. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166107. int rgroup_height = cinfo->max_v_samp_factor;
  166108. int ci, i;
  166109. jpeg_component_info * compptr;
  166110. JSAMPARRAY true_buffer, fake_buffer;
  166111. /* Grab enough space for fake row pointers for all the components;
  166112. * we need five row groups' worth of pointers for each component.
  166113. */
  166114. fake_buffer = (JSAMPARRAY)
  166115. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166116. (cinfo->num_components * 5 * rgroup_height) *
  166117. SIZEOF(JSAMPROW));
  166118. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166119. ci++, compptr++) {
  166120. /* Allocate the actual buffer space (3 row groups) for this component.
  166121. * We make the buffer wide enough to allow the downsampler to edge-expand
  166122. * horizontally within the buffer, if it so chooses.
  166123. */
  166124. true_buffer = (*cinfo->mem->alloc_sarray)
  166125. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166126. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166127. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166128. (JDIMENSION) (3 * rgroup_height));
  166129. /* Copy true buffer row pointers into the middle of the fake row array */
  166130. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166131. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166132. /* Fill in the above and below wraparound pointers */
  166133. for (i = 0; i < rgroup_height; i++) {
  166134. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166135. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166136. }
  166137. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166138. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166139. }
  166140. }
  166141. #endif /* CONTEXT_ROWS_SUPPORTED */
  166142. /*
  166143. * Initialize preprocessing controller.
  166144. */
  166145. GLOBAL(void)
  166146. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166147. {
  166148. my_prep_ptr prep;
  166149. int ci;
  166150. jpeg_component_info * compptr;
  166151. if (need_full_buffer) /* safety check */
  166152. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166153. prep = (my_prep_ptr)
  166154. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166155. SIZEOF(my_prep_controller));
  166156. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166157. prep->pub.start_pass = start_pass_prep;
  166158. /* Allocate the color conversion buffer.
  166159. * We make the buffer wide enough to allow the downsampler to edge-expand
  166160. * horizontally within the buffer, if it so chooses.
  166161. */
  166162. if (cinfo->downsample->need_context_rows) {
  166163. /* Set up to provide context rows */
  166164. #ifdef CONTEXT_ROWS_SUPPORTED
  166165. prep->pub.pre_process_data = pre_process_context;
  166166. create_context_buffer(cinfo);
  166167. #else
  166168. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166169. #endif
  166170. } else {
  166171. /* No context, just make it tall enough for one row group */
  166172. prep->pub.pre_process_data = pre_process_data;
  166173. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166174. ci++, compptr++) {
  166175. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166176. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166177. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166178. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166179. (JDIMENSION) cinfo->max_v_samp_factor);
  166180. }
  166181. }
  166182. }
  166183. /*** End of inlined file: jcprepct.c ***/
  166184. /*** Start of inlined file: jcsample.c ***/
  166185. #define JPEG_INTERNALS
  166186. /* Pointer to routine to downsample a single component */
  166187. typedef JMETHOD(void, downsample1_ptr,
  166188. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166189. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166190. /* Private subobject */
  166191. typedef struct {
  166192. struct jpeg_downsampler pub; /* public fields */
  166193. /* Downsampling method pointers, one per component */
  166194. downsample1_ptr methods[MAX_COMPONENTS];
  166195. } my_downsampler;
  166196. typedef my_downsampler * my_downsample_ptr;
  166197. /*
  166198. * Initialize for a downsampling pass.
  166199. */
  166200. METHODDEF(void)
  166201. start_pass_downsample (j_compress_ptr)
  166202. {
  166203. /* no work for now */
  166204. }
  166205. /*
  166206. * Expand a component horizontally from width input_cols to width output_cols,
  166207. * by duplicating the rightmost samples.
  166208. */
  166209. LOCAL(void)
  166210. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166211. JDIMENSION input_cols, JDIMENSION output_cols)
  166212. {
  166213. register JSAMPROW ptr;
  166214. register JSAMPLE pixval;
  166215. register int count;
  166216. int row;
  166217. int numcols = (int) (output_cols - input_cols);
  166218. if (numcols > 0) {
  166219. for (row = 0; row < num_rows; row++) {
  166220. ptr = image_data[row] + input_cols;
  166221. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166222. for (count = numcols; count > 0; count--)
  166223. *ptr++ = pixval;
  166224. }
  166225. }
  166226. }
  166227. /*
  166228. * Do downsampling for a whole row group (all components).
  166229. *
  166230. * In this version we simply downsample each component independently.
  166231. */
  166232. METHODDEF(void)
  166233. sep_downsample (j_compress_ptr cinfo,
  166234. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166235. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166236. {
  166237. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166238. int ci;
  166239. jpeg_component_info * compptr;
  166240. JSAMPARRAY in_ptr, out_ptr;
  166241. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166242. ci++, compptr++) {
  166243. in_ptr = input_buf[ci] + in_row_index;
  166244. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166245. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166246. }
  166247. }
  166248. /*
  166249. * Downsample pixel values of a single component.
  166250. * One row group is processed per call.
  166251. * This version handles arbitrary integral sampling ratios, without smoothing.
  166252. * Note that this version is not actually used for customary sampling ratios.
  166253. */
  166254. METHODDEF(void)
  166255. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166256. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166257. {
  166258. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166259. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166260. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166261. JSAMPROW inptr, outptr;
  166262. INT32 outvalue;
  166263. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166264. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166265. numpix = h_expand * v_expand;
  166266. numpix2 = numpix/2;
  166267. /* Expand input data enough to let all the output samples be generated
  166268. * by the standard loop. Special-casing padded output would be more
  166269. * efficient.
  166270. */
  166271. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166272. cinfo->image_width, output_cols * h_expand);
  166273. inrow = 0;
  166274. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166275. outptr = output_data[outrow];
  166276. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166277. outcol++, outcol_h += h_expand) {
  166278. outvalue = 0;
  166279. for (v = 0; v < v_expand; v++) {
  166280. inptr = input_data[inrow+v] + outcol_h;
  166281. for (h = 0; h < h_expand; h++) {
  166282. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166283. }
  166284. }
  166285. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166286. }
  166287. inrow += v_expand;
  166288. }
  166289. }
  166290. /*
  166291. * Downsample pixel values of a single component.
  166292. * This version handles the special case of a full-size component,
  166293. * without smoothing.
  166294. */
  166295. METHODDEF(void)
  166296. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166297. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166298. {
  166299. /* Copy the data */
  166300. jcopy_sample_rows(input_data, 0, output_data, 0,
  166301. cinfo->max_v_samp_factor, cinfo->image_width);
  166302. /* Edge-expand */
  166303. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166304. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166305. }
  166306. /*
  166307. * Downsample pixel values of a single component.
  166308. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166309. * without smoothing.
  166310. *
  166311. * A note about the "bias" calculations: when rounding fractional values to
  166312. * integer, we do not want to always round 0.5 up to the next integer.
  166313. * If we did that, we'd introduce a noticeable bias towards larger values.
  166314. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166315. * alternate pixel locations (a simple ordered dither pattern).
  166316. */
  166317. METHODDEF(void)
  166318. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166319. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166320. {
  166321. int outrow;
  166322. JDIMENSION outcol;
  166323. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166324. register JSAMPROW inptr, outptr;
  166325. register int bias;
  166326. /* Expand input data enough to let all the output samples be generated
  166327. * by the standard loop. Special-casing padded output would be more
  166328. * efficient.
  166329. */
  166330. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166331. cinfo->image_width, output_cols * 2);
  166332. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166333. outptr = output_data[outrow];
  166334. inptr = input_data[outrow];
  166335. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166336. for (outcol = 0; outcol < output_cols; outcol++) {
  166337. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166338. + bias) >> 1);
  166339. bias ^= 1; /* 0=>1, 1=>0 */
  166340. inptr += 2;
  166341. }
  166342. }
  166343. }
  166344. /*
  166345. * Downsample pixel values of a single component.
  166346. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166347. * without smoothing.
  166348. */
  166349. METHODDEF(void)
  166350. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166351. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166352. {
  166353. int inrow, outrow;
  166354. JDIMENSION outcol;
  166355. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166356. register JSAMPROW inptr0, inptr1, outptr;
  166357. register int bias;
  166358. /* Expand input data enough to let all the output samples be generated
  166359. * by the standard loop. Special-casing padded output would be more
  166360. * efficient.
  166361. */
  166362. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166363. cinfo->image_width, output_cols * 2);
  166364. inrow = 0;
  166365. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166366. outptr = output_data[outrow];
  166367. inptr0 = input_data[inrow];
  166368. inptr1 = input_data[inrow+1];
  166369. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166370. for (outcol = 0; outcol < output_cols; outcol++) {
  166371. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166372. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166373. + bias) >> 2);
  166374. bias ^= 3; /* 1=>2, 2=>1 */
  166375. inptr0 += 2; inptr1 += 2;
  166376. }
  166377. inrow += 2;
  166378. }
  166379. }
  166380. #ifdef INPUT_SMOOTHING_SUPPORTED
  166381. /*
  166382. * Downsample pixel values of a single component.
  166383. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166384. * with smoothing. One row of context is required.
  166385. */
  166386. METHODDEF(void)
  166387. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166388. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166389. {
  166390. int inrow, outrow;
  166391. JDIMENSION colctr;
  166392. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166393. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166394. INT32 membersum, neighsum, memberscale, neighscale;
  166395. /* Expand input data enough to let all the output samples be generated
  166396. * by the standard loop. Special-casing padded output would be more
  166397. * efficient.
  166398. */
  166399. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166400. cinfo->image_width, output_cols * 2);
  166401. /* We don't bother to form the individual "smoothed" input pixel values;
  166402. * we can directly compute the output which is the average of the four
  166403. * smoothed values. Each of the four member pixels contributes a fraction
  166404. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166405. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166406. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166407. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166408. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166409. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166410. * factors are scaled by 2^16 = 65536.
  166411. * Also recall that SF = smoothing_factor / 1024.
  166412. */
  166413. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166414. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166415. inrow = 0;
  166416. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166417. outptr = output_data[outrow];
  166418. inptr0 = input_data[inrow];
  166419. inptr1 = input_data[inrow+1];
  166420. above_ptr = input_data[inrow-1];
  166421. below_ptr = input_data[inrow+2];
  166422. /* Special case for first column: pretend column -1 is same as column 0 */
  166423. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166424. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166425. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166426. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166427. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166428. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166429. neighsum += neighsum;
  166430. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166431. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166432. membersum = membersum * memberscale + neighsum * neighscale;
  166433. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166434. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166435. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166436. /* sum of pixels directly mapped to this output element */
  166437. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166438. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166439. /* sum of edge-neighbor pixels */
  166440. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166441. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166442. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166443. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166444. /* The edge-neighbors count twice as much as corner-neighbors */
  166445. neighsum += neighsum;
  166446. /* Add in the corner-neighbors */
  166447. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166448. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166449. /* form final output scaled up by 2^16 */
  166450. membersum = membersum * memberscale + neighsum * neighscale;
  166451. /* round, descale and output it */
  166452. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166453. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166454. }
  166455. /* Special case for last column */
  166456. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166457. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166458. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166459. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166460. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166461. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166462. neighsum += neighsum;
  166463. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166464. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166465. membersum = membersum * memberscale + neighsum * neighscale;
  166466. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166467. inrow += 2;
  166468. }
  166469. }
  166470. /*
  166471. * Downsample pixel values of a single component.
  166472. * This version handles the special case of a full-size component,
  166473. * with smoothing. One row of context is required.
  166474. */
  166475. METHODDEF(void)
  166476. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166477. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166478. {
  166479. int outrow;
  166480. JDIMENSION colctr;
  166481. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166482. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166483. INT32 membersum, neighsum, memberscale, neighscale;
  166484. int colsum, lastcolsum, nextcolsum;
  166485. /* Expand input data enough to let all the output samples be generated
  166486. * by the standard loop. Special-casing padded output would be more
  166487. * efficient.
  166488. */
  166489. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166490. cinfo->image_width, output_cols);
  166491. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166492. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166493. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166494. * Also recall that SF = smoothing_factor / 1024.
  166495. */
  166496. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166497. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166498. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166499. outptr = output_data[outrow];
  166500. inptr = input_data[outrow];
  166501. above_ptr = input_data[outrow-1];
  166502. below_ptr = input_data[outrow+1];
  166503. /* Special case for first column */
  166504. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166505. GETJSAMPLE(*inptr);
  166506. membersum = GETJSAMPLE(*inptr++);
  166507. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166508. GETJSAMPLE(*inptr);
  166509. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166510. membersum = membersum * memberscale + neighsum * neighscale;
  166511. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166512. lastcolsum = colsum; colsum = nextcolsum;
  166513. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166514. membersum = GETJSAMPLE(*inptr++);
  166515. above_ptr++; below_ptr++;
  166516. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166517. GETJSAMPLE(*inptr);
  166518. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166519. membersum = membersum * memberscale + neighsum * neighscale;
  166520. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166521. lastcolsum = colsum; colsum = nextcolsum;
  166522. }
  166523. /* Special case for last column */
  166524. membersum = GETJSAMPLE(*inptr);
  166525. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166526. membersum = membersum * memberscale + neighsum * neighscale;
  166527. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166528. }
  166529. }
  166530. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166531. /*
  166532. * Module initialization routine for downsampling.
  166533. * Note that we must select a routine for each component.
  166534. */
  166535. GLOBAL(void)
  166536. jinit_downsampler (j_compress_ptr cinfo)
  166537. {
  166538. my_downsample_ptr downsample;
  166539. int ci;
  166540. jpeg_component_info * compptr;
  166541. boolean smoothok = TRUE;
  166542. downsample = (my_downsample_ptr)
  166543. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166544. SIZEOF(my_downsampler));
  166545. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166546. downsample->pub.start_pass = start_pass_downsample;
  166547. downsample->pub.downsample = sep_downsample;
  166548. downsample->pub.need_context_rows = FALSE;
  166549. if (cinfo->CCIR601_sampling)
  166550. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166551. /* Verify we can handle the sampling factors, and set up method pointers */
  166552. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166553. ci++, compptr++) {
  166554. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166555. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166556. #ifdef INPUT_SMOOTHING_SUPPORTED
  166557. if (cinfo->smoothing_factor) {
  166558. downsample->methods[ci] = fullsize_smooth_downsample;
  166559. downsample->pub.need_context_rows = TRUE;
  166560. } else
  166561. #endif
  166562. downsample->methods[ci] = fullsize_downsample;
  166563. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166564. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166565. smoothok = FALSE;
  166566. downsample->methods[ci] = h2v1_downsample;
  166567. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166568. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166569. #ifdef INPUT_SMOOTHING_SUPPORTED
  166570. if (cinfo->smoothing_factor) {
  166571. downsample->methods[ci] = h2v2_smooth_downsample;
  166572. downsample->pub.need_context_rows = TRUE;
  166573. } else
  166574. #endif
  166575. downsample->methods[ci] = h2v2_downsample;
  166576. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166577. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166578. smoothok = FALSE;
  166579. downsample->methods[ci] = int_downsample;
  166580. } else
  166581. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166582. }
  166583. #ifdef INPUT_SMOOTHING_SUPPORTED
  166584. if (cinfo->smoothing_factor && !smoothok)
  166585. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166586. #endif
  166587. }
  166588. /*** End of inlined file: jcsample.c ***/
  166589. /*** Start of inlined file: jctrans.c ***/
  166590. #define JPEG_INTERNALS
  166591. /* Forward declarations */
  166592. LOCAL(void) transencode_master_selection
  166593. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166594. LOCAL(void) transencode_coef_controller
  166595. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166596. /*
  166597. * Compression initialization for writing raw-coefficient data.
  166598. * Before calling this, all parameters and a data destination must be set up.
  166599. * Call jpeg_finish_compress() to actually write the data.
  166600. *
  166601. * The number of passed virtual arrays must match cinfo->num_components.
  166602. * Note that the virtual arrays need not be filled or even realized at
  166603. * the time write_coefficients is called; indeed, if the virtual arrays
  166604. * were requested from this compression object's memory manager, they
  166605. * typically will be realized during this routine and filled afterwards.
  166606. */
  166607. GLOBAL(void)
  166608. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166609. {
  166610. if (cinfo->global_state != CSTATE_START)
  166611. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166612. /* Mark all tables to be written */
  166613. jpeg_suppress_tables(cinfo, FALSE);
  166614. /* (Re)initialize error mgr and destination modules */
  166615. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166616. (*cinfo->dest->init_destination) (cinfo);
  166617. /* Perform master selection of active modules */
  166618. transencode_master_selection(cinfo, coef_arrays);
  166619. /* Wait for jpeg_finish_compress() call */
  166620. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166621. cinfo->global_state = CSTATE_WRCOEFS;
  166622. }
  166623. /*
  166624. * Initialize the compression object with default parameters,
  166625. * then copy from the source object all parameters needed for lossless
  166626. * transcoding. Parameters that can be varied without loss (such as
  166627. * scan script and Huffman optimization) are left in their default states.
  166628. */
  166629. GLOBAL(void)
  166630. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166631. j_compress_ptr dstinfo)
  166632. {
  166633. JQUANT_TBL ** qtblptr;
  166634. jpeg_component_info *incomp, *outcomp;
  166635. JQUANT_TBL *c_quant, *slot_quant;
  166636. int tblno, ci, coefi;
  166637. /* Safety check to ensure start_compress not called yet. */
  166638. if (dstinfo->global_state != CSTATE_START)
  166639. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166640. /* Copy fundamental image dimensions */
  166641. dstinfo->image_width = srcinfo->image_width;
  166642. dstinfo->image_height = srcinfo->image_height;
  166643. dstinfo->input_components = srcinfo->num_components;
  166644. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166645. /* Initialize all parameters to default values */
  166646. jpeg_set_defaults(dstinfo);
  166647. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166648. * Fix it to get the right header markers for the image colorspace.
  166649. */
  166650. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166651. dstinfo->data_precision = srcinfo->data_precision;
  166652. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166653. /* Copy the source's quantization tables. */
  166654. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166655. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166656. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166657. if (*qtblptr == NULL)
  166658. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166659. MEMCOPY((*qtblptr)->quantval,
  166660. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166661. SIZEOF((*qtblptr)->quantval));
  166662. (*qtblptr)->sent_table = FALSE;
  166663. }
  166664. }
  166665. /* Copy the source's per-component info.
  166666. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166667. */
  166668. dstinfo->num_components = srcinfo->num_components;
  166669. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166670. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166671. MAX_COMPONENTS);
  166672. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166673. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166674. outcomp->component_id = incomp->component_id;
  166675. outcomp->h_samp_factor = incomp->h_samp_factor;
  166676. outcomp->v_samp_factor = incomp->v_samp_factor;
  166677. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166678. /* Make sure saved quantization table for component matches the qtable
  166679. * slot. If not, the input file re-used this qtable slot.
  166680. * IJG encoder currently cannot duplicate this.
  166681. */
  166682. tblno = outcomp->quant_tbl_no;
  166683. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166684. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166685. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166686. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166687. c_quant = incomp->quant_table;
  166688. if (c_quant != NULL) {
  166689. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166690. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166691. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166692. }
  166693. }
  166694. /* Note: we do not copy the source's Huffman table assignments;
  166695. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166696. */
  166697. }
  166698. /* Also copy JFIF version and resolution information, if available.
  166699. * Strictly speaking this isn't "critical" info, but it's nearly
  166700. * always appropriate to copy it if available. In particular,
  166701. * if the application chooses to copy JFIF 1.02 extension markers from
  166702. * the source file, we need to copy the version to make sure we don't
  166703. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166704. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166705. */
  166706. if (srcinfo->saw_JFIF_marker) {
  166707. if (srcinfo->JFIF_major_version == 1) {
  166708. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166709. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166710. }
  166711. dstinfo->density_unit = srcinfo->density_unit;
  166712. dstinfo->X_density = srcinfo->X_density;
  166713. dstinfo->Y_density = srcinfo->Y_density;
  166714. }
  166715. }
  166716. /*
  166717. * Master selection of compression modules for transcoding.
  166718. * This substitutes for jcinit.c's initialization of the full compressor.
  166719. */
  166720. LOCAL(void)
  166721. transencode_master_selection (j_compress_ptr cinfo,
  166722. jvirt_barray_ptr * coef_arrays)
  166723. {
  166724. /* Although we don't actually use input_components for transcoding,
  166725. * jcmaster.c's initial_setup will complain if input_components is 0.
  166726. */
  166727. cinfo->input_components = 1;
  166728. /* Initialize master control (includes parameter checking/processing) */
  166729. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166730. /* Entropy encoding: either Huffman or arithmetic coding. */
  166731. if (cinfo->arith_code) {
  166732. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166733. } else {
  166734. if (cinfo->progressive_mode) {
  166735. #ifdef C_PROGRESSIVE_SUPPORTED
  166736. jinit_phuff_encoder(cinfo);
  166737. #else
  166738. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166739. #endif
  166740. } else
  166741. jinit_huff_encoder(cinfo);
  166742. }
  166743. /* We need a special coefficient buffer controller. */
  166744. transencode_coef_controller(cinfo, coef_arrays);
  166745. jinit_marker_writer(cinfo);
  166746. /* We can now tell the memory manager to allocate virtual arrays. */
  166747. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166748. /* Write the datastream header (SOI, JFIF) immediately.
  166749. * Frame and scan headers are postponed till later.
  166750. * This lets application insert special markers after the SOI.
  166751. */
  166752. (*cinfo->marker->write_file_header) (cinfo);
  166753. }
  166754. /*
  166755. * The rest of this file is a special implementation of the coefficient
  166756. * buffer controller. This is similar to jccoefct.c, but it handles only
  166757. * output from presupplied virtual arrays. Furthermore, we generate any
  166758. * dummy padding blocks on-the-fly rather than expecting them to be present
  166759. * in the arrays.
  166760. */
  166761. /* Private buffer controller object */
  166762. typedef struct {
  166763. struct jpeg_c_coef_controller pub; /* public fields */
  166764. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166765. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166766. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166767. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166768. /* Virtual block array for each component. */
  166769. jvirt_barray_ptr * whole_image;
  166770. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166771. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166772. } my_coef_controller2;
  166773. typedef my_coef_controller2 * my_coef_ptr2;
  166774. LOCAL(void)
  166775. start_iMCU_row2 (j_compress_ptr cinfo)
  166776. /* Reset within-iMCU-row counters for a new row */
  166777. {
  166778. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166779. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166780. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166781. * But at the bottom of the image, process only what's left.
  166782. */
  166783. if (cinfo->comps_in_scan > 1) {
  166784. coef->MCU_rows_per_iMCU_row = 1;
  166785. } else {
  166786. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166787. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166788. else
  166789. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166790. }
  166791. coef->mcu_ctr = 0;
  166792. coef->MCU_vert_offset = 0;
  166793. }
  166794. /*
  166795. * Initialize for a processing pass.
  166796. */
  166797. METHODDEF(void)
  166798. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166799. {
  166800. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166801. if (pass_mode != JBUF_CRANK_DEST)
  166802. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166803. coef->iMCU_row_num = 0;
  166804. start_iMCU_row2(cinfo);
  166805. }
  166806. /*
  166807. * Process some data.
  166808. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166809. * per call, ie, v_samp_factor block rows for each component in the scan.
  166810. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166811. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166812. *
  166813. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166814. */
  166815. METHODDEF(boolean)
  166816. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166817. {
  166818. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166819. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166820. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166821. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166822. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166823. JDIMENSION start_col;
  166824. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  166825. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  166826. JBLOCKROW buffer_ptr;
  166827. jpeg_component_info *compptr;
  166828. /* Align the virtual buffers for the components used in this scan. */
  166829. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166830. compptr = cinfo->cur_comp_info[ci];
  166831. buffer[ci] = (*cinfo->mem->access_virt_barray)
  166832. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  166833. coef->iMCU_row_num * compptr->v_samp_factor,
  166834. (JDIMENSION) compptr->v_samp_factor, FALSE);
  166835. }
  166836. /* Loop to process one whole iMCU row */
  166837. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  166838. yoffset++) {
  166839. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  166840. MCU_col_num++) {
  166841. /* Construct list of pointers to DCT blocks belonging to this MCU */
  166842. blkn = 0; /* index of current DCT block within MCU */
  166843. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166844. compptr = cinfo->cur_comp_info[ci];
  166845. start_col = MCU_col_num * compptr->MCU_width;
  166846. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  166847. : compptr->last_col_width;
  166848. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  166849. if (coef->iMCU_row_num < last_iMCU_row ||
  166850. yindex+yoffset < compptr->last_row_height) {
  166851. /* Fill in pointers to real blocks in this row */
  166852. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  166853. for (xindex = 0; xindex < blockcnt; xindex++)
  166854. MCU_buffer[blkn++] = buffer_ptr++;
  166855. } else {
  166856. /* At bottom of image, need a whole row of dummy blocks */
  166857. xindex = 0;
  166858. }
  166859. /* Fill in any dummy blocks needed in this row.
  166860. * Dummy blocks are filled in the same way as in jccoefct.c:
  166861. * all zeroes in the AC entries, DC entries equal to previous
  166862. * block's DC value. The init routine has already zeroed the
  166863. * AC entries, so we need only set the DC entries correctly.
  166864. */
  166865. for (; xindex < compptr->MCU_width; xindex++) {
  166866. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  166867. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  166868. blkn++;
  166869. }
  166870. }
  166871. }
  166872. /* Try to write the MCU. */
  166873. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  166874. /* Suspension forced; update state counters and exit */
  166875. coef->MCU_vert_offset = yoffset;
  166876. coef->mcu_ctr = MCU_col_num;
  166877. return FALSE;
  166878. }
  166879. }
  166880. /* Completed an MCU row, but perhaps not an iMCU row */
  166881. coef->mcu_ctr = 0;
  166882. }
  166883. /* Completed the iMCU row, advance counters for next one */
  166884. coef->iMCU_row_num++;
  166885. start_iMCU_row2(cinfo);
  166886. return TRUE;
  166887. }
  166888. /*
  166889. * Initialize coefficient buffer controller.
  166890. *
  166891. * Each passed coefficient array must be the right size for that
  166892. * coefficient: width_in_blocks wide and height_in_blocks high,
  166893. * with unitheight at least v_samp_factor.
  166894. */
  166895. LOCAL(void)
  166896. transencode_coef_controller (j_compress_ptr cinfo,
  166897. jvirt_barray_ptr * coef_arrays)
  166898. {
  166899. my_coef_ptr2 coef;
  166900. JBLOCKROW buffer;
  166901. int i;
  166902. coef = (my_coef_ptr2)
  166903. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166904. SIZEOF(my_coef_controller2));
  166905. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  166906. coef->pub.start_pass = start_pass_coef2;
  166907. coef->pub.compress_data = compress_output2;
  166908. /* Save pointer to virtual arrays */
  166909. coef->whole_image = coef_arrays;
  166910. /* Allocate and pre-zero space for dummy DCT blocks. */
  166911. buffer = (JBLOCKROW)
  166912. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166913. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166914. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166915. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  166916. coef->dummy_buffer[i] = buffer + i;
  166917. }
  166918. }
  166919. /*** End of inlined file: jctrans.c ***/
  166920. /*** Start of inlined file: jdapistd.c ***/
  166921. #define JPEG_INTERNALS
  166922. /* Forward declarations */
  166923. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  166924. /*
  166925. * Decompression initialization.
  166926. * jpeg_read_header must be completed before calling this.
  166927. *
  166928. * If a multipass operating mode was selected, this will do all but the
  166929. * last pass, and thus may take a great deal of time.
  166930. *
  166931. * Returns FALSE if suspended. The return value need be inspected only if
  166932. * a suspending data source is used.
  166933. */
  166934. GLOBAL(boolean)
  166935. jpeg_start_decompress (j_decompress_ptr cinfo)
  166936. {
  166937. if (cinfo->global_state == DSTATE_READY) {
  166938. /* First call: initialize master control, select active modules */
  166939. jinit_master_decompress(cinfo);
  166940. if (cinfo->buffered_image) {
  166941. /* No more work here; expecting jpeg_start_output next */
  166942. cinfo->global_state = DSTATE_BUFIMAGE;
  166943. return TRUE;
  166944. }
  166945. cinfo->global_state = DSTATE_PRELOAD;
  166946. }
  166947. if (cinfo->global_state == DSTATE_PRELOAD) {
  166948. /* If file has multiple scans, absorb them all into the coef buffer */
  166949. if (cinfo->inputctl->has_multiple_scans) {
  166950. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166951. for (;;) {
  166952. int retcode;
  166953. /* Call progress monitor hook if present */
  166954. if (cinfo->progress != NULL)
  166955. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166956. /* Absorb some more input */
  166957. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166958. if (retcode == JPEG_SUSPENDED)
  166959. return FALSE;
  166960. if (retcode == JPEG_REACHED_EOI)
  166961. break;
  166962. /* Advance progress counter if appropriate */
  166963. if (cinfo->progress != NULL &&
  166964. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  166965. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  166966. /* jdmaster underestimated number of scans; ratchet up one scan */
  166967. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  166968. }
  166969. }
  166970. }
  166971. #else
  166972. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166973. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166974. }
  166975. cinfo->output_scan_number = cinfo->input_scan_number;
  166976. } else if (cinfo->global_state != DSTATE_PRESCAN)
  166977. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166978. /* Perform any dummy output passes, and set up for the final pass */
  166979. return output_pass_setup(cinfo);
  166980. }
  166981. /*
  166982. * Set up for an output pass, and perform any dummy pass(es) needed.
  166983. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  166984. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  166985. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  166986. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  166987. */
  166988. LOCAL(boolean)
  166989. output_pass_setup (j_decompress_ptr cinfo)
  166990. {
  166991. if (cinfo->global_state != DSTATE_PRESCAN) {
  166992. /* First call: do pass setup */
  166993. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166994. cinfo->output_scanline = 0;
  166995. cinfo->global_state = DSTATE_PRESCAN;
  166996. }
  166997. /* Loop over any required dummy passes */
  166998. while (cinfo->master->is_dummy_pass) {
  166999. #ifdef QUANT_2PASS_SUPPORTED
  167000. /* Crank through the dummy pass */
  167001. while (cinfo->output_scanline < cinfo->output_height) {
  167002. JDIMENSION last_scanline;
  167003. /* Call progress monitor hook if present */
  167004. if (cinfo->progress != NULL) {
  167005. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167006. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167007. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167008. }
  167009. /* Process some data */
  167010. last_scanline = cinfo->output_scanline;
  167011. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167012. &cinfo->output_scanline, (JDIMENSION) 0);
  167013. if (cinfo->output_scanline == last_scanline)
  167014. return FALSE; /* No progress made, must suspend */
  167015. }
  167016. /* Finish up dummy pass, and set up for another one */
  167017. (*cinfo->master->finish_output_pass) (cinfo);
  167018. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167019. cinfo->output_scanline = 0;
  167020. #else
  167021. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167022. #endif /* QUANT_2PASS_SUPPORTED */
  167023. }
  167024. /* Ready for application to drive output pass through
  167025. * jpeg_read_scanlines or jpeg_read_raw_data.
  167026. */
  167027. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167028. return TRUE;
  167029. }
  167030. /*
  167031. * Read some scanlines of data from the JPEG decompressor.
  167032. *
  167033. * The return value will be the number of lines actually read.
  167034. * This may be less than the number requested in several cases,
  167035. * including bottom of image, data source suspension, and operating
  167036. * modes that emit multiple scanlines at a time.
  167037. *
  167038. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167039. * this likely signals an application programmer error. However,
  167040. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167041. */
  167042. GLOBAL(JDIMENSION)
  167043. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167044. JDIMENSION max_lines)
  167045. {
  167046. JDIMENSION row_ctr;
  167047. if (cinfo->global_state != DSTATE_SCANNING)
  167048. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167049. if (cinfo->output_scanline >= cinfo->output_height) {
  167050. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167051. return 0;
  167052. }
  167053. /* Call progress monitor hook if present */
  167054. if (cinfo->progress != NULL) {
  167055. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167056. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167057. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167058. }
  167059. /* Process some data */
  167060. row_ctr = 0;
  167061. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167062. cinfo->output_scanline += row_ctr;
  167063. return row_ctr;
  167064. }
  167065. /*
  167066. * Alternate entry point to read raw data.
  167067. * Processes exactly one iMCU row per call, unless suspended.
  167068. */
  167069. GLOBAL(JDIMENSION)
  167070. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167071. JDIMENSION max_lines)
  167072. {
  167073. JDIMENSION lines_per_iMCU_row;
  167074. if (cinfo->global_state != DSTATE_RAW_OK)
  167075. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167076. if (cinfo->output_scanline >= cinfo->output_height) {
  167077. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167078. return 0;
  167079. }
  167080. /* Call progress monitor hook if present */
  167081. if (cinfo->progress != NULL) {
  167082. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167083. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167084. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167085. }
  167086. /* Verify that at least one iMCU row can be returned. */
  167087. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167088. if (max_lines < lines_per_iMCU_row)
  167089. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167090. /* Decompress directly into user's buffer. */
  167091. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167092. return 0; /* suspension forced, can do nothing more */
  167093. /* OK, we processed one iMCU row. */
  167094. cinfo->output_scanline += lines_per_iMCU_row;
  167095. return lines_per_iMCU_row;
  167096. }
  167097. /* Additional entry points for buffered-image mode. */
  167098. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167099. /*
  167100. * Initialize for an output pass in buffered-image mode.
  167101. */
  167102. GLOBAL(boolean)
  167103. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167104. {
  167105. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167106. cinfo->global_state != DSTATE_PRESCAN)
  167107. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167108. /* Limit scan number to valid range */
  167109. if (scan_number <= 0)
  167110. scan_number = 1;
  167111. if (cinfo->inputctl->eoi_reached &&
  167112. scan_number > cinfo->input_scan_number)
  167113. scan_number = cinfo->input_scan_number;
  167114. cinfo->output_scan_number = scan_number;
  167115. /* Perform any dummy output passes, and set up for the real pass */
  167116. return output_pass_setup(cinfo);
  167117. }
  167118. /*
  167119. * Finish up after an output pass in buffered-image mode.
  167120. *
  167121. * Returns FALSE if suspended. The return value need be inspected only if
  167122. * a suspending data source is used.
  167123. */
  167124. GLOBAL(boolean)
  167125. jpeg_finish_output (j_decompress_ptr cinfo)
  167126. {
  167127. if ((cinfo->global_state == DSTATE_SCANNING ||
  167128. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167129. /* Terminate this pass. */
  167130. /* We do not require the whole pass to have been completed. */
  167131. (*cinfo->master->finish_output_pass) (cinfo);
  167132. cinfo->global_state = DSTATE_BUFPOST;
  167133. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167134. /* BUFPOST = repeat call after a suspension, anything else is error */
  167135. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167136. }
  167137. /* Read markers looking for SOS or EOI */
  167138. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167139. ! cinfo->inputctl->eoi_reached) {
  167140. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167141. return FALSE; /* Suspend, come back later */
  167142. }
  167143. cinfo->global_state = DSTATE_BUFIMAGE;
  167144. return TRUE;
  167145. }
  167146. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167147. /*** End of inlined file: jdapistd.c ***/
  167148. /*** Start of inlined file: jdapimin.c ***/
  167149. #define JPEG_INTERNALS
  167150. /*
  167151. * Initialization of a JPEG decompression object.
  167152. * The error manager must already be set up (in case memory manager fails).
  167153. */
  167154. GLOBAL(void)
  167155. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167156. {
  167157. int i;
  167158. /* Guard against version mismatches between library and caller. */
  167159. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167160. if (version != JPEG_LIB_VERSION)
  167161. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167162. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167163. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167164. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167165. /* For debugging purposes, we zero the whole master structure.
  167166. * But the application has already set the err pointer, and may have set
  167167. * client_data, so we have to save and restore those fields.
  167168. * Note: if application hasn't set client_data, tools like Purify may
  167169. * complain here.
  167170. */
  167171. {
  167172. struct jpeg_error_mgr * err = cinfo->err;
  167173. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167174. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167175. cinfo->err = err;
  167176. cinfo->client_data = client_data;
  167177. }
  167178. cinfo->is_decompressor = TRUE;
  167179. /* Initialize a memory manager instance for this object */
  167180. jinit_memory_mgr((j_common_ptr) cinfo);
  167181. /* Zero out pointers to permanent structures. */
  167182. cinfo->progress = NULL;
  167183. cinfo->src = NULL;
  167184. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167185. cinfo->quant_tbl_ptrs[i] = NULL;
  167186. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167187. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167188. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167189. }
  167190. /* Initialize marker processor so application can override methods
  167191. * for COM, APPn markers before calling jpeg_read_header.
  167192. */
  167193. cinfo->marker_list = NULL;
  167194. jinit_marker_reader(cinfo);
  167195. /* And initialize the overall input controller. */
  167196. jinit_input_controller(cinfo);
  167197. /* OK, I'm ready */
  167198. cinfo->global_state = DSTATE_START;
  167199. }
  167200. /*
  167201. * Destruction of a JPEG decompression object
  167202. */
  167203. GLOBAL(void)
  167204. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167205. {
  167206. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167207. }
  167208. /*
  167209. * Abort processing of a JPEG decompression operation,
  167210. * but don't destroy the object itself.
  167211. */
  167212. GLOBAL(void)
  167213. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167214. {
  167215. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167216. }
  167217. /*
  167218. * Set default decompression parameters.
  167219. */
  167220. LOCAL(void)
  167221. default_decompress_parms (j_decompress_ptr cinfo)
  167222. {
  167223. /* Guess the input colorspace, and set output colorspace accordingly. */
  167224. /* (Wish JPEG committee had provided a real way to specify this...) */
  167225. /* Note application may override our guesses. */
  167226. switch (cinfo->num_components) {
  167227. case 1:
  167228. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167229. cinfo->out_color_space = JCS_GRAYSCALE;
  167230. break;
  167231. case 3:
  167232. if (cinfo->saw_JFIF_marker) {
  167233. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167234. } else if (cinfo->saw_Adobe_marker) {
  167235. switch (cinfo->Adobe_transform) {
  167236. case 0:
  167237. cinfo->jpeg_color_space = JCS_RGB;
  167238. break;
  167239. case 1:
  167240. cinfo->jpeg_color_space = JCS_YCbCr;
  167241. break;
  167242. default:
  167243. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167244. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167245. break;
  167246. }
  167247. } else {
  167248. /* Saw no special markers, try to guess from the component IDs */
  167249. int cid0 = cinfo->comp_info[0].component_id;
  167250. int cid1 = cinfo->comp_info[1].component_id;
  167251. int cid2 = cinfo->comp_info[2].component_id;
  167252. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167253. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167254. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167255. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167256. else {
  167257. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167258. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167259. }
  167260. }
  167261. /* Always guess RGB is proper output colorspace. */
  167262. cinfo->out_color_space = JCS_RGB;
  167263. break;
  167264. case 4:
  167265. if (cinfo->saw_Adobe_marker) {
  167266. switch (cinfo->Adobe_transform) {
  167267. case 0:
  167268. cinfo->jpeg_color_space = JCS_CMYK;
  167269. break;
  167270. case 2:
  167271. cinfo->jpeg_color_space = JCS_YCCK;
  167272. break;
  167273. default:
  167274. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167275. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167276. break;
  167277. }
  167278. } else {
  167279. /* No special markers, assume straight CMYK. */
  167280. cinfo->jpeg_color_space = JCS_CMYK;
  167281. }
  167282. cinfo->out_color_space = JCS_CMYK;
  167283. break;
  167284. default:
  167285. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167286. cinfo->out_color_space = JCS_UNKNOWN;
  167287. break;
  167288. }
  167289. /* Set defaults for other decompression parameters. */
  167290. cinfo->scale_num = 1; /* 1:1 scaling */
  167291. cinfo->scale_denom = 1;
  167292. cinfo->output_gamma = 1.0;
  167293. cinfo->buffered_image = FALSE;
  167294. cinfo->raw_data_out = FALSE;
  167295. cinfo->dct_method = JDCT_DEFAULT;
  167296. cinfo->do_fancy_upsampling = TRUE;
  167297. cinfo->do_block_smoothing = TRUE;
  167298. cinfo->quantize_colors = FALSE;
  167299. /* We set these in case application only sets quantize_colors. */
  167300. cinfo->dither_mode = JDITHER_FS;
  167301. #ifdef QUANT_2PASS_SUPPORTED
  167302. cinfo->two_pass_quantize = TRUE;
  167303. #else
  167304. cinfo->two_pass_quantize = FALSE;
  167305. #endif
  167306. cinfo->desired_number_of_colors = 256;
  167307. cinfo->colormap = NULL;
  167308. /* Initialize for no mode change in buffered-image mode. */
  167309. cinfo->enable_1pass_quant = FALSE;
  167310. cinfo->enable_external_quant = FALSE;
  167311. cinfo->enable_2pass_quant = FALSE;
  167312. }
  167313. /*
  167314. * Decompression startup: read start of JPEG datastream to see what's there.
  167315. * Need only initialize JPEG object and supply a data source before calling.
  167316. *
  167317. * This routine will read as far as the first SOS marker (ie, actual start of
  167318. * compressed data), and will save all tables and parameters in the JPEG
  167319. * object. It will also initialize the decompression parameters to default
  167320. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167321. * adjust the decompression parameters and then call jpeg_start_decompress.
  167322. * (Or, if the application only wanted to determine the image parameters,
  167323. * the data need not be decompressed. In that case, call jpeg_abort or
  167324. * jpeg_destroy to release any temporary space.)
  167325. * If an abbreviated (tables only) datastream is presented, the routine will
  167326. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167327. * re-use the JPEG object to read the abbreviated image datastream(s).
  167328. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167329. * The JPEG_SUSPENDED return code only occurs if the data source module
  167330. * requests suspension of the decompressor. In this case the application
  167331. * should load more source data and then re-call jpeg_read_header to resume
  167332. * processing.
  167333. * If a non-suspending data source is used and require_image is TRUE, then the
  167334. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167335. *
  167336. * This routine is now just a front end to jpeg_consume_input, with some
  167337. * extra error checking.
  167338. */
  167339. GLOBAL(int)
  167340. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167341. {
  167342. int retcode;
  167343. if (cinfo->global_state != DSTATE_START &&
  167344. cinfo->global_state != DSTATE_INHEADER)
  167345. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167346. retcode = jpeg_consume_input(cinfo);
  167347. switch (retcode) {
  167348. case JPEG_REACHED_SOS:
  167349. retcode = JPEG_HEADER_OK;
  167350. break;
  167351. case JPEG_REACHED_EOI:
  167352. if (require_image) /* Complain if application wanted an image */
  167353. ERREXIT(cinfo, JERR_NO_IMAGE);
  167354. /* Reset to start state; it would be safer to require the application to
  167355. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167356. * A side effect is to free any temporary memory (there shouldn't be any).
  167357. */
  167358. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167359. retcode = JPEG_HEADER_TABLES_ONLY;
  167360. break;
  167361. case JPEG_SUSPENDED:
  167362. /* no work */
  167363. break;
  167364. }
  167365. return retcode;
  167366. }
  167367. /*
  167368. * Consume data in advance of what the decompressor requires.
  167369. * This can be called at any time once the decompressor object has
  167370. * been created and a data source has been set up.
  167371. *
  167372. * This routine is essentially a state machine that handles a couple
  167373. * of critical state-transition actions, namely initial setup and
  167374. * transition from header scanning to ready-for-start_decompress.
  167375. * All the actual input is done via the input controller's consume_input
  167376. * method.
  167377. */
  167378. GLOBAL(int)
  167379. jpeg_consume_input (j_decompress_ptr cinfo)
  167380. {
  167381. int retcode = JPEG_SUSPENDED;
  167382. /* NB: every possible DSTATE value should be listed in this switch */
  167383. switch (cinfo->global_state) {
  167384. case DSTATE_START:
  167385. /* Start-of-datastream actions: reset appropriate modules */
  167386. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167387. /* Initialize application's data source module */
  167388. (*cinfo->src->init_source) (cinfo);
  167389. cinfo->global_state = DSTATE_INHEADER;
  167390. /*FALLTHROUGH*/
  167391. case DSTATE_INHEADER:
  167392. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167393. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167394. /* Set up default parameters based on header data */
  167395. default_decompress_parms(cinfo);
  167396. /* Set global state: ready for start_decompress */
  167397. cinfo->global_state = DSTATE_READY;
  167398. }
  167399. break;
  167400. case DSTATE_READY:
  167401. /* Can't advance past first SOS until start_decompress is called */
  167402. retcode = JPEG_REACHED_SOS;
  167403. break;
  167404. case DSTATE_PRELOAD:
  167405. case DSTATE_PRESCAN:
  167406. case DSTATE_SCANNING:
  167407. case DSTATE_RAW_OK:
  167408. case DSTATE_BUFIMAGE:
  167409. case DSTATE_BUFPOST:
  167410. case DSTATE_STOPPING:
  167411. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167412. break;
  167413. default:
  167414. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167415. }
  167416. return retcode;
  167417. }
  167418. /*
  167419. * Have we finished reading the input file?
  167420. */
  167421. GLOBAL(boolean)
  167422. jpeg_input_complete (j_decompress_ptr cinfo)
  167423. {
  167424. /* Check for valid jpeg object */
  167425. if (cinfo->global_state < DSTATE_START ||
  167426. cinfo->global_state > DSTATE_STOPPING)
  167427. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167428. return cinfo->inputctl->eoi_reached;
  167429. }
  167430. /*
  167431. * Is there more than one scan?
  167432. */
  167433. GLOBAL(boolean)
  167434. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167435. {
  167436. /* Only valid after jpeg_read_header completes */
  167437. if (cinfo->global_state < DSTATE_READY ||
  167438. cinfo->global_state > DSTATE_STOPPING)
  167439. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167440. return cinfo->inputctl->has_multiple_scans;
  167441. }
  167442. /*
  167443. * Finish JPEG decompression.
  167444. *
  167445. * This will normally just verify the file trailer and release temp storage.
  167446. *
  167447. * Returns FALSE if suspended. The return value need be inspected only if
  167448. * a suspending data source is used.
  167449. */
  167450. GLOBAL(boolean)
  167451. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167452. {
  167453. if ((cinfo->global_state == DSTATE_SCANNING ||
  167454. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167455. /* Terminate final pass of non-buffered mode */
  167456. if (cinfo->output_scanline < cinfo->output_height)
  167457. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167458. (*cinfo->master->finish_output_pass) (cinfo);
  167459. cinfo->global_state = DSTATE_STOPPING;
  167460. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167461. /* Finishing after a buffered-image operation */
  167462. cinfo->global_state = DSTATE_STOPPING;
  167463. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167464. /* STOPPING = repeat call after a suspension, anything else is error */
  167465. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167466. }
  167467. /* Read until EOI */
  167468. while (! cinfo->inputctl->eoi_reached) {
  167469. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167470. return FALSE; /* Suspend, come back later */
  167471. }
  167472. /* Do final cleanup */
  167473. (*cinfo->src->term_source) (cinfo);
  167474. /* We can use jpeg_abort to release memory and reset global_state */
  167475. jpeg_abort((j_common_ptr) cinfo);
  167476. return TRUE;
  167477. }
  167478. /*** End of inlined file: jdapimin.c ***/
  167479. /*** Start of inlined file: jdatasrc.c ***/
  167480. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167481. /*** Start of inlined file: jerror.h ***/
  167482. /*
  167483. * To define the enum list of message codes, include this file without
  167484. * defining macro JMESSAGE. To create a message string table, include it
  167485. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167486. */
  167487. #ifndef JMESSAGE
  167488. #ifndef JERROR_H
  167489. /* First time through, define the enum list */
  167490. #define JMAKE_ENUM_LIST
  167491. #else
  167492. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167493. #define JMESSAGE(code,string)
  167494. #endif /* JERROR_H */
  167495. #endif /* JMESSAGE */
  167496. #ifdef JMAKE_ENUM_LIST
  167497. typedef enum {
  167498. #define JMESSAGE(code,string) code ,
  167499. #endif /* JMAKE_ENUM_LIST */
  167500. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167501. /* For maintenance convenience, list is alphabetical by message code name */
  167502. JMESSAGE(JERR_ARITH_NOTIMPL,
  167503. "Sorry, there are legal restrictions on arithmetic coding")
  167504. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167505. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167506. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167507. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167508. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167509. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167510. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167511. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167512. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167513. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167514. JMESSAGE(JERR_BAD_LIB_VERSION,
  167515. "Wrong JPEG library version: library is %d, caller expects %d")
  167516. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167517. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167518. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167519. JMESSAGE(JERR_BAD_PROGRESSION,
  167520. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167521. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167522. "Invalid progressive parameters at scan script entry %d")
  167523. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167524. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167525. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167526. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167527. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167528. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167529. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167530. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167531. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167532. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167533. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167534. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167535. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167536. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167537. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167538. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167539. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167540. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167541. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167542. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167543. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167544. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167545. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167546. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167547. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167548. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167549. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167550. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167551. "Cannot transcode due to multiple use of quantization table %d")
  167552. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167553. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167554. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167555. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167556. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167557. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167558. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167559. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167560. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167561. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167562. JMESSAGE(JERR_QUANT_COMPONENTS,
  167563. "Cannot quantize more than %d color components")
  167564. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167565. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167566. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167567. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167568. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167569. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167570. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167571. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167572. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167573. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167574. JMESSAGE(JERR_TFILE_WRITE,
  167575. "Write failed on temporary file --- out of disk space?")
  167576. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167577. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167578. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167579. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167580. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167581. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167582. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167583. JMESSAGE(JMSG_VERSION, JVERSION)
  167584. JMESSAGE(JTRC_16BIT_TABLES,
  167585. "Caution: quantization tables are too coarse for baseline JPEG")
  167586. JMESSAGE(JTRC_ADOBE,
  167587. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167588. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167589. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167590. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167591. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167592. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167593. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167594. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167595. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167596. JMESSAGE(JTRC_EOI, "End Of Image")
  167597. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167598. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167599. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167600. "Warning: thumbnail image size does not match data length %u")
  167601. JMESSAGE(JTRC_JFIF_EXTENSION,
  167602. "JFIF extension marker: type 0x%02x, length %u")
  167603. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167604. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167605. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167606. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167607. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167608. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167609. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167610. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167611. JMESSAGE(JTRC_RST, "RST%d")
  167612. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167613. "Smoothing not supported with nonstandard sampling ratios")
  167614. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167615. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167616. JMESSAGE(JTRC_SOI, "Start of Image")
  167617. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167618. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167619. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167620. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167621. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167622. JMESSAGE(JTRC_THUMB_JPEG,
  167623. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167624. JMESSAGE(JTRC_THUMB_PALETTE,
  167625. "JFIF extension marker: palette thumbnail image, length %u")
  167626. JMESSAGE(JTRC_THUMB_RGB,
  167627. "JFIF extension marker: RGB thumbnail image, length %u")
  167628. JMESSAGE(JTRC_UNKNOWN_IDS,
  167629. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167630. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167631. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167632. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167633. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167634. "Inconsistent progression sequence for component %d coefficient %d")
  167635. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167636. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167637. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167638. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167639. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167640. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167641. JMESSAGE(JWRN_MUST_RESYNC,
  167642. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167643. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167644. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167645. #ifdef JMAKE_ENUM_LIST
  167646. JMSG_LASTMSGCODE
  167647. } J_MESSAGE_CODE;
  167648. #undef JMAKE_ENUM_LIST
  167649. #endif /* JMAKE_ENUM_LIST */
  167650. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167651. #undef JMESSAGE
  167652. #ifndef JERROR_H
  167653. #define JERROR_H
  167654. /* Macros to simplify using the error and trace message stuff */
  167655. /* The first parameter is either type of cinfo pointer */
  167656. /* Fatal errors (print message and exit) */
  167657. #define ERREXIT(cinfo,code) \
  167658. ((cinfo)->err->msg_code = (code), \
  167659. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167660. #define ERREXIT1(cinfo,code,p1) \
  167661. ((cinfo)->err->msg_code = (code), \
  167662. (cinfo)->err->msg_parm.i[0] = (p1), \
  167663. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167664. #define ERREXIT2(cinfo,code,p1,p2) \
  167665. ((cinfo)->err->msg_code = (code), \
  167666. (cinfo)->err->msg_parm.i[0] = (p1), \
  167667. (cinfo)->err->msg_parm.i[1] = (p2), \
  167668. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167669. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167670. ((cinfo)->err->msg_code = (code), \
  167671. (cinfo)->err->msg_parm.i[0] = (p1), \
  167672. (cinfo)->err->msg_parm.i[1] = (p2), \
  167673. (cinfo)->err->msg_parm.i[2] = (p3), \
  167674. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167675. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167676. ((cinfo)->err->msg_code = (code), \
  167677. (cinfo)->err->msg_parm.i[0] = (p1), \
  167678. (cinfo)->err->msg_parm.i[1] = (p2), \
  167679. (cinfo)->err->msg_parm.i[2] = (p3), \
  167680. (cinfo)->err->msg_parm.i[3] = (p4), \
  167681. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167682. #define ERREXITS(cinfo,code,str) \
  167683. ((cinfo)->err->msg_code = (code), \
  167684. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167685. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167686. #define MAKESTMT(stuff) do { stuff } while (0)
  167687. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167688. #define WARNMS(cinfo,code) \
  167689. ((cinfo)->err->msg_code = (code), \
  167690. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167691. #define WARNMS1(cinfo,code,p1) \
  167692. ((cinfo)->err->msg_code = (code), \
  167693. (cinfo)->err->msg_parm.i[0] = (p1), \
  167694. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167695. #define WARNMS2(cinfo,code,p1,p2) \
  167696. ((cinfo)->err->msg_code = (code), \
  167697. (cinfo)->err->msg_parm.i[0] = (p1), \
  167698. (cinfo)->err->msg_parm.i[1] = (p2), \
  167699. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167700. /* Informational/debugging messages */
  167701. #define TRACEMS(cinfo,lvl,code) \
  167702. ((cinfo)->err->msg_code = (code), \
  167703. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167704. #define TRACEMS1(cinfo,lvl,code,p1) \
  167705. ((cinfo)->err->msg_code = (code), \
  167706. (cinfo)->err->msg_parm.i[0] = (p1), \
  167707. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167708. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167709. ((cinfo)->err->msg_code = (code), \
  167710. (cinfo)->err->msg_parm.i[0] = (p1), \
  167711. (cinfo)->err->msg_parm.i[1] = (p2), \
  167712. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167713. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167714. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167715. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167716. (cinfo)->err->msg_code = (code); \
  167717. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167718. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167719. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167720. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167721. (cinfo)->err->msg_code = (code); \
  167722. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167723. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167724. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167725. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167726. _mp[4] = (p5); \
  167727. (cinfo)->err->msg_code = (code); \
  167728. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167729. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167730. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167731. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167732. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167733. (cinfo)->err->msg_code = (code); \
  167734. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167735. #define TRACEMSS(cinfo,lvl,code,str) \
  167736. ((cinfo)->err->msg_code = (code), \
  167737. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167738. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167739. #endif /* JERROR_H */
  167740. /*** End of inlined file: jerror.h ***/
  167741. /* Expanded data source object for stdio input */
  167742. typedef struct {
  167743. struct jpeg_source_mgr pub; /* public fields */
  167744. FILE * infile; /* source stream */
  167745. JOCTET * buffer; /* start of buffer */
  167746. boolean start_of_file; /* have we gotten any data yet? */
  167747. } my_source_mgr;
  167748. typedef my_source_mgr * my_src_ptr;
  167749. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167750. /*
  167751. * Initialize source --- called by jpeg_read_header
  167752. * before any data is actually read.
  167753. */
  167754. METHODDEF(void)
  167755. init_source (j_decompress_ptr cinfo)
  167756. {
  167757. my_src_ptr src = (my_src_ptr) cinfo->src;
  167758. /* We reset the empty-input-file flag for each image,
  167759. * but we don't clear the input buffer.
  167760. * This is correct behavior for reading a series of images from one source.
  167761. */
  167762. src->start_of_file = TRUE;
  167763. }
  167764. /*
  167765. * Fill the input buffer --- called whenever buffer is emptied.
  167766. *
  167767. * In typical applications, this should read fresh data into the buffer
  167768. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167769. * reset the pointer & count to the start of the buffer, and return TRUE
  167770. * indicating that the buffer has been reloaded. It is not necessary to
  167771. * fill the buffer entirely, only to obtain at least one more byte.
  167772. *
  167773. * There is no such thing as an EOF return. If the end of the file has been
  167774. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167775. * the buffer. In most cases, generating a warning message and inserting a
  167776. * fake EOI marker is the best course of action --- this will allow the
  167777. * decompressor to output however much of the image is there. However,
  167778. * the resulting error message is misleading if the real problem is an empty
  167779. * input file, so we handle that case specially.
  167780. *
  167781. * In applications that need to be able to suspend compression due to input
  167782. * not being available yet, a FALSE return indicates that no more data can be
  167783. * obtained right now, but more may be forthcoming later. In this situation,
  167784. * the decompressor will return to its caller (with an indication of the
  167785. * number of scanlines it has read, if any). The application should resume
  167786. * decompression after it has loaded more data into the input buffer. Note
  167787. * that there are substantial restrictions on the use of suspension --- see
  167788. * the documentation.
  167789. *
  167790. * When suspending, the decompressor will back up to a convenient restart point
  167791. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167792. * indicate where the restart point will be if the current call returns FALSE.
  167793. * Data beyond this point must be rescanned after resumption, so move it to
  167794. * the front of the buffer rather than discarding it.
  167795. */
  167796. METHODDEF(boolean)
  167797. fill_input_buffer (j_decompress_ptr cinfo)
  167798. {
  167799. my_src_ptr src = (my_src_ptr) cinfo->src;
  167800. size_t nbytes;
  167801. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167802. if (nbytes <= 0) {
  167803. if (src->start_of_file) /* Treat empty input file as fatal error */
  167804. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167805. WARNMS(cinfo, JWRN_JPEG_EOF);
  167806. /* Insert a fake EOI marker */
  167807. src->buffer[0] = (JOCTET) 0xFF;
  167808. src->buffer[1] = (JOCTET) JPEG_EOI;
  167809. nbytes = 2;
  167810. }
  167811. src->pub.next_input_byte = src->buffer;
  167812. src->pub.bytes_in_buffer = nbytes;
  167813. src->start_of_file = FALSE;
  167814. return TRUE;
  167815. }
  167816. /*
  167817. * Skip data --- used to skip over a potentially large amount of
  167818. * uninteresting data (such as an APPn marker).
  167819. *
  167820. * Writers of suspendable-input applications must note that skip_input_data
  167821. * is not granted the right to give a suspension return. If the skip extends
  167822. * beyond the data currently in the buffer, the buffer can be marked empty so
  167823. * that the next read will cause a fill_input_buffer call that can suspend.
  167824. * Arranging for additional bytes to be discarded before reloading the input
  167825. * buffer is the application writer's problem.
  167826. */
  167827. METHODDEF(void)
  167828. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  167829. {
  167830. my_src_ptr src = (my_src_ptr) cinfo->src;
  167831. /* Just a dumb implementation for now. Could use fseek() except
  167832. * it doesn't work on pipes. Not clear that being smart is worth
  167833. * any trouble anyway --- large skips are infrequent.
  167834. */
  167835. if (num_bytes > 0) {
  167836. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  167837. num_bytes -= (long) src->pub.bytes_in_buffer;
  167838. (void) fill_input_buffer(cinfo);
  167839. /* note we assume that fill_input_buffer will never return FALSE,
  167840. * so suspension need not be handled.
  167841. */
  167842. }
  167843. src->pub.next_input_byte += (size_t) num_bytes;
  167844. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  167845. }
  167846. }
  167847. /*
  167848. * An additional method that can be provided by data source modules is the
  167849. * resync_to_restart method for error recovery in the presence of RST markers.
  167850. * For the moment, this source module just uses the default resync method
  167851. * provided by the JPEG library. That method assumes that no backtracking
  167852. * is possible.
  167853. */
  167854. /*
  167855. * Terminate source --- called by jpeg_finish_decompress
  167856. * after all data has been read. Often a no-op.
  167857. *
  167858. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  167859. * application must deal with any cleanup that should happen even
  167860. * for error exit.
  167861. */
  167862. METHODDEF(void)
  167863. term_source (j_decompress_ptr)
  167864. {
  167865. /* no work necessary here */
  167866. }
  167867. /*
  167868. * Prepare for input from a stdio stream.
  167869. * The caller must have already opened the stream, and is responsible
  167870. * for closing it after finishing decompression.
  167871. */
  167872. GLOBAL(void)
  167873. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  167874. {
  167875. my_src_ptr src;
  167876. /* The source object and input buffer are made permanent so that a series
  167877. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  167878. * only before the first one. (If we discarded the buffer at the end of
  167879. * one image, we'd likely lose the start of the next one.)
  167880. * This makes it unsafe to use this manager and a different source
  167881. * manager serially with the same JPEG object. Caveat programmer.
  167882. */
  167883. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  167884. cinfo->src = (struct jpeg_source_mgr *)
  167885. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167886. SIZEOF(my_source_mgr));
  167887. src = (my_src_ptr) cinfo->src;
  167888. src->buffer = (JOCTET *)
  167889. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167890. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  167891. }
  167892. src = (my_src_ptr) cinfo->src;
  167893. src->pub.init_source = init_source;
  167894. src->pub.fill_input_buffer = fill_input_buffer;
  167895. src->pub.skip_input_data = skip_input_data;
  167896. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  167897. src->pub.term_source = term_source;
  167898. src->infile = infile;
  167899. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  167900. src->pub.next_input_byte = NULL; /* until buffer loaded */
  167901. }
  167902. /*** End of inlined file: jdatasrc.c ***/
  167903. /*** Start of inlined file: jdcoefct.c ***/
  167904. #define JPEG_INTERNALS
  167905. /* Block smoothing is only applicable for progressive JPEG, so: */
  167906. #ifndef D_PROGRESSIVE_SUPPORTED
  167907. #undef BLOCK_SMOOTHING_SUPPORTED
  167908. #endif
  167909. /* Private buffer controller object */
  167910. typedef struct {
  167911. struct jpeg_d_coef_controller pub; /* public fields */
  167912. /* These variables keep track of the current location of the input side. */
  167913. /* cinfo->input_iMCU_row is also used for this. */
  167914. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  167915. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167916. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167917. /* The output side's location is represented by cinfo->output_iMCU_row. */
  167918. /* In single-pass modes, it's sufficient to buffer just one MCU.
  167919. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  167920. * and let the entropy decoder write into that workspace each time.
  167921. * (On 80x86, the workspace is FAR even though it's not really very big;
  167922. * this is to keep the module interfaces unchanged when a large coefficient
  167923. * buffer is necessary.)
  167924. * In multi-pass modes, this array points to the current MCU's blocks
  167925. * within the virtual arrays; it is used only by the input side.
  167926. */
  167927. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  167928. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167929. /* In multi-pass modes, we need a virtual block array for each component. */
  167930. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  167931. #endif
  167932. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167933. /* When doing block smoothing, we latch coefficient Al values here */
  167934. int * coef_bits_latch;
  167935. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  167936. #endif
  167937. } my_coef_controller3;
  167938. typedef my_coef_controller3 * my_coef_ptr3;
  167939. /* Forward declarations */
  167940. METHODDEF(int) decompress_onepass
  167941. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167942. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167943. METHODDEF(int) decompress_data
  167944. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167945. #endif
  167946. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167947. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  167948. METHODDEF(int) decompress_smooth_data
  167949. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167950. #endif
  167951. LOCAL(void)
  167952. start_iMCU_row3 (j_decompress_ptr cinfo)
  167953. /* Reset within-iMCU-row counters for a new row (input side) */
  167954. {
  167955. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167956. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167957. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167958. * But at the bottom of the image, process only what's left.
  167959. */
  167960. if (cinfo->comps_in_scan > 1) {
  167961. coef->MCU_rows_per_iMCU_row = 1;
  167962. } else {
  167963. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  167964. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167965. else
  167966. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167967. }
  167968. coef->MCU_ctr = 0;
  167969. coef->MCU_vert_offset = 0;
  167970. }
  167971. /*
  167972. * Initialize for an input processing pass.
  167973. */
  167974. METHODDEF(void)
  167975. start_input_pass (j_decompress_ptr cinfo)
  167976. {
  167977. cinfo->input_iMCU_row = 0;
  167978. start_iMCU_row3(cinfo);
  167979. }
  167980. /*
  167981. * Initialize for an output processing pass.
  167982. */
  167983. METHODDEF(void)
  167984. start_output_pass (j_decompress_ptr cinfo)
  167985. {
  167986. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167987. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167988. /* If multipass, check to see whether to use block smoothing on this pass */
  167989. if (coef->pub.coef_arrays != NULL) {
  167990. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  167991. coef->pub.decompress_data = decompress_smooth_data;
  167992. else
  167993. coef->pub.decompress_data = decompress_data;
  167994. }
  167995. #endif
  167996. cinfo->output_iMCU_row = 0;
  167997. }
  167998. /*
  167999. * Decompress and return some data in the single-pass case.
  168000. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168001. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168002. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168003. *
  168004. * NB: output_buf contains a plane for each component in image,
  168005. * which we index according to the component's SOF position.
  168006. */
  168007. METHODDEF(int)
  168008. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168009. {
  168010. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168011. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168012. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168013. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168014. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168015. JSAMPARRAY output_ptr;
  168016. JDIMENSION start_col, output_col;
  168017. jpeg_component_info *compptr;
  168018. inverse_DCT_method_ptr inverse_DCT;
  168019. /* Loop to process as much as one whole iMCU row */
  168020. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168021. yoffset++) {
  168022. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168023. MCU_col_num++) {
  168024. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168025. jzero_far((void FAR *) coef->MCU_buffer[0],
  168026. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168027. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168028. /* Suspension forced; update state counters and exit */
  168029. coef->MCU_vert_offset = yoffset;
  168030. coef->MCU_ctr = MCU_col_num;
  168031. return JPEG_SUSPENDED;
  168032. }
  168033. /* Determine where data should go in output_buf and do the IDCT thing.
  168034. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168035. * incremented past them!). Note the inner loop relies on having
  168036. * allocated the MCU_buffer[] blocks sequentially.
  168037. */
  168038. blkn = 0; /* index of current DCT block within MCU */
  168039. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168040. compptr = cinfo->cur_comp_info[ci];
  168041. /* Don't bother to IDCT an uninteresting component. */
  168042. if (! compptr->component_needed) {
  168043. blkn += compptr->MCU_blocks;
  168044. continue;
  168045. }
  168046. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168047. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168048. : compptr->last_col_width;
  168049. output_ptr = output_buf[compptr->component_index] +
  168050. yoffset * compptr->DCT_scaled_size;
  168051. start_col = MCU_col_num * compptr->MCU_sample_width;
  168052. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168053. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168054. yoffset+yindex < compptr->last_row_height) {
  168055. output_col = start_col;
  168056. for (xindex = 0; xindex < useful_width; xindex++) {
  168057. (*inverse_DCT) (cinfo, compptr,
  168058. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168059. output_ptr, output_col);
  168060. output_col += compptr->DCT_scaled_size;
  168061. }
  168062. }
  168063. blkn += compptr->MCU_width;
  168064. output_ptr += compptr->DCT_scaled_size;
  168065. }
  168066. }
  168067. }
  168068. /* Completed an MCU row, but perhaps not an iMCU row */
  168069. coef->MCU_ctr = 0;
  168070. }
  168071. /* Completed the iMCU row, advance counters for next one */
  168072. cinfo->output_iMCU_row++;
  168073. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168074. start_iMCU_row3(cinfo);
  168075. return JPEG_ROW_COMPLETED;
  168076. }
  168077. /* Completed the scan */
  168078. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168079. return JPEG_SCAN_COMPLETED;
  168080. }
  168081. /*
  168082. * Dummy consume-input routine for single-pass operation.
  168083. */
  168084. METHODDEF(int)
  168085. dummy_consume_data (j_decompress_ptr)
  168086. {
  168087. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168088. }
  168089. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168090. /*
  168091. * Consume input data and store it in the full-image coefficient buffer.
  168092. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168093. * ie, v_samp_factor block rows for each component in the scan.
  168094. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168095. */
  168096. METHODDEF(int)
  168097. consume_data (j_decompress_ptr cinfo)
  168098. {
  168099. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168100. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168101. int blkn, ci, xindex, yindex, yoffset;
  168102. JDIMENSION start_col;
  168103. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168104. JBLOCKROW buffer_ptr;
  168105. jpeg_component_info *compptr;
  168106. /* Align the virtual buffers for the components used in this scan. */
  168107. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168108. compptr = cinfo->cur_comp_info[ci];
  168109. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168110. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168111. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168112. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168113. /* Note: entropy decoder expects buffer to be zeroed,
  168114. * but this is handled automatically by the memory manager
  168115. * because we requested a pre-zeroed array.
  168116. */
  168117. }
  168118. /* Loop to process one whole iMCU row */
  168119. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168120. yoffset++) {
  168121. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168122. MCU_col_num++) {
  168123. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168124. blkn = 0; /* index of current DCT block within MCU */
  168125. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168126. compptr = cinfo->cur_comp_info[ci];
  168127. start_col = MCU_col_num * compptr->MCU_width;
  168128. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168129. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168130. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168131. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168132. }
  168133. }
  168134. }
  168135. /* Try to fetch the MCU. */
  168136. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168137. /* Suspension forced; update state counters and exit */
  168138. coef->MCU_vert_offset = yoffset;
  168139. coef->MCU_ctr = MCU_col_num;
  168140. return JPEG_SUSPENDED;
  168141. }
  168142. }
  168143. /* Completed an MCU row, but perhaps not an iMCU row */
  168144. coef->MCU_ctr = 0;
  168145. }
  168146. /* Completed the iMCU row, advance counters for next one */
  168147. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168148. start_iMCU_row3(cinfo);
  168149. return JPEG_ROW_COMPLETED;
  168150. }
  168151. /* Completed the scan */
  168152. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168153. return JPEG_SCAN_COMPLETED;
  168154. }
  168155. /*
  168156. * Decompress and return some data in the multi-pass case.
  168157. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168158. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168159. *
  168160. * NB: output_buf contains a plane for each component in image.
  168161. */
  168162. METHODDEF(int)
  168163. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168164. {
  168165. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168166. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168167. JDIMENSION block_num;
  168168. int ci, block_row, block_rows;
  168169. JBLOCKARRAY buffer;
  168170. JBLOCKROW buffer_ptr;
  168171. JSAMPARRAY output_ptr;
  168172. JDIMENSION output_col;
  168173. jpeg_component_info *compptr;
  168174. inverse_DCT_method_ptr inverse_DCT;
  168175. /* Force some input to be done if we are getting ahead of the input. */
  168176. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168177. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168178. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168179. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168180. return JPEG_SUSPENDED;
  168181. }
  168182. /* OK, output from the virtual arrays. */
  168183. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168184. ci++, compptr++) {
  168185. /* Don't bother to IDCT an uninteresting component. */
  168186. if (! compptr->component_needed)
  168187. continue;
  168188. /* Align the virtual buffer for this component. */
  168189. buffer = (*cinfo->mem->access_virt_barray)
  168190. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168191. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168192. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168193. /* Count non-dummy DCT block rows in this iMCU row. */
  168194. if (cinfo->output_iMCU_row < last_iMCU_row)
  168195. block_rows = compptr->v_samp_factor;
  168196. else {
  168197. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168198. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168199. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168200. }
  168201. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168202. output_ptr = output_buf[ci];
  168203. /* Loop over all DCT blocks to be processed. */
  168204. for (block_row = 0; block_row < block_rows; block_row++) {
  168205. buffer_ptr = buffer[block_row];
  168206. output_col = 0;
  168207. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168208. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168209. output_ptr, output_col);
  168210. buffer_ptr++;
  168211. output_col += compptr->DCT_scaled_size;
  168212. }
  168213. output_ptr += compptr->DCT_scaled_size;
  168214. }
  168215. }
  168216. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168217. return JPEG_ROW_COMPLETED;
  168218. return JPEG_SCAN_COMPLETED;
  168219. }
  168220. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168221. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168222. /*
  168223. * This code applies interblock smoothing as described by section K.8
  168224. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168225. * the DC values of a DCT block and its 8 neighboring blocks.
  168226. * We apply smoothing only for progressive JPEG decoding, and only if
  168227. * the coefficients it can estimate are not yet known to full precision.
  168228. */
  168229. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168230. #define Q01_POS 1
  168231. #define Q10_POS 8
  168232. #define Q20_POS 16
  168233. #define Q11_POS 9
  168234. #define Q02_POS 2
  168235. /*
  168236. * Determine whether block smoothing is applicable and safe.
  168237. * We also latch the current states of the coef_bits[] entries for the
  168238. * AC coefficients; otherwise, if the input side of the decompressor
  168239. * advances into a new scan, we might think the coefficients are known
  168240. * more accurately than they really are.
  168241. */
  168242. LOCAL(boolean)
  168243. smoothing_ok (j_decompress_ptr cinfo)
  168244. {
  168245. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168246. boolean smoothing_useful = FALSE;
  168247. int ci, coefi;
  168248. jpeg_component_info *compptr;
  168249. JQUANT_TBL * qtable;
  168250. int * coef_bits;
  168251. int * coef_bits_latch;
  168252. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168253. return FALSE;
  168254. /* Allocate latch area if not already done */
  168255. if (coef->coef_bits_latch == NULL)
  168256. coef->coef_bits_latch = (int *)
  168257. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168258. cinfo->num_components *
  168259. (SAVED_COEFS * SIZEOF(int)));
  168260. coef_bits_latch = coef->coef_bits_latch;
  168261. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168262. ci++, compptr++) {
  168263. /* All components' quantization values must already be latched. */
  168264. if ((qtable = compptr->quant_table) == NULL)
  168265. return FALSE;
  168266. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168267. if (qtable->quantval[0] == 0 ||
  168268. qtable->quantval[Q01_POS] == 0 ||
  168269. qtable->quantval[Q10_POS] == 0 ||
  168270. qtable->quantval[Q20_POS] == 0 ||
  168271. qtable->quantval[Q11_POS] == 0 ||
  168272. qtable->quantval[Q02_POS] == 0)
  168273. return FALSE;
  168274. /* DC values must be at least partly known for all components. */
  168275. coef_bits = cinfo->coef_bits[ci];
  168276. if (coef_bits[0] < 0)
  168277. return FALSE;
  168278. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168279. for (coefi = 1; coefi <= 5; coefi++) {
  168280. coef_bits_latch[coefi] = coef_bits[coefi];
  168281. if (coef_bits[coefi] != 0)
  168282. smoothing_useful = TRUE;
  168283. }
  168284. coef_bits_latch += SAVED_COEFS;
  168285. }
  168286. return smoothing_useful;
  168287. }
  168288. /*
  168289. * Variant of decompress_data for use when doing block smoothing.
  168290. */
  168291. METHODDEF(int)
  168292. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168293. {
  168294. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168295. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168296. JDIMENSION block_num, last_block_column;
  168297. int ci, block_row, block_rows, access_rows;
  168298. JBLOCKARRAY buffer;
  168299. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168300. JSAMPARRAY output_ptr;
  168301. JDIMENSION output_col;
  168302. jpeg_component_info *compptr;
  168303. inverse_DCT_method_ptr inverse_DCT;
  168304. boolean first_row, last_row;
  168305. JBLOCK workspace;
  168306. int *coef_bits;
  168307. JQUANT_TBL *quanttbl;
  168308. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168309. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168310. int Al, pred;
  168311. /* Force some input to be done if we are getting ahead of the input. */
  168312. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168313. ! cinfo->inputctl->eoi_reached) {
  168314. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168315. /* If input is working on current scan, we ordinarily want it to
  168316. * have completed the current row. But if input scan is DC,
  168317. * we want it to keep one row ahead so that next block row's DC
  168318. * values are up to date.
  168319. */
  168320. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168321. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168322. break;
  168323. }
  168324. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168325. return JPEG_SUSPENDED;
  168326. }
  168327. /* OK, output from the virtual arrays. */
  168328. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168329. ci++, compptr++) {
  168330. /* Don't bother to IDCT an uninteresting component. */
  168331. if (! compptr->component_needed)
  168332. continue;
  168333. /* Count non-dummy DCT block rows in this iMCU row. */
  168334. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168335. block_rows = compptr->v_samp_factor;
  168336. access_rows = block_rows * 2; /* this and next iMCU row */
  168337. last_row = FALSE;
  168338. } else {
  168339. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168340. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168341. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168342. access_rows = block_rows; /* this iMCU row only */
  168343. last_row = TRUE;
  168344. }
  168345. /* Align the virtual buffer for this component. */
  168346. if (cinfo->output_iMCU_row > 0) {
  168347. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168348. buffer = (*cinfo->mem->access_virt_barray)
  168349. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168350. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168351. (JDIMENSION) access_rows, FALSE);
  168352. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168353. first_row = FALSE;
  168354. } else {
  168355. buffer = (*cinfo->mem->access_virt_barray)
  168356. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168357. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168358. first_row = TRUE;
  168359. }
  168360. /* Fetch component-dependent info */
  168361. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168362. quanttbl = compptr->quant_table;
  168363. Q00 = quanttbl->quantval[0];
  168364. Q01 = quanttbl->quantval[Q01_POS];
  168365. Q10 = quanttbl->quantval[Q10_POS];
  168366. Q20 = quanttbl->quantval[Q20_POS];
  168367. Q11 = quanttbl->quantval[Q11_POS];
  168368. Q02 = quanttbl->quantval[Q02_POS];
  168369. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168370. output_ptr = output_buf[ci];
  168371. /* Loop over all DCT blocks to be processed. */
  168372. for (block_row = 0; block_row < block_rows; block_row++) {
  168373. buffer_ptr = buffer[block_row];
  168374. if (first_row && block_row == 0)
  168375. prev_block_row = buffer_ptr;
  168376. else
  168377. prev_block_row = buffer[block_row-1];
  168378. if (last_row && block_row == block_rows-1)
  168379. next_block_row = buffer_ptr;
  168380. else
  168381. next_block_row = buffer[block_row+1];
  168382. /* We fetch the surrounding DC values using a sliding-register approach.
  168383. * Initialize all nine here so as to do the right thing on narrow pics.
  168384. */
  168385. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168386. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168387. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168388. output_col = 0;
  168389. last_block_column = compptr->width_in_blocks - 1;
  168390. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168391. /* Fetch current DCT block into workspace so we can modify it. */
  168392. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168393. /* Update DC values */
  168394. if (block_num < last_block_column) {
  168395. DC3 = (int) prev_block_row[1][0];
  168396. DC6 = (int) buffer_ptr[1][0];
  168397. DC9 = (int) next_block_row[1][0];
  168398. }
  168399. /* Compute coefficient estimates per K.8.
  168400. * An estimate is applied only if coefficient is still zero,
  168401. * and is not known to be fully accurate.
  168402. */
  168403. /* AC01 */
  168404. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168405. num = 36 * Q00 * (DC4 - DC6);
  168406. if (num >= 0) {
  168407. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168408. if (Al > 0 && pred >= (1<<Al))
  168409. pred = (1<<Al)-1;
  168410. } else {
  168411. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168412. if (Al > 0 && pred >= (1<<Al))
  168413. pred = (1<<Al)-1;
  168414. pred = -pred;
  168415. }
  168416. workspace[1] = (JCOEF) pred;
  168417. }
  168418. /* AC10 */
  168419. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168420. num = 36 * Q00 * (DC2 - DC8);
  168421. if (num >= 0) {
  168422. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168423. if (Al > 0 && pred >= (1<<Al))
  168424. pred = (1<<Al)-1;
  168425. } else {
  168426. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168427. if (Al > 0 && pred >= (1<<Al))
  168428. pred = (1<<Al)-1;
  168429. pred = -pred;
  168430. }
  168431. workspace[8] = (JCOEF) pred;
  168432. }
  168433. /* AC20 */
  168434. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168435. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168436. if (num >= 0) {
  168437. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168438. if (Al > 0 && pred >= (1<<Al))
  168439. pred = (1<<Al)-1;
  168440. } else {
  168441. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168442. if (Al > 0 && pred >= (1<<Al))
  168443. pred = (1<<Al)-1;
  168444. pred = -pred;
  168445. }
  168446. workspace[16] = (JCOEF) pred;
  168447. }
  168448. /* AC11 */
  168449. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168450. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168451. if (num >= 0) {
  168452. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168453. if (Al > 0 && pred >= (1<<Al))
  168454. pred = (1<<Al)-1;
  168455. } else {
  168456. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168457. if (Al > 0 && pred >= (1<<Al))
  168458. pred = (1<<Al)-1;
  168459. pred = -pred;
  168460. }
  168461. workspace[9] = (JCOEF) pred;
  168462. }
  168463. /* AC02 */
  168464. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168465. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168466. if (num >= 0) {
  168467. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168468. if (Al > 0 && pred >= (1<<Al))
  168469. pred = (1<<Al)-1;
  168470. } else {
  168471. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168472. if (Al > 0 && pred >= (1<<Al))
  168473. pred = (1<<Al)-1;
  168474. pred = -pred;
  168475. }
  168476. workspace[2] = (JCOEF) pred;
  168477. }
  168478. /* OK, do the IDCT */
  168479. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168480. output_ptr, output_col);
  168481. /* Advance for next column */
  168482. DC1 = DC2; DC2 = DC3;
  168483. DC4 = DC5; DC5 = DC6;
  168484. DC7 = DC8; DC8 = DC9;
  168485. buffer_ptr++, prev_block_row++, next_block_row++;
  168486. output_col += compptr->DCT_scaled_size;
  168487. }
  168488. output_ptr += compptr->DCT_scaled_size;
  168489. }
  168490. }
  168491. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168492. return JPEG_ROW_COMPLETED;
  168493. return JPEG_SCAN_COMPLETED;
  168494. }
  168495. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168496. /*
  168497. * Initialize coefficient buffer controller.
  168498. */
  168499. GLOBAL(void)
  168500. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168501. {
  168502. my_coef_ptr3 coef;
  168503. coef = (my_coef_ptr3)
  168504. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168505. SIZEOF(my_coef_controller3));
  168506. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168507. coef->pub.start_input_pass = start_input_pass;
  168508. coef->pub.start_output_pass = start_output_pass;
  168509. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168510. coef->coef_bits_latch = NULL;
  168511. #endif
  168512. /* Create the coefficient buffer. */
  168513. if (need_full_buffer) {
  168514. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168515. /* Allocate a full-image virtual array for each component, */
  168516. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168517. /* Note we ask for a pre-zeroed array. */
  168518. int ci, access_rows;
  168519. jpeg_component_info *compptr;
  168520. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168521. ci++, compptr++) {
  168522. access_rows = compptr->v_samp_factor;
  168523. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168524. /* If block smoothing could be used, need a bigger window */
  168525. if (cinfo->progressive_mode)
  168526. access_rows *= 3;
  168527. #endif
  168528. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168529. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168530. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168531. (long) compptr->h_samp_factor),
  168532. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168533. (long) compptr->v_samp_factor),
  168534. (JDIMENSION) access_rows);
  168535. }
  168536. coef->pub.consume_data = consume_data;
  168537. coef->pub.decompress_data = decompress_data;
  168538. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168539. #else
  168540. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168541. #endif
  168542. } else {
  168543. /* We only need a single-MCU buffer. */
  168544. JBLOCKROW buffer;
  168545. int i;
  168546. buffer = (JBLOCKROW)
  168547. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168548. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168549. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168550. coef->MCU_buffer[i] = buffer + i;
  168551. }
  168552. coef->pub.consume_data = dummy_consume_data;
  168553. coef->pub.decompress_data = decompress_onepass;
  168554. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168555. }
  168556. }
  168557. /*** End of inlined file: jdcoefct.c ***/
  168558. #undef FIX
  168559. /*** Start of inlined file: jdcolor.c ***/
  168560. #define JPEG_INTERNALS
  168561. /* Private subobject */
  168562. typedef struct {
  168563. struct jpeg_color_deconverter pub; /* public fields */
  168564. /* Private state for YCC->RGB conversion */
  168565. int * Cr_r_tab; /* => table for Cr to R conversion */
  168566. int * Cb_b_tab; /* => table for Cb to B conversion */
  168567. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168568. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168569. } my_color_deconverter2;
  168570. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168571. /**************** YCbCr -> RGB conversion: most common case **************/
  168572. /*
  168573. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168574. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168575. * The conversion equations to be implemented are therefore
  168576. * R = Y + 1.40200 * Cr
  168577. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168578. * B = Y + 1.77200 * Cb
  168579. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168580. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168581. *
  168582. * To avoid floating-point arithmetic, we represent the fractional constants
  168583. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168584. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168585. * Notice that Y, being an integral input, does not contribute any fraction
  168586. * so it need not participate in the rounding.
  168587. *
  168588. * For even more speed, we avoid doing any multiplications in the inner loop
  168589. * by precalculating the constants times Cb and Cr for all possible values.
  168590. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168591. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168592. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168593. * colorspace anyway.
  168594. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168595. * values for the G calculation are left scaled up, since we must add them
  168596. * together before rounding.
  168597. */
  168598. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168599. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168600. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168601. /*
  168602. * Initialize tables for YCC->RGB colorspace conversion.
  168603. */
  168604. LOCAL(void)
  168605. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168606. {
  168607. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168608. int i;
  168609. INT32 x;
  168610. SHIFT_TEMPS
  168611. cconvert->Cr_r_tab = (int *)
  168612. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168613. (MAXJSAMPLE+1) * SIZEOF(int));
  168614. cconvert->Cb_b_tab = (int *)
  168615. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168616. (MAXJSAMPLE+1) * SIZEOF(int));
  168617. cconvert->Cr_g_tab = (INT32 *)
  168618. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168619. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168620. cconvert->Cb_g_tab = (INT32 *)
  168621. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168622. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168623. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168624. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168625. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168626. /* Cr=>R value is nearest int to 1.40200 * x */
  168627. cconvert->Cr_r_tab[i] = (int)
  168628. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168629. /* Cb=>B value is nearest int to 1.77200 * x */
  168630. cconvert->Cb_b_tab[i] = (int)
  168631. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168632. /* Cr=>G value is scaled-up -0.71414 * x */
  168633. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168634. /* Cb=>G value is scaled-up -0.34414 * x */
  168635. /* We also add in ONE_HALF so that need not do it in inner loop */
  168636. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168637. }
  168638. }
  168639. /*
  168640. * Convert some rows of samples to the output colorspace.
  168641. *
  168642. * Note that we change from noninterleaved, one-plane-per-component format
  168643. * to interleaved-pixel format. The output buffer is therefore three times
  168644. * as wide as the input buffer.
  168645. * A starting row offset is provided only for the input buffer. The caller
  168646. * can easily adjust the passed output_buf value to accommodate any row
  168647. * offset required on that side.
  168648. */
  168649. METHODDEF(void)
  168650. ycc_rgb_convert (j_decompress_ptr cinfo,
  168651. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168652. JSAMPARRAY output_buf, int num_rows)
  168653. {
  168654. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168655. register int y, cb, cr;
  168656. register JSAMPROW outptr;
  168657. register JSAMPROW inptr0, inptr1, inptr2;
  168658. register JDIMENSION col;
  168659. JDIMENSION num_cols = cinfo->output_width;
  168660. /* copy these pointers into registers if possible */
  168661. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168662. register int * Crrtab = cconvert->Cr_r_tab;
  168663. register int * Cbbtab = cconvert->Cb_b_tab;
  168664. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168665. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168666. SHIFT_TEMPS
  168667. while (--num_rows >= 0) {
  168668. inptr0 = input_buf[0][input_row];
  168669. inptr1 = input_buf[1][input_row];
  168670. inptr2 = input_buf[2][input_row];
  168671. input_row++;
  168672. outptr = *output_buf++;
  168673. for (col = 0; col < num_cols; col++) {
  168674. y = GETJSAMPLE(inptr0[col]);
  168675. cb = GETJSAMPLE(inptr1[col]);
  168676. cr = GETJSAMPLE(inptr2[col]);
  168677. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168678. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168679. outptr[RGB_GREEN] = range_limit[y +
  168680. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168681. SCALEBITS))];
  168682. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168683. outptr += RGB_PIXELSIZE;
  168684. }
  168685. }
  168686. }
  168687. /**************** Cases other than YCbCr -> RGB **************/
  168688. /*
  168689. * Color conversion for no colorspace change: just copy the data,
  168690. * converting from separate-planes to interleaved representation.
  168691. */
  168692. METHODDEF(void)
  168693. null_convert2 (j_decompress_ptr cinfo,
  168694. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168695. JSAMPARRAY output_buf, int num_rows)
  168696. {
  168697. register JSAMPROW inptr, outptr;
  168698. register JDIMENSION count;
  168699. register int num_components = cinfo->num_components;
  168700. JDIMENSION num_cols = cinfo->output_width;
  168701. int ci;
  168702. while (--num_rows >= 0) {
  168703. for (ci = 0; ci < num_components; ci++) {
  168704. inptr = input_buf[ci][input_row];
  168705. outptr = output_buf[0] + ci;
  168706. for (count = num_cols; count > 0; count--) {
  168707. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168708. outptr += num_components;
  168709. }
  168710. }
  168711. input_row++;
  168712. output_buf++;
  168713. }
  168714. }
  168715. /*
  168716. * Color conversion for grayscale: just copy the data.
  168717. * This also works for YCbCr -> grayscale conversion, in which
  168718. * we just copy the Y (luminance) component and ignore chrominance.
  168719. */
  168720. METHODDEF(void)
  168721. grayscale_convert2 (j_decompress_ptr cinfo,
  168722. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168723. JSAMPARRAY output_buf, int num_rows)
  168724. {
  168725. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168726. num_rows, cinfo->output_width);
  168727. }
  168728. /*
  168729. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168730. * This is provided to support applications that don't want to cope
  168731. * with grayscale as a separate case.
  168732. */
  168733. METHODDEF(void)
  168734. gray_rgb_convert (j_decompress_ptr cinfo,
  168735. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168736. JSAMPARRAY output_buf, int num_rows)
  168737. {
  168738. register JSAMPROW inptr, outptr;
  168739. register JDIMENSION col;
  168740. JDIMENSION num_cols = cinfo->output_width;
  168741. while (--num_rows >= 0) {
  168742. inptr = input_buf[0][input_row++];
  168743. outptr = *output_buf++;
  168744. for (col = 0; col < num_cols; col++) {
  168745. /* We can dispense with GETJSAMPLE() here */
  168746. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168747. outptr += RGB_PIXELSIZE;
  168748. }
  168749. }
  168750. }
  168751. /*
  168752. * Adobe-style YCCK->CMYK conversion.
  168753. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168754. * conversion as above, while passing K (black) unchanged.
  168755. * We assume build_ycc_rgb_table has been called.
  168756. */
  168757. METHODDEF(void)
  168758. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168759. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168760. JSAMPARRAY output_buf, int num_rows)
  168761. {
  168762. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168763. register int y, cb, cr;
  168764. register JSAMPROW outptr;
  168765. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168766. register JDIMENSION col;
  168767. JDIMENSION num_cols = cinfo->output_width;
  168768. /* copy these pointers into registers if possible */
  168769. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168770. register int * Crrtab = cconvert->Cr_r_tab;
  168771. register int * Cbbtab = cconvert->Cb_b_tab;
  168772. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168773. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168774. SHIFT_TEMPS
  168775. while (--num_rows >= 0) {
  168776. inptr0 = input_buf[0][input_row];
  168777. inptr1 = input_buf[1][input_row];
  168778. inptr2 = input_buf[2][input_row];
  168779. inptr3 = input_buf[3][input_row];
  168780. input_row++;
  168781. outptr = *output_buf++;
  168782. for (col = 0; col < num_cols; col++) {
  168783. y = GETJSAMPLE(inptr0[col]);
  168784. cb = GETJSAMPLE(inptr1[col]);
  168785. cr = GETJSAMPLE(inptr2[col]);
  168786. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168787. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168788. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168789. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168790. SCALEBITS)))];
  168791. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168792. /* K passes through unchanged */
  168793. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168794. outptr += 4;
  168795. }
  168796. }
  168797. }
  168798. /*
  168799. * Empty method for start_pass.
  168800. */
  168801. METHODDEF(void)
  168802. start_pass_dcolor (j_decompress_ptr)
  168803. {
  168804. /* no work needed */
  168805. }
  168806. /*
  168807. * Module initialization routine for output colorspace conversion.
  168808. */
  168809. GLOBAL(void)
  168810. jinit_color_deconverter (j_decompress_ptr cinfo)
  168811. {
  168812. my_cconvert_ptr2 cconvert;
  168813. int ci;
  168814. cconvert = (my_cconvert_ptr2)
  168815. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168816. SIZEOF(my_color_deconverter2));
  168817. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168818. cconvert->pub.start_pass = start_pass_dcolor;
  168819. /* Make sure num_components agrees with jpeg_color_space */
  168820. switch (cinfo->jpeg_color_space) {
  168821. case JCS_GRAYSCALE:
  168822. if (cinfo->num_components != 1)
  168823. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168824. break;
  168825. case JCS_RGB:
  168826. case JCS_YCbCr:
  168827. if (cinfo->num_components != 3)
  168828. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168829. break;
  168830. case JCS_CMYK:
  168831. case JCS_YCCK:
  168832. if (cinfo->num_components != 4)
  168833. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168834. break;
  168835. default: /* JCS_UNKNOWN can be anything */
  168836. if (cinfo->num_components < 1)
  168837. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168838. break;
  168839. }
  168840. /* Set out_color_components and conversion method based on requested space.
  168841. * Also clear the component_needed flags for any unused components,
  168842. * so that earlier pipeline stages can avoid useless computation.
  168843. */
  168844. switch (cinfo->out_color_space) {
  168845. case JCS_GRAYSCALE:
  168846. cinfo->out_color_components = 1;
  168847. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  168848. cinfo->jpeg_color_space == JCS_YCbCr) {
  168849. cconvert->pub.color_convert = grayscale_convert2;
  168850. /* For color->grayscale conversion, only the Y (0) component is needed */
  168851. for (ci = 1; ci < cinfo->num_components; ci++)
  168852. cinfo->comp_info[ci].component_needed = FALSE;
  168853. } else
  168854. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168855. break;
  168856. case JCS_RGB:
  168857. cinfo->out_color_components = RGB_PIXELSIZE;
  168858. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  168859. cconvert->pub.color_convert = ycc_rgb_convert;
  168860. build_ycc_rgb_table(cinfo);
  168861. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  168862. cconvert->pub.color_convert = gray_rgb_convert;
  168863. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  168864. cconvert->pub.color_convert = null_convert2;
  168865. } else
  168866. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168867. break;
  168868. case JCS_CMYK:
  168869. cinfo->out_color_components = 4;
  168870. if (cinfo->jpeg_color_space == JCS_YCCK) {
  168871. cconvert->pub.color_convert = ycck_cmyk_convert;
  168872. build_ycc_rgb_table(cinfo);
  168873. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  168874. cconvert->pub.color_convert = null_convert2;
  168875. } else
  168876. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168877. break;
  168878. default:
  168879. /* Permit null conversion to same output space */
  168880. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  168881. cinfo->out_color_components = cinfo->num_components;
  168882. cconvert->pub.color_convert = null_convert2;
  168883. } else /* unsupported non-null conversion */
  168884. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168885. break;
  168886. }
  168887. if (cinfo->quantize_colors)
  168888. cinfo->output_components = 1; /* single colormapped output component */
  168889. else
  168890. cinfo->output_components = cinfo->out_color_components;
  168891. }
  168892. /*** End of inlined file: jdcolor.c ***/
  168893. #undef FIX
  168894. /*** Start of inlined file: jddctmgr.c ***/
  168895. #define JPEG_INTERNALS
  168896. /*
  168897. * The decompressor input side (jdinput.c) saves away the appropriate
  168898. * quantization table for each component at the start of the first scan
  168899. * involving that component. (This is necessary in order to correctly
  168900. * decode files that reuse Q-table slots.)
  168901. * When we are ready to make an output pass, the saved Q-table is converted
  168902. * to a multiplier table that will actually be used by the IDCT routine.
  168903. * The multiplier table contents are IDCT-method-dependent. To support
  168904. * application changes in IDCT method between scans, we can remake the
  168905. * multiplier tables if necessary.
  168906. * In buffered-image mode, the first output pass may occur before any data
  168907. * has been seen for some components, and thus before their Q-tables have
  168908. * been saved away. To handle this case, multiplier tables are preset
  168909. * to zeroes; the result of the IDCT will be a neutral gray level.
  168910. */
  168911. /* Private subobject for this module */
  168912. typedef struct {
  168913. struct jpeg_inverse_dct pub; /* public fields */
  168914. /* This array contains the IDCT method code that each multiplier table
  168915. * is currently set up for, or -1 if it's not yet set up.
  168916. * The actual multiplier tables are pointed to by dct_table in the
  168917. * per-component comp_info structures.
  168918. */
  168919. int cur_method[MAX_COMPONENTS];
  168920. } my_idct_controller;
  168921. typedef my_idct_controller * my_idct_ptr;
  168922. /* Allocated multiplier tables: big enough for any supported variant */
  168923. typedef union {
  168924. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  168925. #ifdef DCT_IFAST_SUPPORTED
  168926. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  168927. #endif
  168928. #ifdef DCT_FLOAT_SUPPORTED
  168929. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  168930. #endif
  168931. } multiplier_table;
  168932. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  168933. * so be sure to compile that code if either ISLOW or SCALING is requested.
  168934. */
  168935. #ifdef DCT_ISLOW_SUPPORTED
  168936. #define PROVIDE_ISLOW_TABLES
  168937. #else
  168938. #ifdef IDCT_SCALING_SUPPORTED
  168939. #define PROVIDE_ISLOW_TABLES
  168940. #endif
  168941. #endif
  168942. /*
  168943. * Prepare for an output pass.
  168944. * Here we select the proper IDCT routine for each component and build
  168945. * a matching multiplier table.
  168946. */
  168947. METHODDEF(void)
  168948. start_pass (j_decompress_ptr cinfo)
  168949. {
  168950. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  168951. int ci, i;
  168952. jpeg_component_info *compptr;
  168953. int method = 0;
  168954. inverse_DCT_method_ptr method_ptr = NULL;
  168955. JQUANT_TBL * qtbl;
  168956. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168957. ci++, compptr++) {
  168958. /* Select the proper IDCT routine for this component's scaling */
  168959. switch (compptr->DCT_scaled_size) {
  168960. #ifdef IDCT_SCALING_SUPPORTED
  168961. case 1:
  168962. method_ptr = jpeg_idct_1x1;
  168963. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168964. break;
  168965. case 2:
  168966. method_ptr = jpeg_idct_2x2;
  168967. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168968. break;
  168969. case 4:
  168970. method_ptr = jpeg_idct_4x4;
  168971. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168972. break;
  168973. #endif
  168974. case DCTSIZE:
  168975. switch (cinfo->dct_method) {
  168976. #ifdef DCT_ISLOW_SUPPORTED
  168977. case JDCT_ISLOW:
  168978. method_ptr = jpeg_idct_islow;
  168979. method = JDCT_ISLOW;
  168980. break;
  168981. #endif
  168982. #ifdef DCT_IFAST_SUPPORTED
  168983. case JDCT_IFAST:
  168984. method_ptr = jpeg_idct_ifast;
  168985. method = JDCT_IFAST;
  168986. break;
  168987. #endif
  168988. #ifdef DCT_FLOAT_SUPPORTED
  168989. case JDCT_FLOAT:
  168990. method_ptr = jpeg_idct_float;
  168991. method = JDCT_FLOAT;
  168992. break;
  168993. #endif
  168994. default:
  168995. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168996. break;
  168997. }
  168998. break;
  168999. default:
  169000. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169001. break;
  169002. }
  169003. idct->pub.inverse_DCT[ci] = method_ptr;
  169004. /* Create multiplier table from quant table.
  169005. * However, we can skip this if the component is uninteresting
  169006. * or if we already built the table. Also, if no quant table
  169007. * has yet been saved for the component, we leave the
  169008. * multiplier table all-zero; we'll be reading zeroes from the
  169009. * coefficient controller's buffer anyway.
  169010. */
  169011. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169012. continue;
  169013. qtbl = compptr->quant_table;
  169014. if (qtbl == NULL) /* happens if no data yet for component */
  169015. continue;
  169016. idct->cur_method[ci] = method;
  169017. switch (method) {
  169018. #ifdef PROVIDE_ISLOW_TABLES
  169019. case JDCT_ISLOW:
  169020. {
  169021. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169022. * coefficients, but are stored as ints to ensure access efficiency.
  169023. */
  169024. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169025. for (i = 0; i < DCTSIZE2; i++) {
  169026. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169027. }
  169028. }
  169029. break;
  169030. #endif
  169031. #ifdef DCT_IFAST_SUPPORTED
  169032. case JDCT_IFAST:
  169033. {
  169034. /* For AA&N IDCT method, multipliers are equal to quantization
  169035. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169036. * scalefactor[0] = 1
  169037. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169038. * For integer operation, the multiplier table is to be scaled by
  169039. * IFAST_SCALE_BITS.
  169040. */
  169041. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169042. #define CONST_BITS 14
  169043. static const INT16 aanscales[DCTSIZE2] = {
  169044. /* precomputed values scaled up by 14 bits */
  169045. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169046. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169047. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169048. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169049. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169050. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169051. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169052. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169053. };
  169054. SHIFT_TEMPS
  169055. for (i = 0; i < DCTSIZE2; i++) {
  169056. ifmtbl[i] = (IFAST_MULT_TYPE)
  169057. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169058. (INT32) aanscales[i]),
  169059. CONST_BITS-IFAST_SCALE_BITS);
  169060. }
  169061. }
  169062. break;
  169063. #endif
  169064. #ifdef DCT_FLOAT_SUPPORTED
  169065. case JDCT_FLOAT:
  169066. {
  169067. /* For float AA&N IDCT method, multipliers are equal to quantization
  169068. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169069. * scalefactor[0] = 1
  169070. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169071. */
  169072. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169073. int row, col;
  169074. static const double aanscalefactor[DCTSIZE] = {
  169075. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169076. 1.0, 0.785694958, 0.541196100, 0.275899379
  169077. };
  169078. i = 0;
  169079. for (row = 0; row < DCTSIZE; row++) {
  169080. for (col = 0; col < DCTSIZE; col++) {
  169081. fmtbl[i] = (FLOAT_MULT_TYPE)
  169082. ((double) qtbl->quantval[i] *
  169083. aanscalefactor[row] * aanscalefactor[col]);
  169084. i++;
  169085. }
  169086. }
  169087. }
  169088. break;
  169089. #endif
  169090. default:
  169091. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169092. break;
  169093. }
  169094. }
  169095. }
  169096. /*
  169097. * Initialize IDCT manager.
  169098. */
  169099. GLOBAL(void)
  169100. jinit_inverse_dct (j_decompress_ptr cinfo)
  169101. {
  169102. my_idct_ptr idct;
  169103. int ci;
  169104. jpeg_component_info *compptr;
  169105. idct = (my_idct_ptr)
  169106. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169107. SIZEOF(my_idct_controller));
  169108. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169109. idct->pub.start_pass = start_pass;
  169110. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169111. ci++, compptr++) {
  169112. /* Allocate and pre-zero a multiplier table for each component */
  169113. compptr->dct_table =
  169114. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169115. SIZEOF(multiplier_table));
  169116. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169117. /* Mark multiplier table not yet set up for any method */
  169118. idct->cur_method[ci] = -1;
  169119. }
  169120. }
  169121. /*** End of inlined file: jddctmgr.c ***/
  169122. #undef CONST_BITS
  169123. #undef ASSIGN_STATE
  169124. /*** Start of inlined file: jdhuff.c ***/
  169125. #define JPEG_INTERNALS
  169126. /*** Start of inlined file: jdhuff.h ***/
  169127. /* Short forms of external names for systems with brain-damaged linkers. */
  169128. #ifndef __jdhuff_h__
  169129. #define __jdhuff_h__
  169130. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169131. #define jpeg_make_d_derived_tbl jMkDDerived
  169132. #define jpeg_fill_bit_buffer jFilBitBuf
  169133. #define jpeg_huff_decode jHufDecode
  169134. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169135. /* Derived data constructed for each Huffman table */
  169136. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169137. typedef struct {
  169138. /* Basic tables: (element [0] of each array is unused) */
  169139. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169140. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169141. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169142. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169143. * the smallest code of length k; so given a code of length k, the
  169144. * corresponding symbol is huffval[code + valoffset[k]]
  169145. */
  169146. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169147. JHUFF_TBL *pub;
  169148. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169149. * the input data stream. If the next Huffman code is no more
  169150. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169151. * the corresponding symbol directly from these tables.
  169152. */
  169153. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169154. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169155. } d_derived_tbl;
  169156. /* Expand a Huffman table definition into the derived format */
  169157. EXTERN(void) jpeg_make_d_derived_tbl
  169158. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169159. d_derived_tbl ** pdtbl));
  169160. /*
  169161. * Fetching the next N bits from the input stream is a time-critical operation
  169162. * for the Huffman decoders. We implement it with a combination of inline
  169163. * macros and out-of-line subroutines. Note that N (the number of bits
  169164. * demanded at one time) never exceeds 15 for JPEG use.
  169165. *
  169166. * We read source bytes into get_buffer and dole out bits as needed.
  169167. * If get_buffer already contains enough bits, they are fetched in-line
  169168. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169169. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169170. * as full as possible (not just to the number of bits needed; this
  169171. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169172. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169173. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169174. * at least the requested number of bits --- dummy zeroes are inserted if
  169175. * necessary.
  169176. */
  169177. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169178. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169179. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169180. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169181. * appropriately should be a win. Unfortunately we can't define the size
  169182. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169183. * because not all machines measure sizeof in 8-bit bytes.
  169184. */
  169185. typedef struct { /* Bitreading state saved across MCUs */
  169186. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169187. int bits_left; /* # of unused bits in it */
  169188. } bitread_perm_state;
  169189. typedef struct { /* Bitreading working state within an MCU */
  169190. /* Current data source location */
  169191. /* We need a copy, rather than munging the original, in case of suspension */
  169192. const JOCTET * next_input_byte; /* => next byte to read from source */
  169193. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169194. /* Bit input buffer --- note these values are kept in register variables,
  169195. * not in this struct, inside the inner loops.
  169196. */
  169197. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169198. int bits_left; /* # of unused bits in it */
  169199. /* Pointer needed by jpeg_fill_bit_buffer. */
  169200. j_decompress_ptr cinfo; /* back link to decompress master record */
  169201. } bitread_working_state;
  169202. /* Macros to declare and load/save bitread local variables. */
  169203. #define BITREAD_STATE_VARS \
  169204. register bit_buf_type get_buffer; \
  169205. register int bits_left; \
  169206. bitread_working_state br_state
  169207. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169208. br_state.cinfo = cinfop; \
  169209. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169210. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169211. get_buffer = permstate.get_buffer; \
  169212. bits_left = permstate.bits_left;
  169213. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169214. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169215. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169216. permstate.get_buffer = get_buffer; \
  169217. permstate.bits_left = bits_left
  169218. /*
  169219. * These macros provide the in-line portion of bit fetching.
  169220. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169221. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169222. * The variables get_buffer and bits_left are assumed to be locals,
  169223. * but the state struct might not be (jpeg_huff_decode needs this).
  169224. * CHECK_BIT_BUFFER(state,n,action);
  169225. * Ensure there are N bits in get_buffer; if suspend, take action.
  169226. * val = GET_BITS(n);
  169227. * Fetch next N bits.
  169228. * val = PEEK_BITS(n);
  169229. * Fetch next N bits without removing them from the buffer.
  169230. * DROP_BITS(n);
  169231. * Discard next N bits.
  169232. * The value N should be a simple variable, not an expression, because it
  169233. * is evaluated multiple times.
  169234. */
  169235. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169236. { if (bits_left < (nbits)) { \
  169237. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169238. { action; } \
  169239. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169240. #define GET_BITS(nbits) \
  169241. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169242. #define PEEK_BITS(nbits) \
  169243. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169244. #define DROP_BITS(nbits) \
  169245. (bits_left -= (nbits))
  169246. /* Load up the bit buffer to a depth of at least nbits */
  169247. EXTERN(boolean) jpeg_fill_bit_buffer
  169248. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169249. register int bits_left, int nbits));
  169250. /*
  169251. * Code for extracting next Huffman-coded symbol from input bit stream.
  169252. * Again, this is time-critical and we make the main paths be macros.
  169253. *
  169254. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169255. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169256. * or fewer bits long. The few overlength codes are handled with a loop,
  169257. * which need not be inline code.
  169258. *
  169259. * Notes about the HUFF_DECODE macro:
  169260. * 1. Near the end of the data segment, we may fail to get enough bits
  169261. * for a lookahead. In that case, we do it the hard way.
  169262. * 2. If the lookahead table contains no entry, the next code must be
  169263. * more than HUFF_LOOKAHEAD bits long.
  169264. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169265. */
  169266. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169267. { register int nb, look; \
  169268. if (bits_left < HUFF_LOOKAHEAD) { \
  169269. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169270. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169271. if (bits_left < HUFF_LOOKAHEAD) { \
  169272. nb = 1; goto slowlabel; \
  169273. } \
  169274. } \
  169275. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169276. if ((nb = htbl->look_nbits[look]) != 0) { \
  169277. DROP_BITS(nb); \
  169278. result = htbl->look_sym[look]; \
  169279. } else { \
  169280. nb = HUFF_LOOKAHEAD+1; \
  169281. slowlabel: \
  169282. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169283. { failaction; } \
  169284. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169285. } \
  169286. }
  169287. /* Out-of-line case for Huffman code fetching */
  169288. EXTERN(int) jpeg_huff_decode
  169289. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169290. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169291. #endif
  169292. /*** End of inlined file: jdhuff.h ***/
  169293. /* Declarations shared with jdphuff.c */
  169294. /*
  169295. * Expanded entropy decoder object for Huffman decoding.
  169296. *
  169297. * The savable_state subrecord contains fields that change within an MCU,
  169298. * but must not be updated permanently until we complete the MCU.
  169299. */
  169300. typedef struct {
  169301. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169302. } savable_state2;
  169303. /* This macro is to work around compilers with missing or broken
  169304. * structure assignment. You'll need to fix this code if you have
  169305. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169306. */
  169307. #ifndef NO_STRUCT_ASSIGN
  169308. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169309. #else
  169310. #if MAX_COMPS_IN_SCAN == 4
  169311. #define ASSIGN_STATE(dest,src) \
  169312. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169313. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169314. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169315. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169316. #endif
  169317. #endif
  169318. typedef struct {
  169319. struct jpeg_entropy_decoder pub; /* public fields */
  169320. /* These fields are loaded into local variables at start of each MCU.
  169321. * In case of suspension, we exit WITHOUT updating them.
  169322. */
  169323. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169324. savable_state2 saved; /* Other state at start of MCU */
  169325. /* These fields are NOT loaded into local working state. */
  169326. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169327. /* Pointers to derived tables (these workspaces have image lifespan) */
  169328. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169329. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169330. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169331. /* Pointers to derived tables to be used for each block within an MCU */
  169332. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169333. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169334. /* Whether we care about the DC and AC coefficient values for each block */
  169335. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169336. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169337. } huff_entropy_decoder2;
  169338. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169339. /*
  169340. * Initialize for a Huffman-compressed scan.
  169341. */
  169342. METHODDEF(void)
  169343. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169344. {
  169345. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169346. int ci, blkn, dctbl, actbl;
  169347. jpeg_component_info * compptr;
  169348. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169349. * This ought to be an error condition, but we make it a warning because
  169350. * there are some baseline files out there with all zeroes in these bytes.
  169351. */
  169352. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169353. cinfo->Ah != 0 || cinfo->Al != 0)
  169354. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169355. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169356. compptr = cinfo->cur_comp_info[ci];
  169357. dctbl = compptr->dc_tbl_no;
  169358. actbl = compptr->ac_tbl_no;
  169359. /* Compute derived values for Huffman tables */
  169360. /* We may do this more than once for a table, but it's not expensive */
  169361. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169362. & entropy->dc_derived_tbls[dctbl]);
  169363. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169364. & entropy->ac_derived_tbls[actbl]);
  169365. /* Initialize DC predictions to 0 */
  169366. entropy->saved.last_dc_val[ci] = 0;
  169367. }
  169368. /* Precalculate decoding info for each block in an MCU of this scan */
  169369. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169370. ci = cinfo->MCU_membership[blkn];
  169371. compptr = cinfo->cur_comp_info[ci];
  169372. /* Precalculate which table to use for each block */
  169373. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169374. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169375. /* Decide whether we really care about the coefficient values */
  169376. if (compptr->component_needed) {
  169377. entropy->dc_needed[blkn] = TRUE;
  169378. /* we don't need the ACs if producing a 1/8th-size image */
  169379. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169380. } else {
  169381. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169382. }
  169383. }
  169384. /* Initialize bitread state variables */
  169385. entropy->bitstate.bits_left = 0;
  169386. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169387. entropy->pub.insufficient_data = FALSE;
  169388. /* Initialize restart counter */
  169389. entropy->restarts_to_go = cinfo->restart_interval;
  169390. }
  169391. /*
  169392. * Compute the derived values for a Huffman table.
  169393. * This routine also performs some validation checks on the table.
  169394. *
  169395. * Note this is also used by jdphuff.c.
  169396. */
  169397. GLOBAL(void)
  169398. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169399. d_derived_tbl ** pdtbl)
  169400. {
  169401. JHUFF_TBL *htbl;
  169402. d_derived_tbl *dtbl;
  169403. int p, i, l, si, numsymbols;
  169404. int lookbits, ctr;
  169405. char huffsize[257];
  169406. unsigned int huffcode[257];
  169407. unsigned int code;
  169408. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169409. * paralleling the order of the symbols themselves in htbl->huffval[].
  169410. */
  169411. /* Find the input Huffman table */
  169412. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169413. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169414. htbl =
  169415. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169416. if (htbl == NULL)
  169417. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169418. /* Allocate a workspace if we haven't already done so. */
  169419. if (*pdtbl == NULL)
  169420. *pdtbl = (d_derived_tbl *)
  169421. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169422. SIZEOF(d_derived_tbl));
  169423. dtbl = *pdtbl;
  169424. dtbl->pub = htbl; /* fill in back link */
  169425. /* Figure C.1: make table of Huffman code length for each symbol */
  169426. p = 0;
  169427. for (l = 1; l <= 16; l++) {
  169428. i = (int) htbl->bits[l];
  169429. if (i < 0 || p + i > 256) /* protect against table overrun */
  169430. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169431. while (i--)
  169432. huffsize[p++] = (char) l;
  169433. }
  169434. huffsize[p] = 0;
  169435. numsymbols = p;
  169436. /* Figure C.2: generate the codes themselves */
  169437. /* We also validate that the counts represent a legal Huffman code tree. */
  169438. code = 0;
  169439. si = huffsize[0];
  169440. p = 0;
  169441. while (huffsize[p]) {
  169442. while (((int) huffsize[p]) == si) {
  169443. huffcode[p++] = code;
  169444. code++;
  169445. }
  169446. /* code is now 1 more than the last code used for codelength si; but
  169447. * it must still fit in si bits, since no code is allowed to be all ones.
  169448. */
  169449. if (((INT32) code) >= (((INT32) 1) << si))
  169450. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169451. code <<= 1;
  169452. si++;
  169453. }
  169454. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169455. p = 0;
  169456. for (l = 1; l <= 16; l++) {
  169457. if (htbl->bits[l]) {
  169458. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169459. * minus the minimum code of length l
  169460. */
  169461. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169462. p += htbl->bits[l];
  169463. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169464. } else {
  169465. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169466. }
  169467. }
  169468. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169469. /* Compute lookahead tables to speed up decoding.
  169470. * First we set all the table entries to 0, indicating "too long";
  169471. * then we iterate through the Huffman codes that are short enough and
  169472. * fill in all the entries that correspond to bit sequences starting
  169473. * with that code.
  169474. */
  169475. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169476. p = 0;
  169477. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169478. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169479. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169480. /* Generate left-justified code followed by all possible bit sequences */
  169481. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169482. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169483. dtbl->look_nbits[lookbits] = l;
  169484. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169485. lookbits++;
  169486. }
  169487. }
  169488. }
  169489. /* Validate symbols as being reasonable.
  169490. * For AC tables, we make no check, but accept all byte values 0..255.
  169491. * For DC tables, we require the symbols to be in range 0..15.
  169492. * (Tighter bounds could be applied depending on the data depth and mode,
  169493. * but this is sufficient to ensure safe decoding.)
  169494. */
  169495. if (isDC) {
  169496. for (i = 0; i < numsymbols; i++) {
  169497. int sym = htbl->huffval[i];
  169498. if (sym < 0 || sym > 15)
  169499. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169500. }
  169501. }
  169502. }
  169503. /*
  169504. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169505. * See jdhuff.h for info about usage.
  169506. * Note: current values of get_buffer and bits_left are passed as parameters,
  169507. * but are returned in the corresponding fields of the state struct.
  169508. *
  169509. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169510. * of get_buffer to be used. (On machines with wider words, an even larger
  169511. * buffer could be used.) However, on some machines 32-bit shifts are
  169512. * quite slow and take time proportional to the number of places shifted.
  169513. * (This is true with most PC compilers, for instance.) In this case it may
  169514. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169515. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169516. */
  169517. #ifdef SLOW_SHIFT_32
  169518. #define MIN_GET_BITS 15 /* minimum allowable value */
  169519. #else
  169520. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169521. #endif
  169522. GLOBAL(boolean)
  169523. jpeg_fill_bit_buffer (bitread_working_state * state,
  169524. register bit_buf_type get_buffer, register int bits_left,
  169525. int nbits)
  169526. /* Load up the bit buffer to a depth of at least nbits */
  169527. {
  169528. /* Copy heavily used state fields into locals (hopefully registers) */
  169529. register const JOCTET * next_input_byte = state->next_input_byte;
  169530. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169531. j_decompress_ptr cinfo = state->cinfo;
  169532. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169533. /* (It is assumed that no request will be for more than that many bits.) */
  169534. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169535. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169536. while (bits_left < MIN_GET_BITS) {
  169537. register int c;
  169538. /* Attempt to read a byte */
  169539. if (bytes_in_buffer == 0) {
  169540. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169541. return FALSE;
  169542. next_input_byte = cinfo->src->next_input_byte;
  169543. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169544. }
  169545. bytes_in_buffer--;
  169546. c = GETJOCTET(*next_input_byte++);
  169547. /* If it's 0xFF, check and discard stuffed zero byte */
  169548. if (c == 0xFF) {
  169549. /* Loop here to discard any padding FF's on terminating marker,
  169550. * so that we can save a valid unread_marker value. NOTE: we will
  169551. * accept multiple FF's followed by a 0 as meaning a single FF data
  169552. * byte. This data pattern is not valid according to the standard.
  169553. */
  169554. do {
  169555. if (bytes_in_buffer == 0) {
  169556. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169557. return FALSE;
  169558. next_input_byte = cinfo->src->next_input_byte;
  169559. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169560. }
  169561. bytes_in_buffer--;
  169562. c = GETJOCTET(*next_input_byte++);
  169563. } while (c == 0xFF);
  169564. if (c == 0) {
  169565. /* Found FF/00, which represents an FF data byte */
  169566. c = 0xFF;
  169567. } else {
  169568. /* Oops, it's actually a marker indicating end of compressed data.
  169569. * Save the marker code for later use.
  169570. * Fine point: it might appear that we should save the marker into
  169571. * bitread working state, not straight into permanent state. But
  169572. * once we have hit a marker, we cannot need to suspend within the
  169573. * current MCU, because we will read no more bytes from the data
  169574. * source. So it is OK to update permanent state right away.
  169575. */
  169576. cinfo->unread_marker = c;
  169577. /* See if we need to insert some fake zero bits. */
  169578. goto no_more_bytes;
  169579. }
  169580. }
  169581. /* OK, load c into get_buffer */
  169582. get_buffer = (get_buffer << 8) | c;
  169583. bits_left += 8;
  169584. } /* end while */
  169585. } else {
  169586. no_more_bytes:
  169587. /* We get here if we've read the marker that terminates the compressed
  169588. * data segment. There should be enough bits in the buffer register
  169589. * to satisfy the request; if so, no problem.
  169590. */
  169591. if (nbits > bits_left) {
  169592. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169593. * the data stream, so that we can produce some kind of image.
  169594. * We use a nonvolatile flag to ensure that only one warning message
  169595. * appears per data segment.
  169596. */
  169597. if (! cinfo->entropy->insufficient_data) {
  169598. WARNMS(cinfo, JWRN_HIT_MARKER);
  169599. cinfo->entropy->insufficient_data = TRUE;
  169600. }
  169601. /* Fill the buffer with zero bits */
  169602. get_buffer <<= MIN_GET_BITS - bits_left;
  169603. bits_left = MIN_GET_BITS;
  169604. }
  169605. }
  169606. /* Unload the local registers */
  169607. state->next_input_byte = next_input_byte;
  169608. state->bytes_in_buffer = bytes_in_buffer;
  169609. state->get_buffer = get_buffer;
  169610. state->bits_left = bits_left;
  169611. return TRUE;
  169612. }
  169613. /*
  169614. * Out-of-line code for Huffman code decoding.
  169615. * See jdhuff.h for info about usage.
  169616. */
  169617. GLOBAL(int)
  169618. jpeg_huff_decode (bitread_working_state * state,
  169619. register bit_buf_type get_buffer, register int bits_left,
  169620. d_derived_tbl * htbl, int min_bits)
  169621. {
  169622. register int l = min_bits;
  169623. register INT32 code;
  169624. /* HUFF_DECODE has determined that the code is at least min_bits */
  169625. /* bits long, so fetch that many bits in one swoop. */
  169626. CHECK_BIT_BUFFER(*state, l, return -1);
  169627. code = GET_BITS(l);
  169628. /* Collect the rest of the Huffman code one bit at a time. */
  169629. /* This is per Figure F.16 in the JPEG spec. */
  169630. while (code > htbl->maxcode[l]) {
  169631. code <<= 1;
  169632. CHECK_BIT_BUFFER(*state, 1, return -1);
  169633. code |= GET_BITS(1);
  169634. l++;
  169635. }
  169636. /* Unload the local registers */
  169637. state->get_buffer = get_buffer;
  169638. state->bits_left = bits_left;
  169639. /* With garbage input we may reach the sentinel value l = 17. */
  169640. if (l > 16) {
  169641. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169642. return 0; /* fake a zero as the safest result */
  169643. }
  169644. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169645. }
  169646. /*
  169647. * Check for a restart marker & resynchronize decoder.
  169648. * Returns FALSE if must suspend.
  169649. */
  169650. LOCAL(boolean)
  169651. process_restart (j_decompress_ptr cinfo)
  169652. {
  169653. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169654. int ci;
  169655. /* Throw away any unused bits remaining in bit buffer; */
  169656. /* include any full bytes in next_marker's count of discarded bytes */
  169657. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169658. entropy->bitstate.bits_left = 0;
  169659. /* Advance past the RSTn marker */
  169660. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169661. return FALSE;
  169662. /* Re-initialize DC predictions to 0 */
  169663. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169664. entropy->saved.last_dc_val[ci] = 0;
  169665. /* Reset restart counter */
  169666. entropy->restarts_to_go = cinfo->restart_interval;
  169667. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169668. * against a marker. In that case we will end up treating the next data
  169669. * segment as empty, and we can avoid producing bogus output pixels by
  169670. * leaving the flag set.
  169671. */
  169672. if (cinfo->unread_marker == 0)
  169673. entropy->pub.insufficient_data = FALSE;
  169674. return TRUE;
  169675. }
  169676. /*
  169677. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169678. * The coefficients are reordered from zigzag order into natural array order,
  169679. * but are not dequantized.
  169680. *
  169681. * The i'th block of the MCU is stored into the block pointed to by
  169682. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169683. * (Wholesale zeroing is usually a little faster than retail...)
  169684. *
  169685. * Returns FALSE if data source requested suspension. In that case no
  169686. * changes have been made to permanent state. (Exception: some output
  169687. * coefficients may already have been assigned. This is harmless for
  169688. * this module, since we'll just re-assign them on the next call.)
  169689. */
  169690. METHODDEF(boolean)
  169691. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169692. {
  169693. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169694. int blkn;
  169695. BITREAD_STATE_VARS;
  169696. savable_state2 state;
  169697. /* Process restart marker if needed; may have to suspend */
  169698. if (cinfo->restart_interval) {
  169699. if (entropy->restarts_to_go == 0)
  169700. if (! process_restart(cinfo))
  169701. return FALSE;
  169702. }
  169703. /* If we've run out of data, just leave the MCU set to zeroes.
  169704. * This way, we return uniform gray for the remainder of the segment.
  169705. */
  169706. if (! entropy->pub.insufficient_data) {
  169707. /* Load up working state */
  169708. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169709. ASSIGN_STATE(state, entropy->saved);
  169710. /* Outer loop handles each block in the MCU */
  169711. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169712. JBLOCKROW block = MCU_data[blkn];
  169713. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169714. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169715. register int s, k, r;
  169716. /* Decode a single block's worth of coefficients */
  169717. /* Section F.2.2.1: decode the DC coefficient difference */
  169718. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169719. if (s) {
  169720. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169721. r = GET_BITS(s);
  169722. s = HUFF_EXTEND(r, s);
  169723. }
  169724. if (entropy->dc_needed[blkn]) {
  169725. /* Convert DC difference to actual value, update last_dc_val */
  169726. int ci = cinfo->MCU_membership[blkn];
  169727. s += state.last_dc_val[ci];
  169728. state.last_dc_val[ci] = s;
  169729. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169730. (*block)[0] = (JCOEF) s;
  169731. }
  169732. if (entropy->ac_needed[blkn]) {
  169733. /* Section F.2.2.2: decode the AC coefficients */
  169734. /* Since zeroes are skipped, output area must be cleared beforehand */
  169735. for (k = 1; k < DCTSIZE2; k++) {
  169736. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169737. r = s >> 4;
  169738. s &= 15;
  169739. if (s) {
  169740. k += r;
  169741. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169742. r = GET_BITS(s);
  169743. s = HUFF_EXTEND(r, s);
  169744. /* Output coefficient in natural (dezigzagged) order.
  169745. * Note: the extra entries in jpeg_natural_order[] will save us
  169746. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169747. */
  169748. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169749. } else {
  169750. if (r != 15)
  169751. break;
  169752. k += 15;
  169753. }
  169754. }
  169755. } else {
  169756. /* Section F.2.2.2: decode the AC coefficients */
  169757. /* In this path we just discard the values */
  169758. for (k = 1; k < DCTSIZE2; k++) {
  169759. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169760. r = s >> 4;
  169761. s &= 15;
  169762. if (s) {
  169763. k += r;
  169764. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169765. DROP_BITS(s);
  169766. } else {
  169767. if (r != 15)
  169768. break;
  169769. k += 15;
  169770. }
  169771. }
  169772. }
  169773. }
  169774. /* Completed MCU, so update state */
  169775. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169776. ASSIGN_STATE(entropy->saved, state);
  169777. }
  169778. /* Account for restart interval (no-op if not using restarts) */
  169779. entropy->restarts_to_go--;
  169780. return TRUE;
  169781. }
  169782. /*
  169783. * Module initialization routine for Huffman entropy decoding.
  169784. */
  169785. GLOBAL(void)
  169786. jinit_huff_decoder (j_decompress_ptr cinfo)
  169787. {
  169788. huff_entropy_ptr2 entropy;
  169789. int i;
  169790. entropy = (huff_entropy_ptr2)
  169791. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169792. SIZEOF(huff_entropy_decoder2));
  169793. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169794. entropy->pub.start_pass = start_pass_huff_decoder;
  169795. entropy->pub.decode_mcu = decode_mcu;
  169796. /* Mark tables unallocated */
  169797. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169798. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169799. }
  169800. }
  169801. /*** End of inlined file: jdhuff.c ***/
  169802. /*** Start of inlined file: jdinput.c ***/
  169803. #define JPEG_INTERNALS
  169804. /* Private state */
  169805. typedef struct {
  169806. struct jpeg_input_controller pub; /* public fields */
  169807. boolean inheaders; /* TRUE until first SOS is reached */
  169808. } my_input_controller;
  169809. typedef my_input_controller * my_inputctl_ptr;
  169810. /* Forward declarations */
  169811. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169812. /*
  169813. * Routines to calculate various quantities related to the size of the image.
  169814. */
  169815. LOCAL(void)
  169816. initial_setup2 (j_decompress_ptr cinfo)
  169817. /* Called once, when first SOS marker is reached */
  169818. {
  169819. int ci;
  169820. jpeg_component_info *compptr;
  169821. /* Make sure image isn't bigger than I can handle */
  169822. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169823. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  169824. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  169825. /* For now, precision must match compiled-in value... */
  169826. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  169827. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  169828. /* Check that number of components won't exceed internal array sizes */
  169829. if (cinfo->num_components > MAX_COMPONENTS)
  169830. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  169831. MAX_COMPONENTS);
  169832. /* Compute maximum sampling factors; check factor validity */
  169833. cinfo->max_h_samp_factor = 1;
  169834. cinfo->max_v_samp_factor = 1;
  169835. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169836. ci++, compptr++) {
  169837. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  169838. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  169839. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  169840. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  169841. compptr->h_samp_factor);
  169842. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  169843. compptr->v_samp_factor);
  169844. }
  169845. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  169846. * In the full decompressor, this will be overridden by jdmaster.c;
  169847. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  169848. */
  169849. cinfo->min_DCT_scaled_size = DCTSIZE;
  169850. /* Compute dimensions of components */
  169851. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169852. ci++, compptr++) {
  169853. compptr->DCT_scaled_size = DCTSIZE;
  169854. /* Size in DCT blocks */
  169855. compptr->width_in_blocks = (JDIMENSION)
  169856. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169857. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169858. compptr->height_in_blocks = (JDIMENSION)
  169859. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169860. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169861. /* downsampled_width and downsampled_height will also be overridden by
  169862. * jdmaster.c if we are doing full decompression. The transcoder library
  169863. * doesn't use these values, but the calling application might.
  169864. */
  169865. /* Size in samples */
  169866. compptr->downsampled_width = (JDIMENSION)
  169867. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169868. (long) cinfo->max_h_samp_factor);
  169869. compptr->downsampled_height = (JDIMENSION)
  169870. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169871. (long) cinfo->max_v_samp_factor);
  169872. /* Mark component needed, until color conversion says otherwise */
  169873. compptr->component_needed = TRUE;
  169874. /* Mark no quantization table yet saved for component */
  169875. compptr->quant_table = NULL;
  169876. }
  169877. /* Compute number of fully interleaved MCU rows. */
  169878. cinfo->total_iMCU_rows = (JDIMENSION)
  169879. jdiv_round_up((long) cinfo->image_height,
  169880. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169881. /* Decide whether file contains multiple scans */
  169882. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  169883. cinfo->inputctl->has_multiple_scans = TRUE;
  169884. else
  169885. cinfo->inputctl->has_multiple_scans = FALSE;
  169886. }
  169887. LOCAL(void)
  169888. per_scan_setup2 (j_decompress_ptr cinfo)
  169889. /* Do computations that are needed before processing a JPEG scan */
  169890. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  169891. {
  169892. int ci, mcublks, tmp;
  169893. jpeg_component_info *compptr;
  169894. if (cinfo->comps_in_scan == 1) {
  169895. /* Noninterleaved (single-component) scan */
  169896. compptr = cinfo->cur_comp_info[0];
  169897. /* Overall image size in MCUs */
  169898. cinfo->MCUs_per_row = compptr->width_in_blocks;
  169899. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  169900. /* For noninterleaved scan, always one block per MCU */
  169901. compptr->MCU_width = 1;
  169902. compptr->MCU_height = 1;
  169903. compptr->MCU_blocks = 1;
  169904. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  169905. compptr->last_col_width = 1;
  169906. /* For noninterleaved scans, it is convenient to define last_row_height
  169907. * as the number of block rows present in the last iMCU row.
  169908. */
  169909. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169910. if (tmp == 0) tmp = compptr->v_samp_factor;
  169911. compptr->last_row_height = tmp;
  169912. /* Prepare array describing MCU composition */
  169913. cinfo->blocks_in_MCU = 1;
  169914. cinfo->MCU_membership[0] = 0;
  169915. } else {
  169916. /* Interleaved (multi-component) scan */
  169917. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  169918. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  169919. MAX_COMPS_IN_SCAN);
  169920. /* Overall image size in MCUs */
  169921. cinfo->MCUs_per_row = (JDIMENSION)
  169922. jdiv_round_up((long) cinfo->image_width,
  169923. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  169924. cinfo->MCU_rows_in_scan = (JDIMENSION)
  169925. jdiv_round_up((long) cinfo->image_height,
  169926. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169927. cinfo->blocks_in_MCU = 0;
  169928. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169929. compptr = cinfo->cur_comp_info[ci];
  169930. /* Sampling factors give # of blocks of component in each MCU */
  169931. compptr->MCU_width = compptr->h_samp_factor;
  169932. compptr->MCU_height = compptr->v_samp_factor;
  169933. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  169934. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  169935. /* Figure number of non-dummy blocks in last MCU column & row */
  169936. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  169937. if (tmp == 0) tmp = compptr->MCU_width;
  169938. compptr->last_col_width = tmp;
  169939. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  169940. if (tmp == 0) tmp = compptr->MCU_height;
  169941. compptr->last_row_height = tmp;
  169942. /* Prepare array describing MCU composition */
  169943. mcublks = compptr->MCU_blocks;
  169944. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  169945. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  169946. while (mcublks-- > 0) {
  169947. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  169948. }
  169949. }
  169950. }
  169951. }
  169952. /*
  169953. * Save away a copy of the Q-table referenced by each component present
  169954. * in the current scan, unless already saved during a prior scan.
  169955. *
  169956. * In a multiple-scan JPEG file, the encoder could assign different components
  169957. * the same Q-table slot number, but change table definitions between scans
  169958. * so that each component uses a different Q-table. (The IJG encoder is not
  169959. * currently capable of doing this, but other encoders might.) Since we want
  169960. * to be able to dequantize all the components at the end of the file, this
  169961. * means that we have to save away the table actually used for each component.
  169962. * We do this by copying the table at the start of the first scan containing
  169963. * the component.
  169964. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  169965. * slot between scans of a component using that slot. If the encoder does so
  169966. * anyway, this decoder will simply use the Q-table values that were current
  169967. * at the start of the first scan for the component.
  169968. *
  169969. * The decompressor output side looks only at the saved quant tables,
  169970. * not at the current Q-table slots.
  169971. */
  169972. LOCAL(void)
  169973. latch_quant_tables (j_decompress_ptr cinfo)
  169974. {
  169975. int ci, qtblno;
  169976. jpeg_component_info *compptr;
  169977. JQUANT_TBL * qtbl;
  169978. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169979. compptr = cinfo->cur_comp_info[ci];
  169980. /* No work if we already saved Q-table for this component */
  169981. if (compptr->quant_table != NULL)
  169982. continue;
  169983. /* Make sure specified quantization table is present */
  169984. qtblno = compptr->quant_tbl_no;
  169985. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  169986. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  169987. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  169988. /* OK, save away the quantization table */
  169989. qtbl = (JQUANT_TBL *)
  169990. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169991. SIZEOF(JQUANT_TBL));
  169992. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  169993. compptr->quant_table = qtbl;
  169994. }
  169995. }
  169996. /*
  169997. * Initialize the input modules to read a scan of compressed data.
  169998. * The first call to this is done by jdmaster.c after initializing
  169999. * the entire decompressor (during jpeg_start_decompress).
  170000. * Subsequent calls come from consume_markers, below.
  170001. */
  170002. METHODDEF(void)
  170003. start_input_pass2 (j_decompress_ptr cinfo)
  170004. {
  170005. per_scan_setup2(cinfo);
  170006. latch_quant_tables(cinfo);
  170007. (*cinfo->entropy->start_pass) (cinfo);
  170008. (*cinfo->coef->start_input_pass) (cinfo);
  170009. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170010. }
  170011. /*
  170012. * Finish up after inputting a compressed-data scan.
  170013. * This is called by the coefficient controller after it's read all
  170014. * the expected data of the scan.
  170015. */
  170016. METHODDEF(void)
  170017. finish_input_pass (j_decompress_ptr cinfo)
  170018. {
  170019. cinfo->inputctl->consume_input = consume_markers;
  170020. }
  170021. /*
  170022. * Read JPEG markers before, between, or after compressed-data scans.
  170023. * Change state as necessary when a new scan is reached.
  170024. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170025. *
  170026. * The consume_input method pointer points either here or to the
  170027. * coefficient controller's consume_data routine, depending on whether
  170028. * we are reading a compressed data segment or inter-segment markers.
  170029. */
  170030. METHODDEF(int)
  170031. consume_markers (j_decompress_ptr cinfo)
  170032. {
  170033. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170034. int val;
  170035. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170036. return JPEG_REACHED_EOI;
  170037. val = (*cinfo->marker->read_markers) (cinfo);
  170038. switch (val) {
  170039. case JPEG_REACHED_SOS: /* Found SOS */
  170040. if (inputctl->inheaders) { /* 1st SOS */
  170041. initial_setup2(cinfo);
  170042. inputctl->inheaders = FALSE;
  170043. /* Note: start_input_pass must be called by jdmaster.c
  170044. * before any more input can be consumed. jdapimin.c is
  170045. * responsible for enforcing this sequencing.
  170046. */
  170047. } else { /* 2nd or later SOS marker */
  170048. if (! inputctl->pub.has_multiple_scans)
  170049. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170050. start_input_pass2(cinfo);
  170051. }
  170052. break;
  170053. case JPEG_REACHED_EOI: /* Found EOI */
  170054. inputctl->pub.eoi_reached = TRUE;
  170055. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170056. if (cinfo->marker->saw_SOF)
  170057. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170058. } else {
  170059. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170060. * if user set output_scan_number larger than number of scans.
  170061. */
  170062. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170063. cinfo->output_scan_number = cinfo->input_scan_number;
  170064. }
  170065. break;
  170066. case JPEG_SUSPENDED:
  170067. break;
  170068. }
  170069. return val;
  170070. }
  170071. /*
  170072. * Reset state to begin a fresh datastream.
  170073. */
  170074. METHODDEF(void)
  170075. reset_input_controller (j_decompress_ptr cinfo)
  170076. {
  170077. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170078. inputctl->pub.consume_input = consume_markers;
  170079. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170080. inputctl->pub.eoi_reached = FALSE;
  170081. inputctl->inheaders = TRUE;
  170082. /* Reset other modules */
  170083. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170084. (*cinfo->marker->reset_marker_reader) (cinfo);
  170085. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170086. cinfo->coef_bits = NULL;
  170087. }
  170088. /*
  170089. * Initialize the input controller module.
  170090. * This is called only once, when the decompression object is created.
  170091. */
  170092. GLOBAL(void)
  170093. jinit_input_controller (j_decompress_ptr cinfo)
  170094. {
  170095. my_inputctl_ptr inputctl;
  170096. /* Create subobject in permanent pool */
  170097. inputctl = (my_inputctl_ptr)
  170098. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170099. SIZEOF(my_input_controller));
  170100. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170101. /* Initialize method pointers */
  170102. inputctl->pub.consume_input = consume_markers;
  170103. inputctl->pub.reset_input_controller = reset_input_controller;
  170104. inputctl->pub.start_input_pass = start_input_pass2;
  170105. inputctl->pub.finish_input_pass = finish_input_pass;
  170106. /* Initialize state: can't use reset_input_controller since we don't
  170107. * want to try to reset other modules yet.
  170108. */
  170109. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170110. inputctl->pub.eoi_reached = FALSE;
  170111. inputctl->inheaders = TRUE;
  170112. }
  170113. /*** End of inlined file: jdinput.c ***/
  170114. /*** Start of inlined file: jdmainct.c ***/
  170115. #define JPEG_INTERNALS
  170116. /*
  170117. * In the current system design, the main buffer need never be a full-image
  170118. * buffer; any full-height buffers will be found inside the coefficient or
  170119. * postprocessing controllers. Nonetheless, the main controller is not
  170120. * trivial. Its responsibility is to provide context rows for upsampling/
  170121. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170122. *
  170123. * Postprocessor input data is counted in "row groups". A row group
  170124. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170125. * sample rows of each component. (We require DCT_scaled_size values to be
  170126. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170127. * values will likely be powers of two, so we actually have the stronger
  170128. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170129. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170130. * row group (times any additional scale factor that the upsampler is
  170131. * applying).
  170132. *
  170133. * The coefficient controller will deliver data to us one iMCU row at a time;
  170134. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170135. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170136. * to one row of MCUs when the image is fully interleaved.) Note that the
  170137. * number of sample rows varies across components, but the number of row
  170138. * groups does not. Some garbage sample rows may be included in the last iMCU
  170139. * row at the bottom of the image.
  170140. *
  170141. * Depending on the vertical scaling algorithm used, the upsampler may need
  170142. * access to the sample row(s) above and below its current input row group.
  170143. * The upsampler is required to set need_context_rows TRUE at global selection
  170144. * time if so. When need_context_rows is FALSE, this controller can simply
  170145. * obtain one iMCU row at a time from the coefficient controller and dole it
  170146. * out as row groups to the postprocessor.
  170147. *
  170148. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170149. * passed to postprocessing contains at least one row group's worth of samples
  170150. * above and below the row group(s) being processed. Note that the context
  170151. * rows "above" the first passed row group appear at negative row offsets in
  170152. * the passed buffer. At the top and bottom of the image, the required
  170153. * context rows are manufactured by duplicating the first or last real sample
  170154. * row; this avoids having special cases in the upsampling inner loops.
  170155. *
  170156. * The amount of context is fixed at one row group just because that's a
  170157. * convenient number for this controller to work with. The existing
  170158. * upsamplers really only need one sample row of context. An upsampler
  170159. * supporting arbitrary output rescaling might wish for more than one row
  170160. * group of context when shrinking the image; tough, we don't handle that.
  170161. * (This is justified by the assumption that downsizing will be handled mostly
  170162. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170163. * the upsample step needn't be much less than one.)
  170164. *
  170165. * To provide the desired context, we have to retain the last two row groups
  170166. * of one iMCU row while reading in the next iMCU row. (The last row group
  170167. * can't be processed until we have another row group for its below-context,
  170168. * and so we have to save the next-to-last group too for its above-context.)
  170169. * We could do this most simply by copying data around in our buffer, but
  170170. * that'd be very slow. We can avoid copying any data by creating a rather
  170171. * strange pointer structure. Here's how it works. We allocate a workspace
  170172. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170173. * of row groups per iMCU row). We create two sets of redundant pointers to
  170174. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170175. * pointer lists look like this:
  170176. * M+1 M-1
  170177. * master pointer --> 0 master pointer --> 0
  170178. * 1 1
  170179. * ... ...
  170180. * M-3 M-3
  170181. * M-2 M
  170182. * M-1 M+1
  170183. * M M-2
  170184. * M+1 M-1
  170185. * 0 0
  170186. * We read alternate iMCU rows using each master pointer; thus the last two
  170187. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170188. * The pointer lists are set up so that the required context rows appear to
  170189. * be adjacent to the proper places when we pass the pointer lists to the
  170190. * upsampler.
  170191. *
  170192. * The above pictures describe the normal state of the pointer lists.
  170193. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170194. * the first or last sample row as necessary (this is cheaper than copying
  170195. * sample rows around).
  170196. *
  170197. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170198. * situation each iMCU row provides only one row group so the buffering logic
  170199. * must be different (eg, we must read two iMCU rows before we can emit the
  170200. * first row group). For now, we simply do not support providing context
  170201. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170202. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170203. * want it quick and dirty, so a context-free upsampler is sufficient.
  170204. */
  170205. /* Private buffer controller object */
  170206. typedef struct {
  170207. struct jpeg_d_main_controller pub; /* public fields */
  170208. /* Pointer to allocated workspace (M or M+2 row groups). */
  170209. JSAMPARRAY buffer[MAX_COMPONENTS];
  170210. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170211. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170212. /* Remaining fields are only used in the context case. */
  170213. /* These are the master pointers to the funny-order pointer lists. */
  170214. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170215. int whichptr; /* indicates which pointer set is now in use */
  170216. int context_state; /* process_data state machine status */
  170217. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170218. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170219. } my_main_controller4;
  170220. typedef my_main_controller4 * my_main_ptr4;
  170221. /* context_state values: */
  170222. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170223. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170224. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170225. /* Forward declarations */
  170226. METHODDEF(void) process_data_simple_main2
  170227. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170228. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170229. METHODDEF(void) process_data_context_main
  170230. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170231. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170232. #ifdef QUANT_2PASS_SUPPORTED
  170233. METHODDEF(void) process_data_crank_post
  170234. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170235. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170236. #endif
  170237. LOCAL(void)
  170238. alloc_funny_pointers (j_decompress_ptr cinfo)
  170239. /* Allocate space for the funny pointer lists.
  170240. * This is done only once, not once per pass.
  170241. */
  170242. {
  170243. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170244. int ci, rgroup;
  170245. int M = cinfo->min_DCT_scaled_size;
  170246. jpeg_component_info *compptr;
  170247. JSAMPARRAY xbuf;
  170248. /* Get top-level space for component array pointers.
  170249. * We alloc both arrays with one call to save a few cycles.
  170250. */
  170251. main_->xbuffer[0] = (JSAMPIMAGE)
  170252. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170253. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170254. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170255. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170256. ci++, compptr++) {
  170257. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170258. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170259. /* Get space for pointer lists --- M+4 row groups in each list.
  170260. * We alloc both pointer lists with one call to save a few cycles.
  170261. */
  170262. xbuf = (JSAMPARRAY)
  170263. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170264. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170265. xbuf += rgroup; /* want one row group at negative offsets */
  170266. main_->xbuffer[0][ci] = xbuf;
  170267. xbuf += rgroup * (M + 4);
  170268. main_->xbuffer[1][ci] = xbuf;
  170269. }
  170270. }
  170271. LOCAL(void)
  170272. make_funny_pointers (j_decompress_ptr cinfo)
  170273. /* Create the funny pointer lists discussed in the comments above.
  170274. * The actual workspace is already allocated (in main->buffer),
  170275. * and the space for the pointer lists is allocated too.
  170276. * This routine just fills in the curiously ordered lists.
  170277. * This will be repeated at the beginning of each pass.
  170278. */
  170279. {
  170280. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170281. int ci, i, rgroup;
  170282. int M = cinfo->min_DCT_scaled_size;
  170283. jpeg_component_info *compptr;
  170284. JSAMPARRAY buf, xbuf0, xbuf1;
  170285. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170286. ci++, compptr++) {
  170287. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170288. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170289. xbuf0 = main_->xbuffer[0][ci];
  170290. xbuf1 = main_->xbuffer[1][ci];
  170291. /* First copy the workspace pointers as-is */
  170292. buf = main_->buffer[ci];
  170293. for (i = 0; i < rgroup * (M + 2); i++) {
  170294. xbuf0[i] = xbuf1[i] = buf[i];
  170295. }
  170296. /* In the second list, put the last four row groups in swapped order */
  170297. for (i = 0; i < rgroup * 2; i++) {
  170298. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170299. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170300. }
  170301. /* The wraparound pointers at top and bottom will be filled later
  170302. * (see set_wraparound_pointers, below). Initially we want the "above"
  170303. * pointers to duplicate the first actual data line. This only needs
  170304. * to happen in xbuffer[0].
  170305. */
  170306. for (i = 0; i < rgroup; i++) {
  170307. xbuf0[i - rgroup] = xbuf0[0];
  170308. }
  170309. }
  170310. }
  170311. LOCAL(void)
  170312. set_wraparound_pointers (j_decompress_ptr cinfo)
  170313. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170314. * This changes the pointer list state from top-of-image to the normal state.
  170315. */
  170316. {
  170317. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170318. int ci, i, rgroup;
  170319. int M = cinfo->min_DCT_scaled_size;
  170320. jpeg_component_info *compptr;
  170321. JSAMPARRAY xbuf0, xbuf1;
  170322. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170323. ci++, compptr++) {
  170324. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170325. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170326. xbuf0 = main_->xbuffer[0][ci];
  170327. xbuf1 = main_->xbuffer[1][ci];
  170328. for (i = 0; i < rgroup; i++) {
  170329. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170330. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170331. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170332. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170333. }
  170334. }
  170335. }
  170336. LOCAL(void)
  170337. set_bottom_pointers (j_decompress_ptr cinfo)
  170338. /* Change the pointer lists to duplicate the last sample row at the bottom
  170339. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170340. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170341. */
  170342. {
  170343. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170344. int ci, i, rgroup, iMCUheight, rows_left;
  170345. jpeg_component_info *compptr;
  170346. JSAMPARRAY xbuf;
  170347. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170348. ci++, compptr++) {
  170349. /* Count sample rows in one iMCU row and in one row group */
  170350. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170351. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170352. /* Count nondummy sample rows remaining for this component */
  170353. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170354. if (rows_left == 0) rows_left = iMCUheight;
  170355. /* Count nondummy row groups. Should get same answer for each component,
  170356. * so we need only do it once.
  170357. */
  170358. if (ci == 0) {
  170359. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170360. }
  170361. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170362. * last partial rowgroup and ensures at least one full rowgroup of context.
  170363. */
  170364. xbuf = main_->xbuffer[main_->whichptr][ci];
  170365. for (i = 0; i < rgroup * 2; i++) {
  170366. xbuf[rows_left + i] = xbuf[rows_left-1];
  170367. }
  170368. }
  170369. }
  170370. /*
  170371. * Initialize for a processing pass.
  170372. */
  170373. METHODDEF(void)
  170374. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170375. {
  170376. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170377. switch (pass_mode) {
  170378. case JBUF_PASS_THRU:
  170379. if (cinfo->upsample->need_context_rows) {
  170380. main_->pub.process_data = process_data_context_main;
  170381. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170382. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170383. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170384. main_->iMCU_row_ctr = 0;
  170385. } else {
  170386. /* Simple case with no context needed */
  170387. main_->pub.process_data = process_data_simple_main2;
  170388. }
  170389. main_->buffer_full = FALSE; /* Mark buffer empty */
  170390. main_->rowgroup_ctr = 0;
  170391. break;
  170392. #ifdef QUANT_2PASS_SUPPORTED
  170393. case JBUF_CRANK_DEST:
  170394. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170395. main_->pub.process_data = process_data_crank_post;
  170396. break;
  170397. #endif
  170398. default:
  170399. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170400. break;
  170401. }
  170402. }
  170403. /*
  170404. * Process some data.
  170405. * This handles the simple case where no context is required.
  170406. */
  170407. METHODDEF(void)
  170408. process_data_simple_main2 (j_decompress_ptr cinfo,
  170409. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170410. JDIMENSION out_rows_avail)
  170411. {
  170412. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170413. JDIMENSION rowgroups_avail;
  170414. /* Read input data if we haven't filled the main buffer yet */
  170415. if (! main_->buffer_full) {
  170416. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170417. return; /* suspension forced, can do nothing more */
  170418. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170419. }
  170420. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170421. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170422. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170423. * to the postprocessor. The postprocessor has to check for bottom
  170424. * of image anyway (at row resolution), so no point in us doing it too.
  170425. */
  170426. /* Feed the postprocessor */
  170427. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170428. &main_->rowgroup_ctr, rowgroups_avail,
  170429. output_buf, out_row_ctr, out_rows_avail);
  170430. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170431. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170432. main_->buffer_full = FALSE;
  170433. main_->rowgroup_ctr = 0;
  170434. }
  170435. }
  170436. /*
  170437. * Process some data.
  170438. * This handles the case where context rows must be provided.
  170439. */
  170440. METHODDEF(void)
  170441. process_data_context_main (j_decompress_ptr cinfo,
  170442. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170443. JDIMENSION out_rows_avail)
  170444. {
  170445. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170446. /* Read input data if we haven't filled the main buffer yet */
  170447. if (! main_->buffer_full) {
  170448. if (! (*cinfo->coef->decompress_data) (cinfo,
  170449. main_->xbuffer[main_->whichptr]))
  170450. return; /* suspension forced, can do nothing more */
  170451. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170452. main_->iMCU_row_ctr++; /* count rows received */
  170453. }
  170454. /* Postprocessor typically will not swallow all the input data it is handed
  170455. * in one call (due to filling the output buffer first). Must be prepared
  170456. * to exit and restart. This switch lets us keep track of how far we got.
  170457. * Note that each case falls through to the next on successful completion.
  170458. */
  170459. switch (main_->context_state) {
  170460. case CTX_POSTPONED_ROW:
  170461. /* Call postprocessor using previously set pointers for postponed row */
  170462. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170463. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170464. output_buf, out_row_ctr, out_rows_avail);
  170465. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170466. return; /* Need to suspend */
  170467. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170468. if (*out_row_ctr >= out_rows_avail)
  170469. return; /* Postprocessor exactly filled output buf */
  170470. /*FALLTHROUGH*/
  170471. case CTX_PREPARE_FOR_IMCU:
  170472. /* Prepare to process first M-1 row groups of this iMCU row */
  170473. main_->rowgroup_ctr = 0;
  170474. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170475. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170476. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170477. */
  170478. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170479. set_bottom_pointers(cinfo);
  170480. main_->context_state = CTX_PROCESS_IMCU;
  170481. /*FALLTHROUGH*/
  170482. case CTX_PROCESS_IMCU:
  170483. /* Call postprocessor using previously set pointers */
  170484. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170485. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170486. output_buf, out_row_ctr, out_rows_avail);
  170487. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170488. return; /* Need to suspend */
  170489. /* After the first iMCU, change wraparound pointers to normal state */
  170490. if (main_->iMCU_row_ctr == 1)
  170491. set_wraparound_pointers(cinfo);
  170492. /* Prepare to load new iMCU row using other xbuffer list */
  170493. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170494. main_->buffer_full = FALSE;
  170495. /* Still need to process last row group of this iMCU row, */
  170496. /* which is saved at index M+1 of the other xbuffer */
  170497. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170498. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170499. main_->context_state = CTX_POSTPONED_ROW;
  170500. }
  170501. }
  170502. /*
  170503. * Process some data.
  170504. * Final pass of two-pass quantization: just call the postprocessor.
  170505. * Source data will be the postprocessor controller's internal buffer.
  170506. */
  170507. #ifdef QUANT_2PASS_SUPPORTED
  170508. METHODDEF(void)
  170509. process_data_crank_post (j_decompress_ptr cinfo,
  170510. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170511. JDIMENSION out_rows_avail)
  170512. {
  170513. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170514. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170515. output_buf, out_row_ctr, out_rows_avail);
  170516. }
  170517. #endif /* QUANT_2PASS_SUPPORTED */
  170518. /*
  170519. * Initialize main buffer controller.
  170520. */
  170521. GLOBAL(void)
  170522. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170523. {
  170524. my_main_ptr4 main_;
  170525. int ci, rgroup, ngroups;
  170526. jpeg_component_info *compptr;
  170527. main_ = (my_main_ptr4)
  170528. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170529. SIZEOF(my_main_controller4));
  170530. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170531. main_->pub.start_pass = start_pass_main2;
  170532. if (need_full_buffer) /* shouldn't happen */
  170533. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170534. /* Allocate the workspace.
  170535. * ngroups is the number of row groups we need.
  170536. */
  170537. if (cinfo->upsample->need_context_rows) {
  170538. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170539. ERREXIT(cinfo, JERR_NOTIMPL);
  170540. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170541. ngroups = cinfo->min_DCT_scaled_size + 2;
  170542. } else {
  170543. ngroups = cinfo->min_DCT_scaled_size;
  170544. }
  170545. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170546. ci++, compptr++) {
  170547. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170548. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170549. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170550. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170551. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170552. (JDIMENSION) (rgroup * ngroups));
  170553. }
  170554. }
  170555. /*** End of inlined file: jdmainct.c ***/
  170556. /*** Start of inlined file: jdmarker.c ***/
  170557. #define JPEG_INTERNALS
  170558. /* Private state */
  170559. typedef struct {
  170560. struct jpeg_marker_reader pub; /* public fields */
  170561. /* Application-overridable marker processing methods */
  170562. jpeg_marker_parser_method process_COM;
  170563. jpeg_marker_parser_method process_APPn[16];
  170564. /* Limit on marker data length to save for each marker type */
  170565. unsigned int length_limit_COM;
  170566. unsigned int length_limit_APPn[16];
  170567. /* Status of COM/APPn marker saving */
  170568. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170569. unsigned int bytes_read; /* data bytes read so far in marker */
  170570. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170571. } my_marker_reader;
  170572. typedef my_marker_reader * my_marker_ptr2;
  170573. /*
  170574. * Macros for fetching data from the data source module.
  170575. *
  170576. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170577. * the current restart point; we update them only when we have reached a
  170578. * suitable place to restart if a suspension occurs.
  170579. */
  170580. /* Declare and initialize local copies of input pointer/count */
  170581. #define INPUT_VARS(cinfo) \
  170582. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170583. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170584. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170585. /* Unload the local copies --- do this only at a restart boundary */
  170586. #define INPUT_SYNC(cinfo) \
  170587. ( datasrc->next_input_byte = next_input_byte, \
  170588. datasrc->bytes_in_buffer = bytes_in_buffer )
  170589. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170590. #define INPUT_RELOAD(cinfo) \
  170591. ( next_input_byte = datasrc->next_input_byte, \
  170592. bytes_in_buffer = datasrc->bytes_in_buffer )
  170593. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170594. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170595. * but we must reload the local copies after a successful fill.
  170596. */
  170597. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170598. if (bytes_in_buffer == 0) { \
  170599. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170600. { action; } \
  170601. INPUT_RELOAD(cinfo); \
  170602. }
  170603. /* Read a byte into variable V.
  170604. * If must suspend, take the specified action (typically "return FALSE").
  170605. */
  170606. #define INPUT_BYTE(cinfo,V,action) \
  170607. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170608. bytes_in_buffer--; \
  170609. V = GETJOCTET(*next_input_byte++); )
  170610. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170611. * V should be declared unsigned int or perhaps INT32.
  170612. */
  170613. #define INPUT_2BYTES(cinfo,V,action) \
  170614. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170615. bytes_in_buffer--; \
  170616. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170617. MAKE_BYTE_AVAIL(cinfo,action); \
  170618. bytes_in_buffer--; \
  170619. V += GETJOCTET(*next_input_byte++); )
  170620. /*
  170621. * Routines to process JPEG markers.
  170622. *
  170623. * Entry condition: JPEG marker itself has been read and its code saved
  170624. * in cinfo->unread_marker; input restart point is just after the marker.
  170625. *
  170626. * Exit: if return TRUE, have read and processed any parameters, and have
  170627. * updated the restart point to point after the parameters.
  170628. * If return FALSE, was forced to suspend before reaching end of
  170629. * marker parameters; restart point has not been moved. Same routine
  170630. * will be called again after application supplies more input data.
  170631. *
  170632. * This approach to suspension assumes that all of a marker's parameters
  170633. * can fit into a single input bufferload. This should hold for "normal"
  170634. * markers. Some COM/APPn markers might have large parameter segments
  170635. * that might not fit. If we are simply dropping such a marker, we use
  170636. * skip_input_data to get past it, and thereby put the problem on the
  170637. * source manager's shoulders. If we are saving the marker's contents
  170638. * into memory, we use a slightly different convention: when forced to
  170639. * suspend, the marker processor updates the restart point to the end of
  170640. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170641. * On resumption, cinfo->unread_marker still contains the marker code,
  170642. * but the data source will point to the next chunk of marker data.
  170643. * The marker processor must retain internal state to deal with this.
  170644. *
  170645. * Note that we don't bother to avoid duplicate trace messages if a
  170646. * suspension occurs within marker parameters. Other side effects
  170647. * require more care.
  170648. */
  170649. LOCAL(boolean)
  170650. get_soi (j_decompress_ptr cinfo)
  170651. /* Process an SOI marker */
  170652. {
  170653. int i;
  170654. TRACEMS(cinfo, 1, JTRC_SOI);
  170655. if (cinfo->marker->saw_SOI)
  170656. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170657. /* Reset all parameters that are defined to be reset by SOI */
  170658. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170659. cinfo->arith_dc_L[i] = 0;
  170660. cinfo->arith_dc_U[i] = 1;
  170661. cinfo->arith_ac_K[i] = 5;
  170662. }
  170663. cinfo->restart_interval = 0;
  170664. /* Set initial assumptions for colorspace etc */
  170665. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170666. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170667. cinfo->saw_JFIF_marker = FALSE;
  170668. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170669. cinfo->JFIF_minor_version = 1;
  170670. cinfo->density_unit = 0;
  170671. cinfo->X_density = 1;
  170672. cinfo->Y_density = 1;
  170673. cinfo->saw_Adobe_marker = FALSE;
  170674. cinfo->Adobe_transform = 0;
  170675. cinfo->marker->saw_SOI = TRUE;
  170676. return TRUE;
  170677. }
  170678. LOCAL(boolean)
  170679. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170680. /* Process a SOFn marker */
  170681. {
  170682. INT32 length;
  170683. int c, ci;
  170684. jpeg_component_info * compptr;
  170685. INPUT_VARS(cinfo);
  170686. cinfo->progressive_mode = is_prog;
  170687. cinfo->arith_code = is_arith;
  170688. INPUT_2BYTES(cinfo, length, return FALSE);
  170689. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170690. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170691. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170692. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170693. length -= 8;
  170694. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170695. (int) cinfo->image_width, (int) cinfo->image_height,
  170696. cinfo->num_components);
  170697. if (cinfo->marker->saw_SOF)
  170698. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170699. /* We don't support files in which the image height is initially specified */
  170700. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170701. /* might as well have a general sanity check. */
  170702. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170703. || cinfo->num_components <= 0)
  170704. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170705. if (length != (cinfo->num_components * 3))
  170706. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170707. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170708. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170709. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170710. cinfo->num_components * SIZEOF(jpeg_component_info));
  170711. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170712. ci++, compptr++) {
  170713. compptr->component_index = ci;
  170714. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170715. INPUT_BYTE(cinfo, c, return FALSE);
  170716. compptr->h_samp_factor = (c >> 4) & 15;
  170717. compptr->v_samp_factor = (c ) & 15;
  170718. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170719. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170720. compptr->component_id, compptr->h_samp_factor,
  170721. compptr->v_samp_factor, compptr->quant_tbl_no);
  170722. }
  170723. cinfo->marker->saw_SOF = TRUE;
  170724. INPUT_SYNC(cinfo);
  170725. return TRUE;
  170726. }
  170727. LOCAL(boolean)
  170728. get_sos (j_decompress_ptr cinfo)
  170729. /* Process a SOS marker */
  170730. {
  170731. INT32 length;
  170732. int i, ci, n, c, cc;
  170733. jpeg_component_info * compptr;
  170734. INPUT_VARS(cinfo);
  170735. if (! cinfo->marker->saw_SOF)
  170736. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170737. INPUT_2BYTES(cinfo, length, return FALSE);
  170738. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170739. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170740. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170741. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170742. cinfo->comps_in_scan = n;
  170743. /* Collect the component-spec parameters */
  170744. for (i = 0; i < n; i++) {
  170745. INPUT_BYTE(cinfo, cc, return FALSE);
  170746. INPUT_BYTE(cinfo, c, return FALSE);
  170747. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170748. ci++, compptr++) {
  170749. if (cc == compptr->component_id)
  170750. goto id_found;
  170751. }
  170752. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170753. id_found:
  170754. cinfo->cur_comp_info[i] = compptr;
  170755. compptr->dc_tbl_no = (c >> 4) & 15;
  170756. compptr->ac_tbl_no = (c ) & 15;
  170757. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170758. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170759. }
  170760. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170761. INPUT_BYTE(cinfo, c, return FALSE);
  170762. cinfo->Ss = c;
  170763. INPUT_BYTE(cinfo, c, return FALSE);
  170764. cinfo->Se = c;
  170765. INPUT_BYTE(cinfo, c, return FALSE);
  170766. cinfo->Ah = (c >> 4) & 15;
  170767. cinfo->Al = (c ) & 15;
  170768. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170769. cinfo->Ah, cinfo->Al);
  170770. /* Prepare to scan data & restart markers */
  170771. cinfo->marker->next_restart_num = 0;
  170772. /* Count another SOS marker */
  170773. cinfo->input_scan_number++;
  170774. INPUT_SYNC(cinfo);
  170775. return TRUE;
  170776. }
  170777. #ifdef D_ARITH_CODING_SUPPORTED
  170778. LOCAL(boolean)
  170779. get_dac (j_decompress_ptr cinfo)
  170780. /* Process a DAC marker */
  170781. {
  170782. INT32 length;
  170783. int index, val;
  170784. INPUT_VARS(cinfo);
  170785. INPUT_2BYTES(cinfo, length, return FALSE);
  170786. length -= 2;
  170787. while (length > 0) {
  170788. INPUT_BYTE(cinfo, index, return FALSE);
  170789. INPUT_BYTE(cinfo, val, return FALSE);
  170790. length -= 2;
  170791. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170792. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170793. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170794. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170795. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170796. } else { /* define DC table */
  170797. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170798. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170799. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170800. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170801. }
  170802. }
  170803. if (length != 0)
  170804. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170805. INPUT_SYNC(cinfo);
  170806. return TRUE;
  170807. }
  170808. #else /* ! D_ARITH_CODING_SUPPORTED */
  170809. #define get_dac(cinfo) skip_variable(cinfo)
  170810. #endif /* D_ARITH_CODING_SUPPORTED */
  170811. LOCAL(boolean)
  170812. get_dht (j_decompress_ptr cinfo)
  170813. /* Process a DHT marker */
  170814. {
  170815. INT32 length;
  170816. UINT8 bits[17];
  170817. UINT8 huffval[256];
  170818. int i, index, count;
  170819. JHUFF_TBL **htblptr;
  170820. INPUT_VARS(cinfo);
  170821. INPUT_2BYTES(cinfo, length, return FALSE);
  170822. length -= 2;
  170823. while (length > 16) {
  170824. INPUT_BYTE(cinfo, index, return FALSE);
  170825. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  170826. bits[0] = 0;
  170827. count = 0;
  170828. for (i = 1; i <= 16; i++) {
  170829. INPUT_BYTE(cinfo, bits[i], return FALSE);
  170830. count += bits[i];
  170831. }
  170832. length -= 1 + 16;
  170833. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170834. bits[1], bits[2], bits[3], bits[4],
  170835. bits[5], bits[6], bits[7], bits[8]);
  170836. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170837. bits[9], bits[10], bits[11], bits[12],
  170838. bits[13], bits[14], bits[15], bits[16]);
  170839. /* Here we just do minimal validation of the counts to avoid walking
  170840. * off the end of our table space. jdhuff.c will check more carefully.
  170841. */
  170842. if (count > 256 || ((INT32) count) > length)
  170843. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170844. for (i = 0; i < count; i++)
  170845. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  170846. length -= count;
  170847. if (index & 0x10) { /* AC table definition */
  170848. index -= 0x10;
  170849. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  170850. } else { /* DC table definition */
  170851. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  170852. }
  170853. if (index < 0 || index >= NUM_HUFF_TBLS)
  170854. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  170855. if (*htblptr == NULL)
  170856. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  170857. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  170858. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  170859. }
  170860. if (length != 0)
  170861. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170862. INPUT_SYNC(cinfo);
  170863. return TRUE;
  170864. }
  170865. LOCAL(boolean)
  170866. get_dqt (j_decompress_ptr cinfo)
  170867. /* Process a DQT marker */
  170868. {
  170869. INT32 length;
  170870. int n, i, prec;
  170871. unsigned int tmp;
  170872. JQUANT_TBL *quant_ptr;
  170873. INPUT_VARS(cinfo);
  170874. INPUT_2BYTES(cinfo, length, return FALSE);
  170875. length -= 2;
  170876. while (length > 0) {
  170877. INPUT_BYTE(cinfo, n, return FALSE);
  170878. prec = n >> 4;
  170879. n &= 0x0F;
  170880. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  170881. if (n >= NUM_QUANT_TBLS)
  170882. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  170883. if (cinfo->quant_tbl_ptrs[n] == NULL)
  170884. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  170885. quant_ptr = cinfo->quant_tbl_ptrs[n];
  170886. for (i = 0; i < DCTSIZE2; i++) {
  170887. if (prec)
  170888. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170889. else
  170890. INPUT_BYTE(cinfo, tmp, return FALSE);
  170891. /* We convert the zigzag-order table to natural array order. */
  170892. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  170893. }
  170894. if (cinfo->err->trace_level >= 2) {
  170895. for (i = 0; i < DCTSIZE2; i += 8) {
  170896. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  170897. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  170898. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  170899. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  170900. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  170901. }
  170902. }
  170903. length -= DCTSIZE2+1;
  170904. if (prec) length -= DCTSIZE2;
  170905. }
  170906. if (length != 0)
  170907. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170908. INPUT_SYNC(cinfo);
  170909. return TRUE;
  170910. }
  170911. LOCAL(boolean)
  170912. get_dri (j_decompress_ptr cinfo)
  170913. /* Process a DRI marker */
  170914. {
  170915. INT32 length;
  170916. unsigned int tmp;
  170917. INPUT_VARS(cinfo);
  170918. INPUT_2BYTES(cinfo, length, return FALSE);
  170919. if (length != 4)
  170920. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170921. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170922. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  170923. cinfo->restart_interval = tmp;
  170924. INPUT_SYNC(cinfo);
  170925. return TRUE;
  170926. }
  170927. /*
  170928. * Routines for processing APPn and COM markers.
  170929. * These are either saved in memory or discarded, per application request.
  170930. * APP0 and APP14 are specially checked to see if they are
  170931. * JFIF and Adobe markers, respectively.
  170932. */
  170933. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  170934. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  170935. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  170936. LOCAL(void)
  170937. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170938. unsigned int datalen, INT32 remaining)
  170939. /* Examine first few bytes from an APP0.
  170940. * Take appropriate action if it is a JFIF marker.
  170941. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170942. */
  170943. {
  170944. INT32 totallen = (INT32) datalen + remaining;
  170945. if (datalen >= APP0_DATA_LEN &&
  170946. GETJOCTET(data[0]) == 0x4A &&
  170947. GETJOCTET(data[1]) == 0x46 &&
  170948. GETJOCTET(data[2]) == 0x49 &&
  170949. GETJOCTET(data[3]) == 0x46 &&
  170950. GETJOCTET(data[4]) == 0) {
  170951. /* Found JFIF APP0 marker: save info */
  170952. cinfo->saw_JFIF_marker = TRUE;
  170953. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  170954. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  170955. cinfo->density_unit = GETJOCTET(data[7]);
  170956. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  170957. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  170958. /* Check version.
  170959. * Major version must be 1, anything else signals an incompatible change.
  170960. * (We used to treat this as an error, but now it's a nonfatal warning,
  170961. * because some bozo at Hijaak couldn't read the spec.)
  170962. * Minor version should be 0..2, but process anyway if newer.
  170963. */
  170964. if (cinfo->JFIF_major_version != 1)
  170965. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  170966. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  170967. /* Generate trace messages */
  170968. TRACEMS5(cinfo, 1, JTRC_JFIF,
  170969. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  170970. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  170971. /* Validate thumbnail dimensions and issue appropriate messages */
  170972. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  170973. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  170974. GETJOCTET(data[12]), GETJOCTET(data[13]));
  170975. totallen -= APP0_DATA_LEN;
  170976. if (totallen !=
  170977. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  170978. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  170979. } else if (datalen >= 6 &&
  170980. GETJOCTET(data[0]) == 0x4A &&
  170981. GETJOCTET(data[1]) == 0x46 &&
  170982. GETJOCTET(data[2]) == 0x58 &&
  170983. GETJOCTET(data[3]) == 0x58 &&
  170984. GETJOCTET(data[4]) == 0) {
  170985. /* Found JFIF "JFXX" extension APP0 marker */
  170986. /* The library doesn't actually do anything with these,
  170987. * but we try to produce a helpful trace message.
  170988. */
  170989. switch (GETJOCTET(data[5])) {
  170990. case 0x10:
  170991. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  170992. break;
  170993. case 0x11:
  170994. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  170995. break;
  170996. case 0x13:
  170997. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  170998. break;
  170999. default:
  171000. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171001. GETJOCTET(data[5]), (int) totallen);
  171002. break;
  171003. }
  171004. } else {
  171005. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171006. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171007. }
  171008. }
  171009. LOCAL(void)
  171010. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171011. unsigned int datalen, INT32 remaining)
  171012. /* Examine first few bytes from an APP14.
  171013. * Take appropriate action if it is an Adobe marker.
  171014. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171015. */
  171016. {
  171017. unsigned int version, flags0, flags1, transform;
  171018. if (datalen >= APP14_DATA_LEN &&
  171019. GETJOCTET(data[0]) == 0x41 &&
  171020. GETJOCTET(data[1]) == 0x64 &&
  171021. GETJOCTET(data[2]) == 0x6F &&
  171022. GETJOCTET(data[3]) == 0x62 &&
  171023. GETJOCTET(data[4]) == 0x65) {
  171024. /* Found Adobe APP14 marker */
  171025. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171026. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171027. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171028. transform = GETJOCTET(data[11]);
  171029. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171030. cinfo->saw_Adobe_marker = TRUE;
  171031. cinfo->Adobe_transform = (UINT8) transform;
  171032. } else {
  171033. /* Start of APP14 does not match "Adobe", or too short */
  171034. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171035. }
  171036. }
  171037. METHODDEF(boolean)
  171038. get_interesting_appn (j_decompress_ptr cinfo)
  171039. /* Process an APP0 or APP14 marker without saving it */
  171040. {
  171041. INT32 length;
  171042. JOCTET b[APPN_DATA_LEN];
  171043. unsigned int i, numtoread;
  171044. INPUT_VARS(cinfo);
  171045. INPUT_2BYTES(cinfo, length, return FALSE);
  171046. length -= 2;
  171047. /* get the interesting part of the marker data */
  171048. if (length >= APPN_DATA_LEN)
  171049. numtoread = APPN_DATA_LEN;
  171050. else if (length > 0)
  171051. numtoread = (unsigned int) length;
  171052. else
  171053. numtoread = 0;
  171054. for (i = 0; i < numtoread; i++)
  171055. INPUT_BYTE(cinfo, b[i], return FALSE);
  171056. length -= numtoread;
  171057. /* process it */
  171058. switch (cinfo->unread_marker) {
  171059. case M_APP0:
  171060. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171061. break;
  171062. case M_APP14:
  171063. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171064. break;
  171065. default:
  171066. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171067. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171068. break;
  171069. }
  171070. /* skip any remaining data -- could be lots */
  171071. INPUT_SYNC(cinfo);
  171072. if (length > 0)
  171073. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171074. return TRUE;
  171075. }
  171076. #ifdef SAVE_MARKERS_SUPPORTED
  171077. METHODDEF(boolean)
  171078. save_marker (j_decompress_ptr cinfo)
  171079. /* Save an APPn or COM marker into the marker list */
  171080. {
  171081. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171082. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171083. unsigned int bytes_read, data_length;
  171084. JOCTET FAR * data;
  171085. INT32 length = 0;
  171086. INPUT_VARS(cinfo);
  171087. if (cur_marker == NULL) {
  171088. /* begin reading a marker */
  171089. INPUT_2BYTES(cinfo, length, return FALSE);
  171090. length -= 2;
  171091. if (length >= 0) { /* watch out for bogus length word */
  171092. /* figure out how much we want to save */
  171093. unsigned int limit;
  171094. if (cinfo->unread_marker == (int) M_COM)
  171095. limit = marker->length_limit_COM;
  171096. else
  171097. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171098. if ((unsigned int) length < limit)
  171099. limit = (unsigned int) length;
  171100. /* allocate and initialize the marker item */
  171101. cur_marker = (jpeg_saved_marker_ptr)
  171102. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171103. SIZEOF(struct jpeg_marker_struct) + limit);
  171104. cur_marker->next = NULL;
  171105. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171106. cur_marker->original_length = (unsigned int) length;
  171107. cur_marker->data_length = limit;
  171108. /* data area is just beyond the jpeg_marker_struct */
  171109. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171110. marker->cur_marker = cur_marker;
  171111. marker->bytes_read = 0;
  171112. bytes_read = 0;
  171113. data_length = limit;
  171114. } else {
  171115. /* deal with bogus length word */
  171116. bytes_read = data_length = 0;
  171117. data = NULL;
  171118. }
  171119. } else {
  171120. /* resume reading a marker */
  171121. bytes_read = marker->bytes_read;
  171122. data_length = cur_marker->data_length;
  171123. data = cur_marker->data + bytes_read;
  171124. }
  171125. while (bytes_read < data_length) {
  171126. INPUT_SYNC(cinfo); /* move the restart point to here */
  171127. marker->bytes_read = bytes_read;
  171128. /* If there's not at least one byte in buffer, suspend */
  171129. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171130. /* Copy bytes with reasonable rapidity */
  171131. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171132. *data++ = *next_input_byte++;
  171133. bytes_in_buffer--;
  171134. bytes_read++;
  171135. }
  171136. }
  171137. /* Done reading what we want to read */
  171138. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171139. /* Add new marker to end of list */
  171140. if (cinfo->marker_list == NULL) {
  171141. cinfo->marker_list = cur_marker;
  171142. } else {
  171143. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171144. while (prev->next != NULL)
  171145. prev = prev->next;
  171146. prev->next = cur_marker;
  171147. }
  171148. /* Reset pointer & calc remaining data length */
  171149. data = cur_marker->data;
  171150. length = cur_marker->original_length - data_length;
  171151. }
  171152. /* Reset to initial state for next marker */
  171153. marker->cur_marker = NULL;
  171154. /* Process the marker if interesting; else just make a generic trace msg */
  171155. switch (cinfo->unread_marker) {
  171156. case M_APP0:
  171157. examine_app0(cinfo, data, data_length, length);
  171158. break;
  171159. case M_APP14:
  171160. examine_app14(cinfo, data, data_length, length);
  171161. break;
  171162. default:
  171163. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171164. (int) (data_length + length));
  171165. break;
  171166. }
  171167. /* skip any remaining data -- could be lots */
  171168. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171169. if (length > 0)
  171170. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171171. return TRUE;
  171172. }
  171173. #endif /* SAVE_MARKERS_SUPPORTED */
  171174. METHODDEF(boolean)
  171175. skip_variable (j_decompress_ptr cinfo)
  171176. /* Skip over an unknown or uninteresting variable-length marker */
  171177. {
  171178. INT32 length;
  171179. INPUT_VARS(cinfo);
  171180. INPUT_2BYTES(cinfo, length, return FALSE);
  171181. length -= 2;
  171182. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171183. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171184. if (length > 0)
  171185. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171186. return TRUE;
  171187. }
  171188. /*
  171189. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171190. * Returns FALSE if had to suspend before reaching a marker;
  171191. * in that case cinfo->unread_marker is unchanged.
  171192. *
  171193. * Note that the result might not be a valid marker code,
  171194. * but it will never be 0 or FF.
  171195. */
  171196. LOCAL(boolean)
  171197. next_marker (j_decompress_ptr cinfo)
  171198. {
  171199. int c;
  171200. INPUT_VARS(cinfo);
  171201. for (;;) {
  171202. INPUT_BYTE(cinfo, c, return FALSE);
  171203. /* Skip any non-FF bytes.
  171204. * This may look a bit inefficient, but it will not occur in a valid file.
  171205. * We sync after each discarded byte so that a suspending data source
  171206. * can discard the byte from its buffer.
  171207. */
  171208. while (c != 0xFF) {
  171209. cinfo->marker->discarded_bytes++;
  171210. INPUT_SYNC(cinfo);
  171211. INPUT_BYTE(cinfo, c, return FALSE);
  171212. }
  171213. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171214. * pad bytes, so don't count them in discarded_bytes. We assume there
  171215. * will not be so many consecutive FF bytes as to overflow a suspending
  171216. * data source's input buffer.
  171217. */
  171218. do {
  171219. INPUT_BYTE(cinfo, c, return FALSE);
  171220. } while (c == 0xFF);
  171221. if (c != 0)
  171222. break; /* found a valid marker, exit loop */
  171223. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171224. * Discard it and loop back to try again.
  171225. */
  171226. cinfo->marker->discarded_bytes += 2;
  171227. INPUT_SYNC(cinfo);
  171228. }
  171229. if (cinfo->marker->discarded_bytes != 0) {
  171230. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171231. cinfo->marker->discarded_bytes = 0;
  171232. }
  171233. cinfo->unread_marker = c;
  171234. INPUT_SYNC(cinfo);
  171235. return TRUE;
  171236. }
  171237. LOCAL(boolean)
  171238. first_marker (j_decompress_ptr cinfo)
  171239. /* Like next_marker, but used to obtain the initial SOI marker. */
  171240. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171241. * we might well scan an entire input file before realizing it ain't JPEG.
  171242. * If an application wants to process non-JFIF files, it must seek to the
  171243. * SOI before calling the JPEG library.
  171244. */
  171245. {
  171246. int c, c2;
  171247. INPUT_VARS(cinfo);
  171248. INPUT_BYTE(cinfo, c, return FALSE);
  171249. INPUT_BYTE(cinfo, c2, return FALSE);
  171250. if (c != 0xFF || c2 != (int) M_SOI)
  171251. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171252. cinfo->unread_marker = c2;
  171253. INPUT_SYNC(cinfo);
  171254. return TRUE;
  171255. }
  171256. /*
  171257. * Read markers until SOS or EOI.
  171258. *
  171259. * Returns same codes as are defined for jpeg_consume_input:
  171260. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171261. */
  171262. METHODDEF(int)
  171263. read_markers (j_decompress_ptr cinfo)
  171264. {
  171265. /* Outer loop repeats once for each marker. */
  171266. for (;;) {
  171267. /* Collect the marker proper, unless we already did. */
  171268. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171269. if (cinfo->unread_marker == 0) {
  171270. if (! cinfo->marker->saw_SOI) {
  171271. if (! first_marker(cinfo))
  171272. return JPEG_SUSPENDED;
  171273. } else {
  171274. if (! next_marker(cinfo))
  171275. return JPEG_SUSPENDED;
  171276. }
  171277. }
  171278. /* At this point cinfo->unread_marker contains the marker code and the
  171279. * input point is just past the marker proper, but before any parameters.
  171280. * A suspension will cause us to return with this state still true.
  171281. */
  171282. switch (cinfo->unread_marker) {
  171283. case M_SOI:
  171284. if (! get_soi(cinfo))
  171285. return JPEG_SUSPENDED;
  171286. break;
  171287. case M_SOF0: /* Baseline */
  171288. case M_SOF1: /* Extended sequential, Huffman */
  171289. if (! get_sof(cinfo, FALSE, FALSE))
  171290. return JPEG_SUSPENDED;
  171291. break;
  171292. case M_SOF2: /* Progressive, Huffman */
  171293. if (! get_sof(cinfo, TRUE, FALSE))
  171294. return JPEG_SUSPENDED;
  171295. break;
  171296. case M_SOF9: /* Extended sequential, arithmetic */
  171297. if (! get_sof(cinfo, FALSE, TRUE))
  171298. return JPEG_SUSPENDED;
  171299. break;
  171300. case M_SOF10: /* Progressive, arithmetic */
  171301. if (! get_sof(cinfo, TRUE, TRUE))
  171302. return JPEG_SUSPENDED;
  171303. break;
  171304. /* Currently unsupported SOFn types */
  171305. case M_SOF3: /* Lossless, Huffman */
  171306. case M_SOF5: /* Differential sequential, Huffman */
  171307. case M_SOF6: /* Differential progressive, Huffman */
  171308. case M_SOF7: /* Differential lossless, Huffman */
  171309. case M_JPG: /* Reserved for JPEG extensions */
  171310. case M_SOF11: /* Lossless, arithmetic */
  171311. case M_SOF13: /* Differential sequential, arithmetic */
  171312. case M_SOF14: /* Differential progressive, arithmetic */
  171313. case M_SOF15: /* Differential lossless, arithmetic */
  171314. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171315. break;
  171316. case M_SOS:
  171317. if (! get_sos(cinfo))
  171318. return JPEG_SUSPENDED;
  171319. cinfo->unread_marker = 0; /* processed the marker */
  171320. return JPEG_REACHED_SOS;
  171321. case M_EOI:
  171322. TRACEMS(cinfo, 1, JTRC_EOI);
  171323. cinfo->unread_marker = 0; /* processed the marker */
  171324. return JPEG_REACHED_EOI;
  171325. case M_DAC:
  171326. if (! get_dac(cinfo))
  171327. return JPEG_SUSPENDED;
  171328. break;
  171329. case M_DHT:
  171330. if (! get_dht(cinfo))
  171331. return JPEG_SUSPENDED;
  171332. break;
  171333. case M_DQT:
  171334. if (! get_dqt(cinfo))
  171335. return JPEG_SUSPENDED;
  171336. break;
  171337. case M_DRI:
  171338. if (! get_dri(cinfo))
  171339. return JPEG_SUSPENDED;
  171340. break;
  171341. case M_APP0:
  171342. case M_APP1:
  171343. case M_APP2:
  171344. case M_APP3:
  171345. case M_APP4:
  171346. case M_APP5:
  171347. case M_APP6:
  171348. case M_APP7:
  171349. case M_APP8:
  171350. case M_APP9:
  171351. case M_APP10:
  171352. case M_APP11:
  171353. case M_APP12:
  171354. case M_APP13:
  171355. case M_APP14:
  171356. case M_APP15:
  171357. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171358. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171359. return JPEG_SUSPENDED;
  171360. break;
  171361. case M_COM:
  171362. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171363. return JPEG_SUSPENDED;
  171364. break;
  171365. case M_RST0: /* these are all parameterless */
  171366. case M_RST1:
  171367. case M_RST2:
  171368. case M_RST3:
  171369. case M_RST4:
  171370. case M_RST5:
  171371. case M_RST6:
  171372. case M_RST7:
  171373. case M_TEM:
  171374. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171375. break;
  171376. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171377. if (! skip_variable(cinfo))
  171378. return JPEG_SUSPENDED;
  171379. break;
  171380. default: /* must be DHP, EXP, JPGn, or RESn */
  171381. /* For now, we treat the reserved markers as fatal errors since they are
  171382. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171383. * Once the JPEG 3 version-number marker is well defined, this code
  171384. * ought to change!
  171385. */
  171386. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171387. break;
  171388. }
  171389. /* Successfully processed marker, so reset state variable */
  171390. cinfo->unread_marker = 0;
  171391. } /* end loop */
  171392. }
  171393. /*
  171394. * Read a restart marker, which is expected to appear next in the datastream;
  171395. * if the marker is not there, take appropriate recovery action.
  171396. * Returns FALSE if suspension is required.
  171397. *
  171398. * This is called by the entropy decoder after it has read an appropriate
  171399. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171400. * has already read a marker from the data source. Under normal conditions
  171401. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171402. * it holds a marker which the decoder will be unable to read past.
  171403. */
  171404. METHODDEF(boolean)
  171405. read_restart_marker (j_decompress_ptr cinfo)
  171406. {
  171407. /* Obtain a marker unless we already did. */
  171408. /* Note that next_marker will complain if it skips any data. */
  171409. if (cinfo->unread_marker == 0) {
  171410. if (! next_marker(cinfo))
  171411. return FALSE;
  171412. }
  171413. if (cinfo->unread_marker ==
  171414. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171415. /* Normal case --- swallow the marker and let entropy decoder continue */
  171416. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171417. cinfo->unread_marker = 0;
  171418. } else {
  171419. /* Uh-oh, the restart markers have been messed up. */
  171420. /* Let the data source manager determine how to resync. */
  171421. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171422. cinfo->marker->next_restart_num))
  171423. return FALSE;
  171424. }
  171425. /* Update next-restart state */
  171426. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171427. return TRUE;
  171428. }
  171429. /*
  171430. * This is the default resync_to_restart method for data source managers
  171431. * to use if they don't have any better approach. Some data source managers
  171432. * may be able to back up, or may have additional knowledge about the data
  171433. * which permits a more intelligent recovery strategy; such managers would
  171434. * presumably supply their own resync method.
  171435. *
  171436. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171437. * the restart marker it was expecting. (This code is *not* used unless
  171438. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171439. * the marker code actually found (might be anything, except 0 or FF).
  171440. * The desired restart marker number (0..7) is passed as a parameter.
  171441. * This routine is supposed to apply whatever error recovery strategy seems
  171442. * appropriate in order to position the input stream to the next data segment.
  171443. * Note that cinfo->unread_marker is treated as a marker appearing before
  171444. * the current data-source input point; usually it should be reset to zero
  171445. * before returning.
  171446. * Returns FALSE if suspension is required.
  171447. *
  171448. * This implementation is substantially constrained by wanting to treat the
  171449. * input as a data stream; this means we can't back up. Therefore, we have
  171450. * only the following actions to work with:
  171451. * 1. Simply discard the marker and let the entropy decoder resume at next
  171452. * byte of file.
  171453. * 2. Read forward until we find another marker, discarding intervening
  171454. * data. (In theory we could look ahead within the current bufferload,
  171455. * without having to discard data if we don't find the desired marker.
  171456. * This idea is not implemented here, in part because it makes behavior
  171457. * dependent on buffer size and chance buffer-boundary positions.)
  171458. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171459. * This will cause the entropy decoder to process an empty data segment,
  171460. * inserting dummy zeroes, and then we will reprocess the marker.
  171461. *
  171462. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171463. * appropriate if the found marker is a future restart marker (indicating
  171464. * that we have missed the desired restart marker, probably because it got
  171465. * corrupted).
  171466. * We apply #2 or #3 if the found marker is a restart marker no more than
  171467. * two counts behind or ahead of the expected one. We also apply #2 if the
  171468. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171469. * If the found marker is a restart marker more than 2 counts away, we do #1
  171470. * (too much risk that the marker is erroneous; with luck we will be able to
  171471. * resync at some future point).
  171472. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171473. * overrunning the end of a scan. An implementation limited to single-scan
  171474. * files might find it better to apply #2 for markers other than EOI, since
  171475. * any other marker would have to be bogus data in that case.
  171476. */
  171477. GLOBAL(boolean)
  171478. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171479. {
  171480. int marker = cinfo->unread_marker;
  171481. int action = 1;
  171482. /* Always put up a warning. */
  171483. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171484. /* Outer loop handles repeated decision after scanning forward. */
  171485. for (;;) {
  171486. if (marker < (int) M_SOF0)
  171487. action = 2; /* invalid marker */
  171488. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171489. action = 3; /* valid non-restart marker */
  171490. else {
  171491. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171492. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171493. action = 3; /* one of the next two expected restarts */
  171494. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171495. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171496. action = 2; /* a prior restart, so advance */
  171497. else
  171498. action = 1; /* desired restart or too far away */
  171499. }
  171500. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171501. switch (action) {
  171502. case 1:
  171503. /* Discard marker and let entropy decoder resume processing. */
  171504. cinfo->unread_marker = 0;
  171505. return TRUE;
  171506. case 2:
  171507. /* Scan to the next marker, and repeat the decision loop. */
  171508. if (! next_marker(cinfo))
  171509. return FALSE;
  171510. marker = cinfo->unread_marker;
  171511. break;
  171512. case 3:
  171513. /* Return without advancing past this marker. */
  171514. /* Entropy decoder will be forced to process an empty segment. */
  171515. return TRUE;
  171516. }
  171517. } /* end loop */
  171518. }
  171519. /*
  171520. * Reset marker processing state to begin a fresh datastream.
  171521. */
  171522. METHODDEF(void)
  171523. reset_marker_reader (j_decompress_ptr cinfo)
  171524. {
  171525. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171526. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171527. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171528. cinfo->unread_marker = 0; /* no pending marker */
  171529. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171530. marker->pub.saw_SOF = FALSE;
  171531. marker->pub.discarded_bytes = 0;
  171532. marker->cur_marker = NULL;
  171533. }
  171534. /*
  171535. * Initialize the marker reader module.
  171536. * This is called only once, when the decompression object is created.
  171537. */
  171538. GLOBAL(void)
  171539. jinit_marker_reader (j_decompress_ptr cinfo)
  171540. {
  171541. my_marker_ptr2 marker;
  171542. int i;
  171543. /* Create subobject in permanent pool */
  171544. marker = (my_marker_ptr2)
  171545. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171546. SIZEOF(my_marker_reader));
  171547. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171548. /* Initialize public method pointers */
  171549. marker->pub.reset_marker_reader = reset_marker_reader;
  171550. marker->pub.read_markers = read_markers;
  171551. marker->pub.read_restart_marker = read_restart_marker;
  171552. /* Initialize COM/APPn processing.
  171553. * By default, we examine and then discard APP0 and APP14,
  171554. * but simply discard COM and all other APPn.
  171555. */
  171556. marker->process_COM = skip_variable;
  171557. marker->length_limit_COM = 0;
  171558. for (i = 0; i < 16; i++) {
  171559. marker->process_APPn[i] = skip_variable;
  171560. marker->length_limit_APPn[i] = 0;
  171561. }
  171562. marker->process_APPn[0] = get_interesting_appn;
  171563. marker->process_APPn[14] = get_interesting_appn;
  171564. /* Reset marker processing state */
  171565. reset_marker_reader(cinfo);
  171566. }
  171567. /*
  171568. * Control saving of COM and APPn markers into marker_list.
  171569. */
  171570. #ifdef SAVE_MARKERS_SUPPORTED
  171571. GLOBAL(void)
  171572. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171573. unsigned int length_limit)
  171574. {
  171575. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171576. long maxlength;
  171577. jpeg_marker_parser_method processor;
  171578. /* Length limit mustn't be larger than what we can allocate
  171579. * (should only be a concern in a 16-bit environment).
  171580. */
  171581. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171582. if (((long) length_limit) > maxlength)
  171583. length_limit = (unsigned int) maxlength;
  171584. /* Choose processor routine to use.
  171585. * APP0/APP14 have special requirements.
  171586. */
  171587. if (length_limit) {
  171588. processor = save_marker;
  171589. /* If saving APP0/APP14, save at least enough for our internal use. */
  171590. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171591. length_limit = APP0_DATA_LEN;
  171592. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171593. length_limit = APP14_DATA_LEN;
  171594. } else {
  171595. processor = skip_variable;
  171596. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171597. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171598. processor = get_interesting_appn;
  171599. }
  171600. if (marker_code == (int) M_COM) {
  171601. marker->process_COM = processor;
  171602. marker->length_limit_COM = length_limit;
  171603. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171604. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171605. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171606. } else
  171607. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171608. }
  171609. #endif /* SAVE_MARKERS_SUPPORTED */
  171610. /*
  171611. * Install a special processing method for COM or APPn markers.
  171612. */
  171613. GLOBAL(void)
  171614. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171615. jpeg_marker_parser_method routine)
  171616. {
  171617. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171618. if (marker_code == (int) M_COM)
  171619. marker->process_COM = routine;
  171620. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171621. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171622. else
  171623. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171624. }
  171625. /*** End of inlined file: jdmarker.c ***/
  171626. /*** Start of inlined file: jdmaster.c ***/
  171627. #define JPEG_INTERNALS
  171628. /* Private state */
  171629. typedef struct {
  171630. struct jpeg_decomp_master pub; /* public fields */
  171631. int pass_number; /* # of passes completed */
  171632. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171633. /* Saved references to initialized quantizer modules,
  171634. * in case we need to switch modes.
  171635. */
  171636. struct jpeg_color_quantizer * quantizer_1pass;
  171637. struct jpeg_color_quantizer * quantizer_2pass;
  171638. } my_decomp_master;
  171639. typedef my_decomp_master * my_master_ptr6;
  171640. /*
  171641. * Determine whether merged upsample/color conversion should be used.
  171642. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171643. */
  171644. LOCAL(boolean)
  171645. use_merged_upsample (j_decompress_ptr cinfo)
  171646. {
  171647. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171648. /* Merging is the equivalent of plain box-filter upsampling */
  171649. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171650. return FALSE;
  171651. /* jdmerge.c only supports YCC=>RGB color conversion */
  171652. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171653. cinfo->out_color_space != JCS_RGB ||
  171654. cinfo->out_color_components != RGB_PIXELSIZE)
  171655. return FALSE;
  171656. /* and it only handles 2h1v or 2h2v sampling ratios */
  171657. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171658. cinfo->comp_info[1].h_samp_factor != 1 ||
  171659. cinfo->comp_info[2].h_samp_factor != 1 ||
  171660. cinfo->comp_info[0].v_samp_factor > 2 ||
  171661. cinfo->comp_info[1].v_samp_factor != 1 ||
  171662. cinfo->comp_info[2].v_samp_factor != 1)
  171663. return FALSE;
  171664. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171665. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171666. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171667. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171668. return FALSE;
  171669. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171670. return TRUE; /* by golly, it'll work... */
  171671. #else
  171672. return FALSE;
  171673. #endif
  171674. }
  171675. /*
  171676. * Compute output image dimensions and related values.
  171677. * NOTE: this is exported for possible use by application.
  171678. * Hence it mustn't do anything that can't be done twice.
  171679. * Also note that it may be called before the master module is initialized!
  171680. */
  171681. GLOBAL(void)
  171682. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171683. /* Do computations that are needed before master selection phase */
  171684. {
  171685. #ifdef IDCT_SCALING_SUPPORTED
  171686. int ci;
  171687. jpeg_component_info *compptr;
  171688. #endif
  171689. /* Prevent application from calling me at wrong times */
  171690. if (cinfo->global_state != DSTATE_READY)
  171691. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171692. #ifdef IDCT_SCALING_SUPPORTED
  171693. /* Compute actual output image dimensions and DCT scaling choices. */
  171694. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171695. /* Provide 1/8 scaling */
  171696. cinfo->output_width = (JDIMENSION)
  171697. jdiv_round_up((long) cinfo->image_width, 8L);
  171698. cinfo->output_height = (JDIMENSION)
  171699. jdiv_round_up((long) cinfo->image_height, 8L);
  171700. cinfo->min_DCT_scaled_size = 1;
  171701. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171702. /* Provide 1/4 scaling */
  171703. cinfo->output_width = (JDIMENSION)
  171704. jdiv_round_up((long) cinfo->image_width, 4L);
  171705. cinfo->output_height = (JDIMENSION)
  171706. jdiv_round_up((long) cinfo->image_height, 4L);
  171707. cinfo->min_DCT_scaled_size = 2;
  171708. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171709. /* Provide 1/2 scaling */
  171710. cinfo->output_width = (JDIMENSION)
  171711. jdiv_round_up((long) cinfo->image_width, 2L);
  171712. cinfo->output_height = (JDIMENSION)
  171713. jdiv_round_up((long) cinfo->image_height, 2L);
  171714. cinfo->min_DCT_scaled_size = 4;
  171715. } else {
  171716. /* Provide 1/1 scaling */
  171717. cinfo->output_width = cinfo->image_width;
  171718. cinfo->output_height = cinfo->image_height;
  171719. cinfo->min_DCT_scaled_size = DCTSIZE;
  171720. }
  171721. /* In selecting the actual DCT scaling for each component, we try to
  171722. * scale up the chroma components via IDCT scaling rather than upsampling.
  171723. * This saves time if the upsampler gets to use 1:1 scaling.
  171724. * Note this code assumes that the supported DCT scalings are powers of 2.
  171725. */
  171726. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171727. ci++, compptr++) {
  171728. int ssize = cinfo->min_DCT_scaled_size;
  171729. while (ssize < DCTSIZE &&
  171730. (compptr->h_samp_factor * ssize * 2 <=
  171731. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171732. (compptr->v_samp_factor * ssize * 2 <=
  171733. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171734. ssize = ssize * 2;
  171735. }
  171736. compptr->DCT_scaled_size = ssize;
  171737. }
  171738. /* Recompute downsampled dimensions of components;
  171739. * application needs to know these if using raw downsampled data.
  171740. */
  171741. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171742. ci++, compptr++) {
  171743. /* Size in samples, after IDCT scaling */
  171744. compptr->downsampled_width = (JDIMENSION)
  171745. jdiv_round_up((long) cinfo->image_width *
  171746. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171747. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171748. compptr->downsampled_height = (JDIMENSION)
  171749. jdiv_round_up((long) cinfo->image_height *
  171750. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171751. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171752. }
  171753. #else /* !IDCT_SCALING_SUPPORTED */
  171754. /* Hardwire it to "no scaling" */
  171755. cinfo->output_width = cinfo->image_width;
  171756. cinfo->output_height = cinfo->image_height;
  171757. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171758. * and has computed unscaled downsampled_width and downsampled_height.
  171759. */
  171760. #endif /* IDCT_SCALING_SUPPORTED */
  171761. /* Report number of components in selected colorspace. */
  171762. /* Probably this should be in the color conversion module... */
  171763. switch (cinfo->out_color_space) {
  171764. case JCS_GRAYSCALE:
  171765. cinfo->out_color_components = 1;
  171766. break;
  171767. case JCS_RGB:
  171768. #if RGB_PIXELSIZE != 3
  171769. cinfo->out_color_components = RGB_PIXELSIZE;
  171770. break;
  171771. #endif /* else share code with YCbCr */
  171772. case JCS_YCbCr:
  171773. cinfo->out_color_components = 3;
  171774. break;
  171775. case JCS_CMYK:
  171776. case JCS_YCCK:
  171777. cinfo->out_color_components = 4;
  171778. break;
  171779. default: /* else must be same colorspace as in file */
  171780. cinfo->out_color_components = cinfo->num_components;
  171781. break;
  171782. }
  171783. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171784. cinfo->out_color_components);
  171785. /* See if upsampler will want to emit more than one row at a time */
  171786. if (use_merged_upsample(cinfo))
  171787. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171788. else
  171789. cinfo->rec_outbuf_height = 1;
  171790. }
  171791. /*
  171792. * Several decompression processes need to range-limit values to the range
  171793. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171794. * due to noise introduced by quantization, roundoff error, etc. These
  171795. * processes are inner loops and need to be as fast as possible. On most
  171796. * machines, particularly CPUs with pipelines or instruction prefetch,
  171797. * a (subscript-check-less) C table lookup
  171798. * x = sample_range_limit[x];
  171799. * is faster than explicit tests
  171800. * if (x < 0) x = 0;
  171801. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171802. * These processes all use a common table prepared by the routine below.
  171803. *
  171804. * For most steps we can mathematically guarantee that the initial value
  171805. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171806. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171807. * limiting step (just after the IDCT), a wildly out-of-range value is
  171808. * possible if the input data is corrupt. To avoid any chance of indexing
  171809. * off the end of memory and getting a bad-pointer trap, we perform the
  171810. * post-IDCT limiting thus:
  171811. * x = range_limit[x & MASK];
  171812. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171813. * samples. Under normal circumstances this is more than enough range and
  171814. * a correct output will be generated; with bogus input data the mask will
  171815. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171816. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171817. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171818. * So the post-IDCT limiting table ends up looking like this:
  171819. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171820. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171821. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171822. * 0,1,...,CENTERJSAMPLE-1
  171823. * Negative inputs select values from the upper half of the table after
  171824. * masking.
  171825. *
  171826. * We can save some space by overlapping the start of the post-IDCT table
  171827. * with the simpler range limiting table. The post-IDCT table begins at
  171828. * sample_range_limit + CENTERJSAMPLE.
  171829. *
  171830. * Note that the table is allocated in near data space on PCs; it's small
  171831. * enough and used often enough to justify this.
  171832. */
  171833. LOCAL(void)
  171834. prepare_range_limit_table (j_decompress_ptr cinfo)
  171835. /* Allocate and fill in the sample_range_limit table */
  171836. {
  171837. JSAMPLE * table;
  171838. int i;
  171839. table = (JSAMPLE *)
  171840. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171841. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171842. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  171843. cinfo->sample_range_limit = table;
  171844. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  171845. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  171846. /* Main part of "simple" table: limit[x] = x */
  171847. for (i = 0; i <= MAXJSAMPLE; i++)
  171848. table[i] = (JSAMPLE) i;
  171849. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  171850. /* End of simple table, rest of first half of post-IDCT table */
  171851. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  171852. table[i] = MAXJSAMPLE;
  171853. /* Second half of post-IDCT table */
  171854. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  171855. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171856. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  171857. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  171858. }
  171859. /*
  171860. * Master selection of decompression modules.
  171861. * This is done once at jpeg_start_decompress time. We determine
  171862. * which modules will be used and give them appropriate initialization calls.
  171863. * We also initialize the decompressor input side to begin consuming data.
  171864. *
  171865. * Since jpeg_read_header has finished, we know what is in the SOF
  171866. * and (first) SOS markers. We also have all the application parameter
  171867. * settings.
  171868. */
  171869. LOCAL(void)
  171870. master_selection (j_decompress_ptr cinfo)
  171871. {
  171872. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171873. boolean use_c_buffer;
  171874. long samplesperrow;
  171875. JDIMENSION jd_samplesperrow;
  171876. /* Initialize dimensions and other stuff */
  171877. jpeg_calc_output_dimensions(cinfo);
  171878. prepare_range_limit_table(cinfo);
  171879. /* Width of an output scanline must be representable as JDIMENSION. */
  171880. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  171881. jd_samplesperrow = (JDIMENSION) samplesperrow;
  171882. if ((long) jd_samplesperrow != samplesperrow)
  171883. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171884. /* Initialize my private state */
  171885. master->pass_number = 0;
  171886. master->using_merged_upsample = use_merged_upsample(cinfo);
  171887. /* Color quantizer selection */
  171888. master->quantizer_1pass = NULL;
  171889. master->quantizer_2pass = NULL;
  171890. /* No mode changes if not using buffered-image mode. */
  171891. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  171892. cinfo->enable_1pass_quant = FALSE;
  171893. cinfo->enable_external_quant = FALSE;
  171894. cinfo->enable_2pass_quant = FALSE;
  171895. }
  171896. if (cinfo->quantize_colors) {
  171897. if (cinfo->raw_data_out)
  171898. ERREXIT(cinfo, JERR_NOTIMPL);
  171899. /* 2-pass quantizer only works in 3-component color space. */
  171900. if (cinfo->out_color_components != 3) {
  171901. cinfo->enable_1pass_quant = TRUE;
  171902. cinfo->enable_external_quant = FALSE;
  171903. cinfo->enable_2pass_quant = FALSE;
  171904. cinfo->colormap = NULL;
  171905. } else if (cinfo->colormap != NULL) {
  171906. cinfo->enable_external_quant = TRUE;
  171907. } else if (cinfo->two_pass_quantize) {
  171908. cinfo->enable_2pass_quant = TRUE;
  171909. } else {
  171910. cinfo->enable_1pass_quant = TRUE;
  171911. }
  171912. if (cinfo->enable_1pass_quant) {
  171913. #ifdef QUANT_1PASS_SUPPORTED
  171914. jinit_1pass_quantizer(cinfo);
  171915. master->quantizer_1pass = cinfo->cquantize;
  171916. #else
  171917. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171918. #endif
  171919. }
  171920. /* We use the 2-pass code to map to external colormaps. */
  171921. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  171922. #ifdef QUANT_2PASS_SUPPORTED
  171923. jinit_2pass_quantizer(cinfo);
  171924. master->quantizer_2pass = cinfo->cquantize;
  171925. #else
  171926. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171927. #endif
  171928. }
  171929. /* If both quantizers are initialized, the 2-pass one is left active;
  171930. * this is necessary for starting with quantization to an external map.
  171931. */
  171932. }
  171933. /* Post-processing: in particular, color conversion first */
  171934. if (! cinfo->raw_data_out) {
  171935. if (master->using_merged_upsample) {
  171936. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171937. jinit_merged_upsampler(cinfo); /* does color conversion too */
  171938. #else
  171939. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171940. #endif
  171941. } else {
  171942. jinit_color_deconverter(cinfo);
  171943. jinit_upsampler(cinfo);
  171944. }
  171945. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  171946. }
  171947. /* Inverse DCT */
  171948. jinit_inverse_dct(cinfo);
  171949. /* Entropy decoding: either Huffman or arithmetic coding. */
  171950. if (cinfo->arith_code) {
  171951. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171952. } else {
  171953. if (cinfo->progressive_mode) {
  171954. #ifdef D_PROGRESSIVE_SUPPORTED
  171955. jinit_phuff_decoder(cinfo);
  171956. #else
  171957. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171958. #endif
  171959. } else
  171960. jinit_huff_decoder(cinfo);
  171961. }
  171962. /* Initialize principal buffer controllers. */
  171963. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  171964. jinit_d_coef_controller(cinfo, use_c_buffer);
  171965. if (! cinfo->raw_data_out)
  171966. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  171967. /* We can now tell the memory manager to allocate virtual arrays. */
  171968. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171969. /* Initialize input side of decompressor to consume first scan. */
  171970. (*cinfo->inputctl->start_input_pass) (cinfo);
  171971. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171972. /* If jpeg_start_decompress will read the whole file, initialize
  171973. * progress monitoring appropriately. The input step is counted
  171974. * as one pass.
  171975. */
  171976. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  171977. cinfo->inputctl->has_multiple_scans) {
  171978. int nscans;
  171979. /* Estimate number of scans to set pass_limit. */
  171980. if (cinfo->progressive_mode) {
  171981. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171982. nscans = 2 + 3 * cinfo->num_components;
  171983. } else {
  171984. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171985. nscans = cinfo->num_components;
  171986. }
  171987. cinfo->progress->pass_counter = 0L;
  171988. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171989. cinfo->progress->completed_passes = 0;
  171990. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  171991. /* Count the input pass as done */
  171992. master->pass_number++;
  171993. }
  171994. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171995. }
  171996. /*
  171997. * Per-pass setup.
  171998. * This is called at the beginning of each output pass. We determine which
  171999. * modules will be active during this pass and give them appropriate
  172000. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172001. * is a "real" output pass or a dummy pass for color quantization.
  172002. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172003. */
  172004. METHODDEF(void)
  172005. prepare_for_output_pass (j_decompress_ptr cinfo)
  172006. {
  172007. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172008. if (master->pub.is_dummy_pass) {
  172009. #ifdef QUANT_2PASS_SUPPORTED
  172010. /* Final pass of 2-pass quantization */
  172011. master->pub.is_dummy_pass = FALSE;
  172012. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172013. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172014. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172015. #else
  172016. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172017. #endif /* QUANT_2PASS_SUPPORTED */
  172018. } else {
  172019. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172020. /* Select new quantization method */
  172021. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172022. cinfo->cquantize = master->quantizer_2pass;
  172023. master->pub.is_dummy_pass = TRUE;
  172024. } else if (cinfo->enable_1pass_quant) {
  172025. cinfo->cquantize = master->quantizer_1pass;
  172026. } else {
  172027. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172028. }
  172029. }
  172030. (*cinfo->idct->start_pass) (cinfo);
  172031. (*cinfo->coef->start_output_pass) (cinfo);
  172032. if (! cinfo->raw_data_out) {
  172033. if (! master->using_merged_upsample)
  172034. (*cinfo->cconvert->start_pass) (cinfo);
  172035. (*cinfo->upsample->start_pass) (cinfo);
  172036. if (cinfo->quantize_colors)
  172037. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172038. (*cinfo->post->start_pass) (cinfo,
  172039. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172040. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172041. }
  172042. }
  172043. /* Set up progress monitor's pass info if present */
  172044. if (cinfo->progress != NULL) {
  172045. cinfo->progress->completed_passes = master->pass_number;
  172046. cinfo->progress->total_passes = master->pass_number +
  172047. (master->pub.is_dummy_pass ? 2 : 1);
  172048. /* In buffered-image mode, we assume one more output pass if EOI not
  172049. * yet reached, but no more passes if EOI has been reached.
  172050. */
  172051. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172052. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172053. }
  172054. }
  172055. }
  172056. /*
  172057. * Finish up at end of an output pass.
  172058. */
  172059. METHODDEF(void)
  172060. finish_output_pass (j_decompress_ptr cinfo)
  172061. {
  172062. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172063. if (cinfo->quantize_colors)
  172064. (*cinfo->cquantize->finish_pass) (cinfo);
  172065. master->pass_number++;
  172066. }
  172067. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172068. /*
  172069. * Switch to a new external colormap between output passes.
  172070. */
  172071. GLOBAL(void)
  172072. jpeg_new_colormap (j_decompress_ptr cinfo)
  172073. {
  172074. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172075. /* Prevent application from calling me at wrong times */
  172076. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172077. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172078. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172079. cinfo->colormap != NULL) {
  172080. /* Select 2-pass quantizer for external colormap use */
  172081. cinfo->cquantize = master->quantizer_2pass;
  172082. /* Notify quantizer of colormap change */
  172083. (*cinfo->cquantize->new_color_map) (cinfo);
  172084. master->pub.is_dummy_pass = FALSE; /* just in case */
  172085. } else
  172086. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172087. }
  172088. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172089. /*
  172090. * Initialize master decompression control and select active modules.
  172091. * This is performed at the start of jpeg_start_decompress.
  172092. */
  172093. GLOBAL(void)
  172094. jinit_master_decompress (j_decompress_ptr cinfo)
  172095. {
  172096. my_master_ptr6 master;
  172097. master = (my_master_ptr6)
  172098. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172099. SIZEOF(my_decomp_master));
  172100. cinfo->master = (struct jpeg_decomp_master *) master;
  172101. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172102. master->pub.finish_output_pass = finish_output_pass;
  172103. master->pub.is_dummy_pass = FALSE;
  172104. master_selection(cinfo);
  172105. }
  172106. /*** End of inlined file: jdmaster.c ***/
  172107. #undef FIX
  172108. /*** Start of inlined file: jdmerge.c ***/
  172109. #define JPEG_INTERNALS
  172110. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172111. /* Private subobject */
  172112. typedef struct {
  172113. struct jpeg_upsampler pub; /* public fields */
  172114. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172115. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172116. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172117. JSAMPARRAY output_buf));
  172118. /* Private state for YCC->RGB conversion */
  172119. int * Cr_r_tab; /* => table for Cr to R conversion */
  172120. int * Cb_b_tab; /* => table for Cb to B conversion */
  172121. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172122. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172123. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172124. * We need a "spare" row buffer to hold the second output row if the
  172125. * application provides just a one-row buffer; we also use the spare
  172126. * to discard the dummy last row if the image height is odd.
  172127. */
  172128. JSAMPROW spare_row;
  172129. boolean spare_full; /* T if spare buffer is occupied */
  172130. JDIMENSION out_row_width; /* samples per output row */
  172131. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172132. } my_upsampler;
  172133. typedef my_upsampler * my_upsample_ptr;
  172134. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172135. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172136. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172137. /*
  172138. * Initialize tables for YCC->RGB colorspace conversion.
  172139. * This is taken directly from jdcolor.c; see that file for more info.
  172140. */
  172141. LOCAL(void)
  172142. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172143. {
  172144. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172145. int i;
  172146. INT32 x;
  172147. SHIFT_TEMPS
  172148. upsample->Cr_r_tab = (int *)
  172149. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172150. (MAXJSAMPLE+1) * SIZEOF(int));
  172151. upsample->Cb_b_tab = (int *)
  172152. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172153. (MAXJSAMPLE+1) * SIZEOF(int));
  172154. upsample->Cr_g_tab = (INT32 *)
  172155. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172156. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172157. upsample->Cb_g_tab = (INT32 *)
  172158. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172159. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172160. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172161. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172162. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172163. /* Cr=>R value is nearest int to 1.40200 * x */
  172164. upsample->Cr_r_tab[i] = (int)
  172165. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172166. /* Cb=>B value is nearest int to 1.77200 * x */
  172167. upsample->Cb_b_tab[i] = (int)
  172168. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172169. /* Cr=>G value is scaled-up -0.71414 * x */
  172170. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172171. /* Cb=>G value is scaled-up -0.34414 * x */
  172172. /* We also add in ONE_HALF so that need not do it in inner loop */
  172173. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172174. }
  172175. }
  172176. /*
  172177. * Initialize for an upsampling pass.
  172178. */
  172179. METHODDEF(void)
  172180. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172181. {
  172182. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172183. /* Mark the spare buffer empty */
  172184. upsample->spare_full = FALSE;
  172185. /* Initialize total-height counter for detecting bottom of image */
  172186. upsample->rows_to_go = cinfo->output_height;
  172187. }
  172188. /*
  172189. * Control routine to do upsampling (and color conversion).
  172190. *
  172191. * The control routine just handles the row buffering considerations.
  172192. */
  172193. METHODDEF(void)
  172194. merged_2v_upsample (j_decompress_ptr cinfo,
  172195. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172196. JDIMENSION,
  172197. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172198. JDIMENSION out_rows_avail)
  172199. /* 2:1 vertical sampling case: may need a spare row. */
  172200. {
  172201. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172202. JSAMPROW work_ptrs[2];
  172203. JDIMENSION num_rows; /* number of rows returned to caller */
  172204. if (upsample->spare_full) {
  172205. /* If we have a spare row saved from a previous cycle, just return it. */
  172206. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172207. 1, upsample->out_row_width);
  172208. num_rows = 1;
  172209. upsample->spare_full = FALSE;
  172210. } else {
  172211. /* Figure number of rows to return to caller. */
  172212. num_rows = 2;
  172213. /* Not more than the distance to the end of the image. */
  172214. if (num_rows > upsample->rows_to_go)
  172215. num_rows = upsample->rows_to_go;
  172216. /* And not more than what the client can accept: */
  172217. out_rows_avail -= *out_row_ctr;
  172218. if (num_rows > out_rows_avail)
  172219. num_rows = out_rows_avail;
  172220. /* Create output pointer array for upsampler. */
  172221. work_ptrs[0] = output_buf[*out_row_ctr];
  172222. if (num_rows > 1) {
  172223. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172224. } else {
  172225. work_ptrs[1] = upsample->spare_row;
  172226. upsample->spare_full = TRUE;
  172227. }
  172228. /* Now do the upsampling. */
  172229. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172230. }
  172231. /* Adjust counts */
  172232. *out_row_ctr += num_rows;
  172233. upsample->rows_to_go -= num_rows;
  172234. /* When the buffer is emptied, declare this input row group consumed */
  172235. if (! upsample->spare_full)
  172236. (*in_row_group_ctr)++;
  172237. }
  172238. METHODDEF(void)
  172239. merged_1v_upsample (j_decompress_ptr cinfo,
  172240. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172241. JDIMENSION,
  172242. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172243. JDIMENSION)
  172244. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172245. {
  172246. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172247. /* Just do the upsampling. */
  172248. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172249. output_buf + *out_row_ctr);
  172250. /* Adjust counts */
  172251. (*out_row_ctr)++;
  172252. (*in_row_group_ctr)++;
  172253. }
  172254. /*
  172255. * These are the routines invoked by the control routines to do
  172256. * the actual upsampling/conversion. One row group is processed per call.
  172257. *
  172258. * Note: since we may be writing directly into application-supplied buffers,
  172259. * we have to be honest about the output width; we can't assume the buffer
  172260. * has been rounded up to an even width.
  172261. */
  172262. /*
  172263. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172264. */
  172265. METHODDEF(void)
  172266. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172267. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172268. JSAMPARRAY output_buf)
  172269. {
  172270. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172271. register int y, cred, cgreen, cblue;
  172272. int cb, cr;
  172273. register JSAMPROW outptr;
  172274. JSAMPROW inptr0, inptr1, inptr2;
  172275. JDIMENSION col;
  172276. /* copy these pointers into registers if possible */
  172277. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172278. int * Crrtab = upsample->Cr_r_tab;
  172279. int * Cbbtab = upsample->Cb_b_tab;
  172280. INT32 * Crgtab = upsample->Cr_g_tab;
  172281. INT32 * Cbgtab = upsample->Cb_g_tab;
  172282. SHIFT_TEMPS
  172283. inptr0 = input_buf[0][in_row_group_ctr];
  172284. inptr1 = input_buf[1][in_row_group_ctr];
  172285. inptr2 = input_buf[2][in_row_group_ctr];
  172286. outptr = output_buf[0];
  172287. /* Loop for each pair of output pixels */
  172288. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172289. /* Do the chroma part of the calculation */
  172290. cb = GETJSAMPLE(*inptr1++);
  172291. cr = GETJSAMPLE(*inptr2++);
  172292. cred = Crrtab[cr];
  172293. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172294. cblue = Cbbtab[cb];
  172295. /* Fetch 2 Y values and emit 2 pixels */
  172296. y = GETJSAMPLE(*inptr0++);
  172297. outptr[RGB_RED] = range_limit[y + cred];
  172298. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172299. outptr[RGB_BLUE] = range_limit[y + cblue];
  172300. outptr += RGB_PIXELSIZE;
  172301. y = GETJSAMPLE(*inptr0++);
  172302. outptr[RGB_RED] = range_limit[y + cred];
  172303. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172304. outptr[RGB_BLUE] = range_limit[y + cblue];
  172305. outptr += RGB_PIXELSIZE;
  172306. }
  172307. /* If image width is odd, do the last output column separately */
  172308. if (cinfo->output_width & 1) {
  172309. cb = GETJSAMPLE(*inptr1);
  172310. cr = GETJSAMPLE(*inptr2);
  172311. cred = Crrtab[cr];
  172312. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172313. cblue = Cbbtab[cb];
  172314. y = GETJSAMPLE(*inptr0);
  172315. outptr[RGB_RED] = range_limit[y + cred];
  172316. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172317. outptr[RGB_BLUE] = range_limit[y + cblue];
  172318. }
  172319. }
  172320. /*
  172321. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172322. */
  172323. METHODDEF(void)
  172324. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172325. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172326. JSAMPARRAY output_buf)
  172327. {
  172328. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172329. register int y, cred, cgreen, cblue;
  172330. int cb, cr;
  172331. register JSAMPROW outptr0, outptr1;
  172332. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172333. JDIMENSION col;
  172334. /* copy these pointers into registers if possible */
  172335. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172336. int * Crrtab = upsample->Cr_r_tab;
  172337. int * Cbbtab = upsample->Cb_b_tab;
  172338. INT32 * Crgtab = upsample->Cr_g_tab;
  172339. INT32 * Cbgtab = upsample->Cb_g_tab;
  172340. SHIFT_TEMPS
  172341. inptr00 = input_buf[0][in_row_group_ctr*2];
  172342. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172343. inptr1 = input_buf[1][in_row_group_ctr];
  172344. inptr2 = input_buf[2][in_row_group_ctr];
  172345. outptr0 = output_buf[0];
  172346. outptr1 = output_buf[1];
  172347. /* Loop for each group of output pixels */
  172348. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172349. /* Do the chroma part of the calculation */
  172350. cb = GETJSAMPLE(*inptr1++);
  172351. cr = GETJSAMPLE(*inptr2++);
  172352. cred = Crrtab[cr];
  172353. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172354. cblue = Cbbtab[cb];
  172355. /* Fetch 4 Y values and emit 4 pixels */
  172356. y = GETJSAMPLE(*inptr00++);
  172357. outptr0[RGB_RED] = range_limit[y + cred];
  172358. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172359. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172360. outptr0 += RGB_PIXELSIZE;
  172361. y = GETJSAMPLE(*inptr00++);
  172362. outptr0[RGB_RED] = range_limit[y + cred];
  172363. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172364. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172365. outptr0 += RGB_PIXELSIZE;
  172366. y = GETJSAMPLE(*inptr01++);
  172367. outptr1[RGB_RED] = range_limit[y + cred];
  172368. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172369. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172370. outptr1 += RGB_PIXELSIZE;
  172371. y = GETJSAMPLE(*inptr01++);
  172372. outptr1[RGB_RED] = range_limit[y + cred];
  172373. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172374. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172375. outptr1 += RGB_PIXELSIZE;
  172376. }
  172377. /* If image width is odd, do the last output column separately */
  172378. if (cinfo->output_width & 1) {
  172379. cb = GETJSAMPLE(*inptr1);
  172380. cr = GETJSAMPLE(*inptr2);
  172381. cred = Crrtab[cr];
  172382. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172383. cblue = Cbbtab[cb];
  172384. y = GETJSAMPLE(*inptr00);
  172385. outptr0[RGB_RED] = range_limit[y + cred];
  172386. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172387. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172388. y = GETJSAMPLE(*inptr01);
  172389. outptr1[RGB_RED] = range_limit[y + cred];
  172390. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172391. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172392. }
  172393. }
  172394. /*
  172395. * Module initialization routine for merged upsampling/color conversion.
  172396. *
  172397. * NB: this is called under the conditions determined by use_merged_upsample()
  172398. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172399. * of this module; no safety checks are made here.
  172400. */
  172401. GLOBAL(void)
  172402. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172403. {
  172404. my_upsample_ptr upsample;
  172405. upsample = (my_upsample_ptr)
  172406. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172407. SIZEOF(my_upsampler));
  172408. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172409. upsample->pub.start_pass = start_pass_merged_upsample;
  172410. upsample->pub.need_context_rows = FALSE;
  172411. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172412. if (cinfo->max_v_samp_factor == 2) {
  172413. upsample->pub.upsample = merged_2v_upsample;
  172414. upsample->upmethod = h2v2_merged_upsample;
  172415. /* Allocate a spare row buffer */
  172416. upsample->spare_row = (JSAMPROW)
  172417. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172418. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172419. } else {
  172420. upsample->pub.upsample = merged_1v_upsample;
  172421. upsample->upmethod = h2v1_merged_upsample;
  172422. /* No spare row needed */
  172423. upsample->spare_row = NULL;
  172424. }
  172425. build_ycc_rgb_table2(cinfo);
  172426. }
  172427. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172428. /*** End of inlined file: jdmerge.c ***/
  172429. #undef ASSIGN_STATE
  172430. /*** Start of inlined file: jdphuff.c ***/
  172431. #define JPEG_INTERNALS
  172432. #ifdef D_PROGRESSIVE_SUPPORTED
  172433. /*
  172434. * Expanded entropy decoder object for progressive Huffman decoding.
  172435. *
  172436. * The savable_state subrecord contains fields that change within an MCU,
  172437. * but must not be updated permanently until we complete the MCU.
  172438. */
  172439. typedef struct {
  172440. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172441. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172442. } savable_state3;
  172443. /* This macro is to work around compilers with missing or broken
  172444. * structure assignment. You'll need to fix this code if you have
  172445. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172446. */
  172447. #ifndef NO_STRUCT_ASSIGN
  172448. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172449. #else
  172450. #if MAX_COMPS_IN_SCAN == 4
  172451. #define ASSIGN_STATE(dest,src) \
  172452. ((dest).EOBRUN = (src).EOBRUN, \
  172453. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172454. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172455. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172456. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172457. #endif
  172458. #endif
  172459. typedef struct {
  172460. struct jpeg_entropy_decoder pub; /* public fields */
  172461. /* These fields are loaded into local variables at start of each MCU.
  172462. * In case of suspension, we exit WITHOUT updating them.
  172463. */
  172464. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172465. savable_state3 saved; /* Other state at start of MCU */
  172466. /* These fields are NOT loaded into local working state. */
  172467. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172468. /* Pointers to derived tables (these workspaces have image lifespan) */
  172469. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172470. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172471. } phuff_entropy_decoder;
  172472. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172473. /* Forward declarations */
  172474. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172475. JBLOCKROW *MCU_data));
  172476. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172477. JBLOCKROW *MCU_data));
  172478. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172479. JBLOCKROW *MCU_data));
  172480. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172481. JBLOCKROW *MCU_data));
  172482. /*
  172483. * Initialize for a Huffman-compressed scan.
  172484. */
  172485. METHODDEF(void)
  172486. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172487. {
  172488. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172489. boolean is_DC_band, bad;
  172490. int ci, coefi, tbl;
  172491. int *coef_bit_ptr;
  172492. jpeg_component_info * compptr;
  172493. is_DC_band = (cinfo->Ss == 0);
  172494. /* Validate scan parameters */
  172495. bad = FALSE;
  172496. if (is_DC_band) {
  172497. if (cinfo->Se != 0)
  172498. bad = TRUE;
  172499. } else {
  172500. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172501. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172502. bad = TRUE;
  172503. /* AC scans may have only one component */
  172504. if (cinfo->comps_in_scan != 1)
  172505. bad = TRUE;
  172506. }
  172507. if (cinfo->Ah != 0) {
  172508. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172509. if (cinfo->Al != cinfo->Ah-1)
  172510. bad = TRUE;
  172511. }
  172512. if (cinfo->Al > 13) /* need not check for < 0 */
  172513. bad = TRUE;
  172514. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172515. * but the spec doesn't say so, and we try to be liberal about what we
  172516. * accept. Note: large Al values could result in out-of-range DC
  172517. * coefficients during early scans, leading to bizarre displays due to
  172518. * overflows in the IDCT math. But we won't crash.
  172519. */
  172520. if (bad)
  172521. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172522. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172523. /* Update progression status, and verify that scan order is legal.
  172524. * Note that inter-scan inconsistencies are treated as warnings
  172525. * not fatal errors ... not clear if this is right way to behave.
  172526. */
  172527. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172528. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172529. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172530. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172531. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172532. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172533. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172534. if (cinfo->Ah != expected)
  172535. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172536. coef_bit_ptr[coefi] = cinfo->Al;
  172537. }
  172538. }
  172539. /* Select MCU decoding routine */
  172540. if (cinfo->Ah == 0) {
  172541. if (is_DC_band)
  172542. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172543. else
  172544. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172545. } else {
  172546. if (is_DC_band)
  172547. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172548. else
  172549. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172550. }
  172551. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172552. compptr = cinfo->cur_comp_info[ci];
  172553. /* Make sure requested tables are present, and compute derived tables.
  172554. * We may build same derived table more than once, but it's not expensive.
  172555. */
  172556. if (is_DC_band) {
  172557. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172558. tbl = compptr->dc_tbl_no;
  172559. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172560. & entropy->derived_tbls[tbl]);
  172561. }
  172562. } else {
  172563. tbl = compptr->ac_tbl_no;
  172564. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172565. & entropy->derived_tbls[tbl]);
  172566. /* remember the single active table */
  172567. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172568. }
  172569. /* Initialize DC predictions to 0 */
  172570. entropy->saved.last_dc_val[ci] = 0;
  172571. }
  172572. /* Initialize bitread state variables */
  172573. entropy->bitstate.bits_left = 0;
  172574. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172575. entropy->pub.insufficient_data = FALSE;
  172576. /* Initialize private state variables */
  172577. entropy->saved.EOBRUN = 0;
  172578. /* Initialize restart counter */
  172579. entropy->restarts_to_go = cinfo->restart_interval;
  172580. }
  172581. /*
  172582. * Check for a restart marker & resynchronize decoder.
  172583. * Returns FALSE if must suspend.
  172584. */
  172585. LOCAL(boolean)
  172586. process_restartp (j_decompress_ptr cinfo)
  172587. {
  172588. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172589. int ci;
  172590. /* Throw away any unused bits remaining in bit buffer; */
  172591. /* include any full bytes in next_marker's count of discarded bytes */
  172592. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172593. entropy->bitstate.bits_left = 0;
  172594. /* Advance past the RSTn marker */
  172595. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172596. return FALSE;
  172597. /* Re-initialize DC predictions to 0 */
  172598. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172599. entropy->saved.last_dc_val[ci] = 0;
  172600. /* Re-init EOB run count, too */
  172601. entropy->saved.EOBRUN = 0;
  172602. /* Reset restart counter */
  172603. entropy->restarts_to_go = cinfo->restart_interval;
  172604. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172605. * against a marker. In that case we will end up treating the next data
  172606. * segment as empty, and we can avoid producing bogus output pixels by
  172607. * leaving the flag set.
  172608. */
  172609. if (cinfo->unread_marker == 0)
  172610. entropy->pub.insufficient_data = FALSE;
  172611. return TRUE;
  172612. }
  172613. /*
  172614. * Huffman MCU decoding.
  172615. * Each of these routines decodes and returns one MCU's worth of
  172616. * Huffman-compressed coefficients.
  172617. * The coefficients are reordered from zigzag order into natural array order,
  172618. * but are not dequantized.
  172619. *
  172620. * The i'th block of the MCU is stored into the block pointed to by
  172621. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172622. *
  172623. * We return FALSE if data source requested suspension. In that case no
  172624. * changes have been made to permanent state. (Exception: some output
  172625. * coefficients may already have been assigned. This is harmless for
  172626. * spectral selection, since we'll just re-assign them on the next call.
  172627. * Successive approximation AC refinement has to be more careful, however.)
  172628. */
  172629. /*
  172630. * MCU decoding for DC initial scan (either spectral selection,
  172631. * or first pass of successive approximation).
  172632. */
  172633. METHODDEF(boolean)
  172634. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172635. {
  172636. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172637. int Al = cinfo->Al;
  172638. register int s, r;
  172639. int blkn, ci;
  172640. JBLOCKROW block;
  172641. BITREAD_STATE_VARS;
  172642. savable_state3 state;
  172643. d_derived_tbl * tbl;
  172644. jpeg_component_info * compptr;
  172645. /* Process restart marker if needed; may have to suspend */
  172646. if (cinfo->restart_interval) {
  172647. if (entropy->restarts_to_go == 0)
  172648. if (! process_restartp(cinfo))
  172649. return FALSE;
  172650. }
  172651. /* If we've run out of data, just leave the MCU set to zeroes.
  172652. * This way, we return uniform gray for the remainder of the segment.
  172653. */
  172654. if (! entropy->pub.insufficient_data) {
  172655. /* Load up working state */
  172656. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172657. ASSIGN_STATE(state, entropy->saved);
  172658. /* Outer loop handles each block in the MCU */
  172659. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172660. block = MCU_data[blkn];
  172661. ci = cinfo->MCU_membership[blkn];
  172662. compptr = cinfo->cur_comp_info[ci];
  172663. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172664. /* Decode a single block's worth of coefficients */
  172665. /* Section F.2.2.1: decode the DC coefficient difference */
  172666. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172667. if (s) {
  172668. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172669. r = GET_BITS(s);
  172670. s = HUFF_EXTEND(r, s);
  172671. }
  172672. /* Convert DC difference to actual value, update last_dc_val */
  172673. s += state.last_dc_val[ci];
  172674. state.last_dc_val[ci] = s;
  172675. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172676. (*block)[0] = (JCOEF) (s << Al);
  172677. }
  172678. /* Completed MCU, so update state */
  172679. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172680. ASSIGN_STATE(entropy->saved, state);
  172681. }
  172682. /* Account for restart interval (no-op if not using restarts) */
  172683. entropy->restarts_to_go--;
  172684. return TRUE;
  172685. }
  172686. /*
  172687. * MCU decoding for AC initial scan (either spectral selection,
  172688. * or first pass of successive approximation).
  172689. */
  172690. METHODDEF(boolean)
  172691. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172692. {
  172693. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172694. int Se = cinfo->Se;
  172695. int Al = cinfo->Al;
  172696. register int s, k, r;
  172697. unsigned int EOBRUN;
  172698. JBLOCKROW block;
  172699. BITREAD_STATE_VARS;
  172700. d_derived_tbl * tbl;
  172701. /* Process restart marker if needed; may have to suspend */
  172702. if (cinfo->restart_interval) {
  172703. if (entropy->restarts_to_go == 0)
  172704. if (! process_restartp(cinfo))
  172705. return FALSE;
  172706. }
  172707. /* If we've run out of data, just leave the MCU set to zeroes.
  172708. * This way, we return uniform gray for the remainder of the segment.
  172709. */
  172710. if (! entropy->pub.insufficient_data) {
  172711. /* Load up working state.
  172712. * We can avoid loading/saving bitread state if in an EOB run.
  172713. */
  172714. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172715. /* There is always only one block per MCU */
  172716. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172717. EOBRUN--; /* ...process it now (we do nothing) */
  172718. else {
  172719. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172720. block = MCU_data[0];
  172721. tbl = entropy->ac_derived_tbl;
  172722. for (k = cinfo->Ss; k <= Se; k++) {
  172723. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172724. r = s >> 4;
  172725. s &= 15;
  172726. if (s) {
  172727. k += r;
  172728. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172729. r = GET_BITS(s);
  172730. s = HUFF_EXTEND(r, s);
  172731. /* Scale and output coefficient in natural (dezigzagged) order */
  172732. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172733. } else {
  172734. if (r == 15) { /* ZRL */
  172735. k += 15; /* skip 15 zeroes in band */
  172736. } else { /* EOBr, run length is 2^r + appended bits */
  172737. EOBRUN = 1 << r;
  172738. if (r) { /* EOBr, r > 0 */
  172739. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172740. r = GET_BITS(r);
  172741. EOBRUN += r;
  172742. }
  172743. EOBRUN--; /* this band is processed at this moment */
  172744. break; /* force end-of-band */
  172745. }
  172746. }
  172747. }
  172748. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172749. }
  172750. /* Completed MCU, so update state */
  172751. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172752. }
  172753. /* Account for restart interval (no-op if not using restarts) */
  172754. entropy->restarts_to_go--;
  172755. return TRUE;
  172756. }
  172757. /*
  172758. * MCU decoding for DC successive approximation refinement scan.
  172759. * Note: we assume such scans can be multi-component, although the spec
  172760. * is not very clear on the point.
  172761. */
  172762. METHODDEF(boolean)
  172763. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172764. {
  172765. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172766. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172767. int blkn;
  172768. JBLOCKROW block;
  172769. BITREAD_STATE_VARS;
  172770. /* Process restart marker if needed; may have to suspend */
  172771. if (cinfo->restart_interval) {
  172772. if (entropy->restarts_to_go == 0)
  172773. if (! process_restartp(cinfo))
  172774. return FALSE;
  172775. }
  172776. /* Not worth the cycles to check insufficient_data here,
  172777. * since we will not change the data anyway if we read zeroes.
  172778. */
  172779. /* Load up working state */
  172780. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172781. /* Outer loop handles each block in the MCU */
  172782. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172783. block = MCU_data[blkn];
  172784. /* Encoded data is simply the next bit of the two's-complement DC value */
  172785. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172786. if (GET_BITS(1))
  172787. (*block)[0] |= p1;
  172788. /* Note: since we use |=, repeating the assignment later is safe */
  172789. }
  172790. /* Completed MCU, so update state */
  172791. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172792. /* Account for restart interval (no-op if not using restarts) */
  172793. entropy->restarts_to_go--;
  172794. return TRUE;
  172795. }
  172796. /*
  172797. * MCU decoding for AC successive approximation refinement scan.
  172798. */
  172799. METHODDEF(boolean)
  172800. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172801. {
  172802. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172803. int Se = cinfo->Se;
  172804. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172805. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172806. register int s, k, r;
  172807. unsigned int EOBRUN;
  172808. JBLOCKROW block;
  172809. JCOEFPTR thiscoef;
  172810. BITREAD_STATE_VARS;
  172811. d_derived_tbl * tbl;
  172812. int num_newnz;
  172813. int newnz_pos[DCTSIZE2];
  172814. /* Process restart marker if needed; may have to suspend */
  172815. if (cinfo->restart_interval) {
  172816. if (entropy->restarts_to_go == 0)
  172817. if (! process_restartp(cinfo))
  172818. return FALSE;
  172819. }
  172820. /* If we've run out of data, don't modify the MCU.
  172821. */
  172822. if (! entropy->pub.insufficient_data) {
  172823. /* Load up working state */
  172824. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172825. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172826. /* There is always only one block per MCU */
  172827. block = MCU_data[0];
  172828. tbl = entropy->ac_derived_tbl;
  172829. /* If we are forced to suspend, we must undo the assignments to any newly
  172830. * nonzero coefficients in the block, because otherwise we'd get confused
  172831. * next time about which coefficients were already nonzero.
  172832. * But we need not undo addition of bits to already-nonzero coefficients;
  172833. * instead, we can test the current bit to see if we already did it.
  172834. */
  172835. num_newnz = 0;
  172836. /* initialize coefficient loop counter to start of band */
  172837. k = cinfo->Ss;
  172838. if (EOBRUN == 0) {
  172839. for (; k <= Se; k++) {
  172840. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  172841. r = s >> 4;
  172842. s &= 15;
  172843. if (s) {
  172844. if (s != 1) /* size of new coef should always be 1 */
  172845. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  172846. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172847. if (GET_BITS(1))
  172848. s = p1; /* newly nonzero coef is positive */
  172849. else
  172850. s = m1; /* newly nonzero coef is negative */
  172851. } else {
  172852. if (r != 15) {
  172853. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  172854. if (r) {
  172855. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  172856. r = GET_BITS(r);
  172857. EOBRUN += r;
  172858. }
  172859. break; /* rest of block is handled by EOB logic */
  172860. }
  172861. /* note s = 0 for processing ZRL */
  172862. }
  172863. /* Advance over already-nonzero coefs and r still-zero coefs,
  172864. * appending correction bits to the nonzeroes. A correction bit is 1
  172865. * if the absolute value of the coefficient must be increased.
  172866. */
  172867. do {
  172868. thiscoef = *block + jpeg_natural_order[k];
  172869. if (*thiscoef != 0) {
  172870. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172871. if (GET_BITS(1)) {
  172872. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  172873. if (*thiscoef >= 0)
  172874. *thiscoef += p1;
  172875. else
  172876. *thiscoef += m1;
  172877. }
  172878. }
  172879. } else {
  172880. if (--r < 0)
  172881. break; /* reached target zero coefficient */
  172882. }
  172883. k++;
  172884. } while (k <= Se);
  172885. if (s) {
  172886. int pos = jpeg_natural_order[k];
  172887. /* Output newly nonzero coefficient */
  172888. (*block)[pos] = (JCOEF) s;
  172889. /* Remember its position in case we have to suspend */
  172890. newnz_pos[num_newnz++] = pos;
  172891. }
  172892. }
  172893. }
  172894. if (EOBRUN > 0) {
  172895. /* Scan any remaining coefficient positions after the end-of-band
  172896. * (the last newly nonzero coefficient, if any). Append a correction
  172897. * bit to each already-nonzero coefficient. A correction bit is 1
  172898. * if the absolute value of the coefficient must be increased.
  172899. */
  172900. for (; k <= Se; k++) {
  172901. thiscoef = *block + jpeg_natural_order[k];
  172902. if (*thiscoef != 0) {
  172903. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172904. if (GET_BITS(1)) {
  172905. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  172906. if (*thiscoef >= 0)
  172907. *thiscoef += p1;
  172908. else
  172909. *thiscoef += m1;
  172910. }
  172911. }
  172912. }
  172913. }
  172914. /* Count one block completed in EOB run */
  172915. EOBRUN--;
  172916. }
  172917. /* Completed MCU, so update state */
  172918. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172919. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172920. }
  172921. /* Account for restart interval (no-op if not using restarts) */
  172922. entropy->restarts_to_go--;
  172923. return TRUE;
  172924. undoit:
  172925. /* Re-zero any output coefficients that we made newly nonzero */
  172926. while (num_newnz > 0)
  172927. (*block)[newnz_pos[--num_newnz]] = 0;
  172928. return FALSE;
  172929. }
  172930. /*
  172931. * Module initialization routine for progressive Huffman entropy decoding.
  172932. */
  172933. GLOBAL(void)
  172934. jinit_phuff_decoder (j_decompress_ptr cinfo)
  172935. {
  172936. phuff_entropy_ptr2 entropy;
  172937. int *coef_bit_ptr;
  172938. int ci, i;
  172939. entropy = (phuff_entropy_ptr2)
  172940. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172941. SIZEOF(phuff_entropy_decoder));
  172942. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  172943. entropy->pub.start_pass = start_pass_phuff_decoder;
  172944. /* Mark derived tables unallocated */
  172945. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  172946. entropy->derived_tbls[i] = NULL;
  172947. }
  172948. /* Create progression status table */
  172949. cinfo->coef_bits = (int (*)[DCTSIZE2])
  172950. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172951. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  172952. coef_bit_ptr = & cinfo->coef_bits[0][0];
  172953. for (ci = 0; ci < cinfo->num_components; ci++)
  172954. for (i = 0; i < DCTSIZE2; i++)
  172955. *coef_bit_ptr++ = -1;
  172956. }
  172957. #endif /* D_PROGRESSIVE_SUPPORTED */
  172958. /*** End of inlined file: jdphuff.c ***/
  172959. /*** Start of inlined file: jdpostct.c ***/
  172960. #define JPEG_INTERNALS
  172961. /* Private buffer controller object */
  172962. typedef struct {
  172963. struct jpeg_d_post_controller pub; /* public fields */
  172964. /* Color quantization source buffer: this holds output data from
  172965. * the upsample/color conversion step to be passed to the quantizer.
  172966. * For two-pass color quantization, we need a full-image buffer;
  172967. * for one-pass operation, a strip buffer is sufficient.
  172968. */
  172969. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  172970. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  172971. JDIMENSION strip_height; /* buffer size in rows */
  172972. /* for two-pass mode only: */
  172973. JDIMENSION starting_row; /* row # of first row in current strip */
  172974. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  172975. } my_post_controller;
  172976. typedef my_post_controller * my_post_ptr;
  172977. /* Forward declarations */
  172978. METHODDEF(void) post_process_1pass
  172979. JPP((j_decompress_ptr cinfo,
  172980. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172981. JDIMENSION in_row_groups_avail,
  172982. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172983. JDIMENSION out_rows_avail));
  172984. #ifdef QUANT_2PASS_SUPPORTED
  172985. METHODDEF(void) post_process_prepass
  172986. JPP((j_decompress_ptr cinfo,
  172987. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172988. JDIMENSION in_row_groups_avail,
  172989. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172990. JDIMENSION out_rows_avail));
  172991. METHODDEF(void) post_process_2pass
  172992. JPP((j_decompress_ptr cinfo,
  172993. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172994. JDIMENSION in_row_groups_avail,
  172995. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172996. JDIMENSION out_rows_avail));
  172997. #endif
  172998. /*
  172999. * Initialize for a processing pass.
  173000. */
  173001. METHODDEF(void)
  173002. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173003. {
  173004. my_post_ptr post = (my_post_ptr) cinfo->post;
  173005. switch (pass_mode) {
  173006. case JBUF_PASS_THRU:
  173007. if (cinfo->quantize_colors) {
  173008. /* Single-pass processing with color quantization. */
  173009. post->pub.post_process_data = post_process_1pass;
  173010. /* We could be doing buffered-image output before starting a 2-pass
  173011. * color quantization; in that case, jinit_d_post_controller did not
  173012. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173013. */
  173014. if (post->buffer == NULL) {
  173015. post->buffer = (*cinfo->mem->access_virt_sarray)
  173016. ((j_common_ptr) cinfo, post->whole_image,
  173017. (JDIMENSION) 0, post->strip_height, TRUE);
  173018. }
  173019. } else {
  173020. /* For single-pass processing without color quantization,
  173021. * I have no work to do; just call the upsampler directly.
  173022. */
  173023. post->pub.post_process_data = cinfo->upsample->upsample;
  173024. }
  173025. break;
  173026. #ifdef QUANT_2PASS_SUPPORTED
  173027. case JBUF_SAVE_AND_PASS:
  173028. /* First pass of 2-pass quantization */
  173029. if (post->whole_image == NULL)
  173030. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173031. post->pub.post_process_data = post_process_prepass;
  173032. break;
  173033. case JBUF_CRANK_DEST:
  173034. /* Second pass of 2-pass quantization */
  173035. if (post->whole_image == NULL)
  173036. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173037. post->pub.post_process_data = post_process_2pass;
  173038. break;
  173039. #endif /* QUANT_2PASS_SUPPORTED */
  173040. default:
  173041. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173042. break;
  173043. }
  173044. post->starting_row = post->next_row = 0;
  173045. }
  173046. /*
  173047. * Process some data in the one-pass (strip buffer) case.
  173048. * This is used for color precision reduction as well as one-pass quantization.
  173049. */
  173050. METHODDEF(void)
  173051. post_process_1pass (j_decompress_ptr cinfo,
  173052. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173053. JDIMENSION in_row_groups_avail,
  173054. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173055. JDIMENSION out_rows_avail)
  173056. {
  173057. my_post_ptr post = (my_post_ptr) cinfo->post;
  173058. JDIMENSION num_rows, max_rows;
  173059. /* Fill the buffer, but not more than what we can dump out in one go. */
  173060. /* Note we rely on the upsampler to detect bottom of image. */
  173061. max_rows = out_rows_avail - *out_row_ctr;
  173062. if (max_rows > post->strip_height)
  173063. max_rows = post->strip_height;
  173064. num_rows = 0;
  173065. (*cinfo->upsample->upsample) (cinfo,
  173066. input_buf, in_row_group_ctr, in_row_groups_avail,
  173067. post->buffer, &num_rows, max_rows);
  173068. /* Quantize and emit data. */
  173069. (*cinfo->cquantize->color_quantize) (cinfo,
  173070. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173071. *out_row_ctr += num_rows;
  173072. }
  173073. #ifdef QUANT_2PASS_SUPPORTED
  173074. /*
  173075. * Process some data in the first pass of 2-pass quantization.
  173076. */
  173077. METHODDEF(void)
  173078. post_process_prepass (j_decompress_ptr cinfo,
  173079. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173080. JDIMENSION in_row_groups_avail,
  173081. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173082. JDIMENSION)
  173083. {
  173084. my_post_ptr post = (my_post_ptr) cinfo->post;
  173085. JDIMENSION old_next_row, num_rows;
  173086. /* Reposition virtual buffer if at start of strip. */
  173087. if (post->next_row == 0) {
  173088. post->buffer = (*cinfo->mem->access_virt_sarray)
  173089. ((j_common_ptr) cinfo, post->whole_image,
  173090. post->starting_row, post->strip_height, TRUE);
  173091. }
  173092. /* Upsample some data (up to a strip height's worth). */
  173093. old_next_row = post->next_row;
  173094. (*cinfo->upsample->upsample) (cinfo,
  173095. input_buf, in_row_group_ctr, in_row_groups_avail,
  173096. post->buffer, &post->next_row, post->strip_height);
  173097. /* Allow quantizer to scan new data. No data is emitted, */
  173098. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173099. if (post->next_row > old_next_row) {
  173100. num_rows = post->next_row - old_next_row;
  173101. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173102. (JSAMPARRAY) NULL, (int) num_rows);
  173103. *out_row_ctr += num_rows;
  173104. }
  173105. /* Advance if we filled the strip. */
  173106. if (post->next_row >= post->strip_height) {
  173107. post->starting_row += post->strip_height;
  173108. post->next_row = 0;
  173109. }
  173110. }
  173111. /*
  173112. * Process some data in the second pass of 2-pass quantization.
  173113. */
  173114. METHODDEF(void)
  173115. post_process_2pass (j_decompress_ptr cinfo,
  173116. JSAMPIMAGE, JDIMENSION *,
  173117. JDIMENSION,
  173118. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173119. JDIMENSION out_rows_avail)
  173120. {
  173121. my_post_ptr post = (my_post_ptr) cinfo->post;
  173122. JDIMENSION num_rows, max_rows;
  173123. /* Reposition virtual buffer if at start of strip. */
  173124. if (post->next_row == 0) {
  173125. post->buffer = (*cinfo->mem->access_virt_sarray)
  173126. ((j_common_ptr) cinfo, post->whole_image,
  173127. post->starting_row, post->strip_height, FALSE);
  173128. }
  173129. /* Determine number of rows to emit. */
  173130. num_rows = post->strip_height - post->next_row; /* available in strip */
  173131. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173132. if (num_rows > max_rows)
  173133. num_rows = max_rows;
  173134. /* We have to check bottom of image here, can't depend on upsampler. */
  173135. max_rows = cinfo->output_height - post->starting_row;
  173136. if (num_rows > max_rows)
  173137. num_rows = max_rows;
  173138. /* Quantize and emit data. */
  173139. (*cinfo->cquantize->color_quantize) (cinfo,
  173140. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173141. (int) num_rows);
  173142. *out_row_ctr += num_rows;
  173143. /* Advance if we filled the strip. */
  173144. post->next_row += num_rows;
  173145. if (post->next_row >= post->strip_height) {
  173146. post->starting_row += post->strip_height;
  173147. post->next_row = 0;
  173148. }
  173149. }
  173150. #endif /* QUANT_2PASS_SUPPORTED */
  173151. /*
  173152. * Initialize postprocessing controller.
  173153. */
  173154. GLOBAL(void)
  173155. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173156. {
  173157. my_post_ptr post;
  173158. post = (my_post_ptr)
  173159. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173160. SIZEOF(my_post_controller));
  173161. cinfo->post = (struct jpeg_d_post_controller *) post;
  173162. post->pub.start_pass = start_pass_dpost;
  173163. post->whole_image = NULL; /* flag for no virtual arrays */
  173164. post->buffer = NULL; /* flag for no strip buffer */
  173165. /* Create the quantization buffer, if needed */
  173166. if (cinfo->quantize_colors) {
  173167. /* The buffer strip height is max_v_samp_factor, which is typically
  173168. * an efficient number of rows for upsampling to return.
  173169. * (In the presence of output rescaling, we might want to be smarter?)
  173170. */
  173171. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173172. if (need_full_buffer) {
  173173. /* Two-pass color quantization: need full-image storage. */
  173174. /* We round up the number of rows to a multiple of the strip height. */
  173175. #ifdef QUANT_2PASS_SUPPORTED
  173176. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173177. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173178. cinfo->output_width * cinfo->out_color_components,
  173179. (JDIMENSION) jround_up((long) cinfo->output_height,
  173180. (long) post->strip_height),
  173181. post->strip_height);
  173182. #else
  173183. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173184. #endif /* QUANT_2PASS_SUPPORTED */
  173185. } else {
  173186. /* One-pass color quantization: just make a strip buffer. */
  173187. post->buffer = (*cinfo->mem->alloc_sarray)
  173188. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173189. cinfo->output_width * cinfo->out_color_components,
  173190. post->strip_height);
  173191. }
  173192. }
  173193. }
  173194. /*** End of inlined file: jdpostct.c ***/
  173195. #undef FIX
  173196. /*** Start of inlined file: jdsample.c ***/
  173197. #define JPEG_INTERNALS
  173198. /* Pointer to routine to upsample a single component */
  173199. typedef JMETHOD(void, upsample1_ptr,
  173200. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173201. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173202. /* Private subobject */
  173203. typedef struct {
  173204. struct jpeg_upsampler pub; /* public fields */
  173205. /* Color conversion buffer. When using separate upsampling and color
  173206. * conversion steps, this buffer holds one upsampled row group until it
  173207. * has been color converted and output.
  173208. * Note: we do not allocate any storage for component(s) which are full-size,
  173209. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173210. * simply set to point to the input data array, thereby avoiding copying.
  173211. */
  173212. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173213. /* Per-component upsampling method pointers */
  173214. upsample1_ptr methods[MAX_COMPONENTS];
  173215. int next_row_out; /* counts rows emitted from color_buf */
  173216. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173217. /* Height of an input row group for each component. */
  173218. int rowgroup_height[MAX_COMPONENTS];
  173219. /* These arrays save pixel expansion factors so that int_expand need not
  173220. * recompute them each time. They are unused for other upsampling methods.
  173221. */
  173222. UINT8 h_expand[MAX_COMPONENTS];
  173223. UINT8 v_expand[MAX_COMPONENTS];
  173224. } my_upsampler2;
  173225. typedef my_upsampler2 * my_upsample_ptr2;
  173226. /*
  173227. * Initialize for an upsampling pass.
  173228. */
  173229. METHODDEF(void)
  173230. start_pass_upsample (j_decompress_ptr cinfo)
  173231. {
  173232. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173233. /* Mark the conversion buffer empty */
  173234. upsample->next_row_out = cinfo->max_v_samp_factor;
  173235. /* Initialize total-height counter for detecting bottom of image */
  173236. upsample->rows_to_go = cinfo->output_height;
  173237. }
  173238. /*
  173239. * Control routine to do upsampling (and color conversion).
  173240. *
  173241. * In this version we upsample each component independently.
  173242. * We upsample one row group into the conversion buffer, then apply
  173243. * color conversion a row at a time.
  173244. */
  173245. METHODDEF(void)
  173246. sep_upsample (j_decompress_ptr cinfo,
  173247. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173248. JDIMENSION,
  173249. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173250. JDIMENSION out_rows_avail)
  173251. {
  173252. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173253. int ci;
  173254. jpeg_component_info * compptr;
  173255. JDIMENSION num_rows;
  173256. /* Fill the conversion buffer, if it's empty */
  173257. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173258. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173259. ci++, compptr++) {
  173260. /* Invoke per-component upsample method. Notice we pass a POINTER
  173261. * to color_buf[ci], so that fullsize_upsample can change it.
  173262. */
  173263. (*upsample->methods[ci]) (cinfo, compptr,
  173264. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173265. upsample->color_buf + ci);
  173266. }
  173267. upsample->next_row_out = 0;
  173268. }
  173269. /* Color-convert and emit rows */
  173270. /* How many we have in the buffer: */
  173271. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173272. /* Not more than the distance to the end of the image. Need this test
  173273. * in case the image height is not a multiple of max_v_samp_factor:
  173274. */
  173275. if (num_rows > upsample->rows_to_go)
  173276. num_rows = upsample->rows_to_go;
  173277. /* And not more than what the client can accept: */
  173278. out_rows_avail -= *out_row_ctr;
  173279. if (num_rows > out_rows_avail)
  173280. num_rows = out_rows_avail;
  173281. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173282. (JDIMENSION) upsample->next_row_out,
  173283. output_buf + *out_row_ctr,
  173284. (int) num_rows);
  173285. /* Adjust counts */
  173286. *out_row_ctr += num_rows;
  173287. upsample->rows_to_go -= num_rows;
  173288. upsample->next_row_out += num_rows;
  173289. /* When the buffer is emptied, declare this input row group consumed */
  173290. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173291. (*in_row_group_ctr)++;
  173292. }
  173293. /*
  173294. * These are the routines invoked by sep_upsample to upsample pixel values
  173295. * of a single component. One row group is processed per call.
  173296. */
  173297. /*
  173298. * For full-size components, we just make color_buf[ci] point at the
  173299. * input buffer, and thus avoid copying any data. Note that this is
  173300. * safe only because sep_upsample doesn't declare the input row group
  173301. * "consumed" until we are done color converting and emitting it.
  173302. */
  173303. METHODDEF(void)
  173304. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173305. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173306. {
  173307. *output_data_ptr = input_data;
  173308. }
  173309. /*
  173310. * This is a no-op version used for "uninteresting" components.
  173311. * These components will not be referenced by color conversion.
  173312. */
  173313. METHODDEF(void)
  173314. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173315. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173316. {
  173317. *output_data_ptr = NULL; /* safety check */
  173318. }
  173319. /*
  173320. * This version handles any integral sampling ratios.
  173321. * This is not used for typical JPEG files, so it need not be fast.
  173322. * Nor, for that matter, is it particularly accurate: the algorithm is
  173323. * simple replication of the input pixel onto the corresponding output
  173324. * pixels. The hi-falutin sampling literature refers to this as a
  173325. * "box filter". A box filter tends to introduce visible artifacts,
  173326. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173327. * you would be well advised to improve this code.
  173328. */
  173329. METHODDEF(void)
  173330. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173331. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173332. {
  173333. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173334. JSAMPARRAY output_data = *output_data_ptr;
  173335. register JSAMPROW inptr, outptr;
  173336. register JSAMPLE invalue;
  173337. register int h;
  173338. JSAMPROW outend;
  173339. int h_expand, v_expand;
  173340. int inrow, outrow;
  173341. h_expand = upsample->h_expand[compptr->component_index];
  173342. v_expand = upsample->v_expand[compptr->component_index];
  173343. inrow = outrow = 0;
  173344. while (outrow < cinfo->max_v_samp_factor) {
  173345. /* Generate one output row with proper horizontal expansion */
  173346. inptr = input_data[inrow];
  173347. outptr = output_data[outrow];
  173348. outend = outptr + cinfo->output_width;
  173349. while (outptr < outend) {
  173350. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173351. for (h = h_expand; h > 0; h--) {
  173352. *outptr++ = invalue;
  173353. }
  173354. }
  173355. /* Generate any additional output rows by duplicating the first one */
  173356. if (v_expand > 1) {
  173357. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173358. v_expand-1, cinfo->output_width);
  173359. }
  173360. inrow++;
  173361. outrow += v_expand;
  173362. }
  173363. }
  173364. /*
  173365. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173366. * It's still a box filter.
  173367. */
  173368. METHODDEF(void)
  173369. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173370. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173371. {
  173372. JSAMPARRAY output_data = *output_data_ptr;
  173373. register JSAMPROW inptr, outptr;
  173374. register JSAMPLE invalue;
  173375. JSAMPROW outend;
  173376. int inrow;
  173377. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173378. inptr = input_data[inrow];
  173379. outptr = output_data[inrow];
  173380. outend = outptr + cinfo->output_width;
  173381. while (outptr < outend) {
  173382. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173383. *outptr++ = invalue;
  173384. *outptr++ = invalue;
  173385. }
  173386. }
  173387. }
  173388. /*
  173389. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173390. * It's still a box filter.
  173391. */
  173392. METHODDEF(void)
  173393. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173394. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173395. {
  173396. JSAMPARRAY output_data = *output_data_ptr;
  173397. register JSAMPROW inptr, outptr;
  173398. register JSAMPLE invalue;
  173399. JSAMPROW outend;
  173400. int inrow, outrow;
  173401. inrow = outrow = 0;
  173402. while (outrow < cinfo->max_v_samp_factor) {
  173403. inptr = input_data[inrow];
  173404. outptr = output_data[outrow];
  173405. outend = outptr + cinfo->output_width;
  173406. while (outptr < outend) {
  173407. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173408. *outptr++ = invalue;
  173409. *outptr++ = invalue;
  173410. }
  173411. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173412. 1, cinfo->output_width);
  173413. inrow++;
  173414. outrow += 2;
  173415. }
  173416. }
  173417. /*
  173418. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173419. *
  173420. * The upsampling algorithm is linear interpolation between pixel centers,
  173421. * also known as a "triangle filter". This is a good compromise between
  173422. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173423. * of the way between input pixel centers.
  173424. *
  173425. * A note about the "bias" calculations: when rounding fractional values to
  173426. * integer, we do not want to always round 0.5 up to the next integer.
  173427. * If we did that, we'd introduce a noticeable bias towards larger values.
  173428. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173429. * alternate pixel locations (a simple ordered dither pattern).
  173430. */
  173431. METHODDEF(void)
  173432. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173433. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173434. {
  173435. JSAMPARRAY output_data = *output_data_ptr;
  173436. register JSAMPROW inptr, outptr;
  173437. register int invalue;
  173438. register JDIMENSION colctr;
  173439. int inrow;
  173440. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173441. inptr = input_data[inrow];
  173442. outptr = output_data[inrow];
  173443. /* Special case for first column */
  173444. invalue = GETJSAMPLE(*inptr++);
  173445. *outptr++ = (JSAMPLE) invalue;
  173446. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173447. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173448. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173449. invalue = GETJSAMPLE(*inptr++) * 3;
  173450. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173451. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173452. }
  173453. /* Special case for last column */
  173454. invalue = GETJSAMPLE(*inptr);
  173455. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173456. *outptr++ = (JSAMPLE) invalue;
  173457. }
  173458. }
  173459. /*
  173460. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173461. * Again a triangle filter; see comments for h2v1 case, above.
  173462. *
  173463. * It is OK for us to reference the adjacent input rows because we demanded
  173464. * context from the main buffer controller (see initialization code).
  173465. */
  173466. METHODDEF(void)
  173467. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173468. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173469. {
  173470. JSAMPARRAY output_data = *output_data_ptr;
  173471. register JSAMPROW inptr0, inptr1, outptr;
  173472. #if BITS_IN_JSAMPLE == 8
  173473. register int thiscolsum, lastcolsum, nextcolsum;
  173474. #else
  173475. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173476. #endif
  173477. register JDIMENSION colctr;
  173478. int inrow, outrow, v;
  173479. inrow = outrow = 0;
  173480. while (outrow < cinfo->max_v_samp_factor) {
  173481. for (v = 0; v < 2; v++) {
  173482. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173483. inptr0 = input_data[inrow];
  173484. if (v == 0) /* next nearest is row above */
  173485. inptr1 = input_data[inrow-1];
  173486. else /* next nearest is row below */
  173487. inptr1 = input_data[inrow+1];
  173488. outptr = output_data[outrow++];
  173489. /* Special case for first column */
  173490. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173491. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173492. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173493. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173494. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173495. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173496. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173497. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173498. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173499. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173500. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173501. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173502. }
  173503. /* Special case for last column */
  173504. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173505. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173506. }
  173507. inrow++;
  173508. }
  173509. }
  173510. /*
  173511. * Module initialization routine for upsampling.
  173512. */
  173513. GLOBAL(void)
  173514. jinit_upsampler (j_decompress_ptr cinfo)
  173515. {
  173516. my_upsample_ptr2 upsample;
  173517. int ci;
  173518. jpeg_component_info * compptr;
  173519. boolean need_buffer, do_fancy;
  173520. int h_in_group, v_in_group, h_out_group, v_out_group;
  173521. upsample = (my_upsample_ptr2)
  173522. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173523. SIZEOF(my_upsampler2));
  173524. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173525. upsample->pub.start_pass = start_pass_upsample;
  173526. upsample->pub.upsample = sep_upsample;
  173527. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173528. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173529. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173530. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173531. * so don't ask for it.
  173532. */
  173533. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173534. /* Verify we can handle the sampling factors, select per-component methods,
  173535. * and create storage as needed.
  173536. */
  173537. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173538. ci++, compptr++) {
  173539. /* Compute size of an "input group" after IDCT scaling. This many samples
  173540. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173541. */
  173542. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173543. cinfo->min_DCT_scaled_size;
  173544. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173545. cinfo->min_DCT_scaled_size;
  173546. h_out_group = cinfo->max_h_samp_factor;
  173547. v_out_group = cinfo->max_v_samp_factor;
  173548. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173549. need_buffer = TRUE;
  173550. if (! compptr->component_needed) {
  173551. /* Don't bother to upsample an uninteresting component. */
  173552. upsample->methods[ci] = noop_upsample;
  173553. need_buffer = FALSE;
  173554. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173555. /* Fullsize components can be processed without any work. */
  173556. upsample->methods[ci] = fullsize_upsample;
  173557. need_buffer = FALSE;
  173558. } else if (h_in_group * 2 == h_out_group &&
  173559. v_in_group == v_out_group) {
  173560. /* Special cases for 2h1v upsampling */
  173561. if (do_fancy && compptr->downsampled_width > 2)
  173562. upsample->methods[ci] = h2v1_fancy_upsample;
  173563. else
  173564. upsample->methods[ci] = h2v1_upsample;
  173565. } else if (h_in_group * 2 == h_out_group &&
  173566. v_in_group * 2 == v_out_group) {
  173567. /* Special cases for 2h2v upsampling */
  173568. if (do_fancy && compptr->downsampled_width > 2) {
  173569. upsample->methods[ci] = h2v2_fancy_upsample;
  173570. upsample->pub.need_context_rows = TRUE;
  173571. } else
  173572. upsample->methods[ci] = h2v2_upsample;
  173573. } else if ((h_out_group % h_in_group) == 0 &&
  173574. (v_out_group % v_in_group) == 0) {
  173575. /* Generic integral-factors upsampling method */
  173576. upsample->methods[ci] = int_upsample;
  173577. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173578. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173579. } else
  173580. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173581. if (need_buffer) {
  173582. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173583. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173584. (JDIMENSION) jround_up((long) cinfo->output_width,
  173585. (long) cinfo->max_h_samp_factor),
  173586. (JDIMENSION) cinfo->max_v_samp_factor);
  173587. }
  173588. }
  173589. }
  173590. /*** End of inlined file: jdsample.c ***/
  173591. /*** Start of inlined file: jdtrans.c ***/
  173592. #define JPEG_INTERNALS
  173593. /* Forward declarations */
  173594. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173595. /*
  173596. * Read the coefficient arrays from a JPEG file.
  173597. * jpeg_read_header must be completed before calling this.
  173598. *
  173599. * The entire image is read into a set of virtual coefficient-block arrays,
  173600. * one per component. The return value is a pointer to the array of
  173601. * virtual-array descriptors. These can be manipulated directly via the
  173602. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173603. * To release the memory occupied by the virtual arrays, call
  173604. * jpeg_finish_decompress() when done with the data.
  173605. *
  173606. * An alternative usage is to simply obtain access to the coefficient arrays
  173607. * during a buffered-image-mode decompression operation. This is allowed
  173608. * after any jpeg_finish_output() call. The arrays can be accessed until
  173609. * jpeg_finish_decompress() is called. (Note that any call to the library
  173610. * may reposition the arrays, so don't rely on access_virt_barray() results
  173611. * to stay valid across library calls.)
  173612. *
  173613. * Returns NULL if suspended. This case need be checked only if
  173614. * a suspending data source is used.
  173615. */
  173616. GLOBAL(jvirt_barray_ptr *)
  173617. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173618. {
  173619. if (cinfo->global_state == DSTATE_READY) {
  173620. /* First call: initialize active modules */
  173621. transdecode_master_selection(cinfo);
  173622. cinfo->global_state = DSTATE_RDCOEFS;
  173623. }
  173624. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173625. /* Absorb whole file into the coef buffer */
  173626. for (;;) {
  173627. int retcode;
  173628. /* Call progress monitor hook if present */
  173629. if (cinfo->progress != NULL)
  173630. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173631. /* Absorb some more input */
  173632. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173633. if (retcode == JPEG_SUSPENDED)
  173634. return NULL;
  173635. if (retcode == JPEG_REACHED_EOI)
  173636. break;
  173637. /* Advance progress counter if appropriate */
  173638. if (cinfo->progress != NULL &&
  173639. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173640. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173641. /* startup underestimated number of scans; ratchet up one scan */
  173642. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173643. }
  173644. }
  173645. }
  173646. /* Set state so that jpeg_finish_decompress does the right thing */
  173647. cinfo->global_state = DSTATE_STOPPING;
  173648. }
  173649. /* At this point we should be in state DSTATE_STOPPING if being used
  173650. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173651. * to the coefficients during a full buffered-image-mode decompression.
  173652. */
  173653. if ((cinfo->global_state == DSTATE_STOPPING ||
  173654. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173655. return cinfo->coef->coef_arrays;
  173656. }
  173657. /* Oops, improper usage */
  173658. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173659. return NULL; /* keep compiler happy */
  173660. }
  173661. /*
  173662. * Master selection of decompression modules for transcoding.
  173663. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173664. */
  173665. LOCAL(void)
  173666. transdecode_master_selection (j_decompress_ptr cinfo)
  173667. {
  173668. /* This is effectively a buffered-image operation. */
  173669. cinfo->buffered_image = TRUE;
  173670. /* Entropy decoding: either Huffman or arithmetic coding. */
  173671. if (cinfo->arith_code) {
  173672. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173673. } else {
  173674. if (cinfo->progressive_mode) {
  173675. #ifdef D_PROGRESSIVE_SUPPORTED
  173676. jinit_phuff_decoder(cinfo);
  173677. #else
  173678. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173679. #endif
  173680. } else
  173681. jinit_huff_decoder(cinfo);
  173682. }
  173683. /* Always get a full-image coefficient buffer. */
  173684. jinit_d_coef_controller(cinfo, TRUE);
  173685. /* We can now tell the memory manager to allocate virtual arrays. */
  173686. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173687. /* Initialize input side of decompressor to consume first scan. */
  173688. (*cinfo->inputctl->start_input_pass) (cinfo);
  173689. /* Initialize progress monitoring. */
  173690. if (cinfo->progress != NULL) {
  173691. int nscans;
  173692. /* Estimate number of scans to set pass_limit. */
  173693. if (cinfo->progressive_mode) {
  173694. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173695. nscans = 2 + 3 * cinfo->num_components;
  173696. } else if (cinfo->inputctl->has_multiple_scans) {
  173697. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173698. nscans = cinfo->num_components;
  173699. } else {
  173700. nscans = 1;
  173701. }
  173702. cinfo->progress->pass_counter = 0L;
  173703. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173704. cinfo->progress->completed_passes = 0;
  173705. cinfo->progress->total_passes = 1;
  173706. }
  173707. }
  173708. /*** End of inlined file: jdtrans.c ***/
  173709. /*** Start of inlined file: jfdctflt.c ***/
  173710. #define JPEG_INTERNALS
  173711. #ifdef DCT_FLOAT_SUPPORTED
  173712. /*
  173713. * This module is specialized to the case DCTSIZE = 8.
  173714. */
  173715. #if DCTSIZE != 8
  173716. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173717. #endif
  173718. /*
  173719. * Perform the forward DCT on one block of samples.
  173720. */
  173721. GLOBAL(void)
  173722. jpeg_fdct_float (FAST_FLOAT * data)
  173723. {
  173724. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173725. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173726. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173727. FAST_FLOAT *dataptr;
  173728. int ctr;
  173729. /* Pass 1: process rows. */
  173730. dataptr = data;
  173731. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173732. tmp0 = dataptr[0] + dataptr[7];
  173733. tmp7 = dataptr[0] - dataptr[7];
  173734. tmp1 = dataptr[1] + dataptr[6];
  173735. tmp6 = dataptr[1] - dataptr[6];
  173736. tmp2 = dataptr[2] + dataptr[5];
  173737. tmp5 = dataptr[2] - dataptr[5];
  173738. tmp3 = dataptr[3] + dataptr[4];
  173739. tmp4 = dataptr[3] - dataptr[4];
  173740. /* Even part */
  173741. tmp10 = tmp0 + tmp3; /* phase 2 */
  173742. tmp13 = tmp0 - tmp3;
  173743. tmp11 = tmp1 + tmp2;
  173744. tmp12 = tmp1 - tmp2;
  173745. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173746. dataptr[4] = tmp10 - tmp11;
  173747. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173748. dataptr[2] = tmp13 + z1; /* phase 5 */
  173749. dataptr[6] = tmp13 - z1;
  173750. /* Odd part */
  173751. tmp10 = tmp4 + tmp5; /* phase 2 */
  173752. tmp11 = tmp5 + tmp6;
  173753. tmp12 = tmp6 + tmp7;
  173754. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173755. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173756. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173757. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173758. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173759. z11 = tmp7 + z3; /* phase 5 */
  173760. z13 = tmp7 - z3;
  173761. dataptr[5] = z13 + z2; /* phase 6 */
  173762. dataptr[3] = z13 - z2;
  173763. dataptr[1] = z11 + z4;
  173764. dataptr[7] = z11 - z4;
  173765. dataptr += DCTSIZE; /* advance pointer to next row */
  173766. }
  173767. /* Pass 2: process columns. */
  173768. dataptr = data;
  173769. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173770. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173771. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173772. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173773. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173774. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173775. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173776. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173777. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173778. /* Even part */
  173779. tmp10 = tmp0 + tmp3; /* phase 2 */
  173780. tmp13 = tmp0 - tmp3;
  173781. tmp11 = tmp1 + tmp2;
  173782. tmp12 = tmp1 - tmp2;
  173783. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173784. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173785. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173786. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173787. dataptr[DCTSIZE*6] = tmp13 - z1;
  173788. /* Odd part */
  173789. tmp10 = tmp4 + tmp5; /* phase 2 */
  173790. tmp11 = tmp5 + tmp6;
  173791. tmp12 = tmp6 + tmp7;
  173792. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173793. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173794. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173795. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173796. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173797. z11 = tmp7 + z3; /* phase 5 */
  173798. z13 = tmp7 - z3;
  173799. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173800. dataptr[DCTSIZE*3] = z13 - z2;
  173801. dataptr[DCTSIZE*1] = z11 + z4;
  173802. dataptr[DCTSIZE*7] = z11 - z4;
  173803. dataptr++; /* advance pointer to next column */
  173804. }
  173805. }
  173806. #endif /* DCT_FLOAT_SUPPORTED */
  173807. /*** End of inlined file: jfdctflt.c ***/
  173808. /*** Start of inlined file: jfdctint.c ***/
  173809. #define JPEG_INTERNALS
  173810. #ifdef DCT_ISLOW_SUPPORTED
  173811. /*
  173812. * This module is specialized to the case DCTSIZE = 8.
  173813. */
  173814. #if DCTSIZE != 8
  173815. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173816. #endif
  173817. /*
  173818. * The poop on this scaling stuff is as follows:
  173819. *
  173820. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173821. * larger than the true DCT outputs. The final outputs are therefore
  173822. * a factor of N larger than desired; since N=8 this can be cured by
  173823. * a simple right shift at the end of the algorithm. The advantage of
  173824. * this arrangement is that we save two multiplications per 1-D DCT,
  173825. * because the y0 and y4 outputs need not be divided by sqrt(N).
  173826. * In the IJG code, this factor of 8 is removed by the quantization step
  173827. * (in jcdctmgr.c), NOT in this module.
  173828. *
  173829. * We have to do addition and subtraction of the integer inputs, which
  173830. * is no problem, and multiplication by fractional constants, which is
  173831. * a problem to do in integer arithmetic. We multiply all the constants
  173832. * by CONST_SCALE and convert them to integer constants (thus retaining
  173833. * CONST_BITS bits of precision in the constants). After doing a
  173834. * multiplication we have to divide the product by CONST_SCALE, with proper
  173835. * rounding, to produce the correct output. This division can be done
  173836. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  173837. * as long as possible so that partial sums can be added together with
  173838. * full fractional precision.
  173839. *
  173840. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  173841. * they are represented to better-than-integral precision. These outputs
  173842. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  173843. * with the recommended scaling. (For 12-bit sample data, the intermediate
  173844. * array is INT32 anyway.)
  173845. *
  173846. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  173847. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  173848. * shows that the values given below are the most effective.
  173849. */
  173850. #if BITS_IN_JSAMPLE == 8
  173851. #define CONST_BITS 13
  173852. #define PASS1_BITS 2
  173853. #else
  173854. #define CONST_BITS 13
  173855. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173856. #endif
  173857. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173858. * causing a lot of useless floating-point operations at run time.
  173859. * To get around this we use the following pre-calculated constants.
  173860. * If you change CONST_BITS you may want to add appropriate values.
  173861. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173862. */
  173863. #if CONST_BITS == 13
  173864. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  173865. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  173866. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  173867. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  173868. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  173869. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  173870. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  173871. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  173872. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  173873. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  173874. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  173875. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  173876. #else
  173877. #define FIX_0_298631336 FIX(0.298631336)
  173878. #define FIX_0_390180644 FIX(0.390180644)
  173879. #define FIX_0_541196100 FIX(0.541196100)
  173880. #define FIX_0_765366865 FIX(0.765366865)
  173881. #define FIX_0_899976223 FIX(0.899976223)
  173882. #define FIX_1_175875602 FIX(1.175875602)
  173883. #define FIX_1_501321110 FIX(1.501321110)
  173884. #define FIX_1_847759065 FIX(1.847759065)
  173885. #define FIX_1_961570560 FIX(1.961570560)
  173886. #define FIX_2_053119869 FIX(2.053119869)
  173887. #define FIX_2_562915447 FIX(2.562915447)
  173888. #define FIX_3_072711026 FIX(3.072711026)
  173889. #endif
  173890. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  173891. * For 8-bit samples with the recommended scaling, all the variable
  173892. * and constant values involved are no more than 16 bits wide, so a
  173893. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  173894. * For 12-bit samples, a full 32-bit multiplication will be needed.
  173895. */
  173896. #if BITS_IN_JSAMPLE == 8
  173897. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  173898. #else
  173899. #define MULTIPLY(var,const) ((var) * (const))
  173900. #endif
  173901. /*
  173902. * Perform the forward DCT on one block of samples.
  173903. */
  173904. GLOBAL(void)
  173905. jpeg_fdct_islow (DCTELEM * data)
  173906. {
  173907. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173908. INT32 tmp10, tmp11, tmp12, tmp13;
  173909. INT32 z1, z2, z3, z4, z5;
  173910. DCTELEM *dataptr;
  173911. int ctr;
  173912. SHIFT_TEMPS
  173913. /* Pass 1: process rows. */
  173914. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  173915. /* furthermore, we scale the results by 2**PASS1_BITS. */
  173916. dataptr = data;
  173917. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173918. tmp0 = dataptr[0] + dataptr[7];
  173919. tmp7 = dataptr[0] - dataptr[7];
  173920. tmp1 = dataptr[1] + dataptr[6];
  173921. tmp6 = dataptr[1] - dataptr[6];
  173922. tmp2 = dataptr[2] + dataptr[5];
  173923. tmp5 = dataptr[2] - dataptr[5];
  173924. tmp3 = dataptr[3] + dataptr[4];
  173925. tmp4 = dataptr[3] - dataptr[4];
  173926. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173927. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173928. */
  173929. tmp10 = tmp0 + tmp3;
  173930. tmp13 = tmp0 - tmp3;
  173931. tmp11 = tmp1 + tmp2;
  173932. tmp12 = tmp1 - tmp2;
  173933. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  173934. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  173935. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173936. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173937. CONST_BITS-PASS1_BITS);
  173938. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173939. CONST_BITS-PASS1_BITS);
  173940. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173941. * cK represents cos(K*pi/16).
  173942. * i0..i3 in the paper are tmp4..tmp7 here.
  173943. */
  173944. z1 = tmp4 + tmp7;
  173945. z2 = tmp5 + tmp6;
  173946. z3 = tmp4 + tmp6;
  173947. z4 = tmp5 + tmp7;
  173948. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173949. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173950. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173951. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173952. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173953. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173954. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173955. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173956. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173957. z3 += z5;
  173958. z4 += z5;
  173959. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  173960. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  173961. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  173962. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  173963. dataptr += DCTSIZE; /* advance pointer to next row */
  173964. }
  173965. /* Pass 2: process columns.
  173966. * We remove the PASS1_BITS scaling, but leave the results scaled up
  173967. * by an overall factor of 8.
  173968. */
  173969. dataptr = data;
  173970. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173971. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173972. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173973. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173974. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173975. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173976. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173977. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173978. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173979. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173980. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173981. */
  173982. tmp10 = tmp0 + tmp3;
  173983. tmp13 = tmp0 - tmp3;
  173984. tmp11 = tmp1 + tmp2;
  173985. tmp12 = tmp1 - tmp2;
  173986. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  173987. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  173988. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173989. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173990. CONST_BITS+PASS1_BITS);
  173991. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173992. CONST_BITS+PASS1_BITS);
  173993. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173994. * cK represents cos(K*pi/16).
  173995. * i0..i3 in the paper are tmp4..tmp7 here.
  173996. */
  173997. z1 = tmp4 + tmp7;
  173998. z2 = tmp5 + tmp6;
  173999. z3 = tmp4 + tmp6;
  174000. z4 = tmp5 + tmp7;
  174001. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174002. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174003. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174004. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174005. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174006. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174007. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174008. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174009. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174010. z3 += z5;
  174011. z4 += z5;
  174012. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174013. CONST_BITS+PASS1_BITS);
  174014. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174015. CONST_BITS+PASS1_BITS);
  174016. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174017. CONST_BITS+PASS1_BITS);
  174018. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174019. CONST_BITS+PASS1_BITS);
  174020. dataptr++; /* advance pointer to next column */
  174021. }
  174022. }
  174023. #endif /* DCT_ISLOW_SUPPORTED */
  174024. /*** End of inlined file: jfdctint.c ***/
  174025. #undef CONST_BITS
  174026. #undef MULTIPLY
  174027. #undef FIX_0_541196100
  174028. /*** Start of inlined file: jfdctfst.c ***/
  174029. #define JPEG_INTERNALS
  174030. #ifdef DCT_IFAST_SUPPORTED
  174031. /*
  174032. * This module is specialized to the case DCTSIZE = 8.
  174033. */
  174034. #if DCTSIZE != 8
  174035. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174036. #endif
  174037. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174038. * see jfdctint.c for more details. However, we choose to descale
  174039. * (right shift) multiplication products as soon as they are formed,
  174040. * rather than carrying additional fractional bits into subsequent additions.
  174041. * This compromises accuracy slightly, but it lets us save a few shifts.
  174042. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174043. * everywhere except in the multiplications proper; this saves a good deal
  174044. * of work on 16-bit-int machines.
  174045. *
  174046. * Again to save a few shifts, the intermediate results between pass 1 and
  174047. * pass 2 are not upscaled, but are represented only to integral precision.
  174048. *
  174049. * A final compromise is to represent the multiplicative constants to only
  174050. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174051. * machines, and may also reduce the cost of multiplication (since there
  174052. * are fewer one-bits in the constants).
  174053. */
  174054. #define CONST_BITS 8
  174055. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174056. * causing a lot of useless floating-point operations at run time.
  174057. * To get around this we use the following pre-calculated constants.
  174058. * If you change CONST_BITS you may want to add appropriate values.
  174059. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174060. */
  174061. #if CONST_BITS == 8
  174062. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174063. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174064. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174065. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174066. #else
  174067. #define FIX_0_382683433 FIX(0.382683433)
  174068. #define FIX_0_541196100 FIX(0.541196100)
  174069. #define FIX_0_707106781 FIX(0.707106781)
  174070. #define FIX_1_306562965 FIX(1.306562965)
  174071. #endif
  174072. /* We can gain a little more speed, with a further compromise in accuracy,
  174073. * by omitting the addition in a descaling shift. This yields an incorrectly
  174074. * rounded result half the time...
  174075. */
  174076. #ifndef USE_ACCURATE_ROUNDING
  174077. #undef DESCALE
  174078. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174079. #endif
  174080. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174081. * descale to yield a DCTELEM result.
  174082. */
  174083. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174084. /*
  174085. * Perform the forward DCT on one block of samples.
  174086. */
  174087. GLOBAL(void)
  174088. jpeg_fdct_ifast (DCTELEM * data)
  174089. {
  174090. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174091. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174092. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174093. DCTELEM *dataptr;
  174094. int ctr;
  174095. SHIFT_TEMPS
  174096. /* Pass 1: process rows. */
  174097. dataptr = data;
  174098. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174099. tmp0 = dataptr[0] + dataptr[7];
  174100. tmp7 = dataptr[0] - dataptr[7];
  174101. tmp1 = dataptr[1] + dataptr[6];
  174102. tmp6 = dataptr[1] - dataptr[6];
  174103. tmp2 = dataptr[2] + dataptr[5];
  174104. tmp5 = dataptr[2] - dataptr[5];
  174105. tmp3 = dataptr[3] + dataptr[4];
  174106. tmp4 = dataptr[3] - dataptr[4];
  174107. /* Even part */
  174108. tmp10 = tmp0 + tmp3; /* phase 2 */
  174109. tmp13 = tmp0 - tmp3;
  174110. tmp11 = tmp1 + tmp2;
  174111. tmp12 = tmp1 - tmp2;
  174112. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174113. dataptr[4] = tmp10 - tmp11;
  174114. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174115. dataptr[2] = tmp13 + z1; /* phase 5 */
  174116. dataptr[6] = tmp13 - z1;
  174117. /* Odd part */
  174118. tmp10 = tmp4 + tmp5; /* phase 2 */
  174119. tmp11 = tmp5 + tmp6;
  174120. tmp12 = tmp6 + tmp7;
  174121. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174122. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174123. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174124. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174125. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174126. z11 = tmp7 + z3; /* phase 5 */
  174127. z13 = tmp7 - z3;
  174128. dataptr[5] = z13 + z2; /* phase 6 */
  174129. dataptr[3] = z13 - z2;
  174130. dataptr[1] = z11 + z4;
  174131. dataptr[7] = z11 - z4;
  174132. dataptr += DCTSIZE; /* advance pointer to next row */
  174133. }
  174134. /* Pass 2: process columns. */
  174135. dataptr = data;
  174136. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174137. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174138. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174139. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174140. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174141. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174142. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174143. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174144. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174145. /* Even part */
  174146. tmp10 = tmp0 + tmp3; /* phase 2 */
  174147. tmp13 = tmp0 - tmp3;
  174148. tmp11 = tmp1 + tmp2;
  174149. tmp12 = tmp1 - tmp2;
  174150. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174151. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174152. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174153. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174154. dataptr[DCTSIZE*6] = tmp13 - z1;
  174155. /* Odd part */
  174156. tmp10 = tmp4 + tmp5; /* phase 2 */
  174157. tmp11 = tmp5 + tmp6;
  174158. tmp12 = tmp6 + tmp7;
  174159. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174160. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174161. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174162. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174163. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174164. z11 = tmp7 + z3; /* phase 5 */
  174165. z13 = tmp7 - z3;
  174166. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174167. dataptr[DCTSIZE*3] = z13 - z2;
  174168. dataptr[DCTSIZE*1] = z11 + z4;
  174169. dataptr[DCTSIZE*7] = z11 - z4;
  174170. dataptr++; /* advance pointer to next column */
  174171. }
  174172. }
  174173. #endif /* DCT_IFAST_SUPPORTED */
  174174. /*** End of inlined file: jfdctfst.c ***/
  174175. #undef FIX_0_541196100
  174176. /*** Start of inlined file: jidctflt.c ***/
  174177. #define JPEG_INTERNALS
  174178. #ifdef DCT_FLOAT_SUPPORTED
  174179. /*
  174180. * This module is specialized to the case DCTSIZE = 8.
  174181. */
  174182. #if DCTSIZE != 8
  174183. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174184. #endif
  174185. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174186. * entry; produce a float result.
  174187. */
  174188. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174189. /*
  174190. * Perform dequantization and inverse DCT on one block of coefficients.
  174191. */
  174192. GLOBAL(void)
  174193. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174194. JCOEFPTR coef_block,
  174195. JSAMPARRAY output_buf, JDIMENSION output_col)
  174196. {
  174197. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174198. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174199. FAST_FLOAT z5, z10, z11, z12, z13;
  174200. JCOEFPTR inptr;
  174201. FLOAT_MULT_TYPE * quantptr;
  174202. FAST_FLOAT * wsptr;
  174203. JSAMPROW outptr;
  174204. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174205. int ctr;
  174206. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174207. SHIFT_TEMPS
  174208. /* Pass 1: process columns from input, store into work array. */
  174209. inptr = coef_block;
  174210. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174211. wsptr = workspace;
  174212. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174213. /* Due to quantization, we will usually find that many of the input
  174214. * coefficients are zero, especially the AC terms. We can exploit this
  174215. * by short-circuiting the IDCT calculation for any column in which all
  174216. * the AC terms are zero. In that case each output is equal to the
  174217. * DC coefficient (with scale factor as needed).
  174218. * With typical images and quantization tables, half or more of the
  174219. * column DCT calculations can be simplified this way.
  174220. */
  174221. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174222. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174223. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174224. inptr[DCTSIZE*7] == 0) {
  174225. /* AC terms all zero */
  174226. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174227. wsptr[DCTSIZE*0] = dcval;
  174228. wsptr[DCTSIZE*1] = dcval;
  174229. wsptr[DCTSIZE*2] = dcval;
  174230. wsptr[DCTSIZE*3] = dcval;
  174231. wsptr[DCTSIZE*4] = dcval;
  174232. wsptr[DCTSIZE*5] = dcval;
  174233. wsptr[DCTSIZE*6] = dcval;
  174234. wsptr[DCTSIZE*7] = dcval;
  174235. inptr++; /* advance pointers to next column */
  174236. quantptr++;
  174237. wsptr++;
  174238. continue;
  174239. }
  174240. /* Even part */
  174241. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174242. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174243. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174244. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174245. tmp10 = tmp0 + tmp2; /* phase 3 */
  174246. tmp11 = tmp0 - tmp2;
  174247. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174248. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174249. tmp0 = tmp10 + tmp13; /* phase 2 */
  174250. tmp3 = tmp10 - tmp13;
  174251. tmp1 = tmp11 + tmp12;
  174252. tmp2 = tmp11 - tmp12;
  174253. /* Odd part */
  174254. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174255. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174256. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174257. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174258. z13 = tmp6 + tmp5; /* phase 6 */
  174259. z10 = tmp6 - tmp5;
  174260. z11 = tmp4 + tmp7;
  174261. z12 = tmp4 - tmp7;
  174262. tmp7 = z11 + z13; /* phase 5 */
  174263. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174264. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174265. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174266. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174267. tmp6 = tmp12 - tmp7; /* phase 2 */
  174268. tmp5 = tmp11 - tmp6;
  174269. tmp4 = tmp10 + tmp5;
  174270. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174271. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174272. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174273. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174274. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174275. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174276. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174277. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174278. inptr++; /* advance pointers to next column */
  174279. quantptr++;
  174280. wsptr++;
  174281. }
  174282. /* Pass 2: process rows from work array, store into output array. */
  174283. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174284. wsptr = workspace;
  174285. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174286. outptr = output_buf[ctr] + output_col;
  174287. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174288. * However, the column calculation has created many nonzero AC terms, so
  174289. * the simplification applies less often (typically 5% to 10% of the time).
  174290. * And testing floats for zero is relatively expensive, so we don't bother.
  174291. */
  174292. /* Even part */
  174293. tmp10 = wsptr[0] + wsptr[4];
  174294. tmp11 = wsptr[0] - wsptr[4];
  174295. tmp13 = wsptr[2] + wsptr[6];
  174296. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174297. tmp0 = tmp10 + tmp13;
  174298. tmp3 = tmp10 - tmp13;
  174299. tmp1 = tmp11 + tmp12;
  174300. tmp2 = tmp11 - tmp12;
  174301. /* Odd part */
  174302. z13 = wsptr[5] + wsptr[3];
  174303. z10 = wsptr[5] - wsptr[3];
  174304. z11 = wsptr[1] + wsptr[7];
  174305. z12 = wsptr[1] - wsptr[7];
  174306. tmp7 = z11 + z13;
  174307. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174308. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174309. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174310. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174311. tmp6 = tmp12 - tmp7;
  174312. tmp5 = tmp11 - tmp6;
  174313. tmp4 = tmp10 + tmp5;
  174314. /* Final output stage: scale down by a factor of 8 and range-limit */
  174315. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174316. & RANGE_MASK];
  174317. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174318. & RANGE_MASK];
  174319. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174320. & RANGE_MASK];
  174321. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174322. & RANGE_MASK];
  174323. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174324. & RANGE_MASK];
  174325. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174326. & RANGE_MASK];
  174327. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174328. & RANGE_MASK];
  174329. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174330. & RANGE_MASK];
  174331. wsptr += DCTSIZE; /* advance pointer to next row */
  174332. }
  174333. }
  174334. #endif /* DCT_FLOAT_SUPPORTED */
  174335. /*** End of inlined file: jidctflt.c ***/
  174336. #undef CONST_BITS
  174337. #undef FIX_1_847759065
  174338. #undef MULTIPLY
  174339. #undef DEQUANTIZE
  174340. #undef DESCALE
  174341. /*** Start of inlined file: jidctfst.c ***/
  174342. #define JPEG_INTERNALS
  174343. #ifdef DCT_IFAST_SUPPORTED
  174344. /*
  174345. * This module is specialized to the case DCTSIZE = 8.
  174346. */
  174347. #if DCTSIZE != 8
  174348. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174349. #endif
  174350. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174351. * see jidctint.c for more details. However, we choose to descale
  174352. * (right shift) multiplication products as soon as they are formed,
  174353. * rather than carrying additional fractional bits into subsequent additions.
  174354. * This compromises accuracy slightly, but it lets us save a few shifts.
  174355. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174356. * everywhere except in the multiplications proper; this saves a good deal
  174357. * of work on 16-bit-int machines.
  174358. *
  174359. * The dequantized coefficients are not integers because the AA&N scaling
  174360. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174361. * so that the first and second IDCT rounds have the same input scaling.
  174362. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174363. * avoid a descaling shift; this compromises accuracy rather drastically
  174364. * for small quantization table entries, but it saves a lot of shifts.
  174365. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174366. * so we use a much larger scaling factor to preserve accuracy.
  174367. *
  174368. * A final compromise is to represent the multiplicative constants to only
  174369. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174370. * machines, and may also reduce the cost of multiplication (since there
  174371. * are fewer one-bits in the constants).
  174372. */
  174373. #if BITS_IN_JSAMPLE == 8
  174374. #define CONST_BITS 8
  174375. #define PASS1_BITS 2
  174376. #else
  174377. #define CONST_BITS 8
  174378. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174379. #endif
  174380. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174381. * causing a lot of useless floating-point operations at run time.
  174382. * To get around this we use the following pre-calculated constants.
  174383. * If you change CONST_BITS you may want to add appropriate values.
  174384. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174385. */
  174386. #if CONST_BITS == 8
  174387. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174388. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174389. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174390. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174391. #else
  174392. #define FIX_1_082392200 FIX(1.082392200)
  174393. #define FIX_1_414213562 FIX(1.414213562)
  174394. #define FIX_1_847759065 FIX(1.847759065)
  174395. #define FIX_2_613125930 FIX(2.613125930)
  174396. #endif
  174397. /* We can gain a little more speed, with a further compromise in accuracy,
  174398. * by omitting the addition in a descaling shift. This yields an incorrectly
  174399. * rounded result half the time...
  174400. */
  174401. #ifndef USE_ACCURATE_ROUNDING
  174402. #undef DESCALE
  174403. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174404. #endif
  174405. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174406. * descale to yield a DCTELEM result.
  174407. */
  174408. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174409. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174410. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174411. * multiplication will do. For 12-bit data, the multiplier table is
  174412. * declared INT32, so a 32-bit multiply will be used.
  174413. */
  174414. #if BITS_IN_JSAMPLE == 8
  174415. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174416. #else
  174417. #define DEQUANTIZE(coef,quantval) \
  174418. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174419. #endif
  174420. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174421. * We assume that int right shift is unsigned if INT32 right shift is.
  174422. */
  174423. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174424. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174425. #if BITS_IN_JSAMPLE == 8
  174426. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174427. #else
  174428. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174429. #endif
  174430. #define IRIGHT_SHIFT(x,shft) \
  174431. ((ishift_temp = (x)) < 0 ? \
  174432. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174433. (ishift_temp >> (shft)))
  174434. #else
  174435. #define ISHIFT_TEMPS
  174436. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174437. #endif
  174438. #ifdef USE_ACCURATE_ROUNDING
  174439. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174440. #else
  174441. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174442. #endif
  174443. /*
  174444. * Perform dequantization and inverse DCT on one block of coefficients.
  174445. */
  174446. GLOBAL(void)
  174447. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174448. JCOEFPTR coef_block,
  174449. JSAMPARRAY output_buf, JDIMENSION output_col)
  174450. {
  174451. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174452. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174453. DCTELEM z5, z10, z11, z12, z13;
  174454. JCOEFPTR inptr;
  174455. IFAST_MULT_TYPE * quantptr;
  174456. int * wsptr;
  174457. JSAMPROW outptr;
  174458. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174459. int ctr;
  174460. int workspace[DCTSIZE2]; /* buffers data between passes */
  174461. SHIFT_TEMPS /* for DESCALE */
  174462. ISHIFT_TEMPS /* for IDESCALE */
  174463. /* Pass 1: process columns from input, store into work array. */
  174464. inptr = coef_block;
  174465. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174466. wsptr = workspace;
  174467. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174468. /* Due to quantization, we will usually find that many of the input
  174469. * coefficients are zero, especially the AC terms. We can exploit this
  174470. * by short-circuiting the IDCT calculation for any column in which all
  174471. * the AC terms are zero. In that case each output is equal to the
  174472. * DC coefficient (with scale factor as needed).
  174473. * With typical images and quantization tables, half or more of the
  174474. * column DCT calculations can be simplified this way.
  174475. */
  174476. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174477. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174478. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174479. inptr[DCTSIZE*7] == 0) {
  174480. /* AC terms all zero */
  174481. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174482. wsptr[DCTSIZE*0] = dcval;
  174483. wsptr[DCTSIZE*1] = dcval;
  174484. wsptr[DCTSIZE*2] = dcval;
  174485. wsptr[DCTSIZE*3] = dcval;
  174486. wsptr[DCTSIZE*4] = dcval;
  174487. wsptr[DCTSIZE*5] = dcval;
  174488. wsptr[DCTSIZE*6] = dcval;
  174489. wsptr[DCTSIZE*7] = dcval;
  174490. inptr++; /* advance pointers to next column */
  174491. quantptr++;
  174492. wsptr++;
  174493. continue;
  174494. }
  174495. /* Even part */
  174496. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174497. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174498. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174499. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174500. tmp10 = tmp0 + tmp2; /* phase 3 */
  174501. tmp11 = tmp0 - tmp2;
  174502. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174503. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174504. tmp0 = tmp10 + tmp13; /* phase 2 */
  174505. tmp3 = tmp10 - tmp13;
  174506. tmp1 = tmp11 + tmp12;
  174507. tmp2 = tmp11 - tmp12;
  174508. /* Odd part */
  174509. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174510. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174511. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174512. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174513. z13 = tmp6 + tmp5; /* phase 6 */
  174514. z10 = tmp6 - tmp5;
  174515. z11 = tmp4 + tmp7;
  174516. z12 = tmp4 - tmp7;
  174517. tmp7 = z11 + z13; /* phase 5 */
  174518. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174519. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174520. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174521. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174522. tmp6 = tmp12 - tmp7; /* phase 2 */
  174523. tmp5 = tmp11 - tmp6;
  174524. tmp4 = tmp10 + tmp5;
  174525. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174526. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174527. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174528. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174529. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174530. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174531. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174532. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174533. inptr++; /* advance pointers to next column */
  174534. quantptr++;
  174535. wsptr++;
  174536. }
  174537. /* Pass 2: process rows from work array, store into output array. */
  174538. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174539. /* and also undo the PASS1_BITS scaling. */
  174540. wsptr = workspace;
  174541. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174542. outptr = output_buf[ctr] + output_col;
  174543. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174544. * However, the column calculation has created many nonzero AC terms, so
  174545. * the simplification applies less often (typically 5% to 10% of the time).
  174546. * On machines with very fast multiplication, it's possible that the
  174547. * test takes more time than it's worth. In that case this section
  174548. * may be commented out.
  174549. */
  174550. #ifndef NO_ZERO_ROW_TEST
  174551. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174552. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174553. /* AC terms all zero */
  174554. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174555. & RANGE_MASK];
  174556. outptr[0] = dcval;
  174557. outptr[1] = dcval;
  174558. outptr[2] = dcval;
  174559. outptr[3] = dcval;
  174560. outptr[4] = dcval;
  174561. outptr[5] = dcval;
  174562. outptr[6] = dcval;
  174563. outptr[7] = dcval;
  174564. wsptr += DCTSIZE; /* advance pointer to next row */
  174565. continue;
  174566. }
  174567. #endif
  174568. /* Even part */
  174569. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174570. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174571. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174572. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174573. - tmp13;
  174574. tmp0 = tmp10 + tmp13;
  174575. tmp3 = tmp10 - tmp13;
  174576. tmp1 = tmp11 + tmp12;
  174577. tmp2 = tmp11 - tmp12;
  174578. /* Odd part */
  174579. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174580. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174581. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174582. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174583. tmp7 = z11 + z13; /* phase 5 */
  174584. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174585. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174586. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174587. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174588. tmp6 = tmp12 - tmp7; /* phase 2 */
  174589. tmp5 = tmp11 - tmp6;
  174590. tmp4 = tmp10 + tmp5;
  174591. /* Final output stage: scale down by a factor of 8 and range-limit */
  174592. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174593. & RANGE_MASK];
  174594. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174595. & RANGE_MASK];
  174596. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174597. & RANGE_MASK];
  174598. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174599. & RANGE_MASK];
  174600. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174601. & RANGE_MASK];
  174602. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174603. & RANGE_MASK];
  174604. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174605. & RANGE_MASK];
  174606. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174607. & RANGE_MASK];
  174608. wsptr += DCTSIZE; /* advance pointer to next row */
  174609. }
  174610. }
  174611. #endif /* DCT_IFAST_SUPPORTED */
  174612. /*** End of inlined file: jidctfst.c ***/
  174613. #undef CONST_BITS
  174614. #undef FIX_1_847759065
  174615. #undef MULTIPLY
  174616. #undef DEQUANTIZE
  174617. /*** Start of inlined file: jidctint.c ***/
  174618. #define JPEG_INTERNALS
  174619. #ifdef DCT_ISLOW_SUPPORTED
  174620. /*
  174621. * This module is specialized to the case DCTSIZE = 8.
  174622. */
  174623. #if DCTSIZE != 8
  174624. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174625. #endif
  174626. /*
  174627. * The poop on this scaling stuff is as follows:
  174628. *
  174629. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174630. * larger than the true IDCT outputs. The final outputs are therefore
  174631. * a factor of N larger than desired; since N=8 this can be cured by
  174632. * a simple right shift at the end of the algorithm. The advantage of
  174633. * this arrangement is that we save two multiplications per 1-D IDCT,
  174634. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174635. *
  174636. * We have to do addition and subtraction of the integer inputs, which
  174637. * is no problem, and multiplication by fractional constants, which is
  174638. * a problem to do in integer arithmetic. We multiply all the constants
  174639. * by CONST_SCALE and convert them to integer constants (thus retaining
  174640. * CONST_BITS bits of precision in the constants). After doing a
  174641. * multiplication we have to divide the product by CONST_SCALE, with proper
  174642. * rounding, to produce the correct output. This division can be done
  174643. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174644. * as long as possible so that partial sums can be added together with
  174645. * full fractional precision.
  174646. *
  174647. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174648. * they are represented to better-than-integral precision. These outputs
  174649. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174650. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174651. * intermediate INT32 array would be needed.)
  174652. *
  174653. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174654. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174655. * shows that the values given below are the most effective.
  174656. */
  174657. #if BITS_IN_JSAMPLE == 8
  174658. #define CONST_BITS 13
  174659. #define PASS1_BITS 2
  174660. #else
  174661. #define CONST_BITS 13
  174662. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174663. #endif
  174664. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174665. * causing a lot of useless floating-point operations at run time.
  174666. * To get around this we use the following pre-calculated constants.
  174667. * If you change CONST_BITS you may want to add appropriate values.
  174668. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174669. */
  174670. #if CONST_BITS == 13
  174671. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174672. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174673. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174674. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174675. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174676. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174677. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174678. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174679. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174680. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174681. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174682. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174683. #else
  174684. #define FIX_0_298631336 FIX(0.298631336)
  174685. #define FIX_0_390180644 FIX(0.390180644)
  174686. #define FIX_0_541196100 FIX(0.541196100)
  174687. #define FIX_0_765366865 FIX(0.765366865)
  174688. #define FIX_0_899976223 FIX(0.899976223)
  174689. #define FIX_1_175875602 FIX(1.175875602)
  174690. #define FIX_1_501321110 FIX(1.501321110)
  174691. #define FIX_1_847759065 FIX(1.847759065)
  174692. #define FIX_1_961570560 FIX(1.961570560)
  174693. #define FIX_2_053119869 FIX(2.053119869)
  174694. #define FIX_2_562915447 FIX(2.562915447)
  174695. #define FIX_3_072711026 FIX(3.072711026)
  174696. #endif
  174697. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174698. * For 8-bit samples with the recommended scaling, all the variable
  174699. * and constant values involved are no more than 16 bits wide, so a
  174700. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174701. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174702. */
  174703. #if BITS_IN_JSAMPLE == 8
  174704. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174705. #else
  174706. #define MULTIPLY(var,const) ((var) * (const))
  174707. #endif
  174708. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174709. * entry; produce an int result. In this module, both inputs and result
  174710. * are 16 bits or less, so either int or short multiply will work.
  174711. */
  174712. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174713. /*
  174714. * Perform dequantization and inverse DCT on one block of coefficients.
  174715. */
  174716. GLOBAL(void)
  174717. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174718. JCOEFPTR coef_block,
  174719. JSAMPARRAY output_buf, JDIMENSION output_col)
  174720. {
  174721. INT32 tmp0, tmp1, tmp2, tmp3;
  174722. INT32 tmp10, tmp11, tmp12, tmp13;
  174723. INT32 z1, z2, z3, z4, z5;
  174724. JCOEFPTR inptr;
  174725. ISLOW_MULT_TYPE * quantptr;
  174726. int * wsptr;
  174727. JSAMPROW outptr;
  174728. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174729. int ctr;
  174730. int workspace[DCTSIZE2]; /* buffers data between passes */
  174731. SHIFT_TEMPS
  174732. /* Pass 1: process columns from input, store into work array. */
  174733. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174734. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174735. inptr = coef_block;
  174736. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174737. wsptr = workspace;
  174738. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174739. /* Due to quantization, we will usually find that many of the input
  174740. * coefficients are zero, especially the AC terms. We can exploit this
  174741. * by short-circuiting the IDCT calculation for any column in which all
  174742. * the AC terms are zero. In that case each output is equal to the
  174743. * DC coefficient (with scale factor as needed).
  174744. * With typical images and quantization tables, half or more of the
  174745. * column DCT calculations can be simplified this way.
  174746. */
  174747. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174748. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174749. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174750. inptr[DCTSIZE*7] == 0) {
  174751. /* AC terms all zero */
  174752. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174753. wsptr[DCTSIZE*0] = dcval;
  174754. wsptr[DCTSIZE*1] = dcval;
  174755. wsptr[DCTSIZE*2] = dcval;
  174756. wsptr[DCTSIZE*3] = dcval;
  174757. wsptr[DCTSIZE*4] = dcval;
  174758. wsptr[DCTSIZE*5] = dcval;
  174759. wsptr[DCTSIZE*6] = dcval;
  174760. wsptr[DCTSIZE*7] = dcval;
  174761. inptr++; /* advance pointers to next column */
  174762. quantptr++;
  174763. wsptr++;
  174764. continue;
  174765. }
  174766. /* Even part: reverse the even part of the forward DCT. */
  174767. /* The rotator is sqrt(2)*c(-6). */
  174768. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174769. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174770. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174771. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174772. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174773. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174774. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174775. tmp0 = (z2 + z3) << CONST_BITS;
  174776. tmp1 = (z2 - z3) << CONST_BITS;
  174777. tmp10 = tmp0 + tmp3;
  174778. tmp13 = tmp0 - tmp3;
  174779. tmp11 = tmp1 + tmp2;
  174780. tmp12 = tmp1 - tmp2;
  174781. /* Odd part per figure 8; the matrix is unitary and hence its
  174782. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174783. */
  174784. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174785. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174786. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174787. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174788. z1 = tmp0 + tmp3;
  174789. z2 = tmp1 + tmp2;
  174790. z3 = tmp0 + tmp2;
  174791. z4 = tmp1 + tmp3;
  174792. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174793. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174794. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174795. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174796. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174797. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174798. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174799. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174800. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174801. z3 += z5;
  174802. z4 += z5;
  174803. tmp0 += z1 + z3;
  174804. tmp1 += z2 + z4;
  174805. tmp2 += z2 + z3;
  174806. tmp3 += z1 + z4;
  174807. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174808. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174809. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174810. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174811. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174812. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174813. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174814. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174815. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174816. inptr++; /* advance pointers to next column */
  174817. quantptr++;
  174818. wsptr++;
  174819. }
  174820. /* Pass 2: process rows from work array, store into output array. */
  174821. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174822. /* and also undo the PASS1_BITS scaling. */
  174823. wsptr = workspace;
  174824. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174825. outptr = output_buf[ctr] + output_col;
  174826. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174827. * However, the column calculation has created many nonzero AC terms, so
  174828. * the simplification applies less often (typically 5% to 10% of the time).
  174829. * On machines with very fast multiplication, it's possible that the
  174830. * test takes more time than it's worth. In that case this section
  174831. * may be commented out.
  174832. */
  174833. #ifndef NO_ZERO_ROW_TEST
  174834. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174835. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174836. /* AC terms all zero */
  174837. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174838. & RANGE_MASK];
  174839. outptr[0] = dcval;
  174840. outptr[1] = dcval;
  174841. outptr[2] = dcval;
  174842. outptr[3] = dcval;
  174843. outptr[4] = dcval;
  174844. outptr[5] = dcval;
  174845. outptr[6] = dcval;
  174846. outptr[7] = dcval;
  174847. wsptr += DCTSIZE; /* advance pointer to next row */
  174848. continue;
  174849. }
  174850. #endif
  174851. /* Even part: reverse the even part of the forward DCT. */
  174852. /* The rotator is sqrt(2)*c(-6). */
  174853. z2 = (INT32) wsptr[2];
  174854. z3 = (INT32) wsptr[6];
  174855. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174856. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174857. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174858. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  174859. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  174860. tmp10 = tmp0 + tmp3;
  174861. tmp13 = tmp0 - tmp3;
  174862. tmp11 = tmp1 + tmp2;
  174863. tmp12 = tmp1 - tmp2;
  174864. /* Odd part per figure 8; the matrix is unitary and hence its
  174865. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174866. */
  174867. tmp0 = (INT32) wsptr[7];
  174868. tmp1 = (INT32) wsptr[5];
  174869. tmp2 = (INT32) wsptr[3];
  174870. tmp3 = (INT32) wsptr[1];
  174871. z1 = tmp0 + tmp3;
  174872. z2 = tmp1 + tmp2;
  174873. z3 = tmp0 + tmp2;
  174874. z4 = tmp1 + tmp3;
  174875. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174876. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174877. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174878. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174879. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174880. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174881. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174882. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174883. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174884. z3 += z5;
  174885. z4 += z5;
  174886. tmp0 += z1 + z3;
  174887. tmp1 += z2 + z4;
  174888. tmp2 += z2 + z3;
  174889. tmp3 += z1 + z4;
  174890. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174891. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  174892. CONST_BITS+PASS1_BITS+3)
  174893. & RANGE_MASK];
  174894. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  174895. CONST_BITS+PASS1_BITS+3)
  174896. & RANGE_MASK];
  174897. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  174898. CONST_BITS+PASS1_BITS+3)
  174899. & RANGE_MASK];
  174900. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  174901. CONST_BITS+PASS1_BITS+3)
  174902. & RANGE_MASK];
  174903. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  174904. CONST_BITS+PASS1_BITS+3)
  174905. & RANGE_MASK];
  174906. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  174907. CONST_BITS+PASS1_BITS+3)
  174908. & RANGE_MASK];
  174909. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  174910. CONST_BITS+PASS1_BITS+3)
  174911. & RANGE_MASK];
  174912. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  174913. CONST_BITS+PASS1_BITS+3)
  174914. & RANGE_MASK];
  174915. wsptr += DCTSIZE; /* advance pointer to next row */
  174916. }
  174917. }
  174918. #endif /* DCT_ISLOW_SUPPORTED */
  174919. /*** End of inlined file: jidctint.c ***/
  174920. /*** Start of inlined file: jidctred.c ***/
  174921. #define JPEG_INTERNALS
  174922. #ifdef IDCT_SCALING_SUPPORTED
  174923. /*
  174924. * This module is specialized to the case DCTSIZE = 8.
  174925. */
  174926. #if DCTSIZE != 8
  174927. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174928. #endif
  174929. /* Scaling is the same as in jidctint.c. */
  174930. #if BITS_IN_JSAMPLE == 8
  174931. #define CONST_BITS 13
  174932. #define PASS1_BITS 2
  174933. #else
  174934. #define CONST_BITS 13
  174935. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174936. #endif
  174937. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174938. * causing a lot of useless floating-point operations at run time.
  174939. * To get around this we use the following pre-calculated constants.
  174940. * If you change CONST_BITS you may want to add appropriate values.
  174941. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174942. */
  174943. #if CONST_BITS == 13
  174944. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  174945. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  174946. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  174947. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  174948. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174949. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  174950. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174951. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  174952. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  174953. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  174954. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174955. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  174956. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174957. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  174958. #else
  174959. #define FIX_0_211164243 FIX(0.211164243)
  174960. #define FIX_0_509795579 FIX(0.509795579)
  174961. #define FIX_0_601344887 FIX(0.601344887)
  174962. #define FIX_0_720959822 FIX(0.720959822)
  174963. #define FIX_0_765366865 FIX(0.765366865)
  174964. #define FIX_0_850430095 FIX(0.850430095)
  174965. #define FIX_0_899976223 FIX(0.899976223)
  174966. #define FIX_1_061594337 FIX(1.061594337)
  174967. #define FIX_1_272758580 FIX(1.272758580)
  174968. #define FIX_1_451774981 FIX(1.451774981)
  174969. #define FIX_1_847759065 FIX(1.847759065)
  174970. #define FIX_2_172734803 FIX(2.172734803)
  174971. #define FIX_2_562915447 FIX(2.562915447)
  174972. #define FIX_3_624509785 FIX(3.624509785)
  174973. #endif
  174974. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174975. * For 8-bit samples with the recommended scaling, all the variable
  174976. * and constant values involved are no more than 16 bits wide, so a
  174977. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174978. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174979. */
  174980. #if BITS_IN_JSAMPLE == 8
  174981. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174982. #else
  174983. #define MULTIPLY(var,const) ((var) * (const))
  174984. #endif
  174985. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174986. * entry; produce an int result. In this module, both inputs and result
  174987. * are 16 bits or less, so either int or short multiply will work.
  174988. */
  174989. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174990. /*
  174991. * Perform dequantization and inverse DCT on one block of coefficients,
  174992. * producing a reduced-size 4x4 output block.
  174993. */
  174994. GLOBAL(void)
  174995. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174996. JCOEFPTR coef_block,
  174997. JSAMPARRAY output_buf, JDIMENSION output_col)
  174998. {
  174999. INT32 tmp0, tmp2, tmp10, tmp12;
  175000. INT32 z1, z2, z3, z4;
  175001. JCOEFPTR inptr;
  175002. ISLOW_MULT_TYPE * quantptr;
  175003. int * wsptr;
  175004. JSAMPROW outptr;
  175005. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175006. int ctr;
  175007. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175008. SHIFT_TEMPS
  175009. /* Pass 1: process columns from input, store into work array. */
  175010. inptr = coef_block;
  175011. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175012. wsptr = workspace;
  175013. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175014. /* Don't bother to process column 4, because second pass won't use it */
  175015. if (ctr == DCTSIZE-4)
  175016. continue;
  175017. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175018. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175019. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175020. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175021. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175022. wsptr[DCTSIZE*0] = dcval;
  175023. wsptr[DCTSIZE*1] = dcval;
  175024. wsptr[DCTSIZE*2] = dcval;
  175025. wsptr[DCTSIZE*3] = dcval;
  175026. continue;
  175027. }
  175028. /* Even part */
  175029. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175030. tmp0 <<= (CONST_BITS+1);
  175031. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175032. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175033. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175034. tmp10 = tmp0 + tmp2;
  175035. tmp12 = tmp0 - tmp2;
  175036. /* Odd part */
  175037. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175038. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175039. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175040. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175041. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175042. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175043. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175044. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175045. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175046. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175047. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175048. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175049. /* Final output stage */
  175050. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175051. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175052. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175053. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175054. }
  175055. /* Pass 2: process 4 rows from work array, store into output array. */
  175056. wsptr = workspace;
  175057. for (ctr = 0; ctr < 4; ctr++) {
  175058. outptr = output_buf[ctr] + output_col;
  175059. /* It's not clear whether a zero row test is worthwhile here ... */
  175060. #ifndef NO_ZERO_ROW_TEST
  175061. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175062. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175063. /* AC terms all zero */
  175064. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175065. & RANGE_MASK];
  175066. outptr[0] = dcval;
  175067. outptr[1] = dcval;
  175068. outptr[2] = dcval;
  175069. outptr[3] = dcval;
  175070. wsptr += DCTSIZE; /* advance pointer to next row */
  175071. continue;
  175072. }
  175073. #endif
  175074. /* Even part */
  175075. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175076. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175077. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175078. tmp10 = tmp0 + tmp2;
  175079. tmp12 = tmp0 - tmp2;
  175080. /* Odd part */
  175081. z1 = (INT32) wsptr[7];
  175082. z2 = (INT32) wsptr[5];
  175083. z3 = (INT32) wsptr[3];
  175084. z4 = (INT32) wsptr[1];
  175085. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175086. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175087. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175088. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175089. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175090. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175091. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175092. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175093. /* Final output stage */
  175094. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175095. CONST_BITS+PASS1_BITS+3+1)
  175096. & RANGE_MASK];
  175097. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175098. CONST_BITS+PASS1_BITS+3+1)
  175099. & RANGE_MASK];
  175100. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175101. CONST_BITS+PASS1_BITS+3+1)
  175102. & RANGE_MASK];
  175103. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175104. CONST_BITS+PASS1_BITS+3+1)
  175105. & RANGE_MASK];
  175106. wsptr += DCTSIZE; /* advance pointer to next row */
  175107. }
  175108. }
  175109. /*
  175110. * Perform dequantization and inverse DCT on one block of coefficients,
  175111. * producing a reduced-size 2x2 output block.
  175112. */
  175113. GLOBAL(void)
  175114. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175115. JCOEFPTR coef_block,
  175116. JSAMPARRAY output_buf, JDIMENSION output_col)
  175117. {
  175118. INT32 tmp0, tmp10, z1;
  175119. JCOEFPTR inptr;
  175120. ISLOW_MULT_TYPE * quantptr;
  175121. int * wsptr;
  175122. JSAMPROW outptr;
  175123. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175124. int ctr;
  175125. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175126. SHIFT_TEMPS
  175127. /* Pass 1: process columns from input, store into work array. */
  175128. inptr = coef_block;
  175129. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175130. wsptr = workspace;
  175131. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175132. /* Don't bother to process columns 2,4,6 */
  175133. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175134. continue;
  175135. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175136. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175137. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175138. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175139. wsptr[DCTSIZE*0] = dcval;
  175140. wsptr[DCTSIZE*1] = dcval;
  175141. continue;
  175142. }
  175143. /* Even part */
  175144. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175145. tmp10 = z1 << (CONST_BITS+2);
  175146. /* Odd part */
  175147. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175148. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175149. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175150. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175151. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175152. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175153. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175154. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175155. /* Final output stage */
  175156. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175157. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175158. }
  175159. /* Pass 2: process 2 rows from work array, store into output array. */
  175160. wsptr = workspace;
  175161. for (ctr = 0; ctr < 2; ctr++) {
  175162. outptr = output_buf[ctr] + output_col;
  175163. /* It's not clear whether a zero row test is worthwhile here ... */
  175164. #ifndef NO_ZERO_ROW_TEST
  175165. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175166. /* AC terms all zero */
  175167. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175168. & RANGE_MASK];
  175169. outptr[0] = dcval;
  175170. outptr[1] = dcval;
  175171. wsptr += DCTSIZE; /* advance pointer to next row */
  175172. continue;
  175173. }
  175174. #endif
  175175. /* Even part */
  175176. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175177. /* Odd part */
  175178. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175179. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175180. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175181. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175182. /* Final output stage */
  175183. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175184. CONST_BITS+PASS1_BITS+3+2)
  175185. & RANGE_MASK];
  175186. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175187. CONST_BITS+PASS1_BITS+3+2)
  175188. & RANGE_MASK];
  175189. wsptr += DCTSIZE; /* advance pointer to next row */
  175190. }
  175191. }
  175192. /*
  175193. * Perform dequantization and inverse DCT on one block of coefficients,
  175194. * producing a reduced-size 1x1 output block.
  175195. */
  175196. GLOBAL(void)
  175197. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175198. JCOEFPTR coef_block,
  175199. JSAMPARRAY output_buf, JDIMENSION output_col)
  175200. {
  175201. int dcval;
  175202. ISLOW_MULT_TYPE * quantptr;
  175203. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175204. SHIFT_TEMPS
  175205. /* We hardly need an inverse DCT routine for this: just take the
  175206. * average pixel value, which is one-eighth of the DC coefficient.
  175207. */
  175208. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175209. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175210. dcval = (int) DESCALE((INT32) dcval, 3);
  175211. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175212. }
  175213. #endif /* IDCT_SCALING_SUPPORTED */
  175214. /*** End of inlined file: jidctred.c ***/
  175215. /*** Start of inlined file: jmemmgr.c ***/
  175216. #define JPEG_INTERNALS
  175217. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175218. /*** Start of inlined file: jmemsys.h ***/
  175219. #ifndef __jmemsys_h__
  175220. #define __jmemsys_h__
  175221. /* Short forms of external names for systems with brain-damaged linkers. */
  175222. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175223. #define jpeg_get_small jGetSmall
  175224. #define jpeg_free_small jFreeSmall
  175225. #define jpeg_get_large jGetLarge
  175226. #define jpeg_free_large jFreeLarge
  175227. #define jpeg_mem_available jMemAvail
  175228. #define jpeg_open_backing_store jOpenBackStore
  175229. #define jpeg_mem_init jMemInit
  175230. #define jpeg_mem_term jMemTerm
  175231. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175232. /*
  175233. * These two functions are used to allocate and release small chunks of
  175234. * memory. (Typically the total amount requested through jpeg_get_small is
  175235. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175236. * Behavior should be the same as for the standard library functions malloc
  175237. * and free; in particular, jpeg_get_small must return NULL on failure.
  175238. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175239. * size of the object being freed, just in case it's needed.
  175240. * On an 80x86 machine using small-data memory model, these manage near heap.
  175241. */
  175242. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175243. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175244. size_t sizeofobject));
  175245. /*
  175246. * These two functions are used to allocate and release large chunks of
  175247. * memory (up to the total free space designated by jpeg_mem_available).
  175248. * The interface is the same as above, except that on an 80x86 machine,
  175249. * far pointers are used. On most other machines these are identical to
  175250. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175251. * in case a different allocation strategy is desirable for large chunks.
  175252. */
  175253. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175254. size_t sizeofobject));
  175255. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175256. size_t sizeofobject));
  175257. /*
  175258. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175259. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175260. * matter, but that case should never come into play). This macro is needed
  175261. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175262. * On those machines, we expect that jconfig.h will provide a proper value.
  175263. * On machines with 32-bit flat address spaces, any large constant may be used.
  175264. *
  175265. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175266. * size_t and will be a multiple of sizeof(align_type).
  175267. */
  175268. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175269. #define MAX_ALLOC_CHUNK 1000000000L
  175270. #endif
  175271. /*
  175272. * This routine computes the total space still available for allocation by
  175273. * jpeg_get_large. If more space than this is needed, backing store will be
  175274. * used. NOTE: any memory already allocated must not be counted.
  175275. *
  175276. * There is a minimum space requirement, corresponding to the minimum
  175277. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175278. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175279. * all working storage in memory, is also passed in case it is useful.
  175280. * Finally, the total space already allocated is passed. If no better
  175281. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175282. * is often a suitable calculation.
  175283. *
  175284. * It is OK for jpeg_mem_available to underestimate the space available
  175285. * (that'll just lead to more backing-store access than is really necessary).
  175286. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175287. * a slop factor from the true available space. 5% should be enough.
  175288. *
  175289. * On machines with lots of virtual memory, any large constant may be returned.
  175290. * Conversely, zero may be returned to always use the minimum amount of memory.
  175291. */
  175292. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175293. long min_bytes_needed,
  175294. long max_bytes_needed,
  175295. long already_allocated));
  175296. /*
  175297. * This structure holds whatever state is needed to access a single
  175298. * backing-store object. The read/write/close method pointers are called
  175299. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175300. * are private to the system-dependent backing store routines.
  175301. */
  175302. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175303. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175304. typedef unsigned short XMSH; /* type of extended-memory handles */
  175305. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175306. typedef union {
  175307. short file_handle; /* DOS file handle if it's a temp file */
  175308. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175309. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175310. } handle_union;
  175311. #endif /* USE_MSDOS_MEMMGR */
  175312. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175313. #include <Files.h>
  175314. #endif /* USE_MAC_MEMMGR */
  175315. //typedef struct backing_store_struct * backing_store_ptr;
  175316. typedef struct backing_store_struct {
  175317. /* Methods for reading/writing/closing this backing-store object */
  175318. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175319. struct backing_store_struct *info,
  175320. void FAR * buffer_address,
  175321. long file_offset, long byte_count));
  175322. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175323. struct backing_store_struct *info,
  175324. void FAR * buffer_address,
  175325. long file_offset, long byte_count));
  175326. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175327. struct backing_store_struct *info));
  175328. /* Private fields for system-dependent backing-store management */
  175329. #ifdef USE_MSDOS_MEMMGR
  175330. /* For the MS-DOS manager (jmemdos.c), we need: */
  175331. handle_union handle; /* reference to backing-store storage object */
  175332. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175333. #else
  175334. #ifdef USE_MAC_MEMMGR
  175335. /* For the Mac manager (jmemmac.c), we need: */
  175336. short temp_file; /* file reference number to temp file */
  175337. FSSpec tempSpec; /* the FSSpec for the temp file */
  175338. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175339. #else
  175340. /* For a typical implementation with temp files, we need: */
  175341. FILE * temp_file; /* stdio reference to temp file */
  175342. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175343. #endif
  175344. #endif
  175345. } backing_store_info;
  175346. /*
  175347. * Initial opening of a backing-store object. This must fill in the
  175348. * read/write/close pointers in the object. The read/write routines
  175349. * may take an error exit if the specified maximum file size is exceeded.
  175350. * (If jpeg_mem_available always returns a large value, this routine can
  175351. * just take an error exit.)
  175352. */
  175353. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175354. struct backing_store_struct *info,
  175355. long total_bytes_needed));
  175356. /*
  175357. * These routines take care of any system-dependent initialization and
  175358. * cleanup required. jpeg_mem_init will be called before anything is
  175359. * allocated (and, therefore, nothing in cinfo is of use except the error
  175360. * manager pointer). It should return a suitable default value for
  175361. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175362. * application. (Note that max_memory_to_use is only important if
  175363. * jpeg_mem_available chooses to consult it ... no one else will.)
  175364. * jpeg_mem_term may assume that all requested memory has been freed and that
  175365. * all opened backing-store objects have been closed.
  175366. */
  175367. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175368. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175369. #endif
  175370. /*** End of inlined file: jmemsys.h ***/
  175371. /* import the system-dependent declarations */
  175372. #ifndef NO_GETENV
  175373. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175374. extern char * getenv JPP((const char * name));
  175375. #endif
  175376. #endif
  175377. /*
  175378. * Some important notes:
  175379. * The allocation routines provided here must never return NULL.
  175380. * They should exit to error_exit if unsuccessful.
  175381. *
  175382. * It's not a good idea to try to merge the sarray and barray routines,
  175383. * even though they are textually almost the same, because samples are
  175384. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175385. * in machines where byte pointers have a different representation from
  175386. * word pointers, the resulting machine code could not be the same.
  175387. */
  175388. /*
  175389. * Many machines require storage alignment: longs must start on 4-byte
  175390. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175391. * always returns pointers that are multiples of the worst-case alignment
  175392. * requirement, and we had better do so too.
  175393. * There isn't any really portable way to determine the worst-case alignment
  175394. * requirement. This module assumes that the alignment requirement is
  175395. * multiples of sizeof(ALIGN_TYPE).
  175396. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175397. * workstations (where doubles really do need 8-byte alignment) and will work
  175398. * fine on nearly everything. If your machine has lesser alignment needs,
  175399. * you can save a few bytes by making ALIGN_TYPE smaller.
  175400. * The only place I know of where this will NOT work is certain Macintosh
  175401. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175402. * Doing 10-byte alignment is counterproductive because longwords won't be
  175403. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175404. * such a compiler.
  175405. */
  175406. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175407. #define ALIGN_TYPE double
  175408. #endif
  175409. /*
  175410. * We allocate objects from "pools", where each pool is gotten with a single
  175411. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175412. * overhead within a pool, except for alignment padding. Each pool has a
  175413. * header with a link to the next pool of the same class.
  175414. * Small and large pool headers are identical except that the latter's
  175415. * link pointer must be FAR on 80x86 machines.
  175416. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175417. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175418. * of the alignment requirement of ALIGN_TYPE.
  175419. */
  175420. typedef union small_pool_struct * small_pool_ptr;
  175421. typedef union small_pool_struct {
  175422. struct {
  175423. small_pool_ptr next; /* next in list of pools */
  175424. size_t bytes_used; /* how many bytes already used within pool */
  175425. size_t bytes_left; /* bytes still available in this pool */
  175426. } hdr;
  175427. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175428. } small_pool_hdr;
  175429. typedef union large_pool_struct FAR * large_pool_ptr;
  175430. typedef union large_pool_struct {
  175431. struct {
  175432. large_pool_ptr next; /* next in list of pools */
  175433. size_t bytes_used; /* how many bytes already used within pool */
  175434. size_t bytes_left; /* bytes still available in this pool */
  175435. } hdr;
  175436. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175437. } large_pool_hdr;
  175438. /*
  175439. * Here is the full definition of a memory manager object.
  175440. */
  175441. typedef struct {
  175442. struct jpeg_memory_mgr pub; /* public fields */
  175443. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175444. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175445. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175446. /* Since we only have one lifetime class of virtual arrays, only one
  175447. * linked list is necessary (for each datatype). Note that the virtual
  175448. * array control blocks being linked together are actually stored somewhere
  175449. * in the small-pool list.
  175450. */
  175451. jvirt_sarray_ptr virt_sarray_list;
  175452. jvirt_barray_ptr virt_barray_list;
  175453. /* This counts total space obtained from jpeg_get_small/large */
  175454. long total_space_allocated;
  175455. /* alloc_sarray and alloc_barray set this value for use by virtual
  175456. * array routines.
  175457. */
  175458. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175459. } my_memory_mgr;
  175460. typedef my_memory_mgr * my_mem_ptr;
  175461. /*
  175462. * The control blocks for virtual arrays.
  175463. * Note that these blocks are allocated in the "small" pool area.
  175464. * System-dependent info for the associated backing store (if any) is hidden
  175465. * inside the backing_store_info struct.
  175466. */
  175467. struct jvirt_sarray_control {
  175468. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175469. JDIMENSION rows_in_array; /* total virtual array height */
  175470. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175471. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175472. JDIMENSION rows_in_mem; /* height of memory buffer */
  175473. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175474. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175475. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175476. boolean pre_zero; /* pre-zero mode requested? */
  175477. boolean dirty; /* do current buffer contents need written? */
  175478. boolean b_s_open; /* is backing-store data valid? */
  175479. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175480. backing_store_info b_s_info; /* System-dependent control info */
  175481. };
  175482. struct jvirt_barray_control {
  175483. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175484. JDIMENSION rows_in_array; /* total virtual array height */
  175485. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175486. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175487. JDIMENSION rows_in_mem; /* height of memory buffer */
  175488. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175489. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175490. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175491. boolean pre_zero; /* pre-zero mode requested? */
  175492. boolean dirty; /* do current buffer contents need written? */
  175493. boolean b_s_open; /* is backing-store data valid? */
  175494. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175495. backing_store_info b_s_info; /* System-dependent control info */
  175496. };
  175497. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175498. LOCAL(void)
  175499. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175500. {
  175501. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175502. small_pool_ptr shdr_ptr;
  175503. large_pool_ptr lhdr_ptr;
  175504. /* Since this is only a debugging stub, we can cheat a little by using
  175505. * fprintf directly rather than going through the trace message code.
  175506. * This is helpful because message parm array can't handle longs.
  175507. */
  175508. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175509. pool_id, mem->total_space_allocated);
  175510. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175511. lhdr_ptr = lhdr_ptr->hdr.next) {
  175512. fprintf(stderr, " Large chunk used %ld\n",
  175513. (long) lhdr_ptr->hdr.bytes_used);
  175514. }
  175515. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175516. shdr_ptr = shdr_ptr->hdr.next) {
  175517. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175518. (long) shdr_ptr->hdr.bytes_used,
  175519. (long) shdr_ptr->hdr.bytes_left);
  175520. }
  175521. }
  175522. #endif /* MEM_STATS */
  175523. LOCAL(void)
  175524. out_of_memory (j_common_ptr cinfo, int which)
  175525. /* Report an out-of-memory error and stop execution */
  175526. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175527. {
  175528. #ifdef MEM_STATS
  175529. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175530. #endif
  175531. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175532. }
  175533. /*
  175534. * Allocation of "small" objects.
  175535. *
  175536. * For these, we use pooled storage. When a new pool must be created,
  175537. * we try to get enough space for the current request plus a "slop" factor,
  175538. * where the slop will be the amount of leftover space in the new pool.
  175539. * The speed vs. space tradeoff is largely determined by the slop values.
  175540. * A different slop value is provided for each pool class (lifetime),
  175541. * and we also distinguish the first pool of a class from later ones.
  175542. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175543. * machines, but may be too small if longs are 64 bits or more.
  175544. */
  175545. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175546. {
  175547. 1600, /* first PERMANENT pool */
  175548. 16000 /* first IMAGE pool */
  175549. };
  175550. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175551. {
  175552. 0, /* additional PERMANENT pools */
  175553. 5000 /* additional IMAGE pools */
  175554. };
  175555. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175556. METHODDEF(void *)
  175557. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175558. /* Allocate a "small" object */
  175559. {
  175560. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175561. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175562. char * data_ptr;
  175563. size_t odd_bytes, min_request, slop;
  175564. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175565. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175566. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175567. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175568. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175569. if (odd_bytes > 0)
  175570. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175571. /* See if space is available in any existing pool */
  175572. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175573. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175574. prev_hdr_ptr = NULL;
  175575. hdr_ptr = mem->small_list[pool_id];
  175576. while (hdr_ptr != NULL) {
  175577. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175578. break; /* found pool with enough space */
  175579. prev_hdr_ptr = hdr_ptr;
  175580. hdr_ptr = hdr_ptr->hdr.next;
  175581. }
  175582. /* Time to make a new pool? */
  175583. if (hdr_ptr == NULL) {
  175584. /* min_request is what we need now, slop is what will be leftover */
  175585. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175586. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175587. slop = first_pool_slop[pool_id];
  175588. else
  175589. slop = extra_pool_slop[pool_id];
  175590. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175591. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175592. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175593. /* Try to get space, if fail reduce slop and try again */
  175594. for (;;) {
  175595. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175596. if (hdr_ptr != NULL)
  175597. break;
  175598. slop /= 2;
  175599. if (slop < MIN_SLOP) /* give up when it gets real small */
  175600. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175601. }
  175602. mem->total_space_allocated += min_request + slop;
  175603. /* Success, initialize the new pool header and add to end of list */
  175604. hdr_ptr->hdr.next = NULL;
  175605. hdr_ptr->hdr.bytes_used = 0;
  175606. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175607. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175608. mem->small_list[pool_id] = hdr_ptr;
  175609. else
  175610. prev_hdr_ptr->hdr.next = hdr_ptr;
  175611. }
  175612. /* OK, allocate the object from the current pool */
  175613. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175614. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175615. hdr_ptr->hdr.bytes_used += sizeofobject;
  175616. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175617. return (void *) data_ptr;
  175618. }
  175619. /*
  175620. * Allocation of "large" objects.
  175621. *
  175622. * The external semantics of these are the same as "small" objects,
  175623. * except that FAR pointers are used on 80x86. However the pool
  175624. * management heuristics are quite different. We assume that each
  175625. * request is large enough that it may as well be passed directly to
  175626. * jpeg_get_large; the pool management just links everything together
  175627. * so that we can free it all on demand.
  175628. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175629. * structures. The routines that create these structures (see below)
  175630. * deliberately bunch rows together to ensure a large request size.
  175631. */
  175632. METHODDEF(void FAR *)
  175633. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175634. /* Allocate a "large" object */
  175635. {
  175636. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175637. large_pool_ptr hdr_ptr;
  175638. size_t odd_bytes;
  175639. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175640. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175641. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175642. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175643. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175644. if (odd_bytes > 0)
  175645. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175646. /* Always make a new pool */
  175647. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175648. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175649. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175650. SIZEOF(large_pool_hdr));
  175651. if (hdr_ptr == NULL)
  175652. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175653. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175654. /* Success, initialize the new pool header and add to list */
  175655. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175656. /* We maintain space counts in each pool header for statistical purposes,
  175657. * even though they are not needed for allocation.
  175658. */
  175659. hdr_ptr->hdr.bytes_used = sizeofobject;
  175660. hdr_ptr->hdr.bytes_left = 0;
  175661. mem->large_list[pool_id] = hdr_ptr;
  175662. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175663. }
  175664. /*
  175665. * Creation of 2-D sample arrays.
  175666. * The pointers are in near heap, the samples themselves in FAR heap.
  175667. *
  175668. * To minimize allocation overhead and to allow I/O of large contiguous
  175669. * blocks, we allocate the sample rows in groups of as many rows as possible
  175670. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175671. * NB: the virtual array control routines, later in this file, know about
  175672. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175673. * object so that it can be saved away if this sarray is the workspace for
  175674. * a virtual array.
  175675. */
  175676. METHODDEF(JSAMPARRAY)
  175677. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175678. JDIMENSION samplesperrow, JDIMENSION numrows)
  175679. /* Allocate a 2-D sample array */
  175680. {
  175681. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175682. JSAMPARRAY result;
  175683. JSAMPROW workspace;
  175684. JDIMENSION rowsperchunk, currow, i;
  175685. long ltemp;
  175686. /* Calculate max # of rows allowed in one allocation chunk */
  175687. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175688. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175689. if (ltemp <= 0)
  175690. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175691. if (ltemp < (long) numrows)
  175692. rowsperchunk = (JDIMENSION) ltemp;
  175693. else
  175694. rowsperchunk = numrows;
  175695. mem->last_rowsperchunk = rowsperchunk;
  175696. /* Get space for row pointers (small object) */
  175697. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175698. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175699. /* Get the rows themselves (large objects) */
  175700. currow = 0;
  175701. while (currow < numrows) {
  175702. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175703. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175704. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175705. * SIZEOF(JSAMPLE)));
  175706. for (i = rowsperchunk; i > 0; i--) {
  175707. result[currow++] = workspace;
  175708. workspace += samplesperrow;
  175709. }
  175710. }
  175711. return result;
  175712. }
  175713. /*
  175714. * Creation of 2-D coefficient-block arrays.
  175715. * This is essentially the same as the code for sample arrays, above.
  175716. */
  175717. METHODDEF(JBLOCKARRAY)
  175718. alloc_barray (j_common_ptr cinfo, int pool_id,
  175719. JDIMENSION blocksperrow, JDIMENSION numrows)
  175720. /* Allocate a 2-D coefficient-block array */
  175721. {
  175722. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175723. JBLOCKARRAY result;
  175724. JBLOCKROW workspace;
  175725. JDIMENSION rowsperchunk, currow, i;
  175726. long ltemp;
  175727. /* Calculate max # of rows allowed in one allocation chunk */
  175728. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175729. ((long) blocksperrow * SIZEOF(JBLOCK));
  175730. if (ltemp <= 0)
  175731. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175732. if (ltemp < (long) numrows)
  175733. rowsperchunk = (JDIMENSION) ltemp;
  175734. else
  175735. rowsperchunk = numrows;
  175736. mem->last_rowsperchunk = rowsperchunk;
  175737. /* Get space for row pointers (small object) */
  175738. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175739. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175740. /* Get the rows themselves (large objects) */
  175741. currow = 0;
  175742. while (currow < numrows) {
  175743. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175744. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175745. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175746. * SIZEOF(JBLOCK)));
  175747. for (i = rowsperchunk; i > 0; i--) {
  175748. result[currow++] = workspace;
  175749. workspace += blocksperrow;
  175750. }
  175751. }
  175752. return result;
  175753. }
  175754. /*
  175755. * About virtual array management:
  175756. *
  175757. * The above "normal" array routines are only used to allocate strip buffers
  175758. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175759. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175760. * time, but the memory manager must save the whole array for repeated
  175761. * accesses. The intended implementation is that there is a strip buffer in
  175762. * memory (as high as is possible given the desired memory limit), plus a
  175763. * backing file that holds the rest of the array.
  175764. *
  175765. * The request_virt_array routines are told the total size of the image and
  175766. * the maximum number of rows that will be accessed at once. The in-memory
  175767. * buffer must be at least as large as the maxaccess value.
  175768. *
  175769. * The request routines create control blocks but not the in-memory buffers.
  175770. * That is postponed until realize_virt_arrays is called. At that time the
  175771. * total amount of space needed is known (approximately, anyway), so free
  175772. * memory can be divided up fairly.
  175773. *
  175774. * The access_virt_array routines are responsible for making a specific strip
  175775. * area accessible (after reading or writing the backing file, if necessary).
  175776. * Note that the access routines are told whether the caller intends to modify
  175777. * the accessed strip; during a read-only pass this saves having to rewrite
  175778. * data to disk. The access routines are also responsible for pre-zeroing
  175779. * any newly accessed rows, if pre-zeroing was requested.
  175780. *
  175781. * In current usage, the access requests are usually for nonoverlapping
  175782. * strips; that is, successive access start_row numbers differ by exactly
  175783. * num_rows = maxaccess. This means we can get good performance with simple
  175784. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175785. * of the access height; then there will never be accesses across bufferload
  175786. * boundaries. The code will still work with overlapping access requests,
  175787. * but it doesn't handle bufferload overlaps very efficiently.
  175788. */
  175789. METHODDEF(jvirt_sarray_ptr)
  175790. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175791. JDIMENSION samplesperrow, JDIMENSION numrows,
  175792. JDIMENSION maxaccess)
  175793. /* Request a virtual 2-D sample array */
  175794. {
  175795. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175796. jvirt_sarray_ptr result;
  175797. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175798. if (pool_id != JPOOL_IMAGE)
  175799. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175800. /* get control block */
  175801. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175802. SIZEOF(struct jvirt_sarray_control));
  175803. result->mem_buffer = NULL; /* marks array not yet realized */
  175804. result->rows_in_array = numrows;
  175805. result->samplesperrow = samplesperrow;
  175806. result->maxaccess = maxaccess;
  175807. result->pre_zero = pre_zero;
  175808. result->b_s_open = FALSE; /* no associated backing-store object */
  175809. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175810. mem->virt_sarray_list = result;
  175811. return result;
  175812. }
  175813. METHODDEF(jvirt_barray_ptr)
  175814. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175815. JDIMENSION blocksperrow, JDIMENSION numrows,
  175816. JDIMENSION maxaccess)
  175817. /* Request a virtual 2-D coefficient-block array */
  175818. {
  175819. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175820. jvirt_barray_ptr result;
  175821. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175822. if (pool_id != JPOOL_IMAGE)
  175823. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175824. /* get control block */
  175825. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  175826. SIZEOF(struct jvirt_barray_control));
  175827. result->mem_buffer = NULL; /* marks array not yet realized */
  175828. result->rows_in_array = numrows;
  175829. result->blocksperrow = blocksperrow;
  175830. result->maxaccess = maxaccess;
  175831. result->pre_zero = pre_zero;
  175832. result->b_s_open = FALSE; /* no associated backing-store object */
  175833. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  175834. mem->virt_barray_list = result;
  175835. return result;
  175836. }
  175837. METHODDEF(void)
  175838. realize_virt_arrays (j_common_ptr cinfo)
  175839. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  175840. {
  175841. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175842. long space_per_minheight, maximum_space, avail_mem;
  175843. long minheights, max_minheights;
  175844. jvirt_sarray_ptr sptr;
  175845. jvirt_barray_ptr bptr;
  175846. /* Compute the minimum space needed (maxaccess rows in each buffer)
  175847. * and the maximum space needed (full image height in each buffer).
  175848. * These may be of use to the system-dependent jpeg_mem_available routine.
  175849. */
  175850. space_per_minheight = 0;
  175851. maximum_space = 0;
  175852. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175853. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175854. space_per_minheight += (long) sptr->maxaccess *
  175855. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175856. maximum_space += (long) sptr->rows_in_array *
  175857. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175858. }
  175859. }
  175860. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175861. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175862. space_per_minheight += (long) bptr->maxaccess *
  175863. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175864. maximum_space += (long) bptr->rows_in_array *
  175865. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175866. }
  175867. }
  175868. if (space_per_minheight <= 0)
  175869. return; /* no unrealized arrays, no work */
  175870. /* Determine amount of memory to actually use; this is system-dependent. */
  175871. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  175872. mem->total_space_allocated);
  175873. /* If the maximum space needed is available, make all the buffers full
  175874. * height; otherwise parcel it out with the same number of minheights
  175875. * in each buffer.
  175876. */
  175877. if (avail_mem >= maximum_space)
  175878. max_minheights = 1000000000L;
  175879. else {
  175880. max_minheights = avail_mem / space_per_minheight;
  175881. /* If there doesn't seem to be enough space, try to get the minimum
  175882. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  175883. */
  175884. if (max_minheights <= 0)
  175885. max_minheights = 1;
  175886. }
  175887. /* Allocate the in-memory buffers and initialize backing store as needed. */
  175888. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175889. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175890. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  175891. if (minheights <= max_minheights) {
  175892. /* This buffer fits in memory */
  175893. sptr->rows_in_mem = sptr->rows_in_array;
  175894. } else {
  175895. /* It doesn't fit in memory, create backing store. */
  175896. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  175897. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  175898. (long) sptr->rows_in_array *
  175899. (long) sptr->samplesperrow *
  175900. (long) SIZEOF(JSAMPLE));
  175901. sptr->b_s_open = TRUE;
  175902. }
  175903. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  175904. sptr->samplesperrow, sptr->rows_in_mem);
  175905. sptr->rowsperchunk = mem->last_rowsperchunk;
  175906. sptr->cur_start_row = 0;
  175907. sptr->first_undef_row = 0;
  175908. sptr->dirty = FALSE;
  175909. }
  175910. }
  175911. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175912. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175913. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  175914. if (minheights <= max_minheights) {
  175915. /* This buffer fits in memory */
  175916. bptr->rows_in_mem = bptr->rows_in_array;
  175917. } else {
  175918. /* It doesn't fit in memory, create backing store. */
  175919. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  175920. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  175921. (long) bptr->rows_in_array *
  175922. (long) bptr->blocksperrow *
  175923. (long) SIZEOF(JBLOCK));
  175924. bptr->b_s_open = TRUE;
  175925. }
  175926. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  175927. bptr->blocksperrow, bptr->rows_in_mem);
  175928. bptr->rowsperchunk = mem->last_rowsperchunk;
  175929. bptr->cur_start_row = 0;
  175930. bptr->first_undef_row = 0;
  175931. bptr->dirty = FALSE;
  175932. }
  175933. }
  175934. }
  175935. LOCAL(void)
  175936. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  175937. /* Do backing store read or write of a virtual sample array */
  175938. {
  175939. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175940. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175941. file_offset = ptr->cur_start_row * bytesperrow;
  175942. /* Loop to read or write each allocation chunk in mem_buffer */
  175943. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175944. /* One chunk, but check for short chunk at end of buffer */
  175945. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175946. /* Transfer no more than is currently defined */
  175947. thisrow = (long) ptr->cur_start_row + i;
  175948. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175949. /* Transfer no more than fits in file */
  175950. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175951. if (rows <= 0) /* this chunk might be past end of file! */
  175952. break;
  175953. byte_count = rows * bytesperrow;
  175954. if (writing)
  175955. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175956. (void FAR *) ptr->mem_buffer[i],
  175957. file_offset, byte_count);
  175958. else
  175959. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175960. (void FAR *) ptr->mem_buffer[i],
  175961. file_offset, byte_count);
  175962. file_offset += byte_count;
  175963. }
  175964. }
  175965. LOCAL(void)
  175966. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  175967. /* Do backing store read or write of a virtual coefficient-block array */
  175968. {
  175969. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175970. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  175971. file_offset = ptr->cur_start_row * bytesperrow;
  175972. /* Loop to read or write each allocation chunk in mem_buffer */
  175973. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175974. /* One chunk, but check for short chunk at end of buffer */
  175975. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175976. /* Transfer no more than is currently defined */
  175977. thisrow = (long) ptr->cur_start_row + i;
  175978. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175979. /* Transfer no more than fits in file */
  175980. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175981. if (rows <= 0) /* this chunk might be past end of file! */
  175982. break;
  175983. byte_count = rows * bytesperrow;
  175984. if (writing)
  175985. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175986. (void FAR *) ptr->mem_buffer[i],
  175987. file_offset, byte_count);
  175988. else
  175989. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175990. (void FAR *) ptr->mem_buffer[i],
  175991. file_offset, byte_count);
  175992. file_offset += byte_count;
  175993. }
  175994. }
  175995. METHODDEF(JSAMPARRAY)
  175996. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  175997. JDIMENSION start_row, JDIMENSION num_rows,
  175998. boolean writable)
  175999. /* Access the part of a virtual sample array starting at start_row */
  176000. /* and extending for num_rows rows. writable is true if */
  176001. /* caller intends to modify the accessed area. */
  176002. {
  176003. JDIMENSION end_row = start_row + num_rows;
  176004. JDIMENSION undef_row;
  176005. /* debugging check */
  176006. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176007. ptr->mem_buffer == NULL)
  176008. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176009. /* Make the desired part of the virtual array accessible */
  176010. if (start_row < ptr->cur_start_row ||
  176011. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176012. if (! ptr->b_s_open)
  176013. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176014. /* Flush old buffer contents if necessary */
  176015. if (ptr->dirty) {
  176016. do_sarray_io(cinfo, ptr, TRUE);
  176017. ptr->dirty = FALSE;
  176018. }
  176019. /* Decide what part of virtual array to access.
  176020. * Algorithm: if target address > current window, assume forward scan,
  176021. * load starting at target address. If target address < current window,
  176022. * assume backward scan, load so that target area is top of window.
  176023. * Note that when switching from forward write to forward read, will have
  176024. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176025. */
  176026. if (start_row > ptr->cur_start_row) {
  176027. ptr->cur_start_row = start_row;
  176028. } else {
  176029. /* use long arithmetic here to avoid overflow & unsigned problems */
  176030. long ltemp;
  176031. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176032. if (ltemp < 0)
  176033. ltemp = 0; /* don't fall off front end of file */
  176034. ptr->cur_start_row = (JDIMENSION) ltemp;
  176035. }
  176036. /* Read in the selected part of the array.
  176037. * During the initial write pass, we will do no actual read
  176038. * because the selected part is all undefined.
  176039. */
  176040. do_sarray_io(cinfo, ptr, FALSE);
  176041. }
  176042. /* Ensure the accessed part of the array is defined; prezero if needed.
  176043. * To improve locality of access, we only prezero the part of the array
  176044. * that the caller is about to access, not the entire in-memory array.
  176045. */
  176046. if (ptr->first_undef_row < end_row) {
  176047. if (ptr->first_undef_row < start_row) {
  176048. if (writable) /* writer skipped over a section of array */
  176049. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176050. undef_row = start_row; /* but reader is allowed to read ahead */
  176051. } else {
  176052. undef_row = ptr->first_undef_row;
  176053. }
  176054. if (writable)
  176055. ptr->first_undef_row = end_row;
  176056. if (ptr->pre_zero) {
  176057. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176058. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176059. end_row -= ptr->cur_start_row;
  176060. while (undef_row < end_row) {
  176061. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176062. undef_row++;
  176063. }
  176064. } else {
  176065. if (! writable) /* reader looking at undefined data */
  176066. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176067. }
  176068. }
  176069. /* Flag the buffer dirty if caller will write in it */
  176070. if (writable)
  176071. ptr->dirty = TRUE;
  176072. /* Return address of proper part of the buffer */
  176073. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176074. }
  176075. METHODDEF(JBLOCKARRAY)
  176076. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176077. JDIMENSION start_row, JDIMENSION num_rows,
  176078. boolean writable)
  176079. /* Access the part of a virtual block array starting at start_row */
  176080. /* and extending for num_rows rows. writable is true if */
  176081. /* caller intends to modify the accessed area. */
  176082. {
  176083. JDIMENSION end_row = start_row + num_rows;
  176084. JDIMENSION undef_row;
  176085. /* debugging check */
  176086. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176087. ptr->mem_buffer == NULL)
  176088. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176089. /* Make the desired part of the virtual array accessible */
  176090. if (start_row < ptr->cur_start_row ||
  176091. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176092. if (! ptr->b_s_open)
  176093. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176094. /* Flush old buffer contents if necessary */
  176095. if (ptr->dirty) {
  176096. do_barray_io(cinfo, ptr, TRUE);
  176097. ptr->dirty = FALSE;
  176098. }
  176099. /* Decide what part of virtual array to access.
  176100. * Algorithm: if target address > current window, assume forward scan,
  176101. * load starting at target address. If target address < current window,
  176102. * assume backward scan, load so that target area is top of window.
  176103. * Note that when switching from forward write to forward read, will have
  176104. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176105. */
  176106. if (start_row > ptr->cur_start_row) {
  176107. ptr->cur_start_row = start_row;
  176108. } else {
  176109. /* use long arithmetic here to avoid overflow & unsigned problems */
  176110. long ltemp;
  176111. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176112. if (ltemp < 0)
  176113. ltemp = 0; /* don't fall off front end of file */
  176114. ptr->cur_start_row = (JDIMENSION) ltemp;
  176115. }
  176116. /* Read in the selected part of the array.
  176117. * During the initial write pass, we will do no actual read
  176118. * because the selected part is all undefined.
  176119. */
  176120. do_barray_io(cinfo, ptr, FALSE);
  176121. }
  176122. /* Ensure the accessed part of the array is defined; prezero if needed.
  176123. * To improve locality of access, we only prezero the part of the array
  176124. * that the caller is about to access, not the entire in-memory array.
  176125. */
  176126. if (ptr->first_undef_row < end_row) {
  176127. if (ptr->first_undef_row < start_row) {
  176128. if (writable) /* writer skipped over a section of array */
  176129. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176130. undef_row = start_row; /* but reader is allowed to read ahead */
  176131. } else {
  176132. undef_row = ptr->first_undef_row;
  176133. }
  176134. if (writable)
  176135. ptr->first_undef_row = end_row;
  176136. if (ptr->pre_zero) {
  176137. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176138. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176139. end_row -= ptr->cur_start_row;
  176140. while (undef_row < end_row) {
  176141. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176142. undef_row++;
  176143. }
  176144. } else {
  176145. if (! writable) /* reader looking at undefined data */
  176146. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176147. }
  176148. }
  176149. /* Flag the buffer dirty if caller will write in it */
  176150. if (writable)
  176151. ptr->dirty = TRUE;
  176152. /* Return address of proper part of the buffer */
  176153. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176154. }
  176155. /*
  176156. * Release all objects belonging to a specified pool.
  176157. */
  176158. METHODDEF(void)
  176159. free_pool (j_common_ptr cinfo, int pool_id)
  176160. {
  176161. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176162. small_pool_ptr shdr_ptr;
  176163. large_pool_ptr lhdr_ptr;
  176164. size_t space_freed;
  176165. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176166. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176167. #ifdef MEM_STATS
  176168. if (cinfo->err->trace_level > 1)
  176169. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176170. #endif
  176171. /* If freeing IMAGE pool, close any virtual arrays first */
  176172. if (pool_id == JPOOL_IMAGE) {
  176173. jvirt_sarray_ptr sptr;
  176174. jvirt_barray_ptr bptr;
  176175. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176176. if (sptr->b_s_open) { /* there may be no backing store */
  176177. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176178. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176179. }
  176180. }
  176181. mem->virt_sarray_list = NULL;
  176182. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176183. if (bptr->b_s_open) { /* there may be no backing store */
  176184. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176185. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176186. }
  176187. }
  176188. mem->virt_barray_list = NULL;
  176189. }
  176190. /* Release large objects */
  176191. lhdr_ptr = mem->large_list[pool_id];
  176192. mem->large_list[pool_id] = NULL;
  176193. while (lhdr_ptr != NULL) {
  176194. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176195. space_freed = lhdr_ptr->hdr.bytes_used +
  176196. lhdr_ptr->hdr.bytes_left +
  176197. SIZEOF(large_pool_hdr);
  176198. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176199. mem->total_space_allocated -= space_freed;
  176200. lhdr_ptr = next_lhdr_ptr;
  176201. }
  176202. /* Release small objects */
  176203. shdr_ptr = mem->small_list[pool_id];
  176204. mem->small_list[pool_id] = NULL;
  176205. while (shdr_ptr != NULL) {
  176206. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176207. space_freed = shdr_ptr->hdr.bytes_used +
  176208. shdr_ptr->hdr.bytes_left +
  176209. SIZEOF(small_pool_hdr);
  176210. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176211. mem->total_space_allocated -= space_freed;
  176212. shdr_ptr = next_shdr_ptr;
  176213. }
  176214. }
  176215. /*
  176216. * Close up shop entirely.
  176217. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176218. */
  176219. METHODDEF(void)
  176220. self_destruct (j_common_ptr cinfo)
  176221. {
  176222. int pool;
  176223. /* Close all backing store, release all memory.
  176224. * Releasing pools in reverse order might help avoid fragmentation
  176225. * with some (brain-damaged) malloc libraries.
  176226. */
  176227. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176228. free_pool(cinfo, pool);
  176229. }
  176230. /* Release the memory manager control block too. */
  176231. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176232. cinfo->mem = NULL; /* ensures I will be called only once */
  176233. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176234. }
  176235. /*
  176236. * Memory manager initialization.
  176237. * When this is called, only the error manager pointer is valid in cinfo!
  176238. */
  176239. GLOBAL(void)
  176240. jinit_memory_mgr (j_common_ptr cinfo)
  176241. {
  176242. my_mem_ptr mem;
  176243. long max_to_use;
  176244. int pool;
  176245. size_t test_mac;
  176246. cinfo->mem = NULL; /* for safety if init fails */
  176247. /* Check for configuration errors.
  176248. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176249. * doesn't reflect any real hardware alignment requirement.
  176250. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176251. * in common if and only if X is a power of 2, ie has only one one-bit.
  176252. * Some compilers may give an "unreachable code" warning here; ignore it.
  176253. */
  176254. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176255. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176256. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176257. * a multiple of SIZEOF(ALIGN_TYPE).
  176258. * Again, an "unreachable code" warning may be ignored here.
  176259. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176260. */
  176261. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176262. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176263. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176264. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176265. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176266. /* Attempt to allocate memory manager's control block */
  176267. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176268. if (mem == NULL) {
  176269. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176270. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176271. }
  176272. /* OK, fill in the method pointers */
  176273. mem->pub.alloc_small = alloc_small;
  176274. mem->pub.alloc_large = alloc_large;
  176275. mem->pub.alloc_sarray = alloc_sarray;
  176276. mem->pub.alloc_barray = alloc_barray;
  176277. mem->pub.request_virt_sarray = request_virt_sarray;
  176278. mem->pub.request_virt_barray = request_virt_barray;
  176279. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176280. mem->pub.access_virt_sarray = access_virt_sarray;
  176281. mem->pub.access_virt_barray = access_virt_barray;
  176282. mem->pub.free_pool = free_pool;
  176283. mem->pub.self_destruct = self_destruct;
  176284. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176285. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176286. /* Initialize working state */
  176287. mem->pub.max_memory_to_use = max_to_use;
  176288. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176289. mem->small_list[pool] = NULL;
  176290. mem->large_list[pool] = NULL;
  176291. }
  176292. mem->virt_sarray_list = NULL;
  176293. mem->virt_barray_list = NULL;
  176294. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176295. /* Declare ourselves open for business */
  176296. cinfo->mem = & mem->pub;
  176297. /* Check for an environment variable JPEGMEM; if found, override the
  176298. * default max_memory setting from jpeg_mem_init. Note that the
  176299. * surrounding application may again override this value.
  176300. * If your system doesn't support getenv(), define NO_GETENV to disable
  176301. * this feature.
  176302. */
  176303. #ifndef NO_GETENV
  176304. { char * memenv;
  176305. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176306. char ch = 'x';
  176307. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176308. if (ch == 'm' || ch == 'M')
  176309. max_to_use *= 1000L;
  176310. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176311. }
  176312. }
  176313. }
  176314. #endif
  176315. }
  176316. /*** End of inlined file: jmemmgr.c ***/
  176317. /*** Start of inlined file: jmemnobs.c ***/
  176318. #define JPEG_INTERNALS
  176319. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176320. extern void * malloc JPP((size_t size));
  176321. extern void free JPP((void *ptr));
  176322. #endif
  176323. /*
  176324. * Memory allocation and freeing are controlled by the regular library
  176325. * routines malloc() and free().
  176326. */
  176327. GLOBAL(void *)
  176328. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176329. {
  176330. return (void *) malloc(sizeofobject);
  176331. }
  176332. GLOBAL(void)
  176333. jpeg_free_small (j_common_ptr , void * object, size_t)
  176334. {
  176335. free(object);
  176336. }
  176337. /*
  176338. * "Large" objects are treated the same as "small" ones.
  176339. * NB: although we include FAR keywords in the routine declarations,
  176340. * this file won't actually work in 80x86 small/medium model; at least,
  176341. * you probably won't be able to process useful-size images in only 64KB.
  176342. */
  176343. GLOBAL(void FAR *)
  176344. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176345. {
  176346. return (void FAR *) malloc(sizeofobject);
  176347. }
  176348. GLOBAL(void)
  176349. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176350. {
  176351. free(object);
  176352. }
  176353. /*
  176354. * This routine computes the total memory space available for allocation.
  176355. * Here we always say, "we got all you want bud!"
  176356. */
  176357. GLOBAL(long)
  176358. jpeg_mem_available (j_common_ptr, long,
  176359. long max_bytes_needed, long)
  176360. {
  176361. return max_bytes_needed;
  176362. }
  176363. /*
  176364. * Backing store (temporary file) management.
  176365. * Since jpeg_mem_available always promised the moon,
  176366. * this should never be called and we can just error out.
  176367. */
  176368. GLOBAL(void)
  176369. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176370. long )
  176371. {
  176372. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176373. }
  176374. /*
  176375. * These routines take care of any system-dependent initialization and
  176376. * cleanup required. Here, there isn't any.
  176377. */
  176378. GLOBAL(long)
  176379. jpeg_mem_init (j_common_ptr)
  176380. {
  176381. return 0; /* just set max_memory_to_use to 0 */
  176382. }
  176383. GLOBAL(void)
  176384. jpeg_mem_term (j_common_ptr)
  176385. {
  176386. /* no work */
  176387. }
  176388. /*** End of inlined file: jmemnobs.c ***/
  176389. /*** Start of inlined file: jquant1.c ***/
  176390. #define JPEG_INTERNALS
  176391. #ifdef QUANT_1PASS_SUPPORTED
  176392. /*
  176393. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176394. * high quality, colormapped output capability. A 2-pass quantizer usually
  176395. * gives better visual quality; however, for quantized grayscale output this
  176396. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176397. * quantizer, though you can turn it off if you really want to.
  176398. *
  176399. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176400. * image. We use a map consisting of all combinations of Ncolors[i] color
  176401. * values for the i'th component. The Ncolors[] values are chosen so that
  176402. * their product, the total number of colors, is no more than that requested.
  176403. * (In most cases, the product will be somewhat less.)
  176404. *
  176405. * Since the colormap is orthogonal, the representative value for each color
  176406. * component can be determined without considering the other components;
  176407. * then these indexes can be combined into a colormap index by a standard
  176408. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176409. * can be precalculated and stored in the lookup table colorindex[].
  176410. * colorindex[i][j] maps pixel value j in component i to the nearest
  176411. * representative value (grid plane) for that component; this index is
  176412. * multiplied by the array stride for component i, so that the
  176413. * index of the colormap entry closest to a given pixel value is just
  176414. * sum( colorindex[component-number][pixel-component-value] )
  176415. * Aside from being fast, this scheme allows for variable spacing between
  176416. * representative values with no additional lookup cost.
  176417. *
  176418. * If gamma correction has been applied in color conversion, it might be wise
  176419. * to adjust the color grid spacing so that the representative colors are
  176420. * equidistant in linear space. At this writing, gamma correction is not
  176421. * implemented by jdcolor, so nothing is done here.
  176422. */
  176423. /* Declarations for ordered dithering.
  176424. *
  176425. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176426. * dithering is described in many references, for instance Dale Schumacher's
  176427. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176428. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176429. * "dither" value to the input pixel and then round the result to the nearest
  176430. * output value. The dither value is equivalent to (0.5 - threshold) times
  176431. * the distance between output values. For ordered dithering, we assume that
  176432. * the output colors are equally spaced; if not, results will probably be
  176433. * worse, since the dither may be too much or too little at a given point.
  176434. *
  176435. * The normal calculation would be to form pixel value + dither, range-limit
  176436. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176437. * We can skip the separate range-limiting step by extending the colorindex
  176438. * table in both directions.
  176439. */
  176440. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176441. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176442. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176443. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176444. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176445. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176446. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176447. /* Bayer's order-4 dither array. Generated by the code given in
  176448. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176449. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176450. */
  176451. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176452. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176453. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176454. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176455. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176456. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176457. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176458. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176459. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176460. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176461. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176462. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176463. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176464. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176465. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176466. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176467. };
  176468. /* Declarations for Floyd-Steinberg dithering.
  176469. *
  176470. * Errors are accumulated into the array fserrors[], at a resolution of
  176471. * 1/16th of a pixel count. The error at a given pixel is propagated
  176472. * to its not-yet-processed neighbors using the standard F-S fractions,
  176473. * ... (here) 7/16
  176474. * 3/16 5/16 1/16
  176475. * We work left-to-right on even rows, right-to-left on odd rows.
  176476. *
  176477. * We can get away with a single array (holding one row's worth of errors)
  176478. * by using it to store the current row's errors at pixel columns not yet
  176479. * processed, but the next row's errors at columns already processed. We
  176480. * need only a few extra variables to hold the errors immediately around the
  176481. * current column. (If we are lucky, those variables are in registers, but
  176482. * even if not, they're probably cheaper to access than array elements are.)
  176483. *
  176484. * The fserrors[] array is indexed [component#][position].
  176485. * We provide (#columns + 2) entries per component; the extra entry at each
  176486. * end saves us from special-casing the first and last pixels.
  176487. *
  176488. * Note: on a wide image, we might not have enough room in a PC's near data
  176489. * segment to hold the error array; so it is allocated with alloc_large.
  176490. */
  176491. #if BITS_IN_JSAMPLE == 8
  176492. typedef INT16 FSERROR; /* 16 bits should be enough */
  176493. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176494. #else
  176495. typedef INT32 FSERROR; /* may need more than 16 bits */
  176496. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176497. #endif
  176498. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176499. /* Private subobject */
  176500. #define MAX_Q_COMPS 4 /* max components I can handle */
  176501. typedef struct {
  176502. struct jpeg_color_quantizer pub; /* public fields */
  176503. /* Initially allocated colormap is saved here */
  176504. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176505. int sv_actual; /* number of entries in use */
  176506. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176507. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176508. * premultiplied as described above. Since colormap indexes must fit into
  176509. * JSAMPLEs, the entries of this array will too.
  176510. */
  176511. boolean is_padded; /* is the colorindex padded for odither? */
  176512. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176513. /* Variables for ordered dithering */
  176514. int row_index; /* cur row's vertical index in dither matrix */
  176515. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176516. /* Variables for Floyd-Steinberg dithering */
  176517. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176518. boolean on_odd_row; /* flag to remember which row we are on */
  176519. } my_cquantizer;
  176520. typedef my_cquantizer * my_cquantize_ptr;
  176521. /*
  176522. * Policy-making subroutines for create_colormap and create_colorindex.
  176523. * These routines determine the colormap to be used. The rest of the module
  176524. * only assumes that the colormap is orthogonal.
  176525. *
  176526. * * select_ncolors decides how to divvy up the available colors
  176527. * among the components.
  176528. * * output_value defines the set of representative values for a component.
  176529. * * largest_input_value defines the mapping from input values to
  176530. * representative values for a component.
  176531. * Note that the latter two routines may impose different policies for
  176532. * different components, though this is not currently done.
  176533. */
  176534. LOCAL(int)
  176535. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176536. /* Determine allocation of desired colors to components, */
  176537. /* and fill in Ncolors[] array to indicate choice. */
  176538. /* Return value is total number of colors (product of Ncolors[] values). */
  176539. {
  176540. int nc = cinfo->out_color_components; /* number of color components */
  176541. int max_colors = cinfo->desired_number_of_colors;
  176542. int total_colors, iroot, i, j;
  176543. boolean changed;
  176544. long temp;
  176545. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176546. /* We can allocate at least the nc'th root of max_colors per component. */
  176547. /* Compute floor(nc'th root of max_colors). */
  176548. iroot = 1;
  176549. do {
  176550. iroot++;
  176551. temp = iroot; /* set temp = iroot ** nc */
  176552. for (i = 1; i < nc; i++)
  176553. temp *= iroot;
  176554. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176555. iroot--; /* now iroot = floor(root) */
  176556. /* Must have at least 2 color values per component */
  176557. if (iroot < 2)
  176558. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176559. /* Initialize to iroot color values for each component */
  176560. total_colors = 1;
  176561. for (i = 0; i < nc; i++) {
  176562. Ncolors[i] = iroot;
  176563. total_colors *= iroot;
  176564. }
  176565. /* We may be able to increment the count for one or more components without
  176566. * exceeding max_colors, though we know not all can be incremented.
  176567. * Sometimes, the first component can be incremented more than once!
  176568. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176569. * In RGB colorspace, try to increment G first, then R, then B.
  176570. */
  176571. do {
  176572. changed = FALSE;
  176573. for (i = 0; i < nc; i++) {
  176574. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176575. /* calculate new total_colors if Ncolors[j] is incremented */
  176576. temp = total_colors / Ncolors[j];
  176577. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176578. if (temp > (long) max_colors)
  176579. break; /* won't fit, done with this pass */
  176580. Ncolors[j]++; /* OK, apply the increment */
  176581. total_colors = (int) temp;
  176582. changed = TRUE;
  176583. }
  176584. } while (changed);
  176585. return total_colors;
  176586. }
  176587. LOCAL(int)
  176588. output_value (j_decompress_ptr, int, int j, int maxj)
  176589. /* Return j'th output value, where j will range from 0 to maxj */
  176590. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176591. {
  176592. /* We always provide values 0 and MAXJSAMPLE for each component;
  176593. * any additional values are equally spaced between these limits.
  176594. * (Forcing the upper and lower values to the limits ensures that
  176595. * dithering can't produce a color outside the selected gamut.)
  176596. */
  176597. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176598. }
  176599. LOCAL(int)
  176600. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176601. /* Return largest input value that should map to j'th output value */
  176602. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176603. {
  176604. /* Breakpoints are halfway between values returned by output_value */
  176605. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176606. }
  176607. /*
  176608. * Create the colormap.
  176609. */
  176610. LOCAL(void)
  176611. create_colormap (j_decompress_ptr cinfo)
  176612. {
  176613. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176614. JSAMPARRAY colormap; /* Created colormap */
  176615. int total_colors; /* Number of distinct output colors */
  176616. int i,j,k, nci, blksize, blkdist, ptr, val;
  176617. /* Select number of colors for each component */
  176618. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176619. /* Report selected color counts */
  176620. if (cinfo->out_color_components == 3)
  176621. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176622. total_colors, cquantize->Ncolors[0],
  176623. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176624. else
  176625. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176626. /* Allocate and fill in the colormap. */
  176627. /* The colors are ordered in the map in standard row-major order, */
  176628. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176629. colormap = (*cinfo->mem->alloc_sarray)
  176630. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176631. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176632. /* blksize is number of adjacent repeated entries for a component */
  176633. /* blkdist is distance between groups of identical entries for a component */
  176634. blkdist = total_colors;
  176635. for (i = 0; i < cinfo->out_color_components; i++) {
  176636. /* fill in colormap entries for i'th color component */
  176637. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176638. blksize = blkdist / nci;
  176639. for (j = 0; j < nci; j++) {
  176640. /* Compute j'th output value (out of nci) for component */
  176641. val = output_value(cinfo, i, j, nci-1);
  176642. /* Fill in all colormap entries that have this value of this component */
  176643. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176644. /* fill in blksize entries beginning at ptr */
  176645. for (k = 0; k < blksize; k++)
  176646. colormap[i][ptr+k] = (JSAMPLE) val;
  176647. }
  176648. }
  176649. blkdist = blksize; /* blksize of this color is blkdist of next */
  176650. }
  176651. /* Save the colormap in private storage,
  176652. * where it will survive color quantization mode changes.
  176653. */
  176654. cquantize->sv_colormap = colormap;
  176655. cquantize->sv_actual = total_colors;
  176656. }
  176657. /*
  176658. * Create the color index table.
  176659. */
  176660. LOCAL(void)
  176661. create_colorindex (j_decompress_ptr cinfo)
  176662. {
  176663. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176664. JSAMPROW indexptr;
  176665. int i,j,k, nci, blksize, val, pad;
  176666. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176667. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176668. * This is not necessary in the other dithering modes. However, we
  176669. * flag whether it was done in case user changes dithering mode.
  176670. */
  176671. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176672. pad = MAXJSAMPLE*2;
  176673. cquantize->is_padded = TRUE;
  176674. } else {
  176675. pad = 0;
  176676. cquantize->is_padded = FALSE;
  176677. }
  176678. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176679. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176680. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176681. (JDIMENSION) cinfo->out_color_components);
  176682. /* blksize is number of adjacent repeated entries for a component */
  176683. blksize = cquantize->sv_actual;
  176684. for (i = 0; i < cinfo->out_color_components; i++) {
  176685. /* fill in colorindex entries for i'th color component */
  176686. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176687. blksize = blksize / nci;
  176688. /* adjust colorindex pointers to provide padding at negative indexes. */
  176689. if (pad)
  176690. cquantize->colorindex[i] += MAXJSAMPLE;
  176691. /* in loop, val = index of current output value, */
  176692. /* and k = largest j that maps to current val */
  176693. indexptr = cquantize->colorindex[i];
  176694. val = 0;
  176695. k = largest_input_value(cinfo, i, 0, nci-1);
  176696. for (j = 0; j <= MAXJSAMPLE; j++) {
  176697. while (j > k) /* advance val if past boundary */
  176698. k = largest_input_value(cinfo, i, ++val, nci-1);
  176699. /* premultiply so that no multiplication needed in main processing */
  176700. indexptr[j] = (JSAMPLE) (val * blksize);
  176701. }
  176702. /* Pad at both ends if necessary */
  176703. if (pad)
  176704. for (j = 1; j <= MAXJSAMPLE; j++) {
  176705. indexptr[-j] = indexptr[0];
  176706. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176707. }
  176708. }
  176709. }
  176710. /*
  176711. * Create an ordered-dither array for a component having ncolors
  176712. * distinct output values.
  176713. */
  176714. LOCAL(ODITHER_MATRIX_PTR)
  176715. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176716. {
  176717. ODITHER_MATRIX_PTR odither;
  176718. int j,k;
  176719. INT32 num,den;
  176720. odither = (ODITHER_MATRIX_PTR)
  176721. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176722. SIZEOF(ODITHER_MATRIX));
  176723. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176724. * Hence the dither value for the matrix cell with fill order f
  176725. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176726. * On 16-bit-int machine, be careful to avoid overflow.
  176727. */
  176728. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176729. for (j = 0; j < ODITHER_SIZE; j++) {
  176730. for (k = 0; k < ODITHER_SIZE; k++) {
  176731. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176732. * MAXJSAMPLE;
  176733. /* Ensure round towards zero despite C's lack of consistency
  176734. * about rounding negative values in integer division...
  176735. */
  176736. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176737. }
  176738. }
  176739. return odither;
  176740. }
  176741. /*
  176742. * Create the ordered-dither tables.
  176743. * Components having the same number of representative colors may
  176744. * share a dither table.
  176745. */
  176746. LOCAL(void)
  176747. create_odither_tables (j_decompress_ptr cinfo)
  176748. {
  176749. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176750. ODITHER_MATRIX_PTR odither;
  176751. int i, j, nci;
  176752. for (i = 0; i < cinfo->out_color_components; i++) {
  176753. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176754. odither = NULL; /* search for matching prior component */
  176755. for (j = 0; j < i; j++) {
  176756. if (nci == cquantize->Ncolors[j]) {
  176757. odither = cquantize->odither[j];
  176758. break;
  176759. }
  176760. }
  176761. if (odither == NULL) /* need a new table? */
  176762. odither = make_odither_array(cinfo, nci);
  176763. cquantize->odither[i] = odither;
  176764. }
  176765. }
  176766. /*
  176767. * Map some rows of pixels to the output colormapped representation.
  176768. */
  176769. METHODDEF(void)
  176770. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176771. JSAMPARRAY output_buf, int num_rows)
  176772. /* General case, no dithering */
  176773. {
  176774. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176775. JSAMPARRAY colorindex = cquantize->colorindex;
  176776. register int pixcode, ci;
  176777. register JSAMPROW ptrin, ptrout;
  176778. int row;
  176779. JDIMENSION col;
  176780. JDIMENSION width = cinfo->output_width;
  176781. register int nc = cinfo->out_color_components;
  176782. for (row = 0; row < num_rows; row++) {
  176783. ptrin = input_buf[row];
  176784. ptrout = output_buf[row];
  176785. for (col = width; col > 0; col--) {
  176786. pixcode = 0;
  176787. for (ci = 0; ci < nc; ci++) {
  176788. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176789. }
  176790. *ptrout++ = (JSAMPLE) pixcode;
  176791. }
  176792. }
  176793. }
  176794. METHODDEF(void)
  176795. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176796. JSAMPARRAY output_buf, int num_rows)
  176797. /* Fast path for out_color_components==3, no dithering */
  176798. {
  176799. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176800. register int pixcode;
  176801. register JSAMPROW ptrin, ptrout;
  176802. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176803. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176804. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176805. int row;
  176806. JDIMENSION col;
  176807. JDIMENSION width = cinfo->output_width;
  176808. for (row = 0; row < num_rows; row++) {
  176809. ptrin = input_buf[row];
  176810. ptrout = output_buf[row];
  176811. for (col = width; col > 0; col--) {
  176812. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176813. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176814. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176815. *ptrout++ = (JSAMPLE) pixcode;
  176816. }
  176817. }
  176818. }
  176819. METHODDEF(void)
  176820. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176821. JSAMPARRAY output_buf, int num_rows)
  176822. /* General case, with ordered dithering */
  176823. {
  176824. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176825. register JSAMPROW input_ptr;
  176826. register JSAMPROW output_ptr;
  176827. JSAMPROW colorindex_ci;
  176828. int * dither; /* points to active row of dither matrix */
  176829. int row_index, col_index; /* current indexes into dither matrix */
  176830. int nc = cinfo->out_color_components;
  176831. int ci;
  176832. int row;
  176833. JDIMENSION col;
  176834. JDIMENSION width = cinfo->output_width;
  176835. for (row = 0; row < num_rows; row++) {
  176836. /* Initialize output values to 0 so can process components separately */
  176837. jzero_far((void FAR *) output_buf[row],
  176838. (size_t) (width * SIZEOF(JSAMPLE)));
  176839. row_index = cquantize->row_index;
  176840. for (ci = 0; ci < nc; ci++) {
  176841. input_ptr = input_buf[row] + ci;
  176842. output_ptr = output_buf[row];
  176843. colorindex_ci = cquantize->colorindex[ci];
  176844. dither = cquantize->odither[ci][row_index];
  176845. col_index = 0;
  176846. for (col = width; col > 0; col--) {
  176847. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  176848. * select output value, accumulate into output code for this pixel.
  176849. * Range-limiting need not be done explicitly, as we have extended
  176850. * the colorindex table to produce the right answers for out-of-range
  176851. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  176852. * required amount of padding.
  176853. */
  176854. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  176855. input_ptr += nc;
  176856. output_ptr++;
  176857. col_index = (col_index + 1) & ODITHER_MASK;
  176858. }
  176859. }
  176860. /* Advance row index for next row */
  176861. row_index = (row_index + 1) & ODITHER_MASK;
  176862. cquantize->row_index = row_index;
  176863. }
  176864. }
  176865. METHODDEF(void)
  176866. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176867. JSAMPARRAY output_buf, int num_rows)
  176868. /* Fast path for out_color_components==3, with ordered dithering */
  176869. {
  176870. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176871. register int pixcode;
  176872. register JSAMPROW input_ptr;
  176873. register JSAMPROW output_ptr;
  176874. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176875. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176876. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176877. int * dither0; /* points to active row of dither matrix */
  176878. int * dither1;
  176879. int * dither2;
  176880. int row_index, col_index; /* current indexes into dither matrix */
  176881. int row;
  176882. JDIMENSION col;
  176883. JDIMENSION width = cinfo->output_width;
  176884. for (row = 0; row < num_rows; row++) {
  176885. row_index = cquantize->row_index;
  176886. input_ptr = input_buf[row];
  176887. output_ptr = output_buf[row];
  176888. dither0 = cquantize->odither[0][row_index];
  176889. dither1 = cquantize->odither[1][row_index];
  176890. dither2 = cquantize->odither[2][row_index];
  176891. col_index = 0;
  176892. for (col = width; col > 0; col--) {
  176893. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  176894. dither0[col_index]]);
  176895. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  176896. dither1[col_index]]);
  176897. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  176898. dither2[col_index]]);
  176899. *output_ptr++ = (JSAMPLE) pixcode;
  176900. col_index = (col_index + 1) & ODITHER_MASK;
  176901. }
  176902. row_index = (row_index + 1) & ODITHER_MASK;
  176903. cquantize->row_index = row_index;
  176904. }
  176905. }
  176906. METHODDEF(void)
  176907. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176908. JSAMPARRAY output_buf, int num_rows)
  176909. /* General case, with Floyd-Steinberg dithering */
  176910. {
  176911. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176912. register LOCFSERROR cur; /* current error or pixel value */
  176913. LOCFSERROR belowerr; /* error for pixel below cur */
  176914. LOCFSERROR bpreverr; /* error for below/prev col */
  176915. LOCFSERROR bnexterr; /* error for below/next col */
  176916. LOCFSERROR delta;
  176917. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  176918. register JSAMPROW input_ptr;
  176919. register JSAMPROW output_ptr;
  176920. JSAMPROW colorindex_ci;
  176921. JSAMPROW colormap_ci;
  176922. int pixcode;
  176923. int nc = cinfo->out_color_components;
  176924. int dir; /* 1 for left-to-right, -1 for right-to-left */
  176925. int dirnc; /* dir * nc */
  176926. int ci;
  176927. int row;
  176928. JDIMENSION col;
  176929. JDIMENSION width = cinfo->output_width;
  176930. JSAMPLE *range_limit = cinfo->sample_range_limit;
  176931. SHIFT_TEMPS
  176932. for (row = 0; row < num_rows; row++) {
  176933. /* Initialize output values to 0 so can process components separately */
  176934. jzero_far((void FAR *) output_buf[row],
  176935. (size_t) (width * SIZEOF(JSAMPLE)));
  176936. for (ci = 0; ci < nc; ci++) {
  176937. input_ptr = input_buf[row] + ci;
  176938. output_ptr = output_buf[row];
  176939. if (cquantize->on_odd_row) {
  176940. /* work right to left in this row */
  176941. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  176942. output_ptr += width-1;
  176943. dir = -1;
  176944. dirnc = -nc;
  176945. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  176946. } else {
  176947. /* work left to right in this row */
  176948. dir = 1;
  176949. dirnc = nc;
  176950. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  176951. }
  176952. colorindex_ci = cquantize->colorindex[ci];
  176953. colormap_ci = cquantize->sv_colormap[ci];
  176954. /* Preset error values: no error propagated to first pixel from left */
  176955. cur = 0;
  176956. /* and no error propagated to row below yet */
  176957. belowerr = bpreverr = 0;
  176958. for (col = width; col > 0; col--) {
  176959. /* cur holds the error propagated from the previous pixel on the
  176960. * current line. Add the error propagated from the previous line
  176961. * to form the complete error correction term for this pixel, and
  176962. * round the error term (which is expressed * 16) to an integer.
  176963. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  176964. * for either sign of the error value.
  176965. * Note: errorptr points to *previous* column's array entry.
  176966. */
  176967. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  176968. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  176969. * The maximum error is +- MAXJSAMPLE; this sets the required size
  176970. * of the range_limit array.
  176971. */
  176972. cur += GETJSAMPLE(*input_ptr);
  176973. cur = GETJSAMPLE(range_limit[cur]);
  176974. /* Select output value, accumulate into output code for this pixel */
  176975. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  176976. *output_ptr += (JSAMPLE) pixcode;
  176977. /* Compute actual representation error at this pixel */
  176978. /* Note: we can do this even though we don't have the final */
  176979. /* pixel code, because the colormap is orthogonal. */
  176980. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  176981. /* Compute error fractions to be propagated to adjacent pixels.
  176982. * Add these into the running sums, and simultaneously shift the
  176983. * next-line error sums left by 1 column.
  176984. */
  176985. bnexterr = cur;
  176986. delta = cur * 2;
  176987. cur += delta; /* form error * 3 */
  176988. errorptr[0] = (FSERROR) (bpreverr + cur);
  176989. cur += delta; /* form error * 5 */
  176990. bpreverr = belowerr + cur;
  176991. belowerr = bnexterr;
  176992. cur += delta; /* form error * 7 */
  176993. /* At this point cur contains the 7/16 error value to be propagated
  176994. * to the next pixel on the current line, and all the errors for the
  176995. * next line have been shifted over. We are therefore ready to move on.
  176996. */
  176997. input_ptr += dirnc; /* advance input ptr to next column */
  176998. output_ptr += dir; /* advance output ptr to next column */
  176999. errorptr += dir; /* advance errorptr to current column */
  177000. }
  177001. /* Post-loop cleanup: we must unload the final error value into the
  177002. * final fserrors[] entry. Note we need not unload belowerr because
  177003. * it is for the dummy column before or after the actual array.
  177004. */
  177005. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177006. }
  177007. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177008. }
  177009. }
  177010. /*
  177011. * Allocate workspace for Floyd-Steinberg errors.
  177012. */
  177013. LOCAL(void)
  177014. alloc_fs_workspace (j_decompress_ptr cinfo)
  177015. {
  177016. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177017. size_t arraysize;
  177018. int i;
  177019. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177020. for (i = 0; i < cinfo->out_color_components; i++) {
  177021. cquantize->fserrors[i] = (FSERRPTR)
  177022. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177023. }
  177024. }
  177025. /*
  177026. * Initialize for one-pass color quantization.
  177027. */
  177028. METHODDEF(void)
  177029. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177030. {
  177031. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177032. size_t arraysize;
  177033. int i;
  177034. /* Install my colormap. */
  177035. cinfo->colormap = cquantize->sv_colormap;
  177036. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177037. /* Initialize for desired dithering mode. */
  177038. switch (cinfo->dither_mode) {
  177039. case JDITHER_NONE:
  177040. if (cinfo->out_color_components == 3)
  177041. cquantize->pub.color_quantize = color_quantize3;
  177042. else
  177043. cquantize->pub.color_quantize = color_quantize;
  177044. break;
  177045. case JDITHER_ORDERED:
  177046. if (cinfo->out_color_components == 3)
  177047. cquantize->pub.color_quantize = quantize3_ord_dither;
  177048. else
  177049. cquantize->pub.color_quantize = quantize_ord_dither;
  177050. cquantize->row_index = 0; /* initialize state for ordered dither */
  177051. /* If user changed to ordered dither from another mode,
  177052. * we must recreate the color index table with padding.
  177053. * This will cost extra space, but probably isn't very likely.
  177054. */
  177055. if (! cquantize->is_padded)
  177056. create_colorindex(cinfo);
  177057. /* Create ordered-dither tables if we didn't already. */
  177058. if (cquantize->odither[0] == NULL)
  177059. create_odither_tables(cinfo);
  177060. break;
  177061. case JDITHER_FS:
  177062. cquantize->pub.color_quantize = quantize_fs_dither;
  177063. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177064. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177065. if (cquantize->fserrors[0] == NULL)
  177066. alloc_fs_workspace(cinfo);
  177067. /* Initialize the propagated errors to zero. */
  177068. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177069. for (i = 0; i < cinfo->out_color_components; i++)
  177070. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177071. break;
  177072. default:
  177073. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177074. break;
  177075. }
  177076. }
  177077. /*
  177078. * Finish up at the end of the pass.
  177079. */
  177080. METHODDEF(void)
  177081. finish_pass_1_quant (j_decompress_ptr)
  177082. {
  177083. /* no work in 1-pass case */
  177084. }
  177085. /*
  177086. * Switch to a new external colormap between output passes.
  177087. * Shouldn't get to this module!
  177088. */
  177089. METHODDEF(void)
  177090. new_color_map_1_quant (j_decompress_ptr cinfo)
  177091. {
  177092. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177093. }
  177094. /*
  177095. * Module initialization routine for 1-pass color quantization.
  177096. */
  177097. GLOBAL(void)
  177098. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177099. {
  177100. my_cquantize_ptr cquantize;
  177101. cquantize = (my_cquantize_ptr)
  177102. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177103. SIZEOF(my_cquantizer));
  177104. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177105. cquantize->pub.start_pass = start_pass_1_quant;
  177106. cquantize->pub.finish_pass = finish_pass_1_quant;
  177107. cquantize->pub.new_color_map = new_color_map_1_quant;
  177108. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177109. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177110. /* Make sure my internal arrays won't overflow */
  177111. if (cinfo->out_color_components > MAX_Q_COMPS)
  177112. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177113. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177114. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177115. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177116. /* Create the colormap and color index table. */
  177117. create_colormap(cinfo);
  177118. create_colorindex(cinfo);
  177119. /* Allocate Floyd-Steinberg workspace now if requested.
  177120. * We do this now since it is FAR storage and may affect the memory
  177121. * manager's space calculations. If the user changes to FS dither
  177122. * mode in a later pass, we will allocate the space then, and will
  177123. * possibly overrun the max_memory_to_use setting.
  177124. */
  177125. if (cinfo->dither_mode == JDITHER_FS)
  177126. alloc_fs_workspace(cinfo);
  177127. }
  177128. #endif /* QUANT_1PASS_SUPPORTED */
  177129. /*** End of inlined file: jquant1.c ***/
  177130. /*** Start of inlined file: jquant2.c ***/
  177131. #define JPEG_INTERNALS
  177132. #ifdef QUANT_2PASS_SUPPORTED
  177133. /*
  177134. * This module implements the well-known Heckbert paradigm for color
  177135. * quantization. Most of the ideas used here can be traced back to
  177136. * Heckbert's seminal paper
  177137. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177138. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177139. *
  177140. * In the first pass over the image, we accumulate a histogram showing the
  177141. * usage count of each possible color. To keep the histogram to a reasonable
  177142. * size, we reduce the precision of the input; typical practice is to retain
  177143. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177144. * in the same histogram cell.
  177145. *
  177146. * Next, the color-selection step begins with a box representing the whole
  177147. * color space, and repeatedly splits the "largest" remaining box until we
  177148. * have as many boxes as desired colors. Then the mean color in each
  177149. * remaining box becomes one of the possible output colors.
  177150. *
  177151. * The second pass over the image maps each input pixel to the closest output
  177152. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177153. * This mapping is logically trivial, but making it go fast enough requires
  177154. * considerable care.
  177155. *
  177156. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177157. * the "largest" box and deciding where to cut it. The particular policies
  177158. * used here have proved out well in experimental comparisons, but better ones
  177159. * may yet be found.
  177160. *
  177161. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177162. * space, processing the raw upsampled data without a color conversion step.
  177163. * This allowed the color conversion math to be done only once per colormap
  177164. * entry, not once per pixel. However, that optimization precluded other
  177165. * useful optimizations (such as merging color conversion with upsampling)
  177166. * and it also interfered with desired capabilities such as quantizing to an
  177167. * externally-supplied colormap. We have therefore abandoned that approach.
  177168. * The present code works in the post-conversion color space, typically RGB.
  177169. *
  177170. * To improve the visual quality of the results, we actually work in scaled
  177171. * RGB space, giving G distances more weight than R, and R in turn more than
  177172. * B. To do everything in integer math, we must use integer scale factors.
  177173. * The 2/3/1 scale factors used here correspond loosely to the relative
  177174. * weights of the colors in the NTSC grayscale equation.
  177175. * If you want to use this code to quantize a non-RGB color space, you'll
  177176. * probably need to change these scale factors.
  177177. */
  177178. #define R_SCALE 2 /* scale R distances by this much */
  177179. #define G_SCALE 3 /* scale G distances by this much */
  177180. #define B_SCALE 1 /* and B by this much */
  177181. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177182. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177183. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177184. * you'll get compile errors until you extend this logic. In that case
  177185. * you'll probably want to tweak the histogram sizes too.
  177186. */
  177187. #if RGB_RED == 0
  177188. #define C0_SCALE R_SCALE
  177189. #endif
  177190. #if RGB_BLUE == 0
  177191. #define C0_SCALE B_SCALE
  177192. #endif
  177193. #if RGB_GREEN == 1
  177194. #define C1_SCALE G_SCALE
  177195. #endif
  177196. #if RGB_RED == 2
  177197. #define C2_SCALE R_SCALE
  177198. #endif
  177199. #if RGB_BLUE == 2
  177200. #define C2_SCALE B_SCALE
  177201. #endif
  177202. /*
  177203. * First we have the histogram data structure and routines for creating it.
  177204. *
  177205. * The number of bits of precision can be adjusted by changing these symbols.
  177206. * We recommend keeping 6 bits for G and 5 each for R and B.
  177207. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177208. * better results; if you are short of memory, 5 bits all around will save
  177209. * some space but degrade the results.
  177210. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177211. * (preferably unsigned long) for each cell. In practice this is overkill;
  177212. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177213. * and clamping those that do overflow to the maximum value will give close-
  177214. * enough results. This reduces the recommended histogram size from 256Kb
  177215. * to 128Kb, which is a useful savings on PC-class machines.
  177216. * (In the second pass the histogram space is re-used for pixel mapping data;
  177217. * in that capacity, each cell must be able to store zero to the number of
  177218. * desired colors. 16 bits/cell is plenty for that too.)
  177219. * Since the JPEG code is intended to run in small memory model on 80x86
  177220. * machines, we can't just allocate the histogram in one chunk. Instead
  177221. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177222. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177223. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177224. * on 80x86 machines, the pointer row is in near memory but the actual
  177225. * arrays are in far memory (same arrangement as we use for image arrays).
  177226. */
  177227. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177228. /* These will do the right thing for either R,G,B or B,G,R color order,
  177229. * but you may not like the results for other color orders.
  177230. */
  177231. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177232. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177233. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177234. /* Number of elements along histogram axes. */
  177235. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177236. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177237. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177238. /* These are the amounts to shift an input value to get a histogram index. */
  177239. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177240. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177241. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177242. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177243. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177244. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177245. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177246. typedef hist2d * hist3d; /* type for top-level pointer */
  177247. /* Declarations for Floyd-Steinberg dithering.
  177248. *
  177249. * Errors are accumulated into the array fserrors[], at a resolution of
  177250. * 1/16th of a pixel count. The error at a given pixel is propagated
  177251. * to its not-yet-processed neighbors using the standard F-S fractions,
  177252. * ... (here) 7/16
  177253. * 3/16 5/16 1/16
  177254. * We work left-to-right on even rows, right-to-left on odd rows.
  177255. *
  177256. * We can get away with a single array (holding one row's worth of errors)
  177257. * by using it to store the current row's errors at pixel columns not yet
  177258. * processed, but the next row's errors at columns already processed. We
  177259. * need only a few extra variables to hold the errors immediately around the
  177260. * current column. (If we are lucky, those variables are in registers, but
  177261. * even if not, they're probably cheaper to access than array elements are.)
  177262. *
  177263. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177264. * each end saves us from special-casing the first and last pixels.
  177265. * Each entry is three values long, one value for each color component.
  177266. *
  177267. * Note: on a wide image, we might not have enough room in a PC's near data
  177268. * segment to hold the error array; so it is allocated with alloc_large.
  177269. */
  177270. #if BITS_IN_JSAMPLE == 8
  177271. typedef INT16 FSERROR; /* 16 bits should be enough */
  177272. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177273. #else
  177274. typedef INT32 FSERROR; /* may need more than 16 bits */
  177275. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177276. #endif
  177277. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177278. /* Private subobject */
  177279. typedef struct {
  177280. struct jpeg_color_quantizer pub; /* public fields */
  177281. /* Space for the eventually created colormap is stashed here */
  177282. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177283. int desired; /* desired # of colors = size of colormap */
  177284. /* Variables for accumulating image statistics */
  177285. hist3d histogram; /* pointer to the histogram */
  177286. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177287. /* Variables for Floyd-Steinberg dithering */
  177288. FSERRPTR fserrors; /* accumulated errors */
  177289. boolean on_odd_row; /* flag to remember which row we are on */
  177290. int * error_limiter; /* table for clamping the applied error */
  177291. } my_cquantizer2;
  177292. typedef my_cquantizer2 * my_cquantize_ptr2;
  177293. /*
  177294. * Prescan some rows of pixels.
  177295. * In this module the prescan simply updates the histogram, which has been
  177296. * initialized to zeroes by start_pass.
  177297. * An output_buf parameter is required by the method signature, but no data
  177298. * is actually output (in fact the buffer controller is probably passing a
  177299. * NULL pointer).
  177300. */
  177301. METHODDEF(void)
  177302. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177303. JSAMPARRAY, int num_rows)
  177304. {
  177305. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177306. register JSAMPROW ptr;
  177307. register histptr histp;
  177308. register hist3d histogram = cquantize->histogram;
  177309. int row;
  177310. JDIMENSION col;
  177311. JDIMENSION width = cinfo->output_width;
  177312. for (row = 0; row < num_rows; row++) {
  177313. ptr = input_buf[row];
  177314. for (col = width; col > 0; col--) {
  177315. /* get pixel value and index into the histogram */
  177316. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177317. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177318. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177319. /* increment, check for overflow and undo increment if so. */
  177320. if (++(*histp) <= 0)
  177321. (*histp)--;
  177322. ptr += 3;
  177323. }
  177324. }
  177325. }
  177326. /*
  177327. * Next we have the really interesting routines: selection of a colormap
  177328. * given the completed histogram.
  177329. * These routines work with a list of "boxes", each representing a rectangular
  177330. * subset of the input color space (to histogram precision).
  177331. */
  177332. typedef struct {
  177333. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177334. int c0min, c0max;
  177335. int c1min, c1max;
  177336. int c2min, c2max;
  177337. /* The volume (actually 2-norm) of the box */
  177338. INT32 volume;
  177339. /* The number of nonzero histogram cells within this box */
  177340. long colorcount;
  177341. } box;
  177342. typedef box * boxptr;
  177343. LOCAL(boxptr)
  177344. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177345. /* Find the splittable box with the largest color population */
  177346. /* Returns NULL if no splittable boxes remain */
  177347. {
  177348. register boxptr boxp;
  177349. register int i;
  177350. register long maxc = 0;
  177351. boxptr which = NULL;
  177352. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177353. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177354. which = boxp;
  177355. maxc = boxp->colorcount;
  177356. }
  177357. }
  177358. return which;
  177359. }
  177360. LOCAL(boxptr)
  177361. find_biggest_volume (boxptr boxlist, int numboxes)
  177362. /* Find the splittable box with the largest (scaled) volume */
  177363. /* Returns NULL if no splittable boxes remain */
  177364. {
  177365. register boxptr boxp;
  177366. register int i;
  177367. register INT32 maxv = 0;
  177368. boxptr which = NULL;
  177369. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177370. if (boxp->volume > maxv) {
  177371. which = boxp;
  177372. maxv = boxp->volume;
  177373. }
  177374. }
  177375. return which;
  177376. }
  177377. LOCAL(void)
  177378. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177379. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177380. /* and recompute its volume and population */
  177381. {
  177382. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177383. hist3d histogram = cquantize->histogram;
  177384. histptr histp;
  177385. int c0,c1,c2;
  177386. int c0min,c0max,c1min,c1max,c2min,c2max;
  177387. INT32 dist0,dist1,dist2;
  177388. long ccount;
  177389. c0min = boxp->c0min; c0max = boxp->c0max;
  177390. c1min = boxp->c1min; c1max = boxp->c1max;
  177391. c2min = boxp->c2min; c2max = boxp->c2max;
  177392. if (c0max > c0min)
  177393. for (c0 = c0min; c0 <= c0max; c0++)
  177394. for (c1 = c1min; c1 <= c1max; c1++) {
  177395. histp = & histogram[c0][c1][c2min];
  177396. for (c2 = c2min; c2 <= c2max; c2++)
  177397. if (*histp++ != 0) {
  177398. boxp->c0min = c0min = c0;
  177399. goto have_c0min;
  177400. }
  177401. }
  177402. have_c0min:
  177403. if (c0max > c0min)
  177404. for (c0 = c0max; c0 >= c0min; c0--)
  177405. for (c1 = c1min; c1 <= c1max; c1++) {
  177406. histp = & histogram[c0][c1][c2min];
  177407. for (c2 = c2min; c2 <= c2max; c2++)
  177408. if (*histp++ != 0) {
  177409. boxp->c0max = c0max = c0;
  177410. goto have_c0max;
  177411. }
  177412. }
  177413. have_c0max:
  177414. if (c1max > c1min)
  177415. for (c1 = c1min; c1 <= c1max; c1++)
  177416. for (c0 = c0min; c0 <= c0max; c0++) {
  177417. histp = & histogram[c0][c1][c2min];
  177418. for (c2 = c2min; c2 <= c2max; c2++)
  177419. if (*histp++ != 0) {
  177420. boxp->c1min = c1min = c1;
  177421. goto have_c1min;
  177422. }
  177423. }
  177424. have_c1min:
  177425. if (c1max > c1min)
  177426. for (c1 = c1max; c1 >= c1min; c1--)
  177427. for (c0 = c0min; c0 <= c0max; c0++) {
  177428. histp = & histogram[c0][c1][c2min];
  177429. for (c2 = c2min; c2 <= c2max; c2++)
  177430. if (*histp++ != 0) {
  177431. boxp->c1max = c1max = c1;
  177432. goto have_c1max;
  177433. }
  177434. }
  177435. have_c1max:
  177436. if (c2max > c2min)
  177437. for (c2 = c2min; c2 <= c2max; c2++)
  177438. for (c0 = c0min; c0 <= c0max; c0++) {
  177439. histp = & histogram[c0][c1min][c2];
  177440. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177441. if (*histp != 0) {
  177442. boxp->c2min = c2min = c2;
  177443. goto have_c2min;
  177444. }
  177445. }
  177446. have_c2min:
  177447. if (c2max > c2min)
  177448. for (c2 = c2max; c2 >= c2min; c2--)
  177449. for (c0 = c0min; c0 <= c0max; c0++) {
  177450. histp = & histogram[c0][c1min][c2];
  177451. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177452. if (*histp != 0) {
  177453. boxp->c2max = c2max = c2;
  177454. goto have_c2max;
  177455. }
  177456. }
  177457. have_c2max:
  177458. /* Update box volume.
  177459. * We use 2-norm rather than real volume here; this biases the method
  177460. * against making long narrow boxes, and it has the side benefit that
  177461. * a box is splittable iff norm > 0.
  177462. * Since the differences are expressed in histogram-cell units,
  177463. * we have to shift back to JSAMPLE units to get consistent distances;
  177464. * after which, we scale according to the selected distance scale factors.
  177465. */
  177466. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177467. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177468. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177469. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177470. /* Now scan remaining volume of box and compute population */
  177471. ccount = 0;
  177472. for (c0 = c0min; c0 <= c0max; c0++)
  177473. for (c1 = c1min; c1 <= c1max; c1++) {
  177474. histp = & histogram[c0][c1][c2min];
  177475. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177476. if (*histp != 0) {
  177477. ccount++;
  177478. }
  177479. }
  177480. boxp->colorcount = ccount;
  177481. }
  177482. LOCAL(int)
  177483. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177484. int desired_colors)
  177485. /* Repeatedly select and split the largest box until we have enough boxes */
  177486. {
  177487. int n,lb;
  177488. int c0,c1,c2,cmax;
  177489. register boxptr b1,b2;
  177490. while (numboxes < desired_colors) {
  177491. /* Select box to split.
  177492. * Current algorithm: by population for first half, then by volume.
  177493. */
  177494. if (numboxes*2 <= desired_colors) {
  177495. b1 = find_biggest_color_pop(boxlist, numboxes);
  177496. } else {
  177497. b1 = find_biggest_volume(boxlist, numboxes);
  177498. }
  177499. if (b1 == NULL) /* no splittable boxes left! */
  177500. break;
  177501. b2 = &boxlist[numboxes]; /* where new box will go */
  177502. /* Copy the color bounds to the new box. */
  177503. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177504. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177505. /* Choose which axis to split the box on.
  177506. * Current algorithm: longest scaled axis.
  177507. * See notes in update_box about scaling distances.
  177508. */
  177509. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177510. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177511. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177512. /* We want to break any ties in favor of green, then red, blue last.
  177513. * This code does the right thing for R,G,B or B,G,R color orders only.
  177514. */
  177515. #if RGB_RED == 0
  177516. cmax = c1; n = 1;
  177517. if (c0 > cmax) { cmax = c0; n = 0; }
  177518. if (c2 > cmax) { n = 2; }
  177519. #else
  177520. cmax = c1; n = 1;
  177521. if (c2 > cmax) { cmax = c2; n = 2; }
  177522. if (c0 > cmax) { n = 0; }
  177523. #endif
  177524. /* Choose split point along selected axis, and update box bounds.
  177525. * Current algorithm: split at halfway point.
  177526. * (Since the box has been shrunk to minimum volume,
  177527. * any split will produce two nonempty subboxes.)
  177528. * Note that lb value is max for lower box, so must be < old max.
  177529. */
  177530. switch (n) {
  177531. case 0:
  177532. lb = (b1->c0max + b1->c0min) / 2;
  177533. b1->c0max = lb;
  177534. b2->c0min = lb+1;
  177535. break;
  177536. case 1:
  177537. lb = (b1->c1max + b1->c1min) / 2;
  177538. b1->c1max = lb;
  177539. b2->c1min = lb+1;
  177540. break;
  177541. case 2:
  177542. lb = (b1->c2max + b1->c2min) / 2;
  177543. b1->c2max = lb;
  177544. b2->c2min = lb+1;
  177545. break;
  177546. }
  177547. /* Update stats for boxes */
  177548. update_box(cinfo, b1);
  177549. update_box(cinfo, b2);
  177550. numboxes++;
  177551. }
  177552. return numboxes;
  177553. }
  177554. LOCAL(void)
  177555. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177556. /* Compute representative color for a box, put it in colormap[icolor] */
  177557. {
  177558. /* Current algorithm: mean weighted by pixels (not colors) */
  177559. /* Note it is important to get the rounding correct! */
  177560. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177561. hist3d histogram = cquantize->histogram;
  177562. histptr histp;
  177563. int c0,c1,c2;
  177564. int c0min,c0max,c1min,c1max,c2min,c2max;
  177565. long count;
  177566. long total = 0;
  177567. long c0total = 0;
  177568. long c1total = 0;
  177569. long c2total = 0;
  177570. c0min = boxp->c0min; c0max = boxp->c0max;
  177571. c1min = boxp->c1min; c1max = boxp->c1max;
  177572. c2min = boxp->c2min; c2max = boxp->c2max;
  177573. for (c0 = c0min; c0 <= c0max; c0++)
  177574. for (c1 = c1min; c1 <= c1max; c1++) {
  177575. histp = & histogram[c0][c1][c2min];
  177576. for (c2 = c2min; c2 <= c2max; c2++) {
  177577. if ((count = *histp++) != 0) {
  177578. total += count;
  177579. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177580. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177581. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177582. }
  177583. }
  177584. }
  177585. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177586. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177587. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177588. }
  177589. LOCAL(void)
  177590. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177591. /* Master routine for color selection */
  177592. {
  177593. boxptr boxlist;
  177594. int numboxes;
  177595. int i;
  177596. /* Allocate workspace for box list */
  177597. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177598. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177599. /* Initialize one box containing whole space */
  177600. numboxes = 1;
  177601. boxlist[0].c0min = 0;
  177602. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177603. boxlist[0].c1min = 0;
  177604. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177605. boxlist[0].c2min = 0;
  177606. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177607. /* Shrink it to actually-used volume and set its statistics */
  177608. update_box(cinfo, & boxlist[0]);
  177609. /* Perform median-cut to produce final box list */
  177610. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177611. /* Compute the representative color for each box, fill colormap */
  177612. for (i = 0; i < numboxes; i++)
  177613. compute_color(cinfo, & boxlist[i], i);
  177614. cinfo->actual_number_of_colors = numboxes;
  177615. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177616. }
  177617. /*
  177618. * These routines are concerned with the time-critical task of mapping input
  177619. * colors to the nearest color in the selected colormap.
  177620. *
  177621. * We re-use the histogram space as an "inverse color map", essentially a
  177622. * cache for the results of nearest-color searches. All colors within a
  177623. * histogram cell will be mapped to the same colormap entry, namely the one
  177624. * closest to the cell's center. This may not be quite the closest entry to
  177625. * the actual input color, but it's almost as good. A zero in the cache
  177626. * indicates we haven't found the nearest color for that cell yet; the array
  177627. * is cleared to zeroes before starting the mapping pass. When we find the
  177628. * nearest color for a cell, its colormap index plus one is recorded in the
  177629. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177630. * when they need to use an unfilled entry in the cache.
  177631. *
  177632. * Our method of efficiently finding nearest colors is based on the "locally
  177633. * sorted search" idea described by Heckbert and on the incremental distance
  177634. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177635. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177636. * the distances from a given colormap entry to each cell of the histogram can
  177637. * be computed quickly using an incremental method: the differences between
  177638. * distances to adjacent cells themselves differ by a constant. This allows a
  177639. * fairly fast implementation of the "brute force" approach of computing the
  177640. * distance from every colormap entry to every histogram cell. Unfortunately,
  177641. * it needs a work array to hold the best-distance-so-far for each histogram
  177642. * cell (because the inner loop has to be over cells, not colormap entries).
  177643. * The work array elements have to be INT32s, so the work array would need
  177644. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177645. *
  177646. * To get around these problems, we apply Thomas' method to compute the
  177647. * nearest colors for only the cells within a small subbox of the histogram.
  177648. * The work array need be only as big as the subbox, so the memory usage
  177649. * problem is solved. Furthermore, we need not fill subboxes that are never
  177650. * referenced in pass2; many images use only part of the color gamut, so a
  177651. * fair amount of work is saved. An additional advantage of this
  177652. * approach is that we can apply Heckbert's locality criterion to quickly
  177653. * eliminate colormap entries that are far away from the subbox; typically
  177654. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177655. * and we need not compute their distances to individual cells in the subbox.
  177656. * The speed of this approach is heavily influenced by the subbox size: too
  177657. * small means too much overhead, too big loses because Heckbert's criterion
  177658. * can't eliminate as many colormap entries. Empirically the best subbox
  177659. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177660. *
  177661. * Thomas' article also describes a refined method which is asymptotically
  177662. * faster than the brute-force method, but it is also far more complex and
  177663. * cannot efficiently be applied to small subboxes. It is therefore not
  177664. * useful for programs intended to be portable to DOS machines. On machines
  177665. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177666. * refined method might be faster than the present code --- but then again,
  177667. * it might not be any faster, and it's certainly more complicated.
  177668. */
  177669. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177670. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177671. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177672. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177673. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177674. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177675. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177676. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177677. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177678. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177679. /*
  177680. * The next three routines implement inverse colormap filling. They could
  177681. * all be folded into one big routine, but splitting them up this way saves
  177682. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177683. * and may allow some compilers to produce better code by registerizing more
  177684. * inner-loop variables.
  177685. */
  177686. LOCAL(int)
  177687. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177688. JSAMPLE colorlist[])
  177689. /* Locate the colormap entries close enough to an update box to be candidates
  177690. * for the nearest entry to some cell(s) in the update box. The update box
  177691. * is specified by the center coordinates of its first cell. The number of
  177692. * candidate colormap entries is returned, and their colormap indexes are
  177693. * placed in colorlist[].
  177694. * This routine uses Heckbert's "locally sorted search" criterion to select
  177695. * the colors that need further consideration.
  177696. */
  177697. {
  177698. int numcolors = cinfo->actual_number_of_colors;
  177699. int maxc0, maxc1, maxc2;
  177700. int centerc0, centerc1, centerc2;
  177701. int i, x, ncolors;
  177702. INT32 minmaxdist, min_dist, max_dist, tdist;
  177703. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177704. /* Compute true coordinates of update box's upper corner and center.
  177705. * Actually we compute the coordinates of the center of the upper-corner
  177706. * histogram cell, which are the upper bounds of the volume we care about.
  177707. * Note that since ">>" rounds down, the "center" values may be closer to
  177708. * min than to max; hence comparisons to them must be "<=", not "<".
  177709. */
  177710. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177711. centerc0 = (minc0 + maxc0) >> 1;
  177712. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177713. centerc1 = (minc1 + maxc1) >> 1;
  177714. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177715. centerc2 = (minc2 + maxc2) >> 1;
  177716. /* For each color in colormap, find:
  177717. * 1. its minimum squared-distance to any point in the update box
  177718. * (zero if color is within update box);
  177719. * 2. its maximum squared-distance to any point in the update box.
  177720. * Both of these can be found by considering only the corners of the box.
  177721. * We save the minimum distance for each color in mindist[];
  177722. * only the smallest maximum distance is of interest.
  177723. */
  177724. minmaxdist = 0x7FFFFFFFL;
  177725. for (i = 0; i < numcolors; i++) {
  177726. /* We compute the squared-c0-distance term, then add in the other two. */
  177727. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177728. if (x < minc0) {
  177729. tdist = (x - minc0) * C0_SCALE;
  177730. min_dist = tdist*tdist;
  177731. tdist = (x - maxc0) * C0_SCALE;
  177732. max_dist = tdist*tdist;
  177733. } else if (x > maxc0) {
  177734. tdist = (x - maxc0) * C0_SCALE;
  177735. min_dist = tdist*tdist;
  177736. tdist = (x - minc0) * C0_SCALE;
  177737. max_dist = tdist*tdist;
  177738. } else {
  177739. /* within cell range so no contribution to min_dist */
  177740. min_dist = 0;
  177741. if (x <= centerc0) {
  177742. tdist = (x - maxc0) * C0_SCALE;
  177743. max_dist = tdist*tdist;
  177744. } else {
  177745. tdist = (x - minc0) * C0_SCALE;
  177746. max_dist = tdist*tdist;
  177747. }
  177748. }
  177749. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177750. if (x < minc1) {
  177751. tdist = (x - minc1) * C1_SCALE;
  177752. min_dist += tdist*tdist;
  177753. tdist = (x - maxc1) * C1_SCALE;
  177754. max_dist += tdist*tdist;
  177755. } else if (x > maxc1) {
  177756. tdist = (x - maxc1) * C1_SCALE;
  177757. min_dist += tdist*tdist;
  177758. tdist = (x - minc1) * C1_SCALE;
  177759. max_dist += tdist*tdist;
  177760. } else {
  177761. /* within cell range so no contribution to min_dist */
  177762. if (x <= centerc1) {
  177763. tdist = (x - maxc1) * C1_SCALE;
  177764. max_dist += tdist*tdist;
  177765. } else {
  177766. tdist = (x - minc1) * C1_SCALE;
  177767. max_dist += tdist*tdist;
  177768. }
  177769. }
  177770. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177771. if (x < minc2) {
  177772. tdist = (x - minc2) * C2_SCALE;
  177773. min_dist += tdist*tdist;
  177774. tdist = (x - maxc2) * C2_SCALE;
  177775. max_dist += tdist*tdist;
  177776. } else if (x > maxc2) {
  177777. tdist = (x - maxc2) * C2_SCALE;
  177778. min_dist += tdist*tdist;
  177779. tdist = (x - minc2) * C2_SCALE;
  177780. max_dist += tdist*tdist;
  177781. } else {
  177782. /* within cell range so no contribution to min_dist */
  177783. if (x <= centerc2) {
  177784. tdist = (x - maxc2) * C2_SCALE;
  177785. max_dist += tdist*tdist;
  177786. } else {
  177787. tdist = (x - minc2) * C2_SCALE;
  177788. max_dist += tdist*tdist;
  177789. }
  177790. }
  177791. mindist[i] = min_dist; /* save away the results */
  177792. if (max_dist < minmaxdist)
  177793. minmaxdist = max_dist;
  177794. }
  177795. /* Now we know that no cell in the update box is more than minmaxdist
  177796. * away from some colormap entry. Therefore, only colors that are
  177797. * within minmaxdist of some part of the box need be considered.
  177798. */
  177799. ncolors = 0;
  177800. for (i = 0; i < numcolors; i++) {
  177801. if (mindist[i] <= minmaxdist)
  177802. colorlist[ncolors++] = (JSAMPLE) i;
  177803. }
  177804. return ncolors;
  177805. }
  177806. LOCAL(void)
  177807. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177808. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177809. /* Find the closest colormap entry for each cell in the update box,
  177810. * given the list of candidate colors prepared by find_nearby_colors.
  177811. * Return the indexes of the closest entries in the bestcolor[] array.
  177812. * This routine uses Thomas' incremental distance calculation method to
  177813. * find the distance from a colormap entry to successive cells in the box.
  177814. */
  177815. {
  177816. int ic0, ic1, ic2;
  177817. int i, icolor;
  177818. register INT32 * bptr; /* pointer into bestdist[] array */
  177819. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177820. INT32 dist0, dist1; /* initial distance values */
  177821. register INT32 dist2; /* current distance in inner loop */
  177822. INT32 xx0, xx1; /* distance increments */
  177823. register INT32 xx2;
  177824. INT32 inc0, inc1, inc2; /* initial values for increments */
  177825. /* This array holds the distance to the nearest-so-far color for each cell */
  177826. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177827. /* Initialize best-distance for each cell of the update box */
  177828. bptr = bestdist;
  177829. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  177830. *bptr++ = 0x7FFFFFFFL;
  177831. /* For each color selected by find_nearby_colors,
  177832. * compute its distance to the center of each cell in the box.
  177833. * If that's less than best-so-far, update best distance and color number.
  177834. */
  177835. /* Nominal steps between cell centers ("x" in Thomas article) */
  177836. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  177837. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  177838. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  177839. for (i = 0; i < numcolors; i++) {
  177840. icolor = GETJSAMPLE(colorlist[i]);
  177841. /* Compute (square of) distance from minc0/c1/c2 to this color */
  177842. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  177843. dist0 = inc0*inc0;
  177844. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  177845. dist0 += inc1*inc1;
  177846. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  177847. dist0 += inc2*inc2;
  177848. /* Form the initial difference increments */
  177849. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  177850. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  177851. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  177852. /* Now loop over all cells in box, updating distance per Thomas method */
  177853. bptr = bestdist;
  177854. cptr = bestcolor;
  177855. xx0 = inc0;
  177856. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  177857. dist1 = dist0;
  177858. xx1 = inc1;
  177859. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  177860. dist2 = dist1;
  177861. xx2 = inc2;
  177862. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  177863. if (dist2 < *bptr) {
  177864. *bptr = dist2;
  177865. *cptr = (JSAMPLE) icolor;
  177866. }
  177867. dist2 += xx2;
  177868. xx2 += 2 * STEP_C2 * STEP_C2;
  177869. bptr++;
  177870. cptr++;
  177871. }
  177872. dist1 += xx1;
  177873. xx1 += 2 * STEP_C1 * STEP_C1;
  177874. }
  177875. dist0 += xx0;
  177876. xx0 += 2 * STEP_C0 * STEP_C0;
  177877. }
  177878. }
  177879. }
  177880. LOCAL(void)
  177881. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  177882. /* Fill the inverse-colormap entries in the update box that contains */
  177883. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  177884. /* we can fill as many others as we wish.) */
  177885. {
  177886. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177887. hist3d histogram = cquantize->histogram;
  177888. int minc0, minc1, minc2; /* lower left corner of update box */
  177889. int ic0, ic1, ic2;
  177890. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177891. register histptr cachep; /* pointer into main cache array */
  177892. /* This array lists the candidate colormap indexes. */
  177893. JSAMPLE colorlist[MAXNUMCOLORS];
  177894. int numcolors; /* number of candidate colors */
  177895. /* This array holds the actually closest colormap index for each cell. */
  177896. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177897. /* Convert cell coordinates to update box ID */
  177898. c0 >>= BOX_C0_LOG;
  177899. c1 >>= BOX_C1_LOG;
  177900. c2 >>= BOX_C2_LOG;
  177901. /* Compute true coordinates of update box's origin corner.
  177902. * Actually we compute the coordinates of the center of the corner
  177903. * histogram cell, which are the lower bounds of the volume we care about.
  177904. */
  177905. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  177906. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  177907. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  177908. /* Determine which colormap entries are close enough to be candidates
  177909. * for the nearest entry to some cell in the update box.
  177910. */
  177911. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  177912. /* Determine the actually nearest colors. */
  177913. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  177914. bestcolor);
  177915. /* Save the best color numbers (plus 1) in the main cache array */
  177916. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  177917. c1 <<= BOX_C1_LOG;
  177918. c2 <<= BOX_C2_LOG;
  177919. cptr = bestcolor;
  177920. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  177921. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  177922. cachep = & histogram[c0+ic0][c1+ic1][c2];
  177923. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  177924. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  177925. }
  177926. }
  177927. }
  177928. }
  177929. /*
  177930. * Map some rows of pixels to the output colormapped representation.
  177931. */
  177932. METHODDEF(void)
  177933. pass2_no_dither (j_decompress_ptr cinfo,
  177934. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177935. /* This version performs no dithering */
  177936. {
  177937. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177938. hist3d histogram = cquantize->histogram;
  177939. register JSAMPROW inptr, outptr;
  177940. register histptr cachep;
  177941. register int c0, c1, c2;
  177942. int row;
  177943. JDIMENSION col;
  177944. JDIMENSION width = cinfo->output_width;
  177945. for (row = 0; row < num_rows; row++) {
  177946. inptr = input_buf[row];
  177947. outptr = output_buf[row];
  177948. for (col = width; col > 0; col--) {
  177949. /* get pixel value and index into the cache */
  177950. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  177951. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  177952. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  177953. cachep = & histogram[c0][c1][c2];
  177954. /* If we have not seen this color before, find nearest colormap entry */
  177955. /* and update the cache */
  177956. if (*cachep == 0)
  177957. fill_inverse_cmap(cinfo, c0,c1,c2);
  177958. /* Now emit the colormap index for this cell */
  177959. *outptr++ = (JSAMPLE) (*cachep - 1);
  177960. }
  177961. }
  177962. }
  177963. METHODDEF(void)
  177964. pass2_fs_dither (j_decompress_ptr cinfo,
  177965. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177966. /* This version performs Floyd-Steinberg dithering */
  177967. {
  177968. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177969. hist3d histogram = cquantize->histogram;
  177970. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  177971. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  177972. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  177973. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177974. JSAMPROW inptr; /* => current input pixel */
  177975. JSAMPROW outptr; /* => current output pixel */
  177976. histptr cachep;
  177977. int dir; /* +1 or -1 depending on direction */
  177978. int dir3; /* 3*dir, for advancing inptr & errorptr */
  177979. int row;
  177980. JDIMENSION col;
  177981. JDIMENSION width = cinfo->output_width;
  177982. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177983. int *error_limit = cquantize->error_limiter;
  177984. JSAMPROW colormap0 = cinfo->colormap[0];
  177985. JSAMPROW colormap1 = cinfo->colormap[1];
  177986. JSAMPROW colormap2 = cinfo->colormap[2];
  177987. SHIFT_TEMPS
  177988. for (row = 0; row < num_rows; row++) {
  177989. inptr = input_buf[row];
  177990. outptr = output_buf[row];
  177991. if (cquantize->on_odd_row) {
  177992. /* work right to left in this row */
  177993. inptr += (width-1) * 3; /* so point to rightmost pixel */
  177994. outptr += width-1;
  177995. dir = -1;
  177996. dir3 = -3;
  177997. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  177998. cquantize->on_odd_row = FALSE; /* flip for next time */
  177999. } else {
  178000. /* work left to right in this row */
  178001. dir = 1;
  178002. dir3 = 3;
  178003. errorptr = cquantize->fserrors; /* => entry before first real column */
  178004. cquantize->on_odd_row = TRUE; /* flip for next time */
  178005. }
  178006. /* Preset error values: no error propagated to first pixel from left */
  178007. cur0 = cur1 = cur2 = 0;
  178008. /* and no error propagated to row below yet */
  178009. belowerr0 = belowerr1 = belowerr2 = 0;
  178010. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178011. for (col = width; col > 0; col--) {
  178012. /* curN holds the error propagated from the previous pixel on the
  178013. * current line. Add the error propagated from the previous line
  178014. * to form the complete error correction term for this pixel, and
  178015. * round the error term (which is expressed * 16) to an integer.
  178016. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178017. * for either sign of the error value.
  178018. * Note: errorptr points to *previous* column's array entry.
  178019. */
  178020. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178021. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178022. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178023. /* Limit the error using transfer function set by init_error_limit.
  178024. * See comments with init_error_limit for rationale.
  178025. */
  178026. cur0 = error_limit[cur0];
  178027. cur1 = error_limit[cur1];
  178028. cur2 = error_limit[cur2];
  178029. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178030. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178031. * this sets the required size of the range_limit array.
  178032. */
  178033. cur0 += GETJSAMPLE(inptr[0]);
  178034. cur1 += GETJSAMPLE(inptr[1]);
  178035. cur2 += GETJSAMPLE(inptr[2]);
  178036. cur0 = GETJSAMPLE(range_limit[cur0]);
  178037. cur1 = GETJSAMPLE(range_limit[cur1]);
  178038. cur2 = GETJSAMPLE(range_limit[cur2]);
  178039. /* Index into the cache with adjusted pixel value */
  178040. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178041. /* If we have not seen this color before, find nearest colormap */
  178042. /* entry and update the cache */
  178043. if (*cachep == 0)
  178044. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178045. /* Now emit the colormap index for this cell */
  178046. { register int pixcode = *cachep - 1;
  178047. *outptr = (JSAMPLE) pixcode;
  178048. /* Compute representation error for this pixel */
  178049. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178050. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178051. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178052. }
  178053. /* Compute error fractions to be propagated to adjacent pixels.
  178054. * Add these into the running sums, and simultaneously shift the
  178055. * next-line error sums left by 1 column.
  178056. */
  178057. { register LOCFSERROR bnexterr, delta;
  178058. bnexterr = cur0; /* Process component 0 */
  178059. delta = cur0 * 2;
  178060. cur0 += delta; /* form error * 3 */
  178061. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178062. cur0 += delta; /* form error * 5 */
  178063. bpreverr0 = belowerr0 + cur0;
  178064. belowerr0 = bnexterr;
  178065. cur0 += delta; /* form error * 7 */
  178066. bnexterr = cur1; /* Process component 1 */
  178067. delta = cur1 * 2;
  178068. cur1 += delta; /* form error * 3 */
  178069. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178070. cur1 += delta; /* form error * 5 */
  178071. bpreverr1 = belowerr1 + cur1;
  178072. belowerr1 = bnexterr;
  178073. cur1 += delta; /* form error * 7 */
  178074. bnexterr = cur2; /* Process component 2 */
  178075. delta = cur2 * 2;
  178076. cur2 += delta; /* form error * 3 */
  178077. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178078. cur2 += delta; /* form error * 5 */
  178079. bpreverr2 = belowerr2 + cur2;
  178080. belowerr2 = bnexterr;
  178081. cur2 += delta; /* form error * 7 */
  178082. }
  178083. /* At this point curN contains the 7/16 error value to be propagated
  178084. * to the next pixel on the current line, and all the errors for the
  178085. * next line have been shifted over. We are therefore ready to move on.
  178086. */
  178087. inptr += dir3; /* Advance pixel pointers to next column */
  178088. outptr += dir;
  178089. errorptr += dir3; /* advance errorptr to current column */
  178090. }
  178091. /* Post-loop cleanup: we must unload the final error values into the
  178092. * final fserrors[] entry. Note we need not unload belowerrN because
  178093. * it is for the dummy column before or after the actual array.
  178094. */
  178095. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178096. errorptr[1] = (FSERROR) bpreverr1;
  178097. errorptr[2] = (FSERROR) bpreverr2;
  178098. }
  178099. }
  178100. /*
  178101. * Initialize the error-limiting transfer function (lookup table).
  178102. * The raw F-S error computation can potentially compute error values of up to
  178103. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178104. * much less, otherwise obviously wrong pixels will be created. (Typical
  178105. * effects include weird fringes at color-area boundaries, isolated bright
  178106. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178107. * is to ensure that the "corners" of the color cube are allocated as output
  178108. * colors; then repeated errors in the same direction cannot cause cascading
  178109. * error buildup. However, that only prevents the error from getting
  178110. * completely out of hand; Aaron Giles reports that error limiting improves
  178111. * the results even with corner colors allocated.
  178112. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178113. * well, but the smoother transfer function used below is even better. Thanks
  178114. * to Aaron Giles for this idea.
  178115. */
  178116. LOCAL(void)
  178117. init_error_limit (j_decompress_ptr cinfo)
  178118. /* Allocate and fill in the error_limiter table */
  178119. {
  178120. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178121. int * table;
  178122. int in, out;
  178123. table = (int *) (*cinfo->mem->alloc_small)
  178124. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178125. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178126. cquantize->error_limiter = table;
  178127. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178128. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178129. out = 0;
  178130. for (in = 0; in < STEPSIZE; in++, out++) {
  178131. table[in] = out; table[-in] = -out;
  178132. }
  178133. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178134. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178135. table[in] = out; table[-in] = -out;
  178136. }
  178137. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178138. for (; in <= MAXJSAMPLE; in++) {
  178139. table[in] = out; table[-in] = -out;
  178140. }
  178141. #undef STEPSIZE
  178142. }
  178143. /*
  178144. * Finish up at the end of each pass.
  178145. */
  178146. METHODDEF(void)
  178147. finish_pass1 (j_decompress_ptr cinfo)
  178148. {
  178149. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178150. /* Select the representative colors and fill in cinfo->colormap */
  178151. cinfo->colormap = cquantize->sv_colormap;
  178152. select_colors(cinfo, cquantize->desired);
  178153. /* Force next pass to zero the color index table */
  178154. cquantize->needs_zeroed = TRUE;
  178155. }
  178156. METHODDEF(void)
  178157. finish_pass2 (j_decompress_ptr)
  178158. {
  178159. /* no work */
  178160. }
  178161. /*
  178162. * Initialize for each processing pass.
  178163. */
  178164. METHODDEF(void)
  178165. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178166. {
  178167. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178168. hist3d histogram = cquantize->histogram;
  178169. int i;
  178170. /* Only F-S dithering or no dithering is supported. */
  178171. /* If user asks for ordered dither, give him F-S. */
  178172. if (cinfo->dither_mode != JDITHER_NONE)
  178173. cinfo->dither_mode = JDITHER_FS;
  178174. if (is_pre_scan) {
  178175. /* Set up method pointers */
  178176. cquantize->pub.color_quantize = prescan_quantize;
  178177. cquantize->pub.finish_pass = finish_pass1;
  178178. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178179. } else {
  178180. /* Set up method pointers */
  178181. if (cinfo->dither_mode == JDITHER_FS)
  178182. cquantize->pub.color_quantize = pass2_fs_dither;
  178183. else
  178184. cquantize->pub.color_quantize = pass2_no_dither;
  178185. cquantize->pub.finish_pass = finish_pass2;
  178186. /* Make sure color count is acceptable */
  178187. i = cinfo->actual_number_of_colors;
  178188. if (i < 1)
  178189. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178190. if (i > MAXNUMCOLORS)
  178191. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178192. if (cinfo->dither_mode == JDITHER_FS) {
  178193. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178194. (3 * SIZEOF(FSERROR)));
  178195. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178196. if (cquantize->fserrors == NULL)
  178197. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178198. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178199. /* Initialize the propagated errors to zero. */
  178200. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178201. /* Make the error-limit table if we didn't already. */
  178202. if (cquantize->error_limiter == NULL)
  178203. init_error_limit(cinfo);
  178204. cquantize->on_odd_row = FALSE;
  178205. }
  178206. }
  178207. /* Zero the histogram or inverse color map, if necessary */
  178208. if (cquantize->needs_zeroed) {
  178209. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178210. jzero_far((void FAR *) histogram[i],
  178211. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178212. }
  178213. cquantize->needs_zeroed = FALSE;
  178214. }
  178215. }
  178216. /*
  178217. * Switch to a new external colormap between output passes.
  178218. */
  178219. METHODDEF(void)
  178220. new_color_map_2_quant (j_decompress_ptr cinfo)
  178221. {
  178222. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178223. /* Reset the inverse color map */
  178224. cquantize->needs_zeroed = TRUE;
  178225. }
  178226. /*
  178227. * Module initialization routine for 2-pass color quantization.
  178228. */
  178229. GLOBAL(void)
  178230. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178231. {
  178232. my_cquantize_ptr2 cquantize;
  178233. int i;
  178234. cquantize = (my_cquantize_ptr2)
  178235. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178236. SIZEOF(my_cquantizer2));
  178237. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178238. cquantize->pub.start_pass = start_pass_2_quant;
  178239. cquantize->pub.new_color_map = new_color_map_2_quant;
  178240. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178241. cquantize->error_limiter = NULL;
  178242. /* Make sure jdmaster didn't give me a case I can't handle */
  178243. if (cinfo->out_color_components != 3)
  178244. ERREXIT(cinfo, JERR_NOTIMPL);
  178245. /* Allocate the histogram/inverse colormap storage */
  178246. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178247. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178248. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178249. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178250. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178251. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178252. }
  178253. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178254. /* Allocate storage for the completed colormap, if required.
  178255. * We do this now since it is FAR storage and may affect
  178256. * the memory manager's space calculations.
  178257. */
  178258. if (cinfo->enable_2pass_quant) {
  178259. /* Make sure color count is acceptable */
  178260. int desired = cinfo->desired_number_of_colors;
  178261. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178262. if (desired < 8)
  178263. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178264. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178265. if (desired > MAXNUMCOLORS)
  178266. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178267. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178268. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178269. cquantize->desired = desired;
  178270. } else
  178271. cquantize->sv_colormap = NULL;
  178272. /* Only F-S dithering or no dithering is supported. */
  178273. /* If user asks for ordered dither, give him F-S. */
  178274. if (cinfo->dither_mode != JDITHER_NONE)
  178275. cinfo->dither_mode = JDITHER_FS;
  178276. /* Allocate Floyd-Steinberg workspace if necessary.
  178277. * This isn't really needed until pass 2, but again it is FAR storage.
  178278. * Although we will cope with a later change in dither_mode,
  178279. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178280. */
  178281. if (cinfo->dither_mode == JDITHER_FS) {
  178282. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178283. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178284. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178285. /* Might as well create the error-limiting table too. */
  178286. init_error_limit(cinfo);
  178287. }
  178288. }
  178289. #endif /* QUANT_2PASS_SUPPORTED */
  178290. /*** End of inlined file: jquant2.c ***/
  178291. /*** Start of inlined file: jutils.c ***/
  178292. #define JPEG_INTERNALS
  178293. /*
  178294. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178295. * of a DCT block read in natural order (left to right, top to bottom).
  178296. */
  178297. #if 0 /* This table is not actually needed in v6a */
  178298. const int jpeg_zigzag_order[DCTSIZE2] = {
  178299. 0, 1, 5, 6, 14, 15, 27, 28,
  178300. 2, 4, 7, 13, 16, 26, 29, 42,
  178301. 3, 8, 12, 17, 25, 30, 41, 43,
  178302. 9, 11, 18, 24, 31, 40, 44, 53,
  178303. 10, 19, 23, 32, 39, 45, 52, 54,
  178304. 20, 22, 33, 38, 46, 51, 55, 60,
  178305. 21, 34, 37, 47, 50, 56, 59, 61,
  178306. 35, 36, 48, 49, 57, 58, 62, 63
  178307. };
  178308. #endif
  178309. /*
  178310. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178311. * of zigzag order.
  178312. *
  178313. * When reading corrupted data, the Huffman decoders could attempt
  178314. * to reference an entry beyond the end of this array (if the decoded
  178315. * zero run length reaches past the end of the block). To prevent
  178316. * wild stores without adding an inner-loop test, we put some extra
  178317. * "63"s after the real entries. This will cause the extra coefficient
  178318. * to be stored in location 63 of the block, not somewhere random.
  178319. * The worst case would be a run-length of 15, which means we need 16
  178320. * fake entries.
  178321. */
  178322. const int jpeg_natural_order[DCTSIZE2+16] = {
  178323. 0, 1, 8, 16, 9, 2, 3, 10,
  178324. 17, 24, 32, 25, 18, 11, 4, 5,
  178325. 12, 19, 26, 33, 40, 48, 41, 34,
  178326. 27, 20, 13, 6, 7, 14, 21, 28,
  178327. 35, 42, 49, 56, 57, 50, 43, 36,
  178328. 29, 22, 15, 23, 30, 37, 44, 51,
  178329. 58, 59, 52, 45, 38, 31, 39, 46,
  178330. 53, 60, 61, 54, 47, 55, 62, 63,
  178331. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178332. 63, 63, 63, 63, 63, 63, 63, 63
  178333. };
  178334. /*
  178335. * Arithmetic utilities
  178336. */
  178337. GLOBAL(long)
  178338. jdiv_round_up (long a, long b)
  178339. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178340. /* Assumes a >= 0, b > 0 */
  178341. {
  178342. return (a + b - 1L) / b;
  178343. }
  178344. GLOBAL(long)
  178345. jround_up (long a, long b)
  178346. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178347. /* Assumes a >= 0, b > 0 */
  178348. {
  178349. a += b - 1L;
  178350. return a - (a % b);
  178351. }
  178352. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178353. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178354. * are FAR and we're assuming a small-pointer memory model. However, some
  178355. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178356. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178357. * Otherwise, the routines below do it the hard way. (The performance cost
  178358. * is not all that great, because these routines aren't very heavily used.)
  178359. */
  178360. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178361. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178362. #define FMEMZERO(target,size) MEMZERO(target,size)
  178363. #else /* 80x86 case, define if we can */
  178364. #ifdef USE_FMEM
  178365. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178366. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178367. #endif
  178368. #endif
  178369. GLOBAL(void)
  178370. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178371. JSAMPARRAY output_array, int dest_row,
  178372. int num_rows, JDIMENSION num_cols)
  178373. /* Copy some rows of samples from one place to another.
  178374. * num_rows rows are copied from input_array[source_row++]
  178375. * to output_array[dest_row++]; these areas may overlap for duplication.
  178376. * The source and destination arrays must be at least as wide as num_cols.
  178377. */
  178378. {
  178379. register JSAMPROW inptr, outptr;
  178380. #ifdef FMEMCOPY
  178381. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178382. #else
  178383. register JDIMENSION count;
  178384. #endif
  178385. register int row;
  178386. input_array += source_row;
  178387. output_array += dest_row;
  178388. for (row = num_rows; row > 0; row--) {
  178389. inptr = *input_array++;
  178390. outptr = *output_array++;
  178391. #ifdef FMEMCOPY
  178392. FMEMCOPY(outptr, inptr, count);
  178393. #else
  178394. for (count = num_cols; count > 0; count--)
  178395. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178396. #endif
  178397. }
  178398. }
  178399. GLOBAL(void)
  178400. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178401. JDIMENSION num_blocks)
  178402. /* Copy a row of coefficient blocks from one place to another. */
  178403. {
  178404. #ifdef FMEMCOPY
  178405. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178406. #else
  178407. register JCOEFPTR inptr, outptr;
  178408. register long count;
  178409. inptr = (JCOEFPTR) input_row;
  178410. outptr = (JCOEFPTR) output_row;
  178411. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178412. *outptr++ = *inptr++;
  178413. }
  178414. #endif
  178415. }
  178416. GLOBAL(void)
  178417. jzero_far (void FAR * target, size_t bytestozero)
  178418. /* Zero out a chunk of FAR memory. */
  178419. /* This might be sample-array data, block-array data, or alloc_large data. */
  178420. {
  178421. #ifdef FMEMZERO
  178422. FMEMZERO(target, bytestozero);
  178423. #else
  178424. register char FAR * ptr = (char FAR *) target;
  178425. register size_t count;
  178426. for (count = bytestozero; count > 0; count--) {
  178427. *ptr++ = 0;
  178428. }
  178429. #endif
  178430. }
  178431. /*** End of inlined file: jutils.c ***/
  178432. /*** Start of inlined file: transupp.c ***/
  178433. /* Although this file really shouldn't have access to the library internals,
  178434. * it's helpful to let it call jround_up() and jcopy_block_row().
  178435. */
  178436. #define JPEG_INTERNALS
  178437. /*** Start of inlined file: transupp.h ***/
  178438. /* If you happen not to want the image transform support, disable it here */
  178439. #ifndef TRANSFORMS_SUPPORTED
  178440. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178441. #endif
  178442. /* Short forms of external names for systems with brain-damaged linkers. */
  178443. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178444. #define jtransform_request_workspace jTrRequest
  178445. #define jtransform_adjust_parameters jTrAdjust
  178446. #define jtransform_execute_transformation jTrExec
  178447. #define jcopy_markers_setup jCMrkSetup
  178448. #define jcopy_markers_execute jCMrkExec
  178449. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178450. /*
  178451. * Codes for supported types of image transformations.
  178452. */
  178453. typedef enum {
  178454. JXFORM_NONE, /* no transformation */
  178455. JXFORM_FLIP_H, /* horizontal flip */
  178456. JXFORM_FLIP_V, /* vertical flip */
  178457. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178458. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178459. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178460. JXFORM_ROT_180, /* 180-degree rotation */
  178461. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178462. } JXFORM_CODE;
  178463. /*
  178464. * Although rotating and flipping data expressed as DCT coefficients is not
  178465. * hard, there is an asymmetry in the JPEG format specification for images
  178466. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178467. * image edges are padded out to the next iMCU boundary with junk data; but
  178468. * no padding is possible at the top and left edges. If we were to flip
  178469. * the whole image including the pad data, then pad garbage would become
  178470. * visible at the top and/or left, and real pixels would disappear into the
  178471. * pad margins --- perhaps permanently, since encoders & decoders may not
  178472. * bother to preserve DCT blocks that appear to be completely outside the
  178473. * nominal image area. So, we have to exclude any partial iMCUs from the
  178474. * basic transformation.
  178475. *
  178476. * Transpose is the only transformation that can handle partial iMCUs at the
  178477. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178478. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178479. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178480. * The other transforms are defined as combinations of these basic transforms
  178481. * and process edge blocks in a way that preserves the equivalence.
  178482. *
  178483. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178484. * this is not strictly lossless, but it usually gives the best-looking
  178485. * result for odd-size images. Note that when this option is active,
  178486. * the expected mathematical equivalences between the transforms may not hold.
  178487. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178488. * followed by -rot 180 -trim trims both edges.)
  178489. *
  178490. * We also offer a "force to grayscale" option, which simply discards the
  178491. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178492. * the luminance channel is preserved exactly. It's not the same kind of
  178493. * thing as the rotate/flip transformations, but it's convenient to handle it
  178494. * as part of this package, mainly because the transformation routines have to
  178495. * be aware of the option to know how many components to work on.
  178496. */
  178497. typedef struct {
  178498. /* Options: set by caller */
  178499. JXFORM_CODE transform; /* image transform operator */
  178500. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178501. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178502. /* Internal workspace: caller should not touch these */
  178503. int num_components; /* # of components in workspace */
  178504. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178505. } jpeg_transform_info;
  178506. #if TRANSFORMS_SUPPORTED
  178507. /* Request any required workspace */
  178508. EXTERN(void) jtransform_request_workspace
  178509. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178510. /* Adjust output image parameters */
  178511. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178512. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178513. jvirt_barray_ptr *src_coef_arrays,
  178514. jpeg_transform_info *info));
  178515. /* Execute the actual transformation, if any */
  178516. EXTERN(void) jtransform_execute_transformation
  178517. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178518. jvirt_barray_ptr *src_coef_arrays,
  178519. jpeg_transform_info *info));
  178520. #endif /* TRANSFORMS_SUPPORTED */
  178521. /*
  178522. * Support for copying optional markers from source to destination file.
  178523. */
  178524. typedef enum {
  178525. JCOPYOPT_NONE, /* copy no optional markers */
  178526. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178527. JCOPYOPT_ALL /* copy all optional markers */
  178528. } JCOPY_OPTION;
  178529. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178530. /* Setup decompression object to save desired markers in memory */
  178531. EXTERN(void) jcopy_markers_setup
  178532. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178533. /* Copy markers saved in the given source object to the destination object */
  178534. EXTERN(void) jcopy_markers_execute
  178535. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178536. JCOPY_OPTION option));
  178537. /*** End of inlined file: transupp.h ***/
  178538. /* My own external interface */
  178539. #if TRANSFORMS_SUPPORTED
  178540. /*
  178541. * Lossless image transformation routines. These routines work on DCT
  178542. * coefficient arrays and thus do not require any lossy decompression
  178543. * or recompression of the image.
  178544. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178545. *
  178546. * Horizontal flipping is done in-place, using a single top-to-bottom
  178547. * pass through the virtual source array. It will thus be much the
  178548. * fastest option for images larger than main memory.
  178549. *
  178550. * The other routines require a set of destination virtual arrays, so they
  178551. * need twice as much memory as jpegtran normally does. The destination
  178552. * arrays are always written in normal scan order (top to bottom) because
  178553. * the virtual array manager expects this. The source arrays will be scanned
  178554. * in the corresponding order, which means multiple passes through the source
  178555. * arrays for most of the transforms. That could result in much thrashing
  178556. * if the image is larger than main memory.
  178557. *
  178558. * Some notes about the operating environment of the individual transform
  178559. * routines:
  178560. * 1. Both the source and destination virtual arrays are allocated from the
  178561. * source JPEG object, and therefore should be manipulated by calling the
  178562. * source's memory manager.
  178563. * 2. The destination's component count should be used. It may be smaller
  178564. * than the source's when forcing to grayscale.
  178565. * 3. Likewise the destination's sampling factors should be used. When
  178566. * forcing to grayscale the destination's sampling factors will be all 1,
  178567. * and we may as well take that as the effective iMCU size.
  178568. * 4. When "trim" is in effect, the destination's dimensions will be the
  178569. * trimmed values but the source's will be untrimmed.
  178570. * 5. All the routines assume that the source and destination buffers are
  178571. * padded out to a full iMCU boundary. This is true, although for the
  178572. * source buffer it is an undocumented property of jdcoefct.c.
  178573. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178574. * dimensions and ignore the source's.
  178575. */
  178576. LOCAL(void)
  178577. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178578. jvirt_barray_ptr *src_coef_arrays)
  178579. /* Horizontal flip; done in-place, so no separate dest array is required */
  178580. {
  178581. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178582. int ci, k, offset_y;
  178583. JBLOCKARRAY buffer;
  178584. JCOEFPTR ptr1, ptr2;
  178585. JCOEF temp1, temp2;
  178586. jpeg_component_info *compptr;
  178587. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178588. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178589. * mirroring by changing the signs of odd-numbered columns.
  178590. * Partial iMCUs at the right edge are left untouched.
  178591. */
  178592. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178593. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178594. compptr = dstinfo->comp_info + ci;
  178595. comp_width = MCU_cols * compptr->h_samp_factor;
  178596. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178597. blk_y += compptr->v_samp_factor) {
  178598. buffer = (*srcinfo->mem->access_virt_barray)
  178599. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178600. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178601. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178602. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178603. ptr1 = buffer[offset_y][blk_x];
  178604. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178605. /* this unrolled loop doesn't need to know which row it's on... */
  178606. for (k = 0; k < DCTSIZE2; k += 2) {
  178607. temp1 = *ptr1; /* swap even column */
  178608. temp2 = *ptr2;
  178609. *ptr1++ = temp2;
  178610. *ptr2++ = temp1;
  178611. temp1 = *ptr1; /* swap odd column with sign change */
  178612. temp2 = *ptr2;
  178613. *ptr1++ = -temp2;
  178614. *ptr2++ = -temp1;
  178615. }
  178616. }
  178617. }
  178618. }
  178619. }
  178620. }
  178621. LOCAL(void)
  178622. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178623. jvirt_barray_ptr *src_coef_arrays,
  178624. jvirt_barray_ptr *dst_coef_arrays)
  178625. /* Vertical flip */
  178626. {
  178627. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178628. int ci, i, j, offset_y;
  178629. JBLOCKARRAY src_buffer, dst_buffer;
  178630. JBLOCKROW src_row_ptr, dst_row_ptr;
  178631. JCOEFPTR src_ptr, dst_ptr;
  178632. jpeg_component_info *compptr;
  178633. /* We output into a separate array because we can't touch different
  178634. * rows of the source virtual array simultaneously. Otherwise, this
  178635. * is a pretty straightforward analog of horizontal flip.
  178636. * Within a DCT block, vertical mirroring is done by changing the signs
  178637. * of odd-numbered rows.
  178638. * Partial iMCUs at the bottom edge are copied verbatim.
  178639. */
  178640. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178641. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178642. compptr = dstinfo->comp_info + ci;
  178643. comp_height = MCU_rows * compptr->v_samp_factor;
  178644. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178645. dst_blk_y += compptr->v_samp_factor) {
  178646. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178647. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178648. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178649. if (dst_blk_y < comp_height) {
  178650. /* Row is within the mirrorable area. */
  178651. src_buffer = (*srcinfo->mem->access_virt_barray)
  178652. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178653. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178654. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178655. } else {
  178656. /* Bottom-edge blocks will be copied verbatim. */
  178657. src_buffer = (*srcinfo->mem->access_virt_barray)
  178658. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178659. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178660. }
  178661. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178662. if (dst_blk_y < comp_height) {
  178663. /* Row is within the mirrorable area. */
  178664. dst_row_ptr = dst_buffer[offset_y];
  178665. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178666. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178667. dst_blk_x++) {
  178668. dst_ptr = dst_row_ptr[dst_blk_x];
  178669. src_ptr = src_row_ptr[dst_blk_x];
  178670. for (i = 0; i < DCTSIZE; i += 2) {
  178671. /* copy even row */
  178672. for (j = 0; j < DCTSIZE; j++)
  178673. *dst_ptr++ = *src_ptr++;
  178674. /* copy odd row with sign change */
  178675. for (j = 0; j < DCTSIZE; j++)
  178676. *dst_ptr++ = - *src_ptr++;
  178677. }
  178678. }
  178679. } else {
  178680. /* Just copy row verbatim. */
  178681. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178682. compptr->width_in_blocks);
  178683. }
  178684. }
  178685. }
  178686. }
  178687. }
  178688. LOCAL(void)
  178689. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178690. jvirt_barray_ptr *src_coef_arrays,
  178691. jvirt_barray_ptr *dst_coef_arrays)
  178692. /* Transpose source into destination */
  178693. {
  178694. JDIMENSION dst_blk_x, dst_blk_y;
  178695. int ci, i, j, offset_x, offset_y;
  178696. JBLOCKARRAY src_buffer, dst_buffer;
  178697. JCOEFPTR src_ptr, dst_ptr;
  178698. jpeg_component_info *compptr;
  178699. /* Transposing pixels within a block just requires transposing the
  178700. * DCT coefficients.
  178701. * Partial iMCUs at the edges require no special treatment; we simply
  178702. * process all the available DCT blocks for every component.
  178703. */
  178704. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178705. compptr = dstinfo->comp_info + ci;
  178706. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178707. dst_blk_y += compptr->v_samp_factor) {
  178708. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178709. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178710. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178711. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178712. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178713. dst_blk_x += compptr->h_samp_factor) {
  178714. src_buffer = (*srcinfo->mem->access_virt_barray)
  178715. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178716. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178717. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178718. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178719. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178720. for (i = 0; i < DCTSIZE; i++)
  178721. for (j = 0; j < DCTSIZE; j++)
  178722. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178723. }
  178724. }
  178725. }
  178726. }
  178727. }
  178728. }
  178729. LOCAL(void)
  178730. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178731. jvirt_barray_ptr *src_coef_arrays,
  178732. jvirt_barray_ptr *dst_coef_arrays)
  178733. /* 90 degree rotation is equivalent to
  178734. * 1. Transposing the image;
  178735. * 2. Horizontal mirroring.
  178736. * These two steps are merged into a single processing routine.
  178737. */
  178738. {
  178739. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178740. int ci, i, j, offset_x, offset_y;
  178741. JBLOCKARRAY src_buffer, dst_buffer;
  178742. JCOEFPTR src_ptr, dst_ptr;
  178743. jpeg_component_info *compptr;
  178744. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178745. * at the (output) right edge properly. They just get transposed and
  178746. * not mirrored.
  178747. */
  178748. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178749. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178750. compptr = dstinfo->comp_info + ci;
  178751. comp_width = MCU_cols * compptr->h_samp_factor;
  178752. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178753. dst_blk_y += compptr->v_samp_factor) {
  178754. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178755. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178756. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178757. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178758. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178759. dst_blk_x += compptr->h_samp_factor) {
  178760. src_buffer = (*srcinfo->mem->access_virt_barray)
  178761. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178762. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178763. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178764. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178765. if (dst_blk_x < comp_width) {
  178766. /* Block is within the mirrorable area. */
  178767. dst_ptr = dst_buffer[offset_y]
  178768. [comp_width - dst_blk_x - offset_x - 1];
  178769. for (i = 0; i < DCTSIZE; i++) {
  178770. for (j = 0; j < DCTSIZE; j++)
  178771. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178772. i++;
  178773. for (j = 0; j < DCTSIZE; j++)
  178774. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178775. }
  178776. } else {
  178777. /* Edge blocks are transposed but not mirrored. */
  178778. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178779. for (i = 0; i < DCTSIZE; i++)
  178780. for (j = 0; j < DCTSIZE; j++)
  178781. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178782. }
  178783. }
  178784. }
  178785. }
  178786. }
  178787. }
  178788. }
  178789. LOCAL(void)
  178790. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178791. jvirt_barray_ptr *src_coef_arrays,
  178792. jvirt_barray_ptr *dst_coef_arrays)
  178793. /* 270 degree rotation is equivalent to
  178794. * 1. Horizontal mirroring;
  178795. * 2. Transposing the image.
  178796. * These two steps are merged into a single processing routine.
  178797. */
  178798. {
  178799. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178800. int ci, i, j, offset_x, offset_y;
  178801. JBLOCKARRAY src_buffer, dst_buffer;
  178802. JCOEFPTR src_ptr, dst_ptr;
  178803. jpeg_component_info *compptr;
  178804. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178805. * at the (output) bottom edge properly. They just get transposed and
  178806. * not mirrored.
  178807. */
  178808. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178809. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178810. compptr = dstinfo->comp_info + ci;
  178811. comp_height = MCU_rows * compptr->v_samp_factor;
  178812. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178813. dst_blk_y += compptr->v_samp_factor) {
  178814. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178815. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178816. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178817. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178818. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178819. dst_blk_x += compptr->h_samp_factor) {
  178820. src_buffer = (*srcinfo->mem->access_virt_barray)
  178821. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178822. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178823. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178824. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178825. if (dst_blk_y < comp_height) {
  178826. /* Block is within the mirrorable area. */
  178827. src_ptr = src_buffer[offset_x]
  178828. [comp_height - dst_blk_y - offset_y - 1];
  178829. for (i = 0; i < DCTSIZE; i++) {
  178830. for (j = 0; j < DCTSIZE; j++) {
  178831. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178832. j++;
  178833. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178834. }
  178835. }
  178836. } else {
  178837. /* Edge blocks are transposed but not mirrored. */
  178838. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178839. for (i = 0; i < DCTSIZE; i++)
  178840. for (j = 0; j < DCTSIZE; j++)
  178841. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178842. }
  178843. }
  178844. }
  178845. }
  178846. }
  178847. }
  178848. }
  178849. LOCAL(void)
  178850. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178851. jvirt_barray_ptr *src_coef_arrays,
  178852. jvirt_barray_ptr *dst_coef_arrays)
  178853. /* 180 degree rotation is equivalent to
  178854. * 1. Vertical mirroring;
  178855. * 2. Horizontal mirroring.
  178856. * These two steps are merged into a single processing routine.
  178857. */
  178858. {
  178859. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178860. int ci, i, j, offset_y;
  178861. JBLOCKARRAY src_buffer, dst_buffer;
  178862. JBLOCKROW src_row_ptr, dst_row_ptr;
  178863. JCOEFPTR src_ptr, dst_ptr;
  178864. jpeg_component_info *compptr;
  178865. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178866. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178867. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178868. compptr = dstinfo->comp_info + ci;
  178869. comp_width = MCU_cols * compptr->h_samp_factor;
  178870. comp_height = MCU_rows * compptr->v_samp_factor;
  178871. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178872. dst_blk_y += compptr->v_samp_factor) {
  178873. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178874. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178875. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178876. if (dst_blk_y < comp_height) {
  178877. /* Row is within the vertically mirrorable area. */
  178878. src_buffer = (*srcinfo->mem->access_virt_barray)
  178879. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178880. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178881. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178882. } else {
  178883. /* Bottom-edge rows are only mirrored horizontally. */
  178884. src_buffer = (*srcinfo->mem->access_virt_barray)
  178885. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178886. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178887. }
  178888. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178889. if (dst_blk_y < comp_height) {
  178890. /* Row is within the mirrorable area. */
  178891. dst_row_ptr = dst_buffer[offset_y];
  178892. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178893. /* Process the blocks that can be mirrored both ways. */
  178894. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178895. dst_ptr = dst_row_ptr[dst_blk_x];
  178896. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178897. for (i = 0; i < DCTSIZE; i += 2) {
  178898. /* For even row, negate every odd column. */
  178899. for (j = 0; j < DCTSIZE; j += 2) {
  178900. *dst_ptr++ = *src_ptr++;
  178901. *dst_ptr++ = - *src_ptr++;
  178902. }
  178903. /* For odd row, negate every even column. */
  178904. for (j = 0; j < DCTSIZE; j += 2) {
  178905. *dst_ptr++ = - *src_ptr++;
  178906. *dst_ptr++ = *src_ptr++;
  178907. }
  178908. }
  178909. }
  178910. /* Any remaining right-edge blocks are only mirrored vertically. */
  178911. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178912. dst_ptr = dst_row_ptr[dst_blk_x];
  178913. src_ptr = src_row_ptr[dst_blk_x];
  178914. for (i = 0; i < DCTSIZE; i += 2) {
  178915. for (j = 0; j < DCTSIZE; j++)
  178916. *dst_ptr++ = *src_ptr++;
  178917. for (j = 0; j < DCTSIZE; j++)
  178918. *dst_ptr++ = - *src_ptr++;
  178919. }
  178920. }
  178921. } else {
  178922. /* Remaining rows are just mirrored horizontally. */
  178923. dst_row_ptr = dst_buffer[offset_y];
  178924. src_row_ptr = src_buffer[offset_y];
  178925. /* Process the blocks that can be mirrored. */
  178926. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178927. dst_ptr = dst_row_ptr[dst_blk_x];
  178928. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178929. for (i = 0; i < DCTSIZE2; i += 2) {
  178930. *dst_ptr++ = *src_ptr++;
  178931. *dst_ptr++ = - *src_ptr++;
  178932. }
  178933. }
  178934. /* Any remaining right-edge blocks are only copied. */
  178935. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178936. dst_ptr = dst_row_ptr[dst_blk_x];
  178937. src_ptr = src_row_ptr[dst_blk_x];
  178938. for (i = 0; i < DCTSIZE2; i++)
  178939. *dst_ptr++ = *src_ptr++;
  178940. }
  178941. }
  178942. }
  178943. }
  178944. }
  178945. }
  178946. LOCAL(void)
  178947. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178948. jvirt_barray_ptr *src_coef_arrays,
  178949. jvirt_barray_ptr *dst_coef_arrays)
  178950. /* Transverse transpose is equivalent to
  178951. * 1. 180 degree rotation;
  178952. * 2. Transposition;
  178953. * or
  178954. * 1. Horizontal mirroring;
  178955. * 2. Transposition;
  178956. * 3. Horizontal mirroring.
  178957. * These steps are merged into a single processing routine.
  178958. */
  178959. {
  178960. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178961. int ci, i, j, offset_x, offset_y;
  178962. JBLOCKARRAY src_buffer, dst_buffer;
  178963. JCOEFPTR src_ptr, dst_ptr;
  178964. jpeg_component_info *compptr;
  178965. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178966. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178967. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178968. compptr = dstinfo->comp_info + ci;
  178969. comp_width = MCU_cols * compptr->h_samp_factor;
  178970. comp_height = MCU_rows * compptr->v_samp_factor;
  178971. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178972. dst_blk_y += compptr->v_samp_factor) {
  178973. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178974. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178975. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178976. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178977. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178978. dst_blk_x += compptr->h_samp_factor) {
  178979. src_buffer = (*srcinfo->mem->access_virt_barray)
  178980. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178981. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178982. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178983. if (dst_blk_y < comp_height) {
  178984. src_ptr = src_buffer[offset_x]
  178985. [comp_height - dst_blk_y - offset_y - 1];
  178986. if (dst_blk_x < comp_width) {
  178987. /* Block is within the mirrorable area. */
  178988. dst_ptr = dst_buffer[offset_y]
  178989. [comp_width - dst_blk_x - offset_x - 1];
  178990. for (i = 0; i < DCTSIZE; i++) {
  178991. for (j = 0; j < DCTSIZE; j++) {
  178992. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178993. j++;
  178994. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178995. }
  178996. i++;
  178997. for (j = 0; j < DCTSIZE; j++) {
  178998. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178999. j++;
  179000. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179001. }
  179002. }
  179003. } else {
  179004. /* Right-edge blocks are mirrored in y only */
  179005. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179006. for (i = 0; i < DCTSIZE; i++) {
  179007. for (j = 0; j < DCTSIZE; j++) {
  179008. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179009. j++;
  179010. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179011. }
  179012. }
  179013. }
  179014. } else {
  179015. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179016. if (dst_blk_x < comp_width) {
  179017. /* Bottom-edge blocks are mirrored in x only */
  179018. dst_ptr = dst_buffer[offset_y]
  179019. [comp_width - dst_blk_x - offset_x - 1];
  179020. for (i = 0; i < DCTSIZE; i++) {
  179021. for (j = 0; j < DCTSIZE; j++)
  179022. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179023. i++;
  179024. for (j = 0; j < DCTSIZE; j++)
  179025. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179026. }
  179027. } else {
  179028. /* At lower right corner, just transpose, no mirroring */
  179029. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179030. for (i = 0; i < DCTSIZE; i++)
  179031. for (j = 0; j < DCTSIZE; j++)
  179032. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179033. }
  179034. }
  179035. }
  179036. }
  179037. }
  179038. }
  179039. }
  179040. }
  179041. /* Request any required workspace.
  179042. *
  179043. * We allocate the workspace virtual arrays from the source decompression
  179044. * object, so that all the arrays (both the original data and the workspace)
  179045. * will be taken into account while making memory management decisions.
  179046. * Hence, this routine must be called after jpeg_read_header (which reads
  179047. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179048. * the source's virtual arrays).
  179049. */
  179050. GLOBAL(void)
  179051. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179052. jpeg_transform_info *info)
  179053. {
  179054. jvirt_barray_ptr *coef_arrays = NULL;
  179055. jpeg_component_info *compptr;
  179056. int ci;
  179057. if (info->force_grayscale &&
  179058. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179059. srcinfo->num_components == 3) {
  179060. /* We'll only process the first component */
  179061. info->num_components = 1;
  179062. } else {
  179063. /* Process all the components */
  179064. info->num_components = srcinfo->num_components;
  179065. }
  179066. switch (info->transform) {
  179067. case JXFORM_NONE:
  179068. case JXFORM_FLIP_H:
  179069. /* Don't need a workspace array */
  179070. break;
  179071. case JXFORM_FLIP_V:
  179072. case JXFORM_ROT_180:
  179073. /* Need workspace arrays having same dimensions as source image.
  179074. * Note that we allocate arrays padded out to the next iMCU boundary,
  179075. * so that transform routines need not worry about missing edge blocks.
  179076. */
  179077. coef_arrays = (jvirt_barray_ptr *)
  179078. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179079. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179080. for (ci = 0; ci < info->num_components; ci++) {
  179081. compptr = srcinfo->comp_info + ci;
  179082. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179083. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179084. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179085. (long) compptr->h_samp_factor),
  179086. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179087. (long) compptr->v_samp_factor),
  179088. (JDIMENSION) compptr->v_samp_factor);
  179089. }
  179090. break;
  179091. case JXFORM_TRANSPOSE:
  179092. case JXFORM_TRANSVERSE:
  179093. case JXFORM_ROT_90:
  179094. case JXFORM_ROT_270:
  179095. /* Need workspace arrays having transposed dimensions.
  179096. * Note that we allocate arrays padded out to the next iMCU boundary,
  179097. * so that transform routines need not worry about missing edge blocks.
  179098. */
  179099. coef_arrays = (jvirt_barray_ptr *)
  179100. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179101. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179102. for (ci = 0; ci < info->num_components; ci++) {
  179103. compptr = srcinfo->comp_info + ci;
  179104. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179105. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179106. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179107. (long) compptr->v_samp_factor),
  179108. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179109. (long) compptr->h_samp_factor),
  179110. (JDIMENSION) compptr->h_samp_factor);
  179111. }
  179112. break;
  179113. }
  179114. info->workspace_coef_arrays = coef_arrays;
  179115. }
  179116. /* Transpose destination image parameters */
  179117. LOCAL(void)
  179118. transpose_critical_parameters (j_compress_ptr dstinfo)
  179119. {
  179120. int tblno, i, j, ci, itemp;
  179121. jpeg_component_info *compptr;
  179122. JQUANT_TBL *qtblptr;
  179123. JDIMENSION dtemp;
  179124. UINT16 qtemp;
  179125. /* Transpose basic image dimensions */
  179126. dtemp = dstinfo->image_width;
  179127. dstinfo->image_width = dstinfo->image_height;
  179128. dstinfo->image_height = dtemp;
  179129. /* Transpose sampling factors */
  179130. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179131. compptr = dstinfo->comp_info + ci;
  179132. itemp = compptr->h_samp_factor;
  179133. compptr->h_samp_factor = compptr->v_samp_factor;
  179134. compptr->v_samp_factor = itemp;
  179135. }
  179136. /* Transpose quantization tables */
  179137. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179138. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179139. if (qtblptr != NULL) {
  179140. for (i = 0; i < DCTSIZE; i++) {
  179141. for (j = 0; j < i; j++) {
  179142. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179143. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179144. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179145. }
  179146. }
  179147. }
  179148. }
  179149. }
  179150. /* Trim off any partial iMCUs on the indicated destination edge */
  179151. LOCAL(void)
  179152. trim_right_edge (j_compress_ptr dstinfo)
  179153. {
  179154. int ci, max_h_samp_factor;
  179155. JDIMENSION MCU_cols;
  179156. /* We have to compute max_h_samp_factor ourselves,
  179157. * because it hasn't been set yet in the destination
  179158. * (and we don't want to use the source's value).
  179159. */
  179160. max_h_samp_factor = 1;
  179161. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179162. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179163. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179164. }
  179165. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179166. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179167. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179168. }
  179169. LOCAL(void)
  179170. trim_bottom_edge (j_compress_ptr dstinfo)
  179171. {
  179172. int ci, max_v_samp_factor;
  179173. JDIMENSION MCU_rows;
  179174. /* We have to compute max_v_samp_factor ourselves,
  179175. * because it hasn't been set yet in the destination
  179176. * (and we don't want to use the source's value).
  179177. */
  179178. max_v_samp_factor = 1;
  179179. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179180. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179181. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179182. }
  179183. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179184. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179185. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179186. }
  179187. /* Adjust output image parameters as needed.
  179188. *
  179189. * This must be called after jpeg_copy_critical_parameters()
  179190. * and before jpeg_write_coefficients().
  179191. *
  179192. * The return value is the set of virtual coefficient arrays to be written
  179193. * (either the ones allocated by jtransform_request_workspace, or the
  179194. * original source data arrays). The caller will need to pass this value
  179195. * to jpeg_write_coefficients().
  179196. */
  179197. GLOBAL(jvirt_barray_ptr *)
  179198. jtransform_adjust_parameters (j_decompress_ptr,
  179199. j_compress_ptr dstinfo,
  179200. jvirt_barray_ptr *src_coef_arrays,
  179201. jpeg_transform_info *info)
  179202. {
  179203. /* If force-to-grayscale is requested, adjust destination parameters */
  179204. if (info->force_grayscale) {
  179205. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179206. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179207. * will get set to 1, which typically won't match the source.
  179208. * In fact we do this even if the source is already grayscale; that
  179209. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179210. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179211. */
  179212. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179213. dstinfo->num_components == 3) ||
  179214. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179215. dstinfo->num_components == 1)) {
  179216. /* We have to preserve the source's quantization table number. */
  179217. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179218. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179219. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179220. } else {
  179221. /* Sorry, can't do it */
  179222. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179223. }
  179224. }
  179225. /* Correct the destination's image dimensions etc if necessary */
  179226. switch (info->transform) {
  179227. case JXFORM_NONE:
  179228. /* Nothing to do */
  179229. break;
  179230. case JXFORM_FLIP_H:
  179231. if (info->trim)
  179232. trim_right_edge(dstinfo);
  179233. break;
  179234. case JXFORM_FLIP_V:
  179235. if (info->trim)
  179236. trim_bottom_edge(dstinfo);
  179237. break;
  179238. case JXFORM_TRANSPOSE:
  179239. transpose_critical_parameters(dstinfo);
  179240. /* transpose does NOT have to trim anything */
  179241. break;
  179242. case JXFORM_TRANSVERSE:
  179243. transpose_critical_parameters(dstinfo);
  179244. if (info->trim) {
  179245. trim_right_edge(dstinfo);
  179246. trim_bottom_edge(dstinfo);
  179247. }
  179248. break;
  179249. case JXFORM_ROT_90:
  179250. transpose_critical_parameters(dstinfo);
  179251. if (info->trim)
  179252. trim_right_edge(dstinfo);
  179253. break;
  179254. case JXFORM_ROT_180:
  179255. if (info->trim) {
  179256. trim_right_edge(dstinfo);
  179257. trim_bottom_edge(dstinfo);
  179258. }
  179259. break;
  179260. case JXFORM_ROT_270:
  179261. transpose_critical_parameters(dstinfo);
  179262. if (info->trim)
  179263. trim_bottom_edge(dstinfo);
  179264. break;
  179265. }
  179266. /* Return the appropriate output data set */
  179267. if (info->workspace_coef_arrays != NULL)
  179268. return info->workspace_coef_arrays;
  179269. return src_coef_arrays;
  179270. }
  179271. /* Execute the actual transformation, if any.
  179272. *
  179273. * This must be called *after* jpeg_write_coefficients, because it depends
  179274. * on jpeg_write_coefficients to have computed subsidiary values such as
  179275. * the per-component width and height fields in the destination object.
  179276. *
  179277. * Note that some transformations will modify the source data arrays!
  179278. */
  179279. GLOBAL(void)
  179280. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179281. j_compress_ptr dstinfo,
  179282. jvirt_barray_ptr *src_coef_arrays,
  179283. jpeg_transform_info *info)
  179284. {
  179285. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179286. switch (info->transform) {
  179287. case JXFORM_NONE:
  179288. break;
  179289. case JXFORM_FLIP_H:
  179290. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179291. break;
  179292. case JXFORM_FLIP_V:
  179293. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179294. break;
  179295. case JXFORM_TRANSPOSE:
  179296. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179297. break;
  179298. case JXFORM_TRANSVERSE:
  179299. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179300. break;
  179301. case JXFORM_ROT_90:
  179302. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179303. break;
  179304. case JXFORM_ROT_180:
  179305. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179306. break;
  179307. case JXFORM_ROT_270:
  179308. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179309. break;
  179310. }
  179311. }
  179312. #endif /* TRANSFORMS_SUPPORTED */
  179313. /* Setup decompression object to save desired markers in memory.
  179314. * This must be called before jpeg_read_header() to have the desired effect.
  179315. */
  179316. GLOBAL(void)
  179317. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179318. {
  179319. #ifdef SAVE_MARKERS_SUPPORTED
  179320. int m;
  179321. /* Save comments except under NONE option */
  179322. if (option != JCOPYOPT_NONE) {
  179323. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179324. }
  179325. /* Save all types of APPn markers iff ALL option */
  179326. if (option == JCOPYOPT_ALL) {
  179327. for (m = 0; m < 16; m++)
  179328. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179329. }
  179330. #endif /* SAVE_MARKERS_SUPPORTED */
  179331. }
  179332. /* Copy markers saved in the given source object to the destination object.
  179333. * This should be called just after jpeg_start_compress() or
  179334. * jpeg_write_coefficients().
  179335. * Note that those routines will have written the SOI, and also the
  179336. * JFIF APP0 or Adobe APP14 markers if selected.
  179337. */
  179338. GLOBAL(void)
  179339. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179340. JCOPY_OPTION)
  179341. {
  179342. jpeg_saved_marker_ptr marker;
  179343. /* In the current implementation, we don't actually need to examine the
  179344. * option flag here; we just copy everything that got saved.
  179345. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179346. * if the encoder library already wrote one.
  179347. */
  179348. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179349. if (dstinfo->write_JFIF_header &&
  179350. marker->marker == JPEG_APP0 &&
  179351. marker->data_length >= 5 &&
  179352. GETJOCTET(marker->data[0]) == 0x4A &&
  179353. GETJOCTET(marker->data[1]) == 0x46 &&
  179354. GETJOCTET(marker->data[2]) == 0x49 &&
  179355. GETJOCTET(marker->data[3]) == 0x46 &&
  179356. GETJOCTET(marker->data[4]) == 0)
  179357. continue; /* reject duplicate JFIF */
  179358. if (dstinfo->write_Adobe_marker &&
  179359. marker->marker == JPEG_APP0+14 &&
  179360. marker->data_length >= 5 &&
  179361. GETJOCTET(marker->data[0]) == 0x41 &&
  179362. GETJOCTET(marker->data[1]) == 0x64 &&
  179363. GETJOCTET(marker->data[2]) == 0x6F &&
  179364. GETJOCTET(marker->data[3]) == 0x62 &&
  179365. GETJOCTET(marker->data[4]) == 0x65)
  179366. continue; /* reject duplicate Adobe */
  179367. #ifdef NEED_FAR_POINTERS
  179368. /* We could use jpeg_write_marker if the data weren't FAR... */
  179369. {
  179370. unsigned int i;
  179371. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179372. for (i = 0; i < marker->data_length; i++)
  179373. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179374. }
  179375. #else
  179376. jpeg_write_marker(dstinfo, marker->marker,
  179377. marker->data, marker->data_length);
  179378. #endif
  179379. }
  179380. }
  179381. /*** End of inlined file: transupp.c ***/
  179382. }
  179383. #else
  179384. #define JPEG_INTERNALS
  179385. #undef FAR
  179386. #include <jpeglib.h>
  179387. #endif
  179388. }
  179389. #undef max
  179390. #undef min
  179391. #if JUCE_MSVC
  179392. #pragma warning (pop)
  179393. #endif
  179394. BEGIN_JUCE_NAMESPACE
  179395. namespace JPEGHelpers
  179396. {
  179397. using namespace jpeglibNamespace;
  179398. #if ! JUCE_MSVC
  179399. using jpeglibNamespace::boolean;
  179400. #endif
  179401. struct JPEGDecodingFailure {};
  179402. static void fatalErrorHandler (j_common_ptr)
  179403. {
  179404. throw JPEGDecodingFailure();
  179405. }
  179406. static void silentErrorCallback1 (j_common_ptr) {}
  179407. static void silentErrorCallback2 (j_common_ptr, int) {}
  179408. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179409. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179410. {
  179411. zerostruct (err);
  179412. err.error_exit = fatalErrorHandler;
  179413. err.emit_message = silentErrorCallback2;
  179414. err.output_message = silentErrorCallback1;
  179415. err.format_message = silentErrorCallback3;
  179416. err.reset_error_mgr = silentErrorCallback1;
  179417. }
  179418. static void dummyCallback1 (j_decompress_ptr)
  179419. {
  179420. }
  179421. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179422. {
  179423. decompStruct->src->next_input_byte += num;
  179424. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179425. decompStruct->src->bytes_in_buffer -= num;
  179426. }
  179427. static boolean jpegFill (j_decompress_ptr)
  179428. {
  179429. return 0;
  179430. }
  179431. static const int jpegBufferSize = 512;
  179432. struct JuceJpegDest : public jpeg_destination_mgr
  179433. {
  179434. OutputStream* output;
  179435. char* buffer;
  179436. };
  179437. static void jpegWriteInit (j_compress_ptr)
  179438. {
  179439. }
  179440. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179441. {
  179442. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179443. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179444. dest->output->write (dest->buffer, (int) numToWrite);
  179445. }
  179446. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179447. {
  179448. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179449. const int numToWrite = jpegBufferSize;
  179450. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179451. dest->free_in_buffer = jpegBufferSize;
  179452. return dest->output->write (dest->buffer, numToWrite);
  179453. }
  179454. }
  179455. JPEGImageFormat::JPEGImageFormat()
  179456. : quality (-1.0f)
  179457. {
  179458. }
  179459. JPEGImageFormat::~JPEGImageFormat() {}
  179460. void JPEGImageFormat::setQuality (const float newQuality)
  179461. {
  179462. quality = newQuality;
  179463. }
  179464. const String JPEGImageFormat::getFormatName()
  179465. {
  179466. return "JPEG";
  179467. }
  179468. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179469. {
  179470. const int bytesNeeded = 10;
  179471. uint8 header [bytesNeeded];
  179472. if (in.read (header, bytesNeeded) == bytesNeeded)
  179473. {
  179474. return header[0] == 0xff
  179475. && header[1] == 0xd8
  179476. && header[2] == 0xff
  179477. && (header[3] == 0xe0 || header[3] == 0xe1);
  179478. }
  179479. return false;
  179480. }
  179481. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179482. {
  179483. using namespace jpeglibNamespace;
  179484. using namespace JPEGHelpers;
  179485. MemoryOutputStream mb;
  179486. mb.writeFromInputStream (in, -1);
  179487. Image image;
  179488. if (mb.getDataSize() > 16)
  179489. {
  179490. struct jpeg_decompress_struct jpegDecompStruct;
  179491. struct jpeg_error_mgr jerr;
  179492. setupSilentErrorHandler (jerr);
  179493. jpegDecompStruct.err = &jerr;
  179494. jpeg_create_decompress (&jpegDecompStruct);
  179495. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179496. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179497. jpegDecompStruct.src->init_source = dummyCallback1;
  179498. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179499. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179500. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179501. jpegDecompStruct.src->term_source = dummyCallback1;
  179502. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179503. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179504. try
  179505. {
  179506. jpeg_read_header (&jpegDecompStruct, TRUE);
  179507. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179508. const int width = jpegDecompStruct.output_width;
  179509. const int height = jpegDecompStruct.output_height;
  179510. jpegDecompStruct.out_color_space = JCS_RGB;
  179511. JSAMPARRAY buffer
  179512. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179513. JPOOL_IMAGE,
  179514. width * 3, 1);
  179515. if (jpeg_start_decompress (&jpegDecompStruct))
  179516. {
  179517. image = Image (Image::RGB, width, height, false);
  179518. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179519. const Image::BitmapData destData (image, true);
  179520. for (int y = 0; y < height; ++y)
  179521. {
  179522. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179523. const uint8* src = *buffer;
  179524. uint8* dest = destData.getLinePointer (y);
  179525. if (hasAlphaChan)
  179526. {
  179527. for (int i = width; --i >= 0;)
  179528. {
  179529. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179530. ((PixelARGB*) dest)->premultiply();
  179531. dest += destData.pixelStride;
  179532. src += 3;
  179533. }
  179534. }
  179535. else
  179536. {
  179537. for (int i = width; --i >= 0;)
  179538. {
  179539. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179540. dest += destData.pixelStride;
  179541. src += 3;
  179542. }
  179543. }
  179544. }
  179545. jpeg_finish_decompress (&jpegDecompStruct);
  179546. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179547. }
  179548. jpeg_destroy_decompress (&jpegDecompStruct);
  179549. }
  179550. catch (...)
  179551. {}
  179552. }
  179553. return image;
  179554. }
  179555. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179556. {
  179557. using namespace jpeglibNamespace;
  179558. using namespace JPEGHelpers;
  179559. if (image.hasAlphaChannel())
  179560. {
  179561. // this method could fill the background in white and still save the image..
  179562. jassertfalse;
  179563. return true;
  179564. }
  179565. struct jpeg_compress_struct jpegCompStruct;
  179566. struct jpeg_error_mgr jerr;
  179567. setupSilentErrorHandler (jerr);
  179568. jpegCompStruct.err = &jerr;
  179569. jpeg_create_compress (&jpegCompStruct);
  179570. JuceJpegDest dest;
  179571. jpegCompStruct.dest = &dest;
  179572. dest.output = &out;
  179573. HeapBlock <char> tempBuffer (jpegBufferSize);
  179574. dest.buffer = tempBuffer;
  179575. dest.next_output_byte = (JOCTET*) dest.buffer;
  179576. dest.free_in_buffer = jpegBufferSize;
  179577. dest.init_destination = jpegWriteInit;
  179578. dest.empty_output_buffer = jpegWriteFlush;
  179579. dest.term_destination = jpegWriteTerminate;
  179580. jpegCompStruct.image_width = image.getWidth();
  179581. jpegCompStruct.image_height = image.getHeight();
  179582. jpegCompStruct.input_components = 3;
  179583. jpegCompStruct.in_color_space = JCS_RGB;
  179584. jpegCompStruct.write_JFIF_header = 1;
  179585. jpegCompStruct.X_density = 72;
  179586. jpegCompStruct.Y_density = 72;
  179587. jpeg_set_defaults (&jpegCompStruct);
  179588. jpegCompStruct.dct_method = JDCT_FLOAT;
  179589. jpegCompStruct.optimize_coding = 1;
  179590. //jpegCompStruct.smoothing_factor = 10;
  179591. if (quality < 0.0f)
  179592. quality = 0.85f;
  179593. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179594. jpeg_start_compress (&jpegCompStruct, TRUE);
  179595. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179596. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179597. JPOOL_IMAGE, strideBytes, 1);
  179598. const Image::BitmapData srcData (image, false);
  179599. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179600. {
  179601. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179602. uint8* dst = *buffer;
  179603. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179604. {
  179605. *dst++ = ((const PixelRGB*) src)->getRed();
  179606. *dst++ = ((const PixelRGB*) src)->getGreen();
  179607. *dst++ = ((const PixelRGB*) src)->getBlue();
  179608. src += srcData.pixelStride;
  179609. }
  179610. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179611. }
  179612. jpeg_finish_compress (&jpegCompStruct);
  179613. jpeg_destroy_compress (&jpegCompStruct);
  179614. out.flush();
  179615. return true;
  179616. }
  179617. END_JUCE_NAMESPACE
  179618. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179619. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179620. #if JUCE_MSVC
  179621. #pragma warning (push)
  179622. #pragma warning (disable: 4390 4611)
  179623. #endif
  179624. namespace zlibNamespace
  179625. {
  179626. #if JUCE_INCLUDE_ZLIB_CODE
  179627. #undef OS_CODE
  179628. #undef fdopen
  179629. #undef OS_CODE
  179630. #else
  179631. #include <zlib.h>
  179632. #endif
  179633. }
  179634. namespace pnglibNamespace
  179635. {
  179636. using namespace zlibNamespace;
  179637. #if JUCE_INCLUDE_PNGLIB_CODE
  179638. #if _MSC_VER != 1310
  179639. using ::calloc; // (causes conflict in VS.NET 2003)
  179640. using ::malloc;
  179641. using ::free;
  179642. #endif
  179643. extern "C"
  179644. {
  179645. using ::abs;
  179646. #define PNG_INTERNAL
  179647. #define NO_DUMMY_DECL
  179648. #define PNG_SETJMP_NOT_SUPPORTED
  179649. /*** Start of inlined file: png.h ***/
  179650. /* png.h - header file for PNG reference library
  179651. *
  179652. * libpng version 1.2.21 - October 4, 2007
  179653. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179654. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179655. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179656. *
  179657. * Authors and maintainers:
  179658. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179659. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179660. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179661. * See also "Contributing Authors", below.
  179662. *
  179663. * Note about libpng version numbers:
  179664. *
  179665. * Due to various miscommunications, unforeseen code incompatibilities
  179666. * and occasional factors outside the authors' control, version numbering
  179667. * on the library has not always been consistent and straightforward.
  179668. * The following table summarizes matters since version 0.89c, which was
  179669. * the first widely used release:
  179670. *
  179671. * source png.h png.h shared-lib
  179672. * version string int version
  179673. * ------- ------ ----- ----------
  179674. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179675. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179676. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179677. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179678. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179679. * 0.97c 0.97 97 2.0.97
  179680. * 0.98 0.98 98 2.0.98
  179681. * 0.99 0.99 98 2.0.99
  179682. * 0.99a-m 0.99 99 2.0.99
  179683. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179684. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179685. * 1.0.1 png.h string is 10001 2.1.0
  179686. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179687. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179688. * 1.0.2a-b 10003 version, except as noted.
  179689. * 1.0.3 10003
  179690. * 1.0.3a-d 10004
  179691. * 1.0.4 10004
  179692. * 1.0.4a-f 10005
  179693. * 1.0.5 (+ 2 patches) 10005
  179694. * 1.0.5a-d 10006
  179695. * 1.0.5e-r 10100 (not source compatible)
  179696. * 1.0.5s-v 10006 (not binary compatible)
  179697. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179698. * 1.0.6d-f 10007 (still binary incompatible)
  179699. * 1.0.6g 10007
  179700. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179701. * 1.0.6i 10007 10.6i
  179702. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179703. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179704. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179705. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179706. * 1.0.7 1 10007 (still compatible)
  179707. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179708. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179709. * 1.0.8 1 10008 2.1.0.8
  179710. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179711. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179712. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179713. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179714. * 1.0.9 1 10009 2.1.0.9
  179715. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179716. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179717. * 1.0.10 1 10010 2.1.0.10
  179718. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179719. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179720. * 1.0.11 1 10011 2.1.0.11
  179721. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179722. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179723. * 1.0.12 2 10012 2.1.0.12
  179724. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179725. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179726. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179727. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179728. * 1.2.0 3 10200 3.1.2.0
  179729. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179730. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179731. * 1.2.1 3 10201 3.1.2.1
  179732. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179733. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179734. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179735. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179736. * 1.0.13 10 10013 10.so.0.1.0.13
  179737. * 1.2.2 12 10202 12.so.0.1.2.2
  179738. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179739. * 1.2.3 12 10203 12.so.0.1.2.3
  179740. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179741. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179742. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179743. * 1.0.14 10 10014 10.so.0.1.0.14
  179744. * 1.2.4 13 10204 12.so.0.1.2.4
  179745. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179746. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179747. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179748. * 1.0.15 10 10015 10.so.0.1.0.15
  179749. * 1.2.5 13 10205 12.so.0.1.2.5
  179750. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179751. * 1.0.16 10 10016 10.so.0.1.0.16
  179752. * 1.2.6 13 10206 12.so.0.1.2.6
  179753. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179754. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179755. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179756. * 1.0.17 10 10017 10.so.0.1.0.17
  179757. * 1.2.7 13 10207 12.so.0.1.2.7
  179758. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179759. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179760. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179761. * 1.0.18 10 10018 10.so.0.1.0.18
  179762. * 1.2.8 13 10208 12.so.0.1.2.8
  179763. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179764. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179765. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179766. * 1.2.9 13 10209 12.so.0.9[.0]
  179767. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179768. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179769. * 1.2.10 13 10210 12.so.0.10[.0]
  179770. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179771. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179772. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179773. * 1.0.19 10 10019 10.so.0.19[.0]
  179774. * 1.2.11 13 10211 12.so.0.11[.0]
  179775. * 1.0.20 10 10020 10.so.0.20[.0]
  179776. * 1.2.12 13 10212 12.so.0.12[.0]
  179777. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179778. * 1.0.21 10 10021 10.so.0.21[.0]
  179779. * 1.2.13 13 10213 12.so.0.13[.0]
  179780. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179781. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179782. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179783. * 1.0.22 10 10022 10.so.0.22[.0]
  179784. * 1.2.14 13 10214 12.so.0.14[.0]
  179785. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179786. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179787. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179788. * 1.0.23 10 10023 10.so.0.23[.0]
  179789. * 1.2.15 13 10215 12.so.0.15[.0]
  179790. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179791. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179792. * 1.0.24 10 10024 10.so.0.24[.0]
  179793. * 1.2.16 13 10216 12.so.0.16[.0]
  179794. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179795. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179796. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179797. * 1.0.25 10 10025 10.so.0.25[.0]
  179798. * 1.2.17 13 10217 12.so.0.17[.0]
  179799. * 1.0.26 10 10026 10.so.0.26[.0]
  179800. * 1.2.18 13 10218 12.so.0.18[.0]
  179801. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179802. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179803. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179804. * 1.0.27 10 10027 10.so.0.27[.0]
  179805. * 1.2.19 13 10219 12.so.0.19[.0]
  179806. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179807. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179808. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179809. * 1.0.28 10 10028 10.so.0.28[.0]
  179810. * 1.2.20 13 10220 12.so.0.20[.0]
  179811. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179812. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179813. * 1.0.29 10 10029 10.so.0.29[.0]
  179814. * 1.2.21 13 10221 12.so.0.21[.0]
  179815. *
  179816. * Henceforth the source version will match the shared-library major
  179817. * and minor numbers; the shared-library major version number will be
  179818. * used for changes in backward compatibility, as it is intended. The
  179819. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  179820. * for applications, is an unsigned integer of the form xyyzz corresponding
  179821. * to the source version x.y.z (leading zeros in y and z). Beta versions
  179822. * were given the previous public release number plus a letter, until
  179823. * version 1.0.6j; from then on they were given the upcoming public
  179824. * release number plus "betaNN" or "rcN".
  179825. *
  179826. * Binary incompatibility exists only when applications make direct access
  179827. * to the info_ptr or png_ptr members through png.h, and the compiled
  179828. * application is loaded with a different version of the library.
  179829. *
  179830. * DLLNUM will change each time there are forward or backward changes
  179831. * in binary compatibility (e.g., when a new feature is added).
  179832. *
  179833. * See libpng.txt or libpng.3 for more information. The PNG specification
  179834. * is available as a W3C Recommendation and as an ISO Specification,
  179835. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  179836. */
  179837. /*
  179838. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  179839. *
  179840. * If you modify libpng you may insert additional notices immediately following
  179841. * this sentence.
  179842. *
  179843. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  179844. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  179845. * distributed according to the same disclaimer and license as libpng-1.2.5
  179846. * with the following individual added to the list of Contributing Authors:
  179847. *
  179848. * Cosmin Truta
  179849. *
  179850. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  179851. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  179852. * distributed according to the same disclaimer and license as libpng-1.0.6
  179853. * with the following individuals added to the list of Contributing Authors:
  179854. *
  179855. * Simon-Pierre Cadieux
  179856. * Eric S. Raymond
  179857. * Gilles Vollant
  179858. *
  179859. * and with the following additions to the disclaimer:
  179860. *
  179861. * There is no warranty against interference with your enjoyment of the
  179862. * library or against infringement. There is no warranty that our
  179863. * efforts or the library will fulfill any of your particular purposes
  179864. * or needs. This library is provided with all faults, and the entire
  179865. * risk of satisfactory quality, performance, accuracy, and effort is with
  179866. * the user.
  179867. *
  179868. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  179869. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  179870. * distributed according to the same disclaimer and license as libpng-0.96,
  179871. * with the following individuals added to the list of Contributing Authors:
  179872. *
  179873. * Tom Lane
  179874. * Glenn Randers-Pehrson
  179875. * Willem van Schaik
  179876. *
  179877. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  179878. * Copyright (c) 1996, 1997 Andreas Dilger
  179879. * Distributed according to the same disclaimer and license as libpng-0.88,
  179880. * with the following individuals added to the list of Contributing Authors:
  179881. *
  179882. * John Bowler
  179883. * Kevin Bracey
  179884. * Sam Bushell
  179885. * Magnus Holmgren
  179886. * Greg Roelofs
  179887. * Tom Tanner
  179888. *
  179889. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  179890. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  179891. *
  179892. * For the purposes of this copyright and license, "Contributing Authors"
  179893. * is defined as the following set of individuals:
  179894. *
  179895. * Andreas Dilger
  179896. * Dave Martindale
  179897. * Guy Eric Schalnat
  179898. * Paul Schmidt
  179899. * Tim Wegner
  179900. *
  179901. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  179902. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  179903. * including, without limitation, the warranties of merchantability and of
  179904. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  179905. * assume no liability for direct, indirect, incidental, special, exemplary,
  179906. * or consequential damages, which may result from the use of the PNG
  179907. * Reference Library, even if advised of the possibility of such damage.
  179908. *
  179909. * Permission is hereby granted to use, copy, modify, and distribute this
  179910. * source code, or portions hereof, for any purpose, without fee, subject
  179911. * to the following restrictions:
  179912. *
  179913. * 1. The origin of this source code must not be misrepresented.
  179914. *
  179915. * 2. Altered versions must be plainly marked as such and
  179916. * must not be misrepresented as being the original source.
  179917. *
  179918. * 3. This Copyright notice may not be removed or altered from
  179919. * any source or altered source distribution.
  179920. *
  179921. * The Contributing Authors and Group 42, Inc. specifically permit, without
  179922. * fee, and encourage the use of this source code as a component to
  179923. * supporting the PNG file format in commercial products. If you use this
  179924. * source code in a product, acknowledgment is not required but would be
  179925. * appreciated.
  179926. */
  179927. /*
  179928. * A "png_get_copyright" function is available, for convenient use in "about"
  179929. * boxes and the like:
  179930. *
  179931. * printf("%s",png_get_copyright(NULL));
  179932. *
  179933. * Also, the PNG logo (in PNG format, of course) is supplied in the
  179934. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  179935. */
  179936. /*
  179937. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  179938. * certification mark of the Open Source Initiative.
  179939. */
  179940. /*
  179941. * The contributing authors would like to thank all those who helped
  179942. * with testing, bug fixes, and patience. This wouldn't have been
  179943. * possible without all of you.
  179944. *
  179945. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  179946. */
  179947. /*
  179948. * Y2K compliance in libpng:
  179949. * =========================
  179950. *
  179951. * October 4, 2007
  179952. *
  179953. * Since the PNG Development group is an ad-hoc body, we can't make
  179954. * an official declaration.
  179955. *
  179956. * This is your unofficial assurance that libpng from version 0.71 and
  179957. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  179958. * versions were also Y2K compliant.
  179959. *
  179960. * Libpng only has three year fields. One is a 2-byte unsigned integer
  179961. * that will hold years up to 65535. The other two hold the date in text
  179962. * format, and will hold years up to 9999.
  179963. *
  179964. * The integer is
  179965. * "png_uint_16 year" in png_time_struct.
  179966. *
  179967. * The strings are
  179968. * "png_charp time_buffer" in png_struct and
  179969. * "near_time_buffer", which is a local character string in png.c.
  179970. *
  179971. * There are seven time-related functions:
  179972. * png.c: png_convert_to_rfc_1123() in png.c
  179973. * (formerly png_convert_to_rfc_1152() in error)
  179974. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  179975. * png_convert_from_time_t() in pngwrite.c
  179976. * png_get_tIME() in pngget.c
  179977. * png_handle_tIME() in pngrutil.c, called in pngread.c
  179978. * png_set_tIME() in pngset.c
  179979. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  179980. *
  179981. * All handle dates properly in a Y2K environment. The
  179982. * png_convert_from_time_t() function calls gmtime() to convert from system
  179983. * clock time, which returns (year - 1900), which we properly convert to
  179984. * the full 4-digit year. There is a possibility that applications using
  179985. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  179986. * function, or that they are incorrectly passing only a 2-digit year
  179987. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  179988. * but this is not under our control. The libpng documentation has always
  179989. * stated that it works with 4-digit years, and the APIs have been
  179990. * documented as such.
  179991. *
  179992. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  179993. * integer to hold the year, and can hold years as large as 65535.
  179994. *
  179995. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  179996. * no date-related code.
  179997. *
  179998. * Glenn Randers-Pehrson
  179999. * libpng maintainer
  180000. * PNG Development Group
  180001. */
  180002. #ifndef PNG_H
  180003. #define PNG_H
  180004. /* This is not the place to learn how to use libpng. The file libpng.txt
  180005. * describes how to use libpng, and the file example.c summarizes it
  180006. * with some code on which to build. This file is useful for looking
  180007. * at the actual function definitions and structure components.
  180008. */
  180009. /* Version information for png.h - this should match the version in png.c */
  180010. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180011. #define PNG_HEADER_VERSION_STRING \
  180012. " libpng version 1.2.21 - October 4, 2007\n"
  180013. #define PNG_LIBPNG_VER_SONUM 0
  180014. #define PNG_LIBPNG_VER_DLLNUM 13
  180015. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180016. #define PNG_LIBPNG_VER_MAJOR 1
  180017. #define PNG_LIBPNG_VER_MINOR 2
  180018. #define PNG_LIBPNG_VER_RELEASE 21
  180019. /* This should match the numeric part of the final component of
  180020. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180021. #define PNG_LIBPNG_VER_BUILD 0
  180022. /* Release Status */
  180023. #define PNG_LIBPNG_BUILD_ALPHA 1
  180024. #define PNG_LIBPNG_BUILD_BETA 2
  180025. #define PNG_LIBPNG_BUILD_RC 3
  180026. #define PNG_LIBPNG_BUILD_STABLE 4
  180027. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180028. /* Release-Specific Flags */
  180029. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180030. PNG_LIBPNG_BUILD_STABLE only */
  180031. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180032. PNG_LIBPNG_BUILD_SPECIAL */
  180033. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180034. PNG_LIBPNG_BUILD_PRIVATE */
  180035. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180036. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180037. * We must not include leading zeros.
  180038. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180039. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180040. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180041. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180042. #ifndef PNG_VERSION_INFO_ONLY
  180043. /* include the compression library's header */
  180044. #endif
  180045. /* include all user configurable info, including optional assembler routines */
  180046. /*** Start of inlined file: pngconf.h ***/
  180047. /* pngconf.h - machine configurable file for libpng
  180048. *
  180049. * libpng version 1.2.21 - October 4, 2007
  180050. * For conditions of distribution and use, see copyright notice in png.h
  180051. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180052. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180053. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180054. */
  180055. /* Any machine specific code is near the front of this file, so if you
  180056. * are configuring libpng for a machine, you may want to read the section
  180057. * starting here down to where it starts to typedef png_color, png_text,
  180058. * and png_info.
  180059. */
  180060. #ifndef PNGCONF_H
  180061. #define PNGCONF_H
  180062. #define PNG_1_2_X
  180063. // These are some Juce config settings that should remove any unnecessary code bloat..
  180064. #define PNG_NO_STDIO 1
  180065. #define PNG_DEBUG 0
  180066. #define PNG_NO_WARNINGS 1
  180067. #define PNG_NO_ERROR_TEXT 1
  180068. #define PNG_NO_ERROR_NUMBERS 1
  180069. #define PNG_NO_USER_MEM 1
  180070. #define PNG_NO_READ_iCCP 1
  180071. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180072. #define PNG_NO_READ_USER_CHUNKS 1
  180073. #define PNG_NO_READ_iTXt 1
  180074. #define PNG_NO_READ_sCAL 1
  180075. #define PNG_NO_READ_sPLT 1
  180076. #define png_error(a, b) png_err(a)
  180077. #define png_warning(a, b)
  180078. #define png_chunk_error(a, b) png_err(a)
  180079. #define png_chunk_warning(a, b)
  180080. /*
  180081. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180082. * includes the resource compiler for Windows DLL configurations.
  180083. */
  180084. #ifdef PNG_USER_CONFIG
  180085. # ifndef PNG_USER_PRIVATEBUILD
  180086. # define PNG_USER_PRIVATEBUILD
  180087. # endif
  180088. #include "pngusr.h"
  180089. #endif
  180090. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180091. #ifdef PNG_CONFIGURE_LIBPNG
  180092. #ifdef HAVE_CONFIG_H
  180093. #include "config.h"
  180094. #endif
  180095. #endif
  180096. /*
  180097. * Added at libpng-1.2.8
  180098. *
  180099. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180100. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180101. * the DLL was built>
  180102. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180103. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180104. * distinguish your DLL from those of the official release. These
  180105. * correspond to the trailing letters that come after the version
  180106. * number and must match your private DLL name>
  180107. * e.g. // private DLL "libpng13gx.dll"
  180108. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180109. *
  180110. * The following macros are also at your disposal if you want to complete the
  180111. * DLL VERSIONINFO structure.
  180112. * - PNG_USER_VERSIONINFO_COMMENTS
  180113. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180114. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180115. */
  180116. #ifdef __STDC__
  180117. #ifdef SPECIALBUILD
  180118. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180119. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180120. #endif
  180121. #ifdef PRIVATEBUILD
  180122. # pragma message("PRIVATEBUILD is deprecated.\
  180123. Use PNG_USER_PRIVATEBUILD instead.")
  180124. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180125. #endif
  180126. #endif /* __STDC__ */
  180127. #ifndef PNG_VERSION_INFO_ONLY
  180128. /* End of material added to libpng-1.2.8 */
  180129. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180130. Restored at libpng-1.2.21 */
  180131. # define PNG_WARN_UNINITIALIZED_ROW 1
  180132. /* End of material added at libpng-1.2.19/1.2.21 */
  180133. /* This is the size of the compression buffer, and thus the size of
  180134. * an IDAT chunk. Make this whatever size you feel is best for your
  180135. * machine. One of these will be allocated per png_struct. When this
  180136. * is full, it writes the data to the disk, and does some other
  180137. * calculations. Making this an extremely small size will slow
  180138. * the library down, but you may want to experiment to determine
  180139. * where it becomes significant, if you are concerned with memory
  180140. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180141. * this describes the size of the buffer available to read the data in.
  180142. * Unless this gets smaller than the size of a row (compressed),
  180143. * it should not make much difference how big this is.
  180144. */
  180145. #ifndef PNG_ZBUF_SIZE
  180146. # define PNG_ZBUF_SIZE 8192
  180147. #endif
  180148. /* Enable if you want a write-only libpng */
  180149. #ifndef PNG_NO_READ_SUPPORTED
  180150. # define PNG_READ_SUPPORTED
  180151. #endif
  180152. /* Enable if you want a read-only libpng */
  180153. #ifndef PNG_NO_WRITE_SUPPORTED
  180154. # define PNG_WRITE_SUPPORTED
  180155. #endif
  180156. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180157. support PNGs that are embedded in MNG datastreams */
  180158. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180159. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180160. # define PNG_MNG_FEATURES_SUPPORTED
  180161. # endif
  180162. #endif
  180163. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180164. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180165. # define PNG_FLOATING_POINT_SUPPORTED
  180166. # endif
  180167. #endif
  180168. /* If you are running on a machine where you cannot allocate more
  180169. * than 64K of memory at once, uncomment this. While libpng will not
  180170. * normally need that much memory in a chunk (unless you load up a very
  180171. * large file), zlib needs to know how big of a chunk it can use, and
  180172. * libpng thus makes sure to check any memory allocation to verify it
  180173. * will fit into memory.
  180174. #define PNG_MAX_MALLOC_64K
  180175. */
  180176. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180177. # define PNG_MAX_MALLOC_64K
  180178. #endif
  180179. /* Special munging to support doing things the 'cygwin' way:
  180180. * 'Normal' png-on-win32 defines/defaults:
  180181. * PNG_BUILD_DLL -- building dll
  180182. * PNG_USE_DLL -- building an application, linking to dll
  180183. * (no define) -- building static library, or building an
  180184. * application and linking to the static lib
  180185. * 'Cygwin' defines/defaults:
  180186. * PNG_BUILD_DLL -- (ignored) building the dll
  180187. * (no define) -- (ignored) building an application, linking to the dll
  180188. * PNG_STATIC -- (ignored) building the static lib, or building an
  180189. * application that links to the static lib.
  180190. * ALL_STATIC -- (ignored) building various static libs, or building an
  180191. * application that links to the static libs.
  180192. * Thus,
  180193. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180194. * this bit of #ifdefs will define the 'correct' config variables based on
  180195. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180196. * unnecessary.
  180197. *
  180198. * Also, the precedence order is:
  180199. * ALL_STATIC (since we can't #undef something outside our namespace)
  180200. * PNG_BUILD_DLL
  180201. * PNG_STATIC
  180202. * (nothing) == PNG_USE_DLL
  180203. *
  180204. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180205. * of auto-import in binutils, we no longer need to worry about
  180206. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180207. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180208. * to __declspec() stuff. However, we DO need to worry about
  180209. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180210. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180211. */
  180212. #if defined(__CYGWIN__)
  180213. # if defined(ALL_STATIC)
  180214. # if defined(PNG_BUILD_DLL)
  180215. # undef PNG_BUILD_DLL
  180216. # endif
  180217. # if defined(PNG_USE_DLL)
  180218. # undef PNG_USE_DLL
  180219. # endif
  180220. # if defined(PNG_DLL)
  180221. # undef PNG_DLL
  180222. # endif
  180223. # if !defined(PNG_STATIC)
  180224. # define PNG_STATIC
  180225. # endif
  180226. # else
  180227. # if defined (PNG_BUILD_DLL)
  180228. # if defined(PNG_STATIC)
  180229. # undef PNG_STATIC
  180230. # endif
  180231. # if defined(PNG_USE_DLL)
  180232. # undef PNG_USE_DLL
  180233. # endif
  180234. # if !defined(PNG_DLL)
  180235. # define PNG_DLL
  180236. # endif
  180237. # else
  180238. # if defined(PNG_STATIC)
  180239. # if defined(PNG_USE_DLL)
  180240. # undef PNG_USE_DLL
  180241. # endif
  180242. # if defined(PNG_DLL)
  180243. # undef PNG_DLL
  180244. # endif
  180245. # else
  180246. # if !defined(PNG_USE_DLL)
  180247. # define PNG_USE_DLL
  180248. # endif
  180249. # if !defined(PNG_DLL)
  180250. # define PNG_DLL
  180251. # endif
  180252. # endif
  180253. # endif
  180254. # endif
  180255. #endif
  180256. /* This protects us against compilers that run on a windowing system
  180257. * and thus don't have or would rather us not use the stdio types:
  180258. * stdin, stdout, and stderr. The only one currently used is stderr
  180259. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180260. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180261. * will also prevent these, plus will prevent the entire set of stdio
  180262. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180263. * unless (PNG_DEBUG > 0) has been #defined.
  180264. *
  180265. * #define PNG_NO_CONSOLE_IO
  180266. * #define PNG_NO_STDIO
  180267. */
  180268. #if defined(_WIN32_WCE)
  180269. # include <windows.h>
  180270. /* Console I/O functions are not supported on WindowsCE */
  180271. # define PNG_NO_CONSOLE_IO
  180272. # ifdef PNG_DEBUG
  180273. # undef PNG_DEBUG
  180274. # endif
  180275. #endif
  180276. #ifdef PNG_BUILD_DLL
  180277. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180278. # ifndef PNG_NO_CONSOLE_IO
  180279. # define PNG_NO_CONSOLE_IO
  180280. # endif
  180281. # endif
  180282. #endif
  180283. # ifdef PNG_NO_STDIO
  180284. # ifndef PNG_NO_CONSOLE_IO
  180285. # define PNG_NO_CONSOLE_IO
  180286. # endif
  180287. # ifdef PNG_DEBUG
  180288. # if (PNG_DEBUG > 0)
  180289. # include <stdio.h>
  180290. # endif
  180291. # endif
  180292. # else
  180293. # if !defined(_WIN32_WCE)
  180294. /* "stdio.h" functions are not supported on WindowsCE */
  180295. # include <stdio.h>
  180296. # endif
  180297. # endif
  180298. /* This macro protects us against machines that don't have function
  180299. * prototypes (ie K&R style headers). If your compiler does not handle
  180300. * function prototypes, define this macro and use the included ansi2knr.
  180301. * I've always been able to use _NO_PROTO as the indicator, but you may
  180302. * need to drag the empty declaration out in front of here, or change the
  180303. * ifdef to suit your own needs.
  180304. */
  180305. #ifndef PNGARG
  180306. #ifdef OF /* zlib prototype munger */
  180307. # define PNGARG(arglist) OF(arglist)
  180308. #else
  180309. #ifdef _NO_PROTO
  180310. # define PNGARG(arglist) ()
  180311. # ifndef PNG_TYPECAST_NULL
  180312. # define PNG_TYPECAST_NULL
  180313. # endif
  180314. #else
  180315. # define PNGARG(arglist) arglist
  180316. #endif /* _NO_PROTO */
  180317. #endif /* OF */
  180318. #endif /* PNGARG */
  180319. /* Try to determine if we are compiling on a Mac. Note that testing for
  180320. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180321. * on non-Mac platforms.
  180322. */
  180323. #ifndef MACOS
  180324. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180325. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180326. # define MACOS
  180327. # endif
  180328. #endif
  180329. /* enough people need this for various reasons to include it here */
  180330. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180331. # include <sys/types.h>
  180332. #endif
  180333. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180334. # define PNG_SETJMP_SUPPORTED
  180335. #endif
  180336. #ifdef PNG_SETJMP_SUPPORTED
  180337. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180338. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180339. */
  180340. # ifdef __linux__
  180341. # ifdef _BSD_SOURCE
  180342. # define PNG_SAVE_BSD_SOURCE
  180343. # undef _BSD_SOURCE
  180344. # endif
  180345. # ifdef _SETJMP_H
  180346. /* If you encounter a compiler error here, see the explanation
  180347. * near the end of INSTALL.
  180348. */
  180349. __png.h__ already includes setjmp.h;
  180350. __dont__ include it again.;
  180351. # endif
  180352. # endif /* __linux__ */
  180353. /* include setjmp.h for error handling */
  180354. # include <setjmp.h>
  180355. # ifdef __linux__
  180356. # ifdef PNG_SAVE_BSD_SOURCE
  180357. # define _BSD_SOURCE
  180358. # undef PNG_SAVE_BSD_SOURCE
  180359. # endif
  180360. # endif /* __linux__ */
  180361. #endif /* PNG_SETJMP_SUPPORTED */
  180362. #ifdef BSD
  180363. #if ! JUCE_MAC
  180364. # include <strings.h>
  180365. #endif
  180366. #else
  180367. # include <string.h>
  180368. #endif
  180369. /* Other defines for things like memory and the like can go here. */
  180370. #ifdef PNG_INTERNAL
  180371. #include <stdlib.h>
  180372. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180373. * aren't usually used outside the library (as far as I know), so it is
  180374. * debatable if they should be exported at all. In the future, when it is
  180375. * possible to have run-time registry of chunk-handling functions, some of
  180376. * these will be made available again.
  180377. #define PNG_EXTERN extern
  180378. */
  180379. #define PNG_EXTERN
  180380. /* Other defines specific to compilers can go here. Try to keep
  180381. * them inside an appropriate ifdef/endif pair for portability.
  180382. */
  180383. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180384. # if defined(MACOS)
  180385. /* We need to check that <math.h> hasn't already been included earlier
  180386. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180387. * <fp.h> if possible.
  180388. */
  180389. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180390. # include <fp.h>
  180391. # endif
  180392. # else
  180393. # include <math.h>
  180394. # endif
  180395. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180396. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180397. * MATH=68881
  180398. */
  180399. # include <m68881.h>
  180400. # endif
  180401. #endif
  180402. /* Codewarrior on NT has linking problems without this. */
  180403. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180404. # define PNG_ALWAYS_EXTERN
  180405. #endif
  180406. /* This provides the non-ANSI (far) memory allocation routines. */
  180407. #if defined(__TURBOC__) && defined(__MSDOS__)
  180408. # include <mem.h>
  180409. # include <alloc.h>
  180410. #endif
  180411. /* I have no idea why is this necessary... */
  180412. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180413. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180414. # include <malloc.h>
  180415. #endif
  180416. /* This controls how fine the dithering gets. As this allocates
  180417. * a largish chunk of memory (32K), those who are not as concerned
  180418. * with dithering quality can decrease some or all of these.
  180419. */
  180420. #ifndef PNG_DITHER_RED_BITS
  180421. # define PNG_DITHER_RED_BITS 5
  180422. #endif
  180423. #ifndef PNG_DITHER_GREEN_BITS
  180424. # define PNG_DITHER_GREEN_BITS 5
  180425. #endif
  180426. #ifndef PNG_DITHER_BLUE_BITS
  180427. # define PNG_DITHER_BLUE_BITS 5
  180428. #endif
  180429. /* This controls how fine the gamma correction becomes when you
  180430. * are only interested in 8 bits anyway. Increasing this value
  180431. * results in more memory being used, and more pow() functions
  180432. * being called to fill in the gamma tables. Don't set this value
  180433. * less then 8, and even that may not work (I haven't tested it).
  180434. */
  180435. #ifndef PNG_MAX_GAMMA_8
  180436. # define PNG_MAX_GAMMA_8 11
  180437. #endif
  180438. /* This controls how much a difference in gamma we can tolerate before
  180439. * we actually start doing gamma conversion.
  180440. */
  180441. #ifndef PNG_GAMMA_THRESHOLD
  180442. # define PNG_GAMMA_THRESHOLD 0.05
  180443. #endif
  180444. #endif /* PNG_INTERNAL */
  180445. /* The following uses const char * instead of char * for error
  180446. * and warning message functions, so some compilers won't complain.
  180447. * If you do not want to use const, define PNG_NO_CONST here.
  180448. */
  180449. #ifndef PNG_NO_CONST
  180450. # define PNG_CONST const
  180451. #else
  180452. # define PNG_CONST
  180453. #endif
  180454. /* The following defines give you the ability to remove code from the
  180455. * library that you will not be using. I wish I could figure out how to
  180456. * automate this, but I can't do that without making it seriously hard
  180457. * on the users. So if you are not using an ability, change the #define
  180458. * to and #undef, and that part of the library will not be compiled. If
  180459. * your linker can't find a function, you may want to make sure the
  180460. * ability is defined here. Some of these depend upon some others being
  180461. * defined. I haven't figured out all the interactions here, so you may
  180462. * have to experiment awhile to get everything to compile. If you are
  180463. * creating or using a shared library, you probably shouldn't touch this,
  180464. * as it will affect the size of the structures, and this will cause bad
  180465. * things to happen if the library and/or application ever change.
  180466. */
  180467. /* Any features you will not be using can be undef'ed here */
  180468. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180469. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180470. * on the compile line, then pick and choose which ones to define without
  180471. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180472. * if you only want to have a png-compliant reader/writer but don't need
  180473. * any of the extra transformations. This saves about 80 kbytes in a
  180474. * typical installation of the library. (PNG_NO_* form added in version
  180475. * 1.0.1c, for consistency)
  180476. */
  180477. /* The size of the png_text structure changed in libpng-1.0.6 when
  180478. * iTXt support was added. iTXt support was turned off by default through
  180479. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180480. * instead of calling png_set_text() and letting libpng malloc it. It
  180481. * was turned on by default in libpng-1.3.0.
  180482. */
  180483. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180484. # ifndef PNG_NO_iTXt_SUPPORTED
  180485. # define PNG_NO_iTXt_SUPPORTED
  180486. # endif
  180487. # ifndef PNG_NO_READ_iTXt
  180488. # define PNG_NO_READ_iTXt
  180489. # endif
  180490. # ifndef PNG_NO_WRITE_iTXt
  180491. # define PNG_NO_WRITE_iTXt
  180492. # endif
  180493. #endif
  180494. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180495. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180496. # define PNG_READ_iTXt
  180497. # endif
  180498. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180499. # define PNG_WRITE_iTXt
  180500. # endif
  180501. #endif
  180502. /* The following support, added after version 1.0.0, can be turned off here en
  180503. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180504. * with old applications that require the length of png_struct and png_info
  180505. * to remain unchanged.
  180506. */
  180507. #ifdef PNG_LEGACY_SUPPORTED
  180508. # define PNG_NO_FREE_ME
  180509. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180510. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180511. # define PNG_NO_READ_USER_CHUNKS
  180512. # define PNG_NO_READ_iCCP
  180513. # define PNG_NO_WRITE_iCCP
  180514. # define PNG_NO_READ_iTXt
  180515. # define PNG_NO_WRITE_iTXt
  180516. # define PNG_NO_READ_sCAL
  180517. # define PNG_NO_WRITE_sCAL
  180518. # define PNG_NO_READ_sPLT
  180519. # define PNG_NO_WRITE_sPLT
  180520. # define PNG_NO_INFO_IMAGE
  180521. # define PNG_NO_READ_RGB_TO_GRAY
  180522. # define PNG_NO_READ_USER_TRANSFORM
  180523. # define PNG_NO_WRITE_USER_TRANSFORM
  180524. # define PNG_NO_USER_MEM
  180525. # define PNG_NO_READ_EMPTY_PLTE
  180526. # define PNG_NO_MNG_FEATURES
  180527. # define PNG_NO_FIXED_POINT_SUPPORTED
  180528. #endif
  180529. /* Ignore attempt to turn off both floating and fixed point support */
  180530. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180531. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180532. # define PNG_FIXED_POINT_SUPPORTED
  180533. #endif
  180534. #ifndef PNG_NO_FREE_ME
  180535. # define PNG_FREE_ME_SUPPORTED
  180536. #endif
  180537. #if defined(PNG_READ_SUPPORTED)
  180538. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180539. !defined(PNG_NO_READ_TRANSFORMS)
  180540. # define PNG_READ_TRANSFORMS_SUPPORTED
  180541. #endif
  180542. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180543. # ifndef PNG_NO_READ_EXPAND
  180544. # define PNG_READ_EXPAND_SUPPORTED
  180545. # endif
  180546. # ifndef PNG_NO_READ_SHIFT
  180547. # define PNG_READ_SHIFT_SUPPORTED
  180548. # endif
  180549. # ifndef PNG_NO_READ_PACK
  180550. # define PNG_READ_PACK_SUPPORTED
  180551. # endif
  180552. # ifndef PNG_NO_READ_BGR
  180553. # define PNG_READ_BGR_SUPPORTED
  180554. # endif
  180555. # ifndef PNG_NO_READ_SWAP
  180556. # define PNG_READ_SWAP_SUPPORTED
  180557. # endif
  180558. # ifndef PNG_NO_READ_PACKSWAP
  180559. # define PNG_READ_PACKSWAP_SUPPORTED
  180560. # endif
  180561. # ifndef PNG_NO_READ_INVERT
  180562. # define PNG_READ_INVERT_SUPPORTED
  180563. # endif
  180564. # ifndef PNG_NO_READ_DITHER
  180565. # define PNG_READ_DITHER_SUPPORTED
  180566. # endif
  180567. # ifndef PNG_NO_READ_BACKGROUND
  180568. # define PNG_READ_BACKGROUND_SUPPORTED
  180569. # endif
  180570. # ifndef PNG_NO_READ_16_TO_8
  180571. # define PNG_READ_16_TO_8_SUPPORTED
  180572. # endif
  180573. # ifndef PNG_NO_READ_FILLER
  180574. # define PNG_READ_FILLER_SUPPORTED
  180575. # endif
  180576. # ifndef PNG_NO_READ_GAMMA
  180577. # define PNG_READ_GAMMA_SUPPORTED
  180578. # endif
  180579. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180580. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180581. # endif
  180582. # ifndef PNG_NO_READ_SWAP_ALPHA
  180583. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180584. # endif
  180585. # ifndef PNG_NO_READ_INVERT_ALPHA
  180586. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180587. # endif
  180588. # ifndef PNG_NO_READ_STRIP_ALPHA
  180589. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180590. # endif
  180591. # ifndef PNG_NO_READ_USER_TRANSFORM
  180592. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180593. # endif
  180594. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180595. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180596. # endif
  180597. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180598. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180599. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180600. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180601. #endif /* about interlacing capability! You'll */
  180602. /* still have interlacing unless you change the following line: */
  180603. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180604. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180605. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180606. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180607. # endif
  180608. #endif
  180609. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180610. /* Deprecated, will be removed from version 2.0.0.
  180611. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180612. #ifndef PNG_NO_READ_EMPTY_PLTE
  180613. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180614. #endif
  180615. #endif
  180616. #endif /* PNG_READ_SUPPORTED */
  180617. #if defined(PNG_WRITE_SUPPORTED)
  180618. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180619. !defined(PNG_NO_WRITE_TRANSFORMS)
  180620. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180621. #endif
  180622. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180623. # ifndef PNG_NO_WRITE_SHIFT
  180624. # define PNG_WRITE_SHIFT_SUPPORTED
  180625. # endif
  180626. # ifndef PNG_NO_WRITE_PACK
  180627. # define PNG_WRITE_PACK_SUPPORTED
  180628. # endif
  180629. # ifndef PNG_NO_WRITE_BGR
  180630. # define PNG_WRITE_BGR_SUPPORTED
  180631. # endif
  180632. # ifndef PNG_NO_WRITE_SWAP
  180633. # define PNG_WRITE_SWAP_SUPPORTED
  180634. # endif
  180635. # ifndef PNG_NO_WRITE_PACKSWAP
  180636. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180637. # endif
  180638. # ifndef PNG_NO_WRITE_INVERT
  180639. # define PNG_WRITE_INVERT_SUPPORTED
  180640. # endif
  180641. # ifndef PNG_NO_WRITE_FILLER
  180642. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180643. # endif
  180644. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180645. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180646. # endif
  180647. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180648. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180649. # endif
  180650. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180651. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180652. # endif
  180653. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180654. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180655. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180656. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180657. encoders, but can cause trouble
  180658. if left undefined */
  180659. #endif
  180660. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180661. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180662. defined(PNG_FLOATING_POINT_SUPPORTED)
  180663. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180664. #endif
  180665. #ifndef PNG_NO_WRITE_FLUSH
  180666. # define PNG_WRITE_FLUSH_SUPPORTED
  180667. #endif
  180668. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180669. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180670. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180671. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180672. #endif
  180673. #endif
  180674. #endif /* PNG_WRITE_SUPPORTED */
  180675. #ifndef PNG_1_0_X
  180676. # ifndef PNG_NO_ERROR_NUMBERS
  180677. # define PNG_ERROR_NUMBERS_SUPPORTED
  180678. # endif
  180679. #endif /* PNG_1_0_X */
  180680. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180681. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180682. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180683. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180684. # endif
  180685. #endif
  180686. #ifndef PNG_NO_STDIO
  180687. # define PNG_TIME_RFC1123_SUPPORTED
  180688. #endif
  180689. /* This adds extra functions in pngget.c for accessing data from the
  180690. * info pointer (added in version 0.99)
  180691. * png_get_image_width()
  180692. * png_get_image_height()
  180693. * png_get_bit_depth()
  180694. * png_get_color_type()
  180695. * png_get_compression_type()
  180696. * png_get_filter_type()
  180697. * png_get_interlace_type()
  180698. * png_get_pixel_aspect_ratio()
  180699. * png_get_pixels_per_meter()
  180700. * png_get_x_offset_pixels()
  180701. * png_get_y_offset_pixels()
  180702. * png_get_x_offset_microns()
  180703. * png_get_y_offset_microns()
  180704. */
  180705. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180706. # define PNG_EASY_ACCESS_SUPPORTED
  180707. #endif
  180708. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180709. * and removed from version 1.2.20. The following will be removed
  180710. * from libpng-1.4.0
  180711. */
  180712. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180713. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180714. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180715. # endif
  180716. #endif
  180717. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180718. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180719. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180720. # endif
  180721. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180722. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180723. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180724. # define PNG_NO_MMX_CODE
  180725. # endif
  180726. # endif
  180727. # if defined(__APPLE__)
  180728. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180729. # define PNG_NO_MMX_CODE
  180730. # endif
  180731. # endif
  180732. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180733. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180734. # define PNG_NO_MMX_CODE
  180735. # endif
  180736. # endif
  180737. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180738. # define PNG_MMX_CODE_SUPPORTED
  180739. # endif
  180740. #endif
  180741. /* end of obsolete code to be removed from libpng-1.4.0 */
  180742. #if !defined(PNG_1_0_X)
  180743. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180744. # define PNG_USER_MEM_SUPPORTED
  180745. #endif
  180746. #endif /* PNG_1_0_X */
  180747. /* Added at libpng-1.2.6 */
  180748. #if !defined(PNG_1_0_X)
  180749. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180750. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180751. # define PNG_SET_USER_LIMITS_SUPPORTED
  180752. #endif
  180753. #endif
  180754. #endif /* PNG_1_0_X */
  180755. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180756. * how large, set these limits to 0x7fffffffL
  180757. */
  180758. #ifndef PNG_USER_WIDTH_MAX
  180759. # define PNG_USER_WIDTH_MAX 1000000L
  180760. #endif
  180761. #ifndef PNG_USER_HEIGHT_MAX
  180762. # define PNG_USER_HEIGHT_MAX 1000000L
  180763. #endif
  180764. /* These are currently experimental features, define them if you want */
  180765. /* very little testing */
  180766. /*
  180767. #ifdef PNG_READ_SUPPORTED
  180768. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180769. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180770. # endif
  180771. #endif
  180772. */
  180773. /* This is only for PowerPC big-endian and 680x0 systems */
  180774. /* some testing */
  180775. /*
  180776. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180777. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180778. #endif
  180779. */
  180780. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180781. /*
  180782. #define PNG_NO_POINTER_INDEXING
  180783. */
  180784. /* These functions are turned off by default, as they will be phased out. */
  180785. /*
  180786. #define PNG_USELESS_TESTS_SUPPORTED
  180787. #define PNG_CORRECT_PALETTE_SUPPORTED
  180788. */
  180789. /* Any chunks you are not interested in, you can undef here. The
  180790. * ones that allocate memory may be expecially important (hIST,
  180791. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180792. * a bit smaller.
  180793. */
  180794. #if defined(PNG_READ_SUPPORTED) && \
  180795. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180796. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180797. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180798. #endif
  180799. #if defined(PNG_WRITE_SUPPORTED) && \
  180800. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180801. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180802. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180803. #endif
  180804. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180805. #ifdef PNG_NO_READ_TEXT
  180806. # define PNG_NO_READ_iTXt
  180807. # define PNG_NO_READ_tEXt
  180808. # define PNG_NO_READ_zTXt
  180809. #endif
  180810. #ifndef PNG_NO_READ_bKGD
  180811. # define PNG_READ_bKGD_SUPPORTED
  180812. # define PNG_bKGD_SUPPORTED
  180813. #endif
  180814. #ifndef PNG_NO_READ_cHRM
  180815. # define PNG_READ_cHRM_SUPPORTED
  180816. # define PNG_cHRM_SUPPORTED
  180817. #endif
  180818. #ifndef PNG_NO_READ_gAMA
  180819. # define PNG_READ_gAMA_SUPPORTED
  180820. # define PNG_gAMA_SUPPORTED
  180821. #endif
  180822. #ifndef PNG_NO_READ_hIST
  180823. # define PNG_READ_hIST_SUPPORTED
  180824. # define PNG_hIST_SUPPORTED
  180825. #endif
  180826. #ifndef PNG_NO_READ_iCCP
  180827. # define PNG_READ_iCCP_SUPPORTED
  180828. # define PNG_iCCP_SUPPORTED
  180829. #endif
  180830. #ifndef PNG_NO_READ_iTXt
  180831. # ifndef PNG_READ_iTXt_SUPPORTED
  180832. # define PNG_READ_iTXt_SUPPORTED
  180833. # endif
  180834. # ifndef PNG_iTXt_SUPPORTED
  180835. # define PNG_iTXt_SUPPORTED
  180836. # endif
  180837. #endif
  180838. #ifndef PNG_NO_READ_oFFs
  180839. # define PNG_READ_oFFs_SUPPORTED
  180840. # define PNG_oFFs_SUPPORTED
  180841. #endif
  180842. #ifndef PNG_NO_READ_pCAL
  180843. # define PNG_READ_pCAL_SUPPORTED
  180844. # define PNG_pCAL_SUPPORTED
  180845. #endif
  180846. #ifndef PNG_NO_READ_sCAL
  180847. # define PNG_READ_sCAL_SUPPORTED
  180848. # define PNG_sCAL_SUPPORTED
  180849. #endif
  180850. #ifndef PNG_NO_READ_pHYs
  180851. # define PNG_READ_pHYs_SUPPORTED
  180852. # define PNG_pHYs_SUPPORTED
  180853. #endif
  180854. #ifndef PNG_NO_READ_sBIT
  180855. # define PNG_READ_sBIT_SUPPORTED
  180856. # define PNG_sBIT_SUPPORTED
  180857. #endif
  180858. #ifndef PNG_NO_READ_sPLT
  180859. # define PNG_READ_sPLT_SUPPORTED
  180860. # define PNG_sPLT_SUPPORTED
  180861. #endif
  180862. #ifndef PNG_NO_READ_sRGB
  180863. # define PNG_READ_sRGB_SUPPORTED
  180864. # define PNG_sRGB_SUPPORTED
  180865. #endif
  180866. #ifndef PNG_NO_READ_tEXt
  180867. # define PNG_READ_tEXt_SUPPORTED
  180868. # define PNG_tEXt_SUPPORTED
  180869. #endif
  180870. #ifndef PNG_NO_READ_tIME
  180871. # define PNG_READ_tIME_SUPPORTED
  180872. # define PNG_tIME_SUPPORTED
  180873. #endif
  180874. #ifndef PNG_NO_READ_tRNS
  180875. # define PNG_READ_tRNS_SUPPORTED
  180876. # define PNG_tRNS_SUPPORTED
  180877. #endif
  180878. #ifndef PNG_NO_READ_zTXt
  180879. # define PNG_READ_zTXt_SUPPORTED
  180880. # define PNG_zTXt_SUPPORTED
  180881. #endif
  180882. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  180883. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  180884. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180885. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180886. # endif
  180887. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180888. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180889. # endif
  180890. #endif
  180891. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  180892. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  180893. # define PNG_READ_USER_CHUNKS_SUPPORTED
  180894. # define PNG_USER_CHUNKS_SUPPORTED
  180895. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  180896. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  180897. # endif
  180898. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  180899. # undef PNG_NO_HANDLE_AS_UNKNOWN
  180900. # endif
  180901. #endif
  180902. #ifndef PNG_NO_READ_OPT_PLTE
  180903. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  180904. #endif /* optional PLTE chunk in RGB and RGBA images */
  180905. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  180906. defined(PNG_READ_zTXt_SUPPORTED)
  180907. # define PNG_READ_TEXT_SUPPORTED
  180908. # define PNG_TEXT_SUPPORTED
  180909. #endif
  180910. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  180911. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180912. #ifdef PNG_NO_WRITE_TEXT
  180913. # define PNG_NO_WRITE_iTXt
  180914. # define PNG_NO_WRITE_tEXt
  180915. # define PNG_NO_WRITE_zTXt
  180916. #endif
  180917. #ifndef PNG_NO_WRITE_bKGD
  180918. # define PNG_WRITE_bKGD_SUPPORTED
  180919. # ifndef PNG_bKGD_SUPPORTED
  180920. # define PNG_bKGD_SUPPORTED
  180921. # endif
  180922. #endif
  180923. #ifndef PNG_NO_WRITE_cHRM
  180924. # define PNG_WRITE_cHRM_SUPPORTED
  180925. # ifndef PNG_cHRM_SUPPORTED
  180926. # define PNG_cHRM_SUPPORTED
  180927. # endif
  180928. #endif
  180929. #ifndef PNG_NO_WRITE_gAMA
  180930. # define PNG_WRITE_gAMA_SUPPORTED
  180931. # ifndef PNG_gAMA_SUPPORTED
  180932. # define PNG_gAMA_SUPPORTED
  180933. # endif
  180934. #endif
  180935. #ifndef PNG_NO_WRITE_hIST
  180936. # define PNG_WRITE_hIST_SUPPORTED
  180937. # ifndef PNG_hIST_SUPPORTED
  180938. # define PNG_hIST_SUPPORTED
  180939. # endif
  180940. #endif
  180941. #ifndef PNG_NO_WRITE_iCCP
  180942. # define PNG_WRITE_iCCP_SUPPORTED
  180943. # ifndef PNG_iCCP_SUPPORTED
  180944. # define PNG_iCCP_SUPPORTED
  180945. # endif
  180946. #endif
  180947. #ifndef PNG_NO_WRITE_iTXt
  180948. # ifndef PNG_WRITE_iTXt_SUPPORTED
  180949. # define PNG_WRITE_iTXt_SUPPORTED
  180950. # endif
  180951. # ifndef PNG_iTXt_SUPPORTED
  180952. # define PNG_iTXt_SUPPORTED
  180953. # endif
  180954. #endif
  180955. #ifndef PNG_NO_WRITE_oFFs
  180956. # define PNG_WRITE_oFFs_SUPPORTED
  180957. # ifndef PNG_oFFs_SUPPORTED
  180958. # define PNG_oFFs_SUPPORTED
  180959. # endif
  180960. #endif
  180961. #ifndef PNG_NO_WRITE_pCAL
  180962. # define PNG_WRITE_pCAL_SUPPORTED
  180963. # ifndef PNG_pCAL_SUPPORTED
  180964. # define PNG_pCAL_SUPPORTED
  180965. # endif
  180966. #endif
  180967. #ifndef PNG_NO_WRITE_sCAL
  180968. # define PNG_WRITE_sCAL_SUPPORTED
  180969. # ifndef PNG_sCAL_SUPPORTED
  180970. # define PNG_sCAL_SUPPORTED
  180971. # endif
  180972. #endif
  180973. #ifndef PNG_NO_WRITE_pHYs
  180974. # define PNG_WRITE_pHYs_SUPPORTED
  180975. # ifndef PNG_pHYs_SUPPORTED
  180976. # define PNG_pHYs_SUPPORTED
  180977. # endif
  180978. #endif
  180979. #ifndef PNG_NO_WRITE_sBIT
  180980. # define PNG_WRITE_sBIT_SUPPORTED
  180981. # ifndef PNG_sBIT_SUPPORTED
  180982. # define PNG_sBIT_SUPPORTED
  180983. # endif
  180984. #endif
  180985. #ifndef PNG_NO_WRITE_sPLT
  180986. # define PNG_WRITE_sPLT_SUPPORTED
  180987. # ifndef PNG_sPLT_SUPPORTED
  180988. # define PNG_sPLT_SUPPORTED
  180989. # endif
  180990. #endif
  180991. #ifndef PNG_NO_WRITE_sRGB
  180992. # define PNG_WRITE_sRGB_SUPPORTED
  180993. # ifndef PNG_sRGB_SUPPORTED
  180994. # define PNG_sRGB_SUPPORTED
  180995. # endif
  180996. #endif
  180997. #ifndef PNG_NO_WRITE_tEXt
  180998. # define PNG_WRITE_tEXt_SUPPORTED
  180999. # ifndef PNG_tEXt_SUPPORTED
  181000. # define PNG_tEXt_SUPPORTED
  181001. # endif
  181002. #endif
  181003. #ifndef PNG_NO_WRITE_tIME
  181004. # define PNG_WRITE_tIME_SUPPORTED
  181005. # ifndef PNG_tIME_SUPPORTED
  181006. # define PNG_tIME_SUPPORTED
  181007. # endif
  181008. #endif
  181009. #ifndef PNG_NO_WRITE_tRNS
  181010. # define PNG_WRITE_tRNS_SUPPORTED
  181011. # ifndef PNG_tRNS_SUPPORTED
  181012. # define PNG_tRNS_SUPPORTED
  181013. # endif
  181014. #endif
  181015. #ifndef PNG_NO_WRITE_zTXt
  181016. # define PNG_WRITE_zTXt_SUPPORTED
  181017. # ifndef PNG_zTXt_SUPPORTED
  181018. # define PNG_zTXt_SUPPORTED
  181019. # endif
  181020. #endif
  181021. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181022. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181023. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181024. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181025. # endif
  181026. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181027. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181028. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181029. # endif
  181030. # endif
  181031. #endif
  181032. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181033. defined(PNG_WRITE_zTXt_SUPPORTED)
  181034. # define PNG_WRITE_TEXT_SUPPORTED
  181035. # ifndef PNG_TEXT_SUPPORTED
  181036. # define PNG_TEXT_SUPPORTED
  181037. # endif
  181038. #endif
  181039. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181040. /* Turn this off to disable png_read_png() and
  181041. * png_write_png() and leave the row_pointers member
  181042. * out of the info structure.
  181043. */
  181044. #ifndef PNG_NO_INFO_IMAGE
  181045. # define PNG_INFO_IMAGE_SUPPORTED
  181046. #endif
  181047. /* need the time information for reading tIME chunks */
  181048. #if defined(PNG_tIME_SUPPORTED)
  181049. # if !defined(_WIN32_WCE)
  181050. /* "time.h" functions are not supported on WindowsCE */
  181051. # include <time.h>
  181052. # endif
  181053. #endif
  181054. /* Some typedefs to get us started. These should be safe on most of the
  181055. * common platforms. The typedefs should be at least as large as the
  181056. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181057. * don't have to be exactly that size. Some compilers dislike passing
  181058. * unsigned shorts as function parameters, so you may be better off using
  181059. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181060. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181061. */
  181062. typedef unsigned long png_uint_32;
  181063. typedef long png_int_32;
  181064. typedef unsigned short png_uint_16;
  181065. typedef short png_int_16;
  181066. typedef unsigned char png_byte;
  181067. /* This is usually size_t. It is typedef'ed just in case you need it to
  181068. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181069. #ifdef PNG_SIZE_T
  181070. typedef PNG_SIZE_T png_size_t;
  181071. # define png_sizeof(x) png_convert_size(sizeof (x))
  181072. #else
  181073. typedef size_t png_size_t;
  181074. # define png_sizeof(x) sizeof (x)
  181075. #endif
  181076. /* The following is needed for medium model support. It cannot be in the
  181077. * PNG_INTERNAL section. Needs modification for other compilers besides
  181078. * MSC. Model independent support declares all arrays and pointers to be
  181079. * large using the far keyword. The zlib version used must also support
  181080. * model independent data. As of version zlib 1.0.4, the necessary changes
  181081. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181082. * changes that are needed. (Tim Wegner)
  181083. */
  181084. /* Separate compiler dependencies (problem here is that zlib.h always
  181085. defines FAR. (SJT) */
  181086. #ifdef __BORLANDC__
  181087. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181088. # define LDATA 1
  181089. # else
  181090. # define LDATA 0
  181091. # endif
  181092. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181093. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181094. # define PNG_MAX_MALLOC_64K
  181095. # if (LDATA != 1)
  181096. # ifndef FAR
  181097. # define FAR __far
  181098. # endif
  181099. # define USE_FAR_KEYWORD
  181100. # endif /* LDATA != 1 */
  181101. /* Possibly useful for moving data out of default segment.
  181102. * Uncomment it if you want. Could also define FARDATA as
  181103. * const if your compiler supports it. (SJT)
  181104. # define FARDATA FAR
  181105. */
  181106. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181107. #endif /* __BORLANDC__ */
  181108. /* Suggest testing for specific compiler first before testing for
  181109. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181110. * making reliance oncertain keywords suspect. (SJT)
  181111. */
  181112. /* MSC Medium model */
  181113. #if defined(FAR)
  181114. # if defined(M_I86MM)
  181115. # define USE_FAR_KEYWORD
  181116. # define FARDATA FAR
  181117. # include <dos.h>
  181118. # endif
  181119. #endif
  181120. /* SJT: default case */
  181121. #ifndef FAR
  181122. # define FAR
  181123. #endif
  181124. /* At this point FAR is always defined */
  181125. #ifndef FARDATA
  181126. # define FARDATA
  181127. #endif
  181128. /* Typedef for floating-point numbers that are converted
  181129. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181130. typedef png_int_32 png_fixed_point;
  181131. /* Add typedefs for pointers */
  181132. typedef void FAR * png_voidp;
  181133. typedef png_byte FAR * png_bytep;
  181134. typedef png_uint_32 FAR * png_uint_32p;
  181135. typedef png_int_32 FAR * png_int_32p;
  181136. typedef png_uint_16 FAR * png_uint_16p;
  181137. typedef png_int_16 FAR * png_int_16p;
  181138. typedef PNG_CONST char FAR * png_const_charp;
  181139. typedef char FAR * png_charp;
  181140. typedef png_fixed_point FAR * png_fixed_point_p;
  181141. #ifndef PNG_NO_STDIO
  181142. #if defined(_WIN32_WCE)
  181143. typedef HANDLE png_FILE_p;
  181144. #else
  181145. typedef FILE * png_FILE_p;
  181146. #endif
  181147. #endif
  181148. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181149. typedef double FAR * png_doublep;
  181150. #endif
  181151. /* Pointers to pointers; i.e. arrays */
  181152. typedef png_byte FAR * FAR * png_bytepp;
  181153. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181154. typedef png_int_32 FAR * FAR * png_int_32pp;
  181155. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181156. typedef png_int_16 FAR * FAR * png_int_16pp;
  181157. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181158. typedef char FAR * FAR * png_charpp;
  181159. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181160. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181161. typedef double FAR * FAR * png_doublepp;
  181162. #endif
  181163. /* Pointers to pointers to pointers; i.e., pointer to array */
  181164. typedef char FAR * FAR * FAR * png_charppp;
  181165. #if 0
  181166. /* SPC - Is this stuff deprecated? */
  181167. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181168. /* libpng typedefs for types in zlib. If zlib changes
  181169. * or another compression library is used, then change these.
  181170. * Eliminates need to change all the source files.
  181171. */
  181172. typedef charf * png_zcharp;
  181173. typedef charf * FAR * png_zcharpp;
  181174. typedef z_stream FAR * png_zstreamp;
  181175. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181176. /*
  181177. * Define PNG_BUILD_DLL if the module being built is a Windows
  181178. * LIBPNG DLL.
  181179. *
  181180. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181181. * It is equivalent to Microsoft predefined macro _DLL that is
  181182. * automatically defined when you compile using the share
  181183. * version of the CRT (C Run-Time library)
  181184. *
  181185. * The cygwin mods make this behavior a little different:
  181186. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181187. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181188. * -or- if you are building an application that you want to link to the
  181189. * static library.
  181190. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181191. * the other flags is defined.
  181192. */
  181193. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181194. # define PNG_DLL
  181195. #endif
  181196. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181197. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181198. * command-line override
  181199. */
  181200. #if defined(__CYGWIN__)
  181201. # if !defined(PNG_STATIC)
  181202. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181203. # undef PNG_USE_GLOBAL_ARRAYS
  181204. # endif
  181205. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181206. # define PNG_USE_LOCAL_ARRAYS
  181207. # endif
  181208. # else
  181209. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181210. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181211. # undef PNG_USE_GLOBAL_ARRAYS
  181212. # endif
  181213. # endif
  181214. # endif
  181215. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181216. # define PNG_USE_LOCAL_ARRAYS
  181217. # endif
  181218. #endif
  181219. /* Do not use global arrays (helps with building DLL's)
  181220. * They are no longer used in libpng itself, since version 1.0.5c,
  181221. * but might be required for some pre-1.0.5c applications.
  181222. */
  181223. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181224. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181225. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181226. # define PNG_USE_LOCAL_ARRAYS
  181227. # else
  181228. # define PNG_USE_GLOBAL_ARRAYS
  181229. # endif
  181230. #endif
  181231. #if defined(__CYGWIN__)
  181232. # undef PNGAPI
  181233. # define PNGAPI __cdecl
  181234. # undef PNG_IMPEXP
  181235. # define PNG_IMPEXP
  181236. #endif
  181237. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181238. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181239. * Don't ignore those warnings; you must also reset the default calling
  181240. * convention in your compiler to match your PNGAPI, and you must build
  181241. * zlib and your applications the same way you build libpng.
  181242. */
  181243. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181244. # ifndef PNG_NO_MODULEDEF
  181245. # define PNG_NO_MODULEDEF
  181246. # endif
  181247. #endif
  181248. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181249. # define PNG_IMPEXP
  181250. #endif
  181251. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181252. (( defined(_Windows) || defined(_WINDOWS) || \
  181253. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181254. # ifndef PNGAPI
  181255. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181256. # define PNGAPI __cdecl
  181257. # else
  181258. # define PNGAPI _cdecl
  181259. # endif
  181260. # endif
  181261. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181262. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181263. # define PNG_IMPEXP
  181264. # endif
  181265. # if !defined(PNG_IMPEXP)
  181266. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181267. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181268. /* Borland/Microsoft */
  181269. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181270. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181271. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181272. # else
  181273. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181274. # if defined(PNG_BUILD_DLL)
  181275. # define PNG_IMPEXP __export
  181276. # else
  181277. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181278. VC++ */
  181279. # endif /* Exists in Borland C++ for
  181280. C++ classes (== huge) */
  181281. # endif
  181282. # endif
  181283. # if !defined(PNG_IMPEXP)
  181284. # if defined(PNG_BUILD_DLL)
  181285. # define PNG_IMPEXP __declspec(dllexport)
  181286. # else
  181287. # define PNG_IMPEXP __declspec(dllimport)
  181288. # endif
  181289. # endif
  181290. # endif /* PNG_IMPEXP */
  181291. #else /* !(DLL || non-cygwin WINDOWS) */
  181292. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181293. # ifndef PNGAPI
  181294. # define PNGAPI _System
  181295. # endif
  181296. # else
  181297. # if 0 /* ... other platforms, with other meanings */
  181298. # endif
  181299. # endif
  181300. #endif
  181301. #ifndef PNGAPI
  181302. # define PNGAPI
  181303. #endif
  181304. #ifndef PNG_IMPEXP
  181305. # define PNG_IMPEXP
  181306. #endif
  181307. #ifdef PNG_BUILDSYMS
  181308. # ifndef PNG_EXPORT
  181309. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181310. # endif
  181311. # ifdef PNG_USE_GLOBAL_ARRAYS
  181312. # ifndef PNG_EXPORT_VAR
  181313. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181314. # endif
  181315. # endif
  181316. #endif
  181317. #ifndef PNG_EXPORT
  181318. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181319. #endif
  181320. #ifdef PNG_USE_GLOBAL_ARRAYS
  181321. # ifndef PNG_EXPORT_VAR
  181322. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181323. # endif
  181324. #endif
  181325. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181326. * functions that are passed far data must be model independent.
  181327. */
  181328. #ifndef PNG_ABORT
  181329. # define PNG_ABORT() abort()
  181330. #endif
  181331. #ifdef PNG_SETJMP_SUPPORTED
  181332. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181333. #else
  181334. # define png_jmpbuf(png_ptr) \
  181335. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181336. #endif
  181337. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181338. /* use this to make far-to-near assignments */
  181339. # define CHECK 1
  181340. # define NOCHECK 0
  181341. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181342. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181343. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181344. # define png_strcpy _fstrcpy
  181345. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181346. # define png_strlen _fstrlen
  181347. # define png_memcmp _fmemcmp /* SJT: added */
  181348. # define png_memcpy _fmemcpy
  181349. # define png_memset _fmemset
  181350. #else /* use the usual functions */
  181351. # define CVT_PTR(ptr) (ptr)
  181352. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181353. # ifndef PNG_NO_SNPRINTF
  181354. # ifdef _MSC_VER
  181355. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181356. # define png_snprintf2 _snprintf
  181357. # define png_snprintf6 _snprintf
  181358. # else
  181359. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181360. # define png_snprintf2 snprintf
  181361. # define png_snprintf6 snprintf
  181362. # endif
  181363. # else
  181364. /* You don't have or don't want to use snprintf(). Caution: Using
  181365. * sprintf instead of snprintf exposes your application to accidental
  181366. * or malevolent buffer overflows. If you don't have snprintf()
  181367. * as a general rule you should provide one (you can get one from
  181368. * Portable OpenSSH). */
  181369. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181370. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181371. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181372. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181373. # endif
  181374. # define png_strcpy strcpy
  181375. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181376. # define png_strlen strlen
  181377. # define png_memcmp memcmp /* SJT: added */
  181378. # define png_memcpy memcpy
  181379. # define png_memset memset
  181380. #endif
  181381. /* End of memory model independent support */
  181382. /* Just a little check that someone hasn't tried to define something
  181383. * contradictory.
  181384. */
  181385. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181386. # undef PNG_ZBUF_SIZE
  181387. # define PNG_ZBUF_SIZE 65536L
  181388. #endif
  181389. /* Added at libpng-1.2.8 */
  181390. #endif /* PNG_VERSION_INFO_ONLY */
  181391. #endif /* PNGCONF_H */
  181392. /*** End of inlined file: pngconf.h ***/
  181393. #ifdef _MSC_VER
  181394. #pragma warning (disable: 4996 4100)
  181395. #endif
  181396. /*
  181397. * Added at libpng-1.2.8 */
  181398. /* Ref MSDN: Private as priority over Special
  181399. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181400. * procedures. If this value is given, the StringFileInfo block must
  181401. * contain a PrivateBuild string.
  181402. *
  181403. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181404. * standard release procedures but is a variation of the standard
  181405. * file of the same version number. If this value is given, the
  181406. * StringFileInfo block must contain a SpecialBuild string.
  181407. */
  181408. #if defined(PNG_USER_PRIVATEBUILD)
  181409. # define PNG_LIBPNG_BUILD_TYPE \
  181410. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181411. #else
  181412. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181413. # define PNG_LIBPNG_BUILD_TYPE \
  181414. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181415. # else
  181416. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181417. # endif
  181418. #endif
  181419. #ifndef PNG_VERSION_INFO_ONLY
  181420. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181421. #ifdef __cplusplus
  181422. extern "C" {
  181423. #endif /* __cplusplus */
  181424. /* This file is arranged in several sections. The first section contains
  181425. * structure and type definitions. The second section contains the external
  181426. * library functions, while the third has the internal library functions,
  181427. * which applications aren't expected to use directly.
  181428. */
  181429. #ifndef PNG_NO_TYPECAST_NULL
  181430. #define int_p_NULL (int *)NULL
  181431. #define png_bytep_NULL (png_bytep)NULL
  181432. #define png_bytepp_NULL (png_bytepp)NULL
  181433. #define png_doublep_NULL (png_doublep)NULL
  181434. #define png_error_ptr_NULL (png_error_ptr)NULL
  181435. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181436. #define png_free_ptr_NULL (png_free_ptr)NULL
  181437. #define png_infopp_NULL (png_infopp)NULL
  181438. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181439. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181440. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181441. #define png_structp_NULL (png_structp)NULL
  181442. #define png_uint_16p_NULL (png_uint_16p)NULL
  181443. #define png_voidp_NULL (png_voidp)NULL
  181444. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181445. #else
  181446. #define int_p_NULL NULL
  181447. #define png_bytep_NULL NULL
  181448. #define png_bytepp_NULL NULL
  181449. #define png_doublep_NULL NULL
  181450. #define png_error_ptr_NULL NULL
  181451. #define png_flush_ptr_NULL NULL
  181452. #define png_free_ptr_NULL NULL
  181453. #define png_infopp_NULL NULL
  181454. #define png_malloc_ptr_NULL NULL
  181455. #define png_read_status_ptr_NULL NULL
  181456. #define png_rw_ptr_NULL NULL
  181457. #define png_structp_NULL NULL
  181458. #define png_uint_16p_NULL NULL
  181459. #define png_voidp_NULL NULL
  181460. #define png_write_status_ptr_NULL NULL
  181461. #endif
  181462. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181463. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181464. /* Version information for C files, stored in png.c. This had better match
  181465. * the version above.
  181466. */
  181467. #ifdef PNG_USE_GLOBAL_ARRAYS
  181468. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181469. /* need room for 99.99.99beta99z */
  181470. #else
  181471. #define png_libpng_ver png_get_header_ver(NULL)
  181472. #endif
  181473. #ifdef PNG_USE_GLOBAL_ARRAYS
  181474. /* This was removed in version 1.0.5c */
  181475. /* Structures to facilitate easy interlacing. See png.c for more details */
  181476. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181477. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181478. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181479. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181480. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181481. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181482. /* This isn't currently used. If you need it, see png.c for more details.
  181483. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181484. */
  181485. #endif
  181486. #endif /* PNG_NO_EXTERN */
  181487. /* Three color definitions. The order of the red, green, and blue, (and the
  181488. * exact size) is not important, although the size of the fields need to
  181489. * be png_byte or png_uint_16 (as defined below).
  181490. */
  181491. typedef struct png_color_struct
  181492. {
  181493. png_byte red;
  181494. png_byte green;
  181495. png_byte blue;
  181496. } png_color;
  181497. typedef png_color FAR * png_colorp;
  181498. typedef png_color FAR * FAR * png_colorpp;
  181499. typedef struct png_color_16_struct
  181500. {
  181501. png_byte index; /* used for palette files */
  181502. png_uint_16 red; /* for use in red green blue files */
  181503. png_uint_16 green;
  181504. png_uint_16 blue;
  181505. png_uint_16 gray; /* for use in grayscale files */
  181506. } png_color_16;
  181507. typedef png_color_16 FAR * png_color_16p;
  181508. typedef png_color_16 FAR * FAR * png_color_16pp;
  181509. typedef struct png_color_8_struct
  181510. {
  181511. png_byte red; /* for use in red green blue files */
  181512. png_byte green;
  181513. png_byte blue;
  181514. png_byte gray; /* for use in grayscale files */
  181515. png_byte alpha; /* for alpha channel files */
  181516. } png_color_8;
  181517. typedef png_color_8 FAR * png_color_8p;
  181518. typedef png_color_8 FAR * FAR * png_color_8pp;
  181519. /*
  181520. * The following two structures are used for the in-core representation
  181521. * of sPLT chunks.
  181522. */
  181523. typedef struct png_sPLT_entry_struct
  181524. {
  181525. png_uint_16 red;
  181526. png_uint_16 green;
  181527. png_uint_16 blue;
  181528. png_uint_16 alpha;
  181529. png_uint_16 frequency;
  181530. } png_sPLT_entry;
  181531. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181532. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181533. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181534. * occupy the LSB of their respective members, and the MSB of each member
  181535. * is zero-filled. The frequency member always occupies the full 16 bits.
  181536. */
  181537. typedef struct png_sPLT_struct
  181538. {
  181539. png_charp name; /* palette name */
  181540. png_byte depth; /* depth of palette samples */
  181541. png_sPLT_entryp entries; /* palette entries */
  181542. png_int_32 nentries; /* number of palette entries */
  181543. } png_sPLT_t;
  181544. typedef png_sPLT_t FAR * png_sPLT_tp;
  181545. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181546. #ifdef PNG_TEXT_SUPPORTED
  181547. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181548. * and whether that contents is compressed or not. The "key" field
  181549. * points to a regular zero-terminated C string. The "text", "lang", and
  181550. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181551. * However, the * structure returned by png_get_text() will always contain
  181552. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181553. * so they can be safely used in printf() and other string-handling functions.
  181554. */
  181555. typedef struct png_text_struct
  181556. {
  181557. int compression; /* compression value:
  181558. -1: tEXt, none
  181559. 0: zTXt, deflate
  181560. 1: iTXt, none
  181561. 2: iTXt, deflate */
  181562. png_charp key; /* keyword, 1-79 character description of "text" */
  181563. png_charp text; /* comment, may be an empty string (ie "")
  181564. or a NULL pointer */
  181565. png_size_t text_length; /* length of the text string */
  181566. #ifdef PNG_iTXt_SUPPORTED
  181567. png_size_t itxt_length; /* length of the itxt string */
  181568. png_charp lang; /* language code, 0-79 characters
  181569. or a NULL pointer */
  181570. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181571. chars or a NULL pointer */
  181572. #endif
  181573. } png_text;
  181574. typedef png_text FAR * png_textp;
  181575. typedef png_text FAR * FAR * png_textpp;
  181576. #endif
  181577. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181578. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181579. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181580. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181581. #define PNG_TEXT_COMPRESSION_NONE -1
  181582. #define PNG_TEXT_COMPRESSION_zTXt 0
  181583. #define PNG_ITXT_COMPRESSION_NONE 1
  181584. #define PNG_ITXT_COMPRESSION_zTXt 2
  181585. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181586. /* png_time is a way to hold the time in an machine independent way.
  181587. * Two conversions are provided, both from time_t and struct tm. There
  181588. * is no portable way to convert to either of these structures, as far
  181589. * as I know. If you know of a portable way, send it to me. As a side
  181590. * note - PNG has always been Year 2000 compliant!
  181591. */
  181592. typedef struct png_time_struct
  181593. {
  181594. png_uint_16 year; /* full year, as in, 1995 */
  181595. png_byte month; /* month of year, 1 - 12 */
  181596. png_byte day; /* day of month, 1 - 31 */
  181597. png_byte hour; /* hour of day, 0 - 23 */
  181598. png_byte minute; /* minute of hour, 0 - 59 */
  181599. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181600. } png_time;
  181601. typedef png_time FAR * png_timep;
  181602. typedef png_time FAR * FAR * png_timepp;
  181603. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181604. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181605. * no specific support. The idea is that we can use this to queue
  181606. * up private chunks for output even though the library doesn't actually
  181607. * know about their semantics.
  181608. */
  181609. typedef struct png_unknown_chunk_t
  181610. {
  181611. png_byte name[5];
  181612. png_byte *data;
  181613. png_size_t size;
  181614. /* libpng-using applications should NOT directly modify this byte. */
  181615. png_byte location; /* mode of operation at read time */
  181616. }
  181617. png_unknown_chunk;
  181618. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181619. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181620. #endif
  181621. /* png_info is a structure that holds the information in a PNG file so
  181622. * that the application can find out the characteristics of the image.
  181623. * If you are reading the file, this structure will tell you what is
  181624. * in the PNG file. If you are writing the file, fill in the information
  181625. * you want to put into the PNG file, then call png_write_info().
  181626. * The names chosen should be very close to the PNG specification, so
  181627. * consult that document for information about the meaning of each field.
  181628. *
  181629. * With libpng < 0.95, it was only possible to directly set and read the
  181630. * the values in the png_info_struct, which meant that the contents and
  181631. * order of the values had to remain fixed. With libpng 0.95 and later,
  181632. * however, there are now functions that abstract the contents of
  181633. * png_info_struct from the application, so this makes it easier to use
  181634. * libpng with dynamic libraries, and even makes it possible to use
  181635. * libraries that don't have all of the libpng ancillary chunk-handing
  181636. * functionality.
  181637. *
  181638. * In any case, the order of the parameters in png_info_struct should NOT
  181639. * be changed for as long as possible to keep compatibility with applications
  181640. * that use the old direct-access method with png_info_struct.
  181641. *
  181642. * The following members may have allocated storage attached that should be
  181643. * cleaned up before the structure is discarded: palette, trans, text,
  181644. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181645. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181646. * are automatically freed when the info structure is deallocated, if they were
  181647. * allocated internally by libpng. This behavior can be changed by means
  181648. * of the png_data_freer() function.
  181649. *
  181650. * More allocation details: all the chunk-reading functions that
  181651. * change these members go through the corresponding png_set_*
  181652. * functions. A function to clear these members is available: see
  181653. * png_free_data(). The png_set_* functions do not depend on being
  181654. * able to point info structure members to any of the storage they are
  181655. * passed (they make their own copies), EXCEPT that the png_set_text
  181656. * functions use the same storage passed to them in the text_ptr or
  181657. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181658. * functions do not make their own copies.
  181659. */
  181660. typedef struct png_info_struct
  181661. {
  181662. /* the following are necessary for every PNG file */
  181663. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181664. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181665. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181666. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181667. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181668. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181669. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181670. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181671. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181672. /* The following three should have been named *_method not *_type */
  181673. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181674. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181675. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181676. /* The following is informational only on read, and not used on writes. */
  181677. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181678. png_byte pixel_depth; /* number of bits per pixel */
  181679. png_byte spare_byte; /* to align the data, and for future use */
  181680. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181681. /* The rest of the data is optional. If you are reading, check the
  181682. * valid field to see if the information in these are valid. If you
  181683. * are writing, set the valid field to those chunks you want written,
  181684. * and initialize the appropriate fields below.
  181685. */
  181686. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181687. /* The gAMA chunk describes the gamma characteristics of the system
  181688. * on which the image was created, normally in the range [1.0, 2.5].
  181689. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181690. */
  181691. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181692. #endif
  181693. #if defined(PNG_sRGB_SUPPORTED)
  181694. /* GR-P, 0.96a */
  181695. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181696. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181697. #endif
  181698. #if defined(PNG_TEXT_SUPPORTED)
  181699. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181700. * uncompressed, compressed, and optionally compressed forms, respectively.
  181701. * The data in "text" is an array of pointers to uncompressed,
  181702. * null-terminated C strings. Each chunk has a keyword that describes the
  181703. * textual data contained in that chunk. Keywords are not required to be
  181704. * unique, and the text string may be empty. Any number of text chunks may
  181705. * be in an image.
  181706. */
  181707. int num_text; /* number of comments read/to write */
  181708. int max_text; /* current size of text array */
  181709. png_textp text; /* array of comments read/to write */
  181710. #endif /* PNG_TEXT_SUPPORTED */
  181711. #if defined(PNG_tIME_SUPPORTED)
  181712. /* The tIME chunk holds the last time the displayed image data was
  181713. * modified. See the png_time struct for the contents of this struct.
  181714. */
  181715. png_time mod_time;
  181716. #endif
  181717. #if defined(PNG_sBIT_SUPPORTED)
  181718. /* The sBIT chunk specifies the number of significant high-order bits
  181719. * in the pixel data. Values are in the range [1, bit_depth], and are
  181720. * only specified for the channels in the pixel data. The contents of
  181721. * the low-order bits is not specified. Data is valid if
  181722. * (valid & PNG_INFO_sBIT) is non-zero.
  181723. */
  181724. png_color_8 sig_bit; /* significant bits in color channels */
  181725. #endif
  181726. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181727. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181728. /* The tRNS chunk supplies transparency data for paletted images and
  181729. * other image types that don't need a full alpha channel. There are
  181730. * "num_trans" transparency values for a paletted image, stored in the
  181731. * same order as the palette colors, starting from index 0. Values
  181732. * for the data are in the range [0, 255], ranging from fully transparent
  181733. * to fully opaque, respectively. For non-paletted images, there is a
  181734. * single color specified that should be treated as fully transparent.
  181735. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181736. */
  181737. png_bytep trans; /* transparent values for paletted image */
  181738. png_color_16 trans_values; /* transparent color for non-palette image */
  181739. #endif
  181740. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181741. /* The bKGD chunk gives the suggested image background color if the
  181742. * display program does not have its own background color and the image
  181743. * is needs to composited onto a background before display. The colors
  181744. * in "background" are normally in the same color space/depth as the
  181745. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181746. */
  181747. png_color_16 background;
  181748. #endif
  181749. #if defined(PNG_oFFs_SUPPORTED)
  181750. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181751. * and downwards from the top-left corner of the display, page, or other
  181752. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181753. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181754. */
  181755. png_int_32 x_offset; /* x offset on page */
  181756. png_int_32 y_offset; /* y offset on page */
  181757. png_byte offset_unit_type; /* offset units type */
  181758. #endif
  181759. #if defined(PNG_pHYs_SUPPORTED)
  181760. /* The pHYs chunk gives the physical pixel density of the image for
  181761. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181762. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181763. */
  181764. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181765. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181766. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181767. #endif
  181768. #if defined(PNG_hIST_SUPPORTED)
  181769. /* The hIST chunk contains the relative frequency or importance of the
  181770. * various palette entries, so that a viewer can intelligently select a
  181771. * reduced-color palette, if required. Data is an array of "num_palette"
  181772. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181773. * is non-zero.
  181774. */
  181775. png_uint_16p hist;
  181776. #endif
  181777. #ifdef PNG_cHRM_SUPPORTED
  181778. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181779. * on which the PNG was created. This data allows the viewer to do gamut
  181780. * mapping of the input image to ensure that the viewer sees the same
  181781. * colors in the image as the creator. Values are in the range
  181782. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181783. */
  181784. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181785. float x_white;
  181786. float y_white;
  181787. float x_red;
  181788. float y_red;
  181789. float x_green;
  181790. float y_green;
  181791. float x_blue;
  181792. float y_blue;
  181793. #endif
  181794. #endif
  181795. #if defined(PNG_pCAL_SUPPORTED)
  181796. /* The pCAL chunk describes a transformation between the stored pixel
  181797. * values and original physical data values used to create the image.
  181798. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181799. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181800. * (possibly non-linear) transformation function given by "pcal_type"
  181801. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181802. * defines below, and the PNG-Group's PNG extensions document for a
  181803. * complete description of the transformations and how they should be
  181804. * implemented, and for a description of the ASCII parameter strings.
  181805. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181806. */
  181807. png_charp pcal_purpose; /* pCAL chunk description string */
  181808. png_int_32 pcal_X0; /* minimum value */
  181809. png_int_32 pcal_X1; /* maximum value */
  181810. png_charp pcal_units; /* Latin-1 string giving physical units */
  181811. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181812. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181813. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181814. #endif
  181815. /* New members added in libpng-1.0.6 */
  181816. #ifdef PNG_FREE_ME_SUPPORTED
  181817. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181818. #endif
  181819. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181820. /* storage for unknown chunks that the library doesn't recognize. */
  181821. png_unknown_chunkp unknown_chunks;
  181822. png_size_t unknown_chunks_num;
  181823. #endif
  181824. #if defined(PNG_iCCP_SUPPORTED)
  181825. /* iCCP chunk data. */
  181826. png_charp iccp_name; /* profile name */
  181827. png_charp iccp_profile; /* International Color Consortium profile data */
  181828. /* Note to maintainer: should be png_bytep */
  181829. png_uint_32 iccp_proflen; /* ICC profile data length */
  181830. png_byte iccp_compression; /* Always zero */
  181831. #endif
  181832. #if defined(PNG_sPLT_SUPPORTED)
  181833. /* data on sPLT chunks (there may be more than one). */
  181834. png_sPLT_tp splt_palettes;
  181835. png_uint_32 splt_palettes_num;
  181836. #endif
  181837. #if defined(PNG_sCAL_SUPPORTED)
  181838. /* The sCAL chunk describes the actual physical dimensions of the
  181839. * subject matter of the graphic. The chunk contains a unit specification
  181840. * a byte value, and two ASCII strings representing floating-point
  181841. * values. The values are width and height corresponsing to one pixel
  181842. * in the image. This external representation is converted to double
  181843. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  181844. */
  181845. png_byte scal_unit; /* unit of physical scale */
  181846. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181847. double scal_pixel_width; /* width of one pixel */
  181848. double scal_pixel_height; /* height of one pixel */
  181849. #endif
  181850. #ifdef PNG_FIXED_POINT_SUPPORTED
  181851. png_charp scal_s_width; /* string containing height */
  181852. png_charp scal_s_height; /* string containing width */
  181853. #endif
  181854. #endif
  181855. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181856. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  181857. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  181858. png_bytepp row_pointers; /* the image bits */
  181859. #endif
  181860. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  181861. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  181862. #endif
  181863. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  181864. png_fixed_point int_x_white;
  181865. png_fixed_point int_y_white;
  181866. png_fixed_point int_x_red;
  181867. png_fixed_point int_y_red;
  181868. png_fixed_point int_x_green;
  181869. png_fixed_point int_y_green;
  181870. png_fixed_point int_x_blue;
  181871. png_fixed_point int_y_blue;
  181872. #endif
  181873. } png_info;
  181874. typedef png_info FAR * png_infop;
  181875. typedef png_info FAR * FAR * png_infopp;
  181876. /* Maximum positive integer used in PNG is (2^31)-1 */
  181877. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  181878. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  181879. #define PNG_SIZE_MAX ((png_size_t)(-1))
  181880. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181881. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  181882. #define PNG_MAX_UINT PNG_UINT_31_MAX
  181883. #endif
  181884. /* These describe the color_type field in png_info. */
  181885. /* color type masks */
  181886. #define PNG_COLOR_MASK_PALETTE 1
  181887. #define PNG_COLOR_MASK_COLOR 2
  181888. #define PNG_COLOR_MASK_ALPHA 4
  181889. /* color types. Note that not all combinations are legal */
  181890. #define PNG_COLOR_TYPE_GRAY 0
  181891. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  181892. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  181893. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  181894. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  181895. /* aliases */
  181896. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  181897. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  181898. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  181899. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  181900. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  181901. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  181902. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  181903. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  181904. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  181905. /* These are for the interlacing type. These values should NOT be changed. */
  181906. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  181907. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  181908. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  181909. /* These are for the oFFs chunk. These values should NOT be changed. */
  181910. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  181911. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  181912. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  181913. /* These are for the pCAL chunk. These values should NOT be changed. */
  181914. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  181915. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  181916. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  181917. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  181918. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  181919. /* These are for the sCAL chunk. These values should NOT be changed. */
  181920. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  181921. #define PNG_SCALE_METER 1 /* meters per pixel */
  181922. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  181923. #define PNG_SCALE_LAST 3 /* Not a valid value */
  181924. /* These are for the pHYs chunk. These values should NOT be changed. */
  181925. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  181926. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  181927. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  181928. /* These are for the sRGB chunk. These values should NOT be changed. */
  181929. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  181930. #define PNG_sRGB_INTENT_RELATIVE 1
  181931. #define PNG_sRGB_INTENT_SATURATION 2
  181932. #define PNG_sRGB_INTENT_ABSOLUTE 3
  181933. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  181934. /* This is for text chunks */
  181935. #define PNG_KEYWORD_MAX_LENGTH 79
  181936. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  181937. #define PNG_MAX_PALETTE_LENGTH 256
  181938. /* These determine if an ancillary chunk's data has been successfully read
  181939. * from the PNG header, or if the application has filled in the corresponding
  181940. * data in the info_struct to be written into the output file. The values
  181941. * of the PNG_INFO_<chunk> defines should NOT be changed.
  181942. */
  181943. #define PNG_INFO_gAMA 0x0001
  181944. #define PNG_INFO_sBIT 0x0002
  181945. #define PNG_INFO_cHRM 0x0004
  181946. #define PNG_INFO_PLTE 0x0008
  181947. #define PNG_INFO_tRNS 0x0010
  181948. #define PNG_INFO_bKGD 0x0020
  181949. #define PNG_INFO_hIST 0x0040
  181950. #define PNG_INFO_pHYs 0x0080
  181951. #define PNG_INFO_oFFs 0x0100
  181952. #define PNG_INFO_tIME 0x0200
  181953. #define PNG_INFO_pCAL 0x0400
  181954. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  181955. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  181956. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  181957. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  181958. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  181959. /* This is used for the transformation routines, as some of them
  181960. * change these values for the row. It also should enable using
  181961. * the routines for other purposes.
  181962. */
  181963. typedef struct png_row_info_struct
  181964. {
  181965. png_uint_32 width; /* width of row */
  181966. png_uint_32 rowbytes; /* number of bytes in row */
  181967. png_byte color_type; /* color type of row */
  181968. png_byte bit_depth; /* bit depth of row */
  181969. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  181970. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  181971. } png_row_info;
  181972. typedef png_row_info FAR * png_row_infop;
  181973. typedef png_row_info FAR * FAR * png_row_infopp;
  181974. /* These are the function types for the I/O functions and for the functions
  181975. * that allow the user to override the default I/O functions with his or her
  181976. * own. The png_error_ptr type should match that of user-supplied warning
  181977. * and error functions, while the png_rw_ptr type should match that of the
  181978. * user read/write data functions.
  181979. */
  181980. typedef struct png_struct_def png_struct;
  181981. typedef png_struct FAR * png_structp;
  181982. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  181983. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  181984. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  181985. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  181986. int));
  181987. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  181988. int));
  181989. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181990. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  181991. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  181992. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  181993. png_uint_32, int));
  181994. #endif
  181995. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181996. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  181997. defined(PNG_LEGACY_SUPPORTED)
  181998. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  181999. png_row_infop, png_bytep));
  182000. #endif
  182001. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182002. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182003. #endif
  182004. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182005. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182006. #endif
  182007. /* Transform masks for the high-level interface */
  182008. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182009. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182010. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182011. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182012. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182013. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182014. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182015. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182016. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182017. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182018. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182019. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182020. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182021. /* Flags for MNG supported features */
  182022. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182023. #define PNG_FLAG_MNG_FILTER_64 0x04
  182024. #define PNG_ALL_MNG_FEATURES 0x05
  182025. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182026. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182027. /* The structure that holds the information to read and write PNG files.
  182028. * The only people who need to care about what is inside of this are the
  182029. * people who will be modifying the library for their own special needs.
  182030. * It should NOT be accessed directly by an application, except to store
  182031. * the jmp_buf.
  182032. */
  182033. struct png_struct_def
  182034. {
  182035. #ifdef PNG_SETJMP_SUPPORTED
  182036. jmp_buf jmpbuf; /* used in png_error */
  182037. #endif
  182038. png_error_ptr error_fn; /* function for printing errors and aborting */
  182039. png_error_ptr warning_fn; /* function for printing warnings */
  182040. png_voidp error_ptr; /* user supplied struct for error functions */
  182041. png_rw_ptr write_data_fn; /* function for writing output data */
  182042. png_rw_ptr read_data_fn; /* function for reading input data */
  182043. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182044. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182045. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182046. #endif
  182047. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182048. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182049. #endif
  182050. /* These were added in libpng-1.0.2 */
  182051. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182052. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182053. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182054. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182055. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182056. png_byte user_transform_channels; /* channels in user transformed pixels */
  182057. #endif
  182058. #endif
  182059. png_uint_32 mode; /* tells us where we are in the PNG file */
  182060. png_uint_32 flags; /* flags indicating various things to libpng */
  182061. png_uint_32 transformations; /* which transformations to perform */
  182062. z_stream zstream; /* pointer to decompression structure (below) */
  182063. png_bytep zbuf; /* buffer for zlib */
  182064. png_size_t zbuf_size; /* size of zbuf */
  182065. int zlib_level; /* holds zlib compression level */
  182066. int zlib_method; /* holds zlib compression method */
  182067. int zlib_window_bits; /* holds zlib compression window bits */
  182068. int zlib_mem_level; /* holds zlib compression memory level */
  182069. int zlib_strategy; /* holds zlib compression strategy */
  182070. png_uint_32 width; /* width of image in pixels */
  182071. png_uint_32 height; /* height of image in pixels */
  182072. png_uint_32 num_rows; /* number of rows in current pass */
  182073. png_uint_32 usr_width; /* width of row at start of write */
  182074. png_uint_32 rowbytes; /* size of row in bytes */
  182075. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182076. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182077. png_uint_32 row_number; /* current row in interlace pass */
  182078. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182079. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182080. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182081. png_bytep up_row; /* buffer to save "up" row when filtering */
  182082. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182083. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182084. png_row_info row_info; /* used for transformation routines */
  182085. png_uint_32 idat_size; /* current IDAT size for read */
  182086. png_uint_32 crc; /* current chunk CRC value */
  182087. png_colorp palette; /* palette from the input file */
  182088. png_uint_16 num_palette; /* number of color entries in palette */
  182089. png_uint_16 num_trans; /* number of transparency values */
  182090. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182091. png_byte compression; /* file compression type (always 0) */
  182092. png_byte filter; /* file filter type (always 0) */
  182093. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182094. png_byte pass; /* current interlace pass (0 - 6) */
  182095. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182096. png_byte color_type; /* color type of file */
  182097. png_byte bit_depth; /* bit depth of file */
  182098. png_byte usr_bit_depth; /* bit depth of users row */
  182099. png_byte pixel_depth; /* number of bits per pixel */
  182100. png_byte channels; /* number of channels in file */
  182101. png_byte usr_channels; /* channels at start of write */
  182102. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182103. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182104. #ifdef PNG_LEGACY_SUPPORTED
  182105. png_byte filler; /* filler byte for pixel expansion */
  182106. #else
  182107. png_uint_16 filler; /* filler bytes for pixel expansion */
  182108. #endif
  182109. #endif
  182110. #if defined(PNG_bKGD_SUPPORTED)
  182111. png_byte background_gamma_type;
  182112. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182113. float background_gamma;
  182114. # endif
  182115. png_color_16 background; /* background color in screen gamma space */
  182116. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182117. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182118. #endif
  182119. #endif /* PNG_bKGD_SUPPORTED */
  182120. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182121. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182122. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182123. png_uint_32 flush_rows; /* number of rows written since last flush */
  182124. #endif
  182125. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182126. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182127. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182128. float gamma; /* file gamma value */
  182129. float screen_gamma; /* screen gamma value (display_exponent) */
  182130. #endif
  182131. #endif
  182132. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182133. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182134. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182135. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182136. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182137. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182138. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182139. #endif
  182140. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182141. png_color_8 sig_bit; /* significant bits in each available channel */
  182142. #endif
  182143. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182144. png_color_8 shift; /* shift for significant bit tranformation */
  182145. #endif
  182146. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182147. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182148. png_bytep trans; /* transparency values for paletted files */
  182149. png_color_16 trans_values; /* transparency values for non-paletted files */
  182150. #endif
  182151. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182152. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182153. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182154. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182155. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182156. png_progressive_end_ptr end_fn; /* called after image is complete */
  182157. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182158. png_bytep save_buffer; /* buffer for previously read data */
  182159. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182160. png_bytep current_buffer; /* buffer for recently used data */
  182161. png_uint_32 push_length; /* size of current input chunk */
  182162. png_uint_32 skip_length; /* bytes to skip in input data */
  182163. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182164. png_size_t save_buffer_max; /* total size of save_buffer */
  182165. png_size_t buffer_size; /* total amount of available input data */
  182166. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182167. int process_mode; /* what push library is currently doing */
  182168. int cur_palette; /* current push library palette index */
  182169. # if defined(PNG_TEXT_SUPPORTED)
  182170. png_size_t current_text_size; /* current size of text input data */
  182171. png_size_t current_text_left; /* how much text left to read in input */
  182172. png_charp current_text; /* current text chunk buffer */
  182173. png_charp current_text_ptr; /* current location in current_text */
  182174. # endif /* PNG_TEXT_SUPPORTED */
  182175. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182176. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182177. /* for the Borland special 64K segment handler */
  182178. png_bytepp offset_table_ptr;
  182179. png_bytep offset_table;
  182180. png_uint_16 offset_table_number;
  182181. png_uint_16 offset_table_count;
  182182. png_uint_16 offset_table_count_free;
  182183. #endif
  182184. #if defined(PNG_READ_DITHER_SUPPORTED)
  182185. png_bytep palette_lookup; /* lookup table for dithering */
  182186. png_bytep dither_index; /* index translation for palette files */
  182187. #endif
  182188. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182189. png_uint_16p hist; /* histogram */
  182190. #endif
  182191. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182192. png_byte heuristic_method; /* heuristic for row filter selection */
  182193. png_byte num_prev_filters; /* number of weights for previous rows */
  182194. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182195. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182196. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182197. png_uint_16p filter_costs; /* relative filter calculation cost */
  182198. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182199. #endif
  182200. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182201. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182202. #endif
  182203. /* New members added in libpng-1.0.6 */
  182204. #ifdef PNG_FREE_ME_SUPPORTED
  182205. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182206. #endif
  182207. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182208. png_voidp user_chunk_ptr;
  182209. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182210. #endif
  182211. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182212. int num_chunk_list;
  182213. png_bytep chunk_list;
  182214. #endif
  182215. /* New members added in libpng-1.0.3 */
  182216. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182217. png_byte rgb_to_gray_status;
  182218. /* These were changed from png_byte in libpng-1.0.6 */
  182219. png_uint_16 rgb_to_gray_red_coeff;
  182220. png_uint_16 rgb_to_gray_green_coeff;
  182221. png_uint_16 rgb_to_gray_blue_coeff;
  182222. #endif
  182223. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182224. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182225. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182226. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182227. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182228. #ifdef PNG_1_0_X
  182229. png_byte mng_features_permitted;
  182230. #else
  182231. png_uint_32 mng_features_permitted;
  182232. #endif /* PNG_1_0_X */
  182233. #endif
  182234. /* New member added in libpng-1.0.7 */
  182235. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182236. png_fixed_point int_gamma;
  182237. #endif
  182238. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182239. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182240. png_byte filter_type;
  182241. #endif
  182242. #if defined(PNG_1_0_X)
  182243. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182244. png_uint_32 row_buf_size;
  182245. #endif
  182246. /* New members added in libpng-1.2.0 */
  182247. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182248. # if !defined(PNG_1_0_X)
  182249. # if defined(PNG_MMX_CODE_SUPPORTED)
  182250. png_byte mmx_bitdepth_threshold;
  182251. png_uint_32 mmx_rowbytes_threshold;
  182252. # endif
  182253. png_uint_32 asm_flags;
  182254. # endif
  182255. #endif
  182256. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182257. #ifdef PNG_USER_MEM_SUPPORTED
  182258. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182259. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182260. png_free_ptr free_fn; /* function for freeing memory */
  182261. #endif
  182262. /* New member added in libpng-1.0.13 and 1.2.0 */
  182263. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182264. #if defined(PNG_READ_DITHER_SUPPORTED)
  182265. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182266. png_bytep dither_sort; /* working sort array */
  182267. png_bytep index_to_palette; /* where the original index currently is */
  182268. /* in the palette */
  182269. png_bytep palette_to_index; /* which original index points to this */
  182270. /* palette color */
  182271. #endif
  182272. /* New members added in libpng-1.0.16 and 1.2.6 */
  182273. png_byte compression_type;
  182274. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182275. png_uint_32 user_width_max;
  182276. png_uint_32 user_height_max;
  182277. #endif
  182278. /* New member added in libpng-1.0.25 and 1.2.17 */
  182279. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182280. /* storage for unknown chunk that the library doesn't recognize. */
  182281. png_unknown_chunk unknown_chunk;
  182282. #endif
  182283. };
  182284. /* This triggers a compiler error in png.c, if png.c and png.h
  182285. * do not agree upon the version number.
  182286. */
  182287. typedef png_structp version_1_2_21;
  182288. typedef png_struct FAR * FAR * png_structpp;
  182289. /* Here are the function definitions most commonly used. This is not
  182290. * the place to find out how to use libpng. See libpng.txt for the
  182291. * full explanation, see example.c for the summary. This just provides
  182292. * a simple one line description of the use of each function.
  182293. */
  182294. /* Returns the version number of the library */
  182295. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182296. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182297. * Handling more than 8 bytes from the beginning of the file is an error.
  182298. */
  182299. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182300. int num_bytes));
  182301. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182302. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182303. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182304. * start > 7 will always fail (ie return non-zero).
  182305. */
  182306. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182307. png_size_t num_to_check));
  182308. /* Simple signature checking function. This is the same as calling
  182309. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182310. */
  182311. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182312. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182313. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182314. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182315. png_error_ptr error_fn, png_error_ptr warn_fn));
  182316. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182317. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182318. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182319. png_error_ptr error_fn, png_error_ptr warn_fn));
  182320. #ifdef PNG_WRITE_SUPPORTED
  182321. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182322. PNGARG((png_structp png_ptr));
  182323. #endif
  182324. #ifdef PNG_WRITE_SUPPORTED
  182325. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182326. PNGARG((png_structp png_ptr, png_uint_32 size));
  182327. #endif
  182328. /* Reset the compression stream */
  182329. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182330. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182331. #ifdef PNG_USER_MEM_SUPPORTED
  182332. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182333. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182334. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182335. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182336. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182337. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182338. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182339. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182340. #endif
  182341. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182342. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182343. png_bytep chunk_name, png_bytep data, png_size_t length));
  182344. /* Write the start of a PNG chunk - length and chunk name. */
  182345. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182346. png_bytep chunk_name, png_uint_32 length));
  182347. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182348. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182349. png_bytep data, png_size_t length));
  182350. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182351. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182352. /* Allocate and initialize the info structure */
  182353. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182354. PNGARG((png_structp png_ptr));
  182355. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182356. /* Initialize the info structure (old interface - DEPRECATED) */
  182357. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182358. #undef png_info_init
  182359. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182360. png_sizeof(png_info));
  182361. #endif
  182362. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182363. png_size_t png_info_struct_size));
  182364. /* Writes all the PNG information before the image. */
  182365. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182366. png_infop info_ptr));
  182367. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182368. png_infop info_ptr));
  182369. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182370. /* read the information before the actual image data. */
  182371. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182372. png_infop info_ptr));
  182373. #endif
  182374. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182375. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182376. PNGARG((png_structp png_ptr, png_timep ptime));
  182377. #endif
  182378. #if !defined(_WIN32_WCE)
  182379. /* "time.h" functions are not supported on WindowsCE */
  182380. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182381. /* convert from a struct tm to png_time */
  182382. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182383. struct tm FAR * ttime));
  182384. /* convert from time_t to png_time. Uses gmtime() */
  182385. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182386. time_t ttime));
  182387. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182388. #endif /* _WIN32_WCE */
  182389. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182390. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182391. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182392. #if !defined(PNG_1_0_X)
  182393. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182394. png_ptr));
  182395. #endif
  182396. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182397. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182398. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182399. /* Deprecated */
  182400. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182401. #endif
  182402. #endif
  182403. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182404. /* Use blue, green, red order for pixels. */
  182405. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182406. #endif
  182407. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182408. /* Expand the grayscale to 24-bit RGB if necessary. */
  182409. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182410. #endif
  182411. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182412. /* Reduce RGB to grayscale. */
  182413. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182414. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182415. int error_action, double red, double green ));
  182416. #endif
  182417. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182418. int error_action, png_fixed_point red, png_fixed_point green ));
  182419. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182420. png_ptr));
  182421. #endif
  182422. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182423. png_colorp palette));
  182424. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182425. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182426. #endif
  182427. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182428. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182429. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182430. #endif
  182431. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182432. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182433. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182434. #endif
  182435. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182436. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182437. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182438. png_uint_32 filler, int flags));
  182439. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182440. #define PNG_FILLER_BEFORE 0
  182441. #define PNG_FILLER_AFTER 1
  182442. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182443. #if !defined(PNG_1_0_X)
  182444. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182445. png_uint_32 filler, int flags));
  182446. #endif
  182447. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182448. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182449. /* Swap bytes in 16-bit depth files. */
  182450. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182451. #endif
  182452. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182453. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182454. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182455. #endif
  182456. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182457. /* Swap packing order of pixels in bytes. */
  182458. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182459. #endif
  182460. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182461. /* Converts files to legal bit depths. */
  182462. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182463. png_color_8p true_bits));
  182464. #endif
  182465. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182466. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182467. /* Have the code handle the interlacing. Returns the number of passes. */
  182468. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182469. #endif
  182470. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182471. /* Invert monochrome files */
  182472. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182473. #endif
  182474. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182475. /* Handle alpha and tRNS by replacing with a background color. */
  182476. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182477. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182478. png_color_16p background_color, int background_gamma_code,
  182479. int need_expand, double background_gamma));
  182480. #endif
  182481. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182482. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182483. #define PNG_BACKGROUND_GAMMA_FILE 2
  182484. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182485. #endif
  182486. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182487. /* strip the second byte of information from a 16-bit depth file. */
  182488. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182489. #endif
  182490. #if defined(PNG_READ_DITHER_SUPPORTED)
  182491. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182492. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182493. png_colorp palette, int num_palette, int maximum_colors,
  182494. png_uint_16p histogram, int full_dither));
  182495. #endif
  182496. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182497. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182498. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182499. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182500. double screen_gamma, double default_file_gamma));
  182501. #endif
  182502. #endif
  182503. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182504. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182505. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182506. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182507. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182508. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182509. int empty_plte_permitted));
  182510. #endif
  182511. #endif
  182512. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182513. /* Set how many lines between output flushes - 0 for no flushing */
  182514. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182515. /* Flush the current PNG output buffer */
  182516. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182517. #endif
  182518. /* optional update palette with requested transformations */
  182519. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182520. /* optional call to update the users info structure */
  182521. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182522. png_infop info_ptr));
  182523. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182524. /* read one or more rows of image data. */
  182525. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182526. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182527. #endif
  182528. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182529. /* read a row of data. */
  182530. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182531. png_bytep row,
  182532. png_bytep display_row));
  182533. #endif
  182534. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182535. /* read the whole image into memory at once. */
  182536. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182537. png_bytepp image));
  182538. #endif
  182539. /* write a row of image data */
  182540. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182541. png_bytep row));
  182542. /* write a few rows of image data */
  182543. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182544. png_bytepp row, png_uint_32 num_rows));
  182545. /* write the image data */
  182546. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182547. png_bytepp image));
  182548. /* writes the end of the PNG file. */
  182549. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182550. png_infop info_ptr));
  182551. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182552. /* read the end of the PNG file. */
  182553. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182554. png_infop info_ptr));
  182555. #endif
  182556. /* free any memory associated with the png_info_struct */
  182557. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182558. png_infopp info_ptr_ptr));
  182559. /* free any memory associated with the png_struct and the png_info_structs */
  182560. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182561. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182562. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182563. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182564. png_infop end_info_ptr));
  182565. /* free any memory associated with the png_struct and the png_info_structs */
  182566. extern PNG_EXPORT(void,png_destroy_write_struct)
  182567. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182568. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182569. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182570. /* set the libpng method of handling chunk CRC errors */
  182571. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182572. int crit_action, int ancil_action));
  182573. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182574. * ancillary and critical chunks, and whether to use the data contained
  182575. * therein. Note that it is impossible to "discard" data in a critical
  182576. * chunk. For versions prior to 0.90, the action was always error/quit,
  182577. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182578. * chunks is warn/discard. These values should NOT be changed.
  182579. *
  182580. * value action:critical action:ancillary
  182581. */
  182582. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182583. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182584. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182585. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182586. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182587. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182588. /* These functions give the user control over the scan-line filtering in
  182589. * libpng and the compression methods used by zlib. These functions are
  182590. * mainly useful for testing, as the defaults should work with most users.
  182591. * Those users who are tight on memory or want faster performance at the
  182592. * expense of compression can modify them. See the compression library
  182593. * header file (zlib.h) for an explination of the compression functions.
  182594. */
  182595. /* set the filtering method(s) used by libpng. Currently, the only valid
  182596. * value for "method" is 0.
  182597. */
  182598. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182599. int filters));
  182600. /* Flags for png_set_filter() to say which filters to use. The flags
  182601. * are chosen so that they don't conflict with real filter types
  182602. * below, in case they are supplied instead of the #defined constants.
  182603. * These values should NOT be changed.
  182604. */
  182605. #define PNG_NO_FILTERS 0x00
  182606. #define PNG_FILTER_NONE 0x08
  182607. #define PNG_FILTER_SUB 0x10
  182608. #define PNG_FILTER_UP 0x20
  182609. #define PNG_FILTER_AVG 0x40
  182610. #define PNG_FILTER_PAETH 0x80
  182611. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182612. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182613. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182614. * These defines should NOT be changed.
  182615. */
  182616. #define PNG_FILTER_VALUE_NONE 0
  182617. #define PNG_FILTER_VALUE_SUB 1
  182618. #define PNG_FILTER_VALUE_UP 2
  182619. #define PNG_FILTER_VALUE_AVG 3
  182620. #define PNG_FILTER_VALUE_PAETH 4
  182621. #define PNG_FILTER_VALUE_LAST 5
  182622. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182623. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182624. * defines, either the default (minimum-sum-of-absolute-differences), or
  182625. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182626. *
  182627. * Weights are factors >= 1.0, indicating how important it is to keep the
  182628. * filter type consistent between rows. Larger numbers mean the current
  182629. * filter is that many times as likely to be the same as the "num_weights"
  182630. * previous filters. This is cumulative for each previous row with a weight.
  182631. * There needs to be "num_weights" values in "filter_weights", or it can be
  182632. * NULL if the weights aren't being specified. Weights have no influence on
  182633. * the selection of the first row filter. Well chosen weights can (in theory)
  182634. * improve the compression for a given image.
  182635. *
  182636. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182637. * filter type. Higher costs indicate more decoding expense, and are
  182638. * therefore less likely to be selected over a filter with lower computational
  182639. * costs. There needs to be a value in "filter_costs" for each valid filter
  182640. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182641. * setting the costs. Costs try to improve the speed of decompression without
  182642. * unduly increasing the compressed image size.
  182643. *
  182644. * A negative weight or cost indicates the default value is to be used, and
  182645. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182646. * The default values for both weights and costs are currently 1.0, but may
  182647. * change if good general weighting/cost heuristics can be found. If both
  182648. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182649. * to the UNWEIGHTED method, but with added encoding time/computation.
  182650. */
  182651. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182652. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182653. int heuristic_method, int num_weights, png_doublep filter_weights,
  182654. png_doublep filter_costs));
  182655. #endif
  182656. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182657. /* Heuristic used for row filter selection. These defines should NOT be
  182658. * changed.
  182659. */
  182660. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182661. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182662. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182663. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182664. /* Set the library compression level. Currently, valid values range from
  182665. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182666. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182667. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182668. * for PNG images, and do considerably fewer caclulations. In the future,
  182669. * these values may not correspond directly to the zlib compression levels.
  182670. */
  182671. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182672. int level));
  182673. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182674. PNGARG((png_structp png_ptr, int mem_level));
  182675. extern PNG_EXPORT(void,png_set_compression_strategy)
  182676. PNGARG((png_structp png_ptr, int strategy));
  182677. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182678. PNGARG((png_structp png_ptr, int window_bits));
  182679. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182680. int method));
  182681. /* These next functions are called for input/output, memory, and error
  182682. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182683. * and call standard C I/O routines such as fread(), fwrite(), and
  182684. * fprintf(). These functions can be made to use other I/O routines
  182685. * at run time for those applications that need to handle I/O in a
  182686. * different manner by calling png_set_???_fn(). See libpng.txt for
  182687. * more information.
  182688. */
  182689. #if !defined(PNG_NO_STDIO)
  182690. /* Initialize the input/output for the PNG file to the default functions. */
  182691. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182692. #endif
  182693. /* Replace the (error and abort), and warning functions with user
  182694. * supplied functions. If no messages are to be printed you must still
  182695. * write and use replacement functions. The replacement error_fn should
  182696. * still do a longjmp to the last setjmp location if you are using this
  182697. * method of error handling. If error_fn or warning_fn is NULL, the
  182698. * default function will be used.
  182699. */
  182700. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182701. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182702. /* Return the user pointer associated with the error functions */
  182703. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182704. /* Replace the default data output functions with a user supplied one(s).
  182705. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182706. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182707. * output_flush_fn will be ignored (and thus can be NULL).
  182708. */
  182709. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182710. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182711. /* Replace the default data input function with a user supplied one. */
  182712. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182713. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182714. /* Return the user pointer associated with the I/O functions */
  182715. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182716. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182717. png_read_status_ptr read_row_fn));
  182718. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182719. png_write_status_ptr write_row_fn));
  182720. #ifdef PNG_USER_MEM_SUPPORTED
  182721. /* Replace the default memory allocation functions with user supplied one(s). */
  182722. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182723. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182724. /* Return the user pointer associated with the memory functions */
  182725. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182726. #endif
  182727. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182728. defined(PNG_LEGACY_SUPPORTED)
  182729. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182730. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182731. #endif
  182732. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182733. defined(PNG_LEGACY_SUPPORTED)
  182734. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182735. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182736. #endif
  182737. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182738. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182739. defined(PNG_LEGACY_SUPPORTED)
  182740. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182741. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182742. int user_transform_channels));
  182743. /* Return the user pointer associated with the user transform functions */
  182744. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182745. PNGARG((png_structp png_ptr));
  182746. #endif
  182747. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182748. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182749. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182750. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182751. png_ptr));
  182752. #endif
  182753. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182754. /* Sets the function callbacks for the push reader, and a pointer to a
  182755. * user-defined structure available to the callback functions.
  182756. */
  182757. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182758. png_voidp progressive_ptr,
  182759. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182760. png_progressive_end_ptr end_fn));
  182761. /* returns the user pointer associated with the push read functions */
  182762. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182763. PNGARG((png_structp png_ptr));
  182764. /* function to be called when data becomes available */
  182765. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182766. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182767. /* function that combines rows. Not very much different than the
  182768. * png_combine_row() call. Is this even used?????
  182769. */
  182770. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182771. png_bytep old_row, png_bytep new_row));
  182772. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182773. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182774. png_uint_32 size));
  182775. #if defined(PNG_1_0_X)
  182776. # define png_malloc_warn png_malloc
  182777. #else
  182778. /* Added at libpng version 1.2.4 */
  182779. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182780. png_uint_32 size));
  182781. #endif
  182782. /* frees a pointer allocated by png_malloc() */
  182783. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182784. #if defined(PNG_1_0_X)
  182785. /* Function to allocate memory for zlib. */
  182786. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182787. uInt size));
  182788. /* Function to free memory for zlib */
  182789. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182790. #endif
  182791. /* Free data that was allocated internally */
  182792. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182793. png_infop info_ptr, png_uint_32 free_me, int num));
  182794. #ifdef PNG_FREE_ME_SUPPORTED
  182795. /* Reassign responsibility for freeing existing data, whether allocated
  182796. * by libpng or by the application */
  182797. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182798. png_infop info_ptr, int freer, png_uint_32 mask));
  182799. #endif
  182800. /* assignments for png_data_freer */
  182801. #define PNG_DESTROY_WILL_FREE_DATA 1
  182802. #define PNG_SET_WILL_FREE_DATA 1
  182803. #define PNG_USER_WILL_FREE_DATA 2
  182804. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182805. #define PNG_FREE_HIST 0x0008
  182806. #define PNG_FREE_ICCP 0x0010
  182807. #define PNG_FREE_SPLT 0x0020
  182808. #define PNG_FREE_ROWS 0x0040
  182809. #define PNG_FREE_PCAL 0x0080
  182810. #define PNG_FREE_SCAL 0x0100
  182811. #define PNG_FREE_UNKN 0x0200
  182812. #define PNG_FREE_LIST 0x0400
  182813. #define PNG_FREE_PLTE 0x1000
  182814. #define PNG_FREE_TRNS 0x2000
  182815. #define PNG_FREE_TEXT 0x4000
  182816. #define PNG_FREE_ALL 0x7fff
  182817. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  182818. #ifdef PNG_USER_MEM_SUPPORTED
  182819. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  182820. png_uint_32 size));
  182821. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  182822. png_voidp ptr));
  182823. #endif
  182824. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  182825. png_voidp s1, png_voidp s2, png_uint_32 size));
  182826. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  182827. png_voidp s1, int value, png_uint_32 size));
  182828. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  182829. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  182830. int check));
  182831. #endif /* USE_FAR_KEYWORD */
  182832. #ifndef PNG_NO_ERROR_TEXT
  182833. /* Fatal error in PNG image of libpng - can't continue */
  182834. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  182835. png_const_charp error_message));
  182836. /* The same, but the chunk name is prepended to the error string. */
  182837. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  182838. png_const_charp error_message));
  182839. #else
  182840. /* Fatal error in PNG image of libpng - can't continue */
  182841. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  182842. #endif
  182843. #ifndef PNG_NO_WARNINGS
  182844. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  182845. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  182846. png_const_charp warning_message));
  182847. #ifdef PNG_READ_SUPPORTED
  182848. /* Non-fatal error in libpng, chunk name is prepended to message. */
  182849. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  182850. png_const_charp warning_message));
  182851. #endif /* PNG_READ_SUPPORTED */
  182852. #endif /* PNG_NO_WARNINGS */
  182853. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  182854. * Similarly, the png_get_<chunk> calls are used to read values from the
  182855. * png_info_struct, either storing the parameters in the passed variables, or
  182856. * setting pointers into the png_info_struct where the data is stored. The
  182857. * png_get_<chunk> functions return a non-zero value if the data was available
  182858. * in info_ptr, or return zero and do not change any of the parameters if the
  182859. * data was not available.
  182860. *
  182861. * These functions should be used instead of directly accessing png_info
  182862. * to avoid problems with future changes in the size and internal layout of
  182863. * png_info_struct.
  182864. */
  182865. /* Returns "flag" if chunk data is valid in info_ptr. */
  182866. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  182867. png_infop info_ptr, png_uint_32 flag));
  182868. /* Returns number of bytes needed to hold a transformed row. */
  182869. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  182870. png_infop info_ptr));
  182871. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182872. /* Returns row_pointers, which is an array of pointers to scanlines that was
  182873. returned from png_read_png(). */
  182874. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  182875. png_infop info_ptr));
  182876. /* Set row_pointers, which is an array of pointers to scanlines for use
  182877. by png_write_png(). */
  182878. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  182879. png_infop info_ptr, png_bytepp row_pointers));
  182880. #endif
  182881. /* Returns number of color channels in image. */
  182882. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  182883. png_infop info_ptr));
  182884. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182885. /* Returns image width in pixels. */
  182886. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  182887. png_ptr, png_infop info_ptr));
  182888. /* Returns image height in pixels. */
  182889. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  182890. png_ptr, png_infop info_ptr));
  182891. /* Returns image bit_depth. */
  182892. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  182893. png_ptr, png_infop info_ptr));
  182894. /* Returns image color_type. */
  182895. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  182896. png_ptr, png_infop info_ptr));
  182897. /* Returns image filter_type. */
  182898. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  182899. png_ptr, png_infop info_ptr));
  182900. /* Returns image interlace_type. */
  182901. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  182902. png_ptr, png_infop info_ptr));
  182903. /* Returns image compression_type. */
  182904. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  182905. png_ptr, png_infop info_ptr));
  182906. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  182907. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  182908. png_ptr, png_infop info_ptr));
  182909. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  182910. png_ptr, png_infop info_ptr));
  182911. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  182912. png_ptr, png_infop info_ptr));
  182913. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  182914. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182915. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  182916. png_ptr, png_infop info_ptr));
  182917. #endif
  182918. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  182919. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  182920. png_ptr, png_infop info_ptr));
  182921. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  182922. png_ptr, png_infop info_ptr));
  182923. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  182924. png_ptr, png_infop info_ptr));
  182925. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  182926. png_ptr, png_infop info_ptr));
  182927. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182928. /* Returns pointer to signature string read from PNG header */
  182929. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  182930. png_infop info_ptr));
  182931. #if defined(PNG_bKGD_SUPPORTED)
  182932. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  182933. png_infop info_ptr, png_color_16p *background));
  182934. #endif
  182935. #if defined(PNG_bKGD_SUPPORTED)
  182936. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  182937. png_infop info_ptr, png_color_16p background));
  182938. #endif
  182939. #if defined(PNG_cHRM_SUPPORTED)
  182940. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182941. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  182942. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  182943. double *red_y, double *green_x, double *green_y, double *blue_x,
  182944. double *blue_y));
  182945. #endif
  182946. #ifdef PNG_FIXED_POINT_SUPPORTED
  182947. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  182948. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  182949. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  182950. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  182951. *int_blue_x, png_fixed_point *int_blue_y));
  182952. #endif
  182953. #endif
  182954. #if defined(PNG_cHRM_SUPPORTED)
  182955. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182956. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  182957. png_infop info_ptr, double white_x, double white_y, double red_x,
  182958. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  182959. #endif
  182960. #ifdef PNG_FIXED_POINT_SUPPORTED
  182961. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  182962. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  182963. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  182964. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  182965. png_fixed_point int_blue_y));
  182966. #endif
  182967. #endif
  182968. #if defined(PNG_gAMA_SUPPORTED)
  182969. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182970. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  182971. png_infop info_ptr, double *file_gamma));
  182972. #endif
  182973. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  182974. png_infop info_ptr, png_fixed_point *int_file_gamma));
  182975. #endif
  182976. #if defined(PNG_gAMA_SUPPORTED)
  182977. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182978. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  182979. png_infop info_ptr, double file_gamma));
  182980. #endif
  182981. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  182982. png_infop info_ptr, png_fixed_point int_file_gamma));
  182983. #endif
  182984. #if defined(PNG_hIST_SUPPORTED)
  182985. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  182986. png_infop info_ptr, png_uint_16p *hist));
  182987. #endif
  182988. #if defined(PNG_hIST_SUPPORTED)
  182989. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  182990. png_infop info_ptr, png_uint_16p hist));
  182991. #endif
  182992. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  182993. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  182994. int *bit_depth, int *color_type, int *interlace_method,
  182995. int *compression_method, int *filter_method));
  182996. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  182997. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  182998. int color_type, int interlace_method, int compression_method,
  182999. int filter_method));
  183000. #if defined(PNG_oFFs_SUPPORTED)
  183001. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183002. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183003. int *unit_type));
  183004. #endif
  183005. #if defined(PNG_oFFs_SUPPORTED)
  183006. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183007. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183008. int unit_type));
  183009. #endif
  183010. #if defined(PNG_pCAL_SUPPORTED)
  183011. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183012. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183013. int *type, int *nparams, png_charp *units, png_charpp *params));
  183014. #endif
  183015. #if defined(PNG_pCAL_SUPPORTED)
  183016. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183017. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183018. int type, int nparams, png_charp units, png_charpp params));
  183019. #endif
  183020. #if defined(PNG_pHYs_SUPPORTED)
  183021. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183022. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183023. #endif
  183024. #if defined(PNG_pHYs_SUPPORTED)
  183025. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183026. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183027. #endif
  183028. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183029. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183030. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183031. png_infop info_ptr, png_colorp palette, int num_palette));
  183032. #if defined(PNG_sBIT_SUPPORTED)
  183033. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183034. png_infop info_ptr, png_color_8p *sig_bit));
  183035. #endif
  183036. #if defined(PNG_sBIT_SUPPORTED)
  183037. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183038. png_infop info_ptr, png_color_8p sig_bit));
  183039. #endif
  183040. #if defined(PNG_sRGB_SUPPORTED)
  183041. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183042. png_infop info_ptr, int *intent));
  183043. #endif
  183044. #if defined(PNG_sRGB_SUPPORTED)
  183045. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183046. png_infop info_ptr, int intent));
  183047. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183048. png_infop info_ptr, int intent));
  183049. #endif
  183050. #if defined(PNG_iCCP_SUPPORTED)
  183051. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183052. png_infop info_ptr, png_charpp name, int *compression_type,
  183053. png_charpp profile, png_uint_32 *proflen));
  183054. /* Note to maintainer: profile should be png_bytepp */
  183055. #endif
  183056. #if defined(PNG_iCCP_SUPPORTED)
  183057. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183058. png_infop info_ptr, png_charp name, int compression_type,
  183059. png_charp profile, png_uint_32 proflen));
  183060. /* Note to maintainer: profile should be png_bytep */
  183061. #endif
  183062. #if defined(PNG_sPLT_SUPPORTED)
  183063. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183064. png_infop info_ptr, png_sPLT_tpp entries));
  183065. #endif
  183066. #if defined(PNG_sPLT_SUPPORTED)
  183067. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183068. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183069. #endif
  183070. #if defined(PNG_TEXT_SUPPORTED)
  183071. /* png_get_text also returns the number of text chunks in *num_text */
  183072. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183073. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183074. #endif
  183075. /*
  183076. * Note while png_set_text() will accept a structure whose text,
  183077. * language, and translated keywords are NULL pointers, the structure
  183078. * returned by png_get_text will always contain regular
  183079. * zero-terminated C strings. They might be empty strings but
  183080. * they will never be NULL pointers.
  183081. */
  183082. #if defined(PNG_TEXT_SUPPORTED)
  183083. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183084. png_infop info_ptr, png_textp text_ptr, int num_text));
  183085. #endif
  183086. #if defined(PNG_tIME_SUPPORTED)
  183087. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183088. png_infop info_ptr, png_timep *mod_time));
  183089. #endif
  183090. #if defined(PNG_tIME_SUPPORTED)
  183091. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183092. png_infop info_ptr, png_timep mod_time));
  183093. #endif
  183094. #if defined(PNG_tRNS_SUPPORTED)
  183095. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183096. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183097. png_color_16p *trans_values));
  183098. #endif
  183099. #if defined(PNG_tRNS_SUPPORTED)
  183100. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183101. png_infop info_ptr, png_bytep trans, int num_trans,
  183102. png_color_16p trans_values));
  183103. #endif
  183104. #if defined(PNG_tRNS_SUPPORTED)
  183105. #endif
  183106. #if defined(PNG_sCAL_SUPPORTED)
  183107. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183108. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183109. png_infop info_ptr, int *unit, double *width, double *height));
  183110. #else
  183111. #ifdef PNG_FIXED_POINT_SUPPORTED
  183112. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183113. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183114. #endif
  183115. #endif
  183116. #endif /* PNG_sCAL_SUPPORTED */
  183117. #if defined(PNG_sCAL_SUPPORTED)
  183118. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183119. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183120. png_infop info_ptr, int unit, double width, double height));
  183121. #else
  183122. #ifdef PNG_FIXED_POINT_SUPPORTED
  183123. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183124. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183125. #endif
  183126. #endif
  183127. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183128. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183129. /* provide a list of chunks and how they are to be handled, if the built-in
  183130. handling or default unknown chunk handling is not desired. Any chunks not
  183131. listed will be handled in the default manner. The IHDR and IEND chunks
  183132. must not be listed.
  183133. keep = 0: follow default behaviour
  183134. = 1: do not keep
  183135. = 2: keep only if safe-to-copy
  183136. = 3: keep even if unsafe-to-copy
  183137. */
  183138. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183139. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183140. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183141. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183142. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183143. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183144. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183145. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183146. #endif
  183147. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183148. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183149. chunk_name));
  183150. #endif
  183151. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183152. If you need to turn it off for a chunk that your application has freed,
  183153. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183154. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183155. png_infop info_ptr, int mask));
  183156. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183157. /* The "params" pointer is currently not used and is for future expansion. */
  183158. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183159. png_infop info_ptr,
  183160. int transforms,
  183161. png_voidp params));
  183162. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183163. png_infop info_ptr,
  183164. int transforms,
  183165. png_voidp params));
  183166. #endif
  183167. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183168. * numbers for PNG_DEBUG mean more debugging information. This has
  183169. * only been added since version 0.95 so it is not implemented throughout
  183170. * libpng yet, but more support will be added as needed.
  183171. */
  183172. #ifdef PNG_DEBUG
  183173. #if (PNG_DEBUG > 0)
  183174. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183175. #include <crtdbg.h>
  183176. #if (PNG_DEBUG > 1)
  183177. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183178. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183179. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183180. #endif
  183181. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183182. #ifndef PNG_DEBUG_FILE
  183183. #define PNG_DEBUG_FILE stderr
  183184. #endif /* PNG_DEBUG_FILE */
  183185. #if (PNG_DEBUG > 1)
  183186. #define png_debug(l,m) \
  183187. { \
  183188. int num_tabs=l; \
  183189. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183190. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183191. }
  183192. #define png_debug1(l,m,p1) \
  183193. { \
  183194. int num_tabs=l; \
  183195. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183196. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183197. }
  183198. #define png_debug2(l,m,p1,p2) \
  183199. { \
  183200. int num_tabs=l; \
  183201. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183202. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183203. }
  183204. #endif /* (PNG_DEBUG > 1) */
  183205. #endif /* _MSC_VER */
  183206. #endif /* (PNG_DEBUG > 0) */
  183207. #endif /* PNG_DEBUG */
  183208. #ifndef png_debug
  183209. #define png_debug(l, m)
  183210. #endif
  183211. #ifndef png_debug1
  183212. #define png_debug1(l, m, p1)
  183213. #endif
  183214. #ifndef png_debug2
  183215. #define png_debug2(l, m, p1, p2)
  183216. #endif
  183217. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183218. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183219. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183220. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183221. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183222. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183223. png_ptr, png_uint_32 mng_features_permitted));
  183224. #endif
  183225. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183226. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183227. #define PNG_HANDLE_CHUNK_NEVER 1
  183228. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183229. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183230. /* Added to version 1.2.0 */
  183231. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183232. #if defined(PNG_MMX_CODE_SUPPORTED)
  183233. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183234. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183235. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183236. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183237. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183238. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183239. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183240. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183241. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183242. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183243. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183244. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183245. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183246. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183247. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183248. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183249. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183250. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183251. | PNG_MMX_READ_FLAGS \
  183252. | PNG_MMX_WRITE_FLAGS )
  183253. #define PNG_SELECT_READ 1
  183254. #define PNG_SELECT_WRITE 2
  183255. #endif /* PNG_MMX_CODE_SUPPORTED */
  183256. #if !defined(PNG_1_0_X)
  183257. /* pngget.c */
  183258. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183259. PNGARG((int flag_select, int *compilerID));
  183260. /* pngget.c */
  183261. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183262. PNGARG((int flag_select));
  183263. /* pngget.c */
  183264. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183265. PNGARG((png_structp png_ptr));
  183266. /* pngget.c */
  183267. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183268. PNGARG((png_structp png_ptr));
  183269. /* pngget.c */
  183270. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183271. PNGARG((png_structp png_ptr));
  183272. /* pngset.c */
  183273. extern PNG_EXPORT(void,png_set_asm_flags)
  183274. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183275. /* pngset.c */
  183276. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183277. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183278. png_uint_32 mmx_rowbytes_threshold));
  183279. #endif /* PNG_1_0_X */
  183280. #if !defined(PNG_1_0_X)
  183281. /* png.c, pnggccrd.c, or pngvcrd.c */
  183282. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183283. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183284. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183285. * messages before passing them to the error or warning handler. */
  183286. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183287. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183288. png_ptr, png_uint_32 strip_mode));
  183289. #endif
  183290. #endif /* PNG_1_0_X */
  183291. /* Added at libpng-1.2.6 */
  183292. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183293. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183294. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183295. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183296. png_ptr));
  183297. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183298. png_ptr));
  183299. #endif
  183300. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183301. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183302. /* With these routines we avoid an integer divide, which will be slower on
  183303. * most machines. However, it does take more operations than the corresponding
  183304. * divide method, so it may be slower on a few RISC systems. There are two
  183305. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183306. *
  183307. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183308. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183309. * standard method.
  183310. *
  183311. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183312. */
  183313. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183314. # define png_composite(composite, fg, alpha, bg) \
  183315. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183316. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183317. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183318. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183319. # define png_composite_16(composite, fg, alpha, bg) \
  183320. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183321. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183322. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183323. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183324. #else /* standard method using integer division */
  183325. # define png_composite(composite, fg, alpha, bg) \
  183326. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183327. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183328. (png_uint_16)127) / 255)
  183329. # define png_composite_16(composite, fg, alpha, bg) \
  183330. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183331. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183332. (png_uint_32)32767) / (png_uint_32)65535L)
  183333. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183334. /* Inline macros to do direct reads of bytes from the input buffer. These
  183335. * require that you are using an architecture that uses PNG byte ordering
  183336. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183337. * in big-endian mode and 680x0 are the only ones that will support this.
  183338. * The x86 line of processors definitely do not. The png_get_int_32()
  183339. * routine also assumes we are using two's complement format for negative
  183340. * values, which is almost certainly true.
  183341. */
  183342. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183343. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183344. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183345. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183346. #else
  183347. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183348. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183349. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183350. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183351. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183352. PNGARG((png_structp png_ptr, png_bytep buf));
  183353. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183354. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183355. */
  183356. extern PNG_EXPORT(void,png_save_uint_32)
  183357. PNGARG((png_bytep buf, png_uint_32 i));
  183358. extern PNG_EXPORT(void,png_save_int_32)
  183359. PNGARG((png_bytep buf, png_int_32 i));
  183360. /* Place a 16-bit number into a buffer in PNG byte order.
  183361. * The parameter is declared unsigned int, not png_uint_16,
  183362. * just to avoid potential problems on pre-ANSI C compilers.
  183363. */
  183364. extern PNG_EXPORT(void,png_save_uint_16)
  183365. PNGARG((png_bytep buf, unsigned int i));
  183366. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183367. /* ************************************************************************* */
  183368. /* These next functions are used internally in the code. They generally
  183369. * shouldn't be used unless you are writing code to add or replace some
  183370. * functionality in libpng. More information about most functions can
  183371. * be found in the files where the functions are located.
  183372. */
  183373. /* Various modes of operation, that are visible to applications because
  183374. * they are used for unknown chunk location.
  183375. */
  183376. #define PNG_HAVE_IHDR 0x01
  183377. #define PNG_HAVE_PLTE 0x02
  183378. #define PNG_HAVE_IDAT 0x04
  183379. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183380. #define PNG_HAVE_IEND 0x10
  183381. #if defined(PNG_INTERNAL)
  183382. /* More modes of operation. Note that after an init, mode is set to
  183383. * zero automatically when the structure is created.
  183384. */
  183385. #define PNG_HAVE_gAMA 0x20
  183386. #define PNG_HAVE_cHRM 0x40
  183387. #define PNG_HAVE_sRGB 0x80
  183388. #define PNG_HAVE_CHUNK_HEADER 0x100
  183389. #define PNG_WROTE_tIME 0x200
  183390. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183391. #define PNG_BACKGROUND_IS_GRAY 0x800
  183392. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183393. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183394. /* flags for the transformations the PNG library does on the image data */
  183395. #define PNG_BGR 0x0001
  183396. #define PNG_INTERLACE 0x0002
  183397. #define PNG_PACK 0x0004
  183398. #define PNG_SHIFT 0x0008
  183399. #define PNG_SWAP_BYTES 0x0010
  183400. #define PNG_INVERT_MONO 0x0020
  183401. #define PNG_DITHER 0x0040
  183402. #define PNG_BACKGROUND 0x0080
  183403. #define PNG_BACKGROUND_EXPAND 0x0100
  183404. /* 0x0200 unused */
  183405. #define PNG_16_TO_8 0x0400
  183406. #define PNG_RGBA 0x0800
  183407. #define PNG_EXPAND 0x1000
  183408. #define PNG_GAMMA 0x2000
  183409. #define PNG_GRAY_TO_RGB 0x4000
  183410. #define PNG_FILLER 0x8000L
  183411. #define PNG_PACKSWAP 0x10000L
  183412. #define PNG_SWAP_ALPHA 0x20000L
  183413. #define PNG_STRIP_ALPHA 0x40000L
  183414. #define PNG_INVERT_ALPHA 0x80000L
  183415. #define PNG_USER_TRANSFORM 0x100000L
  183416. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183417. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183418. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183419. /* 0x800000L Unused */
  183420. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183421. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183422. /* 0x4000000L unused */
  183423. /* 0x8000000L unused */
  183424. /* 0x10000000L unused */
  183425. /* 0x20000000L unused */
  183426. /* 0x40000000L unused */
  183427. /* flags for png_create_struct */
  183428. #define PNG_STRUCT_PNG 0x0001
  183429. #define PNG_STRUCT_INFO 0x0002
  183430. /* Scaling factor for filter heuristic weighting calculations */
  183431. #define PNG_WEIGHT_SHIFT 8
  183432. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183433. #define PNG_COST_SHIFT 3
  183434. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183435. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183436. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183437. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183438. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183439. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183440. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183441. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183442. #define PNG_FLAG_ROW_INIT 0x0040
  183443. #define PNG_FLAG_FILLER_AFTER 0x0080
  183444. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183445. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183446. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183447. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183448. #define PNG_FLAG_FREE_PLTE 0x1000
  183449. #define PNG_FLAG_FREE_TRNS 0x2000
  183450. #define PNG_FLAG_FREE_HIST 0x4000
  183451. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183452. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183453. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183454. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183455. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183456. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183457. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183458. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183459. /* 0x800000L unused */
  183460. /* 0x1000000L unused */
  183461. /* 0x2000000L unused */
  183462. /* 0x4000000L unused */
  183463. /* 0x8000000L unused */
  183464. /* 0x10000000L unused */
  183465. /* 0x20000000L unused */
  183466. /* 0x40000000L unused */
  183467. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183468. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183469. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183470. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183471. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183472. PNG_FLAG_CRC_CRITICAL_MASK)
  183473. /* save typing and make code easier to understand */
  183474. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183475. abs((int)((c1).green) - (int)((c2).green)) + \
  183476. abs((int)((c1).blue) - (int)((c2).blue)))
  183477. /* Added to libpng-1.2.6 JB */
  183478. #define PNG_ROWBYTES(pixel_bits, width) \
  183479. ((pixel_bits) >= 8 ? \
  183480. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183481. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183482. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183483. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183484. "ideal" and "delta" should be constants, normally simple
  183485. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183486. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183487. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183488. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183489. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183490. /* place to hold the signature string for a PNG file. */
  183491. #ifdef PNG_USE_GLOBAL_ARRAYS
  183492. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183493. #else
  183494. #endif
  183495. #endif /* PNG_NO_EXTERN */
  183496. /* Constant strings for known chunk types. If you need to add a chunk,
  183497. * define the name here, and add an invocation of the macro in png.c and
  183498. * wherever it's needed.
  183499. */
  183500. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183501. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183502. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183503. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183504. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183505. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183506. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183507. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183508. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183509. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183510. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183511. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183512. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183513. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183514. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183515. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183516. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183517. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183518. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183519. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183520. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183521. #ifdef PNG_USE_GLOBAL_ARRAYS
  183522. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183523. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183524. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183525. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183526. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183527. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183528. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183529. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183530. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183531. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183532. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183533. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183534. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183535. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183536. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183537. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183538. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183539. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183540. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183541. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183542. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183543. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183544. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183545. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183546. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183547. */
  183548. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183549. #undef png_read_init
  183550. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183551. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183552. #endif
  183553. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183554. png_const_charp user_png_ver, png_size_t png_struct_size));
  183555. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183556. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183557. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183558. png_info_size));
  183559. #endif
  183560. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183561. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183562. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183563. */
  183564. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183565. #undef png_write_init
  183566. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183567. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183568. #endif
  183569. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183570. png_const_charp user_png_ver, png_size_t png_struct_size));
  183571. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183572. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183573. png_info_size));
  183574. /* Allocate memory for an internal libpng struct */
  183575. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183576. /* Free memory from internal libpng struct */
  183577. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183578. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183579. malloc_fn, png_voidp mem_ptr));
  183580. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183581. png_free_ptr free_fn, png_voidp mem_ptr));
  183582. /* Free any memory that info_ptr points to and reset struct. */
  183583. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183584. png_infop info_ptr));
  183585. #ifndef PNG_1_0_X
  183586. /* Function to allocate memory for zlib. */
  183587. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183588. /* Function to free memory for zlib */
  183589. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183590. #ifdef PNG_SIZE_T
  183591. /* Function to convert a sizeof an item to png_sizeof item */
  183592. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183593. #endif
  183594. /* Next four functions are used internally as callbacks. PNGAPI is required
  183595. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183596. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183597. png_bytep data, png_size_t length));
  183598. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183599. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183600. png_bytep buffer, png_size_t length));
  183601. #endif
  183602. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183603. png_bytep data, png_size_t length));
  183604. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183605. #if !defined(PNG_NO_STDIO)
  183606. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183607. #endif
  183608. #endif
  183609. #else /* PNG_1_0_X */
  183610. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183611. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183612. png_bytep buffer, png_size_t length));
  183613. #endif
  183614. #endif /* PNG_1_0_X */
  183615. /* Reset the CRC variable */
  183616. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183617. /* Write the "data" buffer to whatever output you are using. */
  183618. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183619. png_size_t length));
  183620. /* Read data from whatever input you are using into the "data" buffer */
  183621. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183622. png_size_t length));
  183623. /* Read bytes into buf, and update png_ptr->crc */
  183624. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183625. png_size_t length));
  183626. /* Decompress data in a chunk that uses compression */
  183627. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183628. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183629. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183630. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183631. png_size_t prefix_length, png_size_t *data_length));
  183632. #endif
  183633. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183634. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183635. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183636. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183637. /* Calculate the CRC over a section of data. Note that we are only
  183638. * passing a maximum of 64K on systems that have this as a memory limit,
  183639. * since this is the maximum buffer size we can specify.
  183640. */
  183641. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183642. png_size_t length));
  183643. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183644. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183645. #endif
  183646. /* simple function to write the signature */
  183647. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183648. /* write various chunks */
  183649. /* Write the IHDR chunk, and update the png_struct with the necessary
  183650. * information.
  183651. */
  183652. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183653. png_uint_32 height,
  183654. int bit_depth, int color_type, int compression_method, int filter_method,
  183655. int interlace_method));
  183656. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183657. png_uint_32 num_pal));
  183658. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183659. png_size_t length));
  183660. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183661. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183662. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183663. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183664. #endif
  183665. #ifdef PNG_FIXED_POINT_SUPPORTED
  183666. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183667. file_gamma));
  183668. #endif
  183669. #endif
  183670. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183671. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183672. int color_type));
  183673. #endif
  183674. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183675. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183676. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183677. double white_x, double white_y,
  183678. double red_x, double red_y, double green_x, double green_y,
  183679. double blue_x, double blue_y));
  183680. #endif
  183681. #ifdef PNG_FIXED_POINT_SUPPORTED
  183682. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183683. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183684. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183685. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183686. png_fixed_point int_blue_y));
  183687. #endif
  183688. #endif
  183689. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183690. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183691. int intent));
  183692. #endif
  183693. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183694. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183695. png_charp name, int compression_type,
  183696. png_charp profile, int proflen));
  183697. /* Note to maintainer: profile should be png_bytep */
  183698. #endif
  183699. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183700. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183701. png_sPLT_tp palette));
  183702. #endif
  183703. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183704. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183705. png_color_16p values, int number, int color_type));
  183706. #endif
  183707. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183708. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183709. png_color_16p values, int color_type));
  183710. #endif
  183711. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183712. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183713. int num_hist));
  183714. #endif
  183715. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183716. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183717. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183718. png_charp key, png_charpp new_key));
  183719. #endif
  183720. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183721. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183722. png_charp text, png_size_t text_len));
  183723. #endif
  183724. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183725. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183726. png_charp text, png_size_t text_len, int compression));
  183727. #endif
  183728. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183729. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183730. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183731. png_charp text));
  183732. #endif
  183733. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183734. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183735. png_infop info_ptr, png_textp text_ptr, int num_text));
  183736. #endif
  183737. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183738. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183739. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183740. #endif
  183741. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183742. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183743. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183744. png_charp units, png_charpp params));
  183745. #endif
  183746. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183747. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183748. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183749. int unit_type));
  183750. #endif
  183751. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183752. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183753. png_timep mod_time));
  183754. #endif
  183755. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183756. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183757. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183758. int unit, double width, double height));
  183759. #else
  183760. #ifdef PNG_FIXED_POINT_SUPPORTED
  183761. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183762. int unit, png_charp width, png_charp height));
  183763. #endif
  183764. #endif
  183765. #endif
  183766. /* Called when finished processing a row of data */
  183767. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183768. /* Internal use only. Called before first row of data */
  183769. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183770. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183771. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183772. #endif
  183773. /* combine a row of data, dealing with alpha, etc. if requested */
  183774. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183775. int mask));
  183776. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183777. /* expand an interlaced row */
  183778. /* OLD pre-1.0.9 interface:
  183779. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183780. png_bytep row, int pass, png_uint_32 transformations));
  183781. */
  183782. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183783. #endif
  183784. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183785. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183786. /* grab pixels out of a row for an interlaced pass */
  183787. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183788. png_bytep row, int pass));
  183789. #endif
  183790. /* unfilter a row */
  183791. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183792. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183793. /* Choose the best filter to use and filter the row data */
  183794. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183795. png_row_infop row_info));
  183796. /* Write out the filtered row. */
  183797. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183798. png_bytep filtered_row));
  183799. /* finish a row while reading, dealing with interlacing passes, etc. */
  183800. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183801. /* initialize the row buffers, etc. */
  183802. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183803. /* optional call to update the users info structure */
  183804. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183805. png_infop info_ptr));
  183806. /* these are the functions that do the transformations */
  183807. #if defined(PNG_READ_FILLER_SUPPORTED)
  183808. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183809. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183810. #endif
  183811. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183812. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183813. png_bytep row));
  183814. #endif
  183815. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183816. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  183817. png_bytep row));
  183818. #endif
  183819. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183820. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  183821. png_bytep row));
  183822. #endif
  183823. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183824. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  183825. png_bytep row));
  183826. #endif
  183827. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  183828. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183829. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  183830. png_bytep row, png_uint_32 flags));
  183831. #endif
  183832. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183833. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  183834. #endif
  183835. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183836. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  183837. #endif
  183838. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183839. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  183840. row_info, png_bytep row));
  183841. #endif
  183842. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183843. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  183844. png_bytep row));
  183845. #endif
  183846. #if defined(PNG_READ_PACK_SUPPORTED)
  183847. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  183848. #endif
  183849. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183850. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  183851. png_color_8p sig_bits));
  183852. #endif
  183853. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183854. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  183855. #endif
  183856. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183857. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  183858. #endif
  183859. #if defined(PNG_READ_DITHER_SUPPORTED)
  183860. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  183861. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  183862. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  183863. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  183864. png_colorp palette, int num_palette));
  183865. # endif
  183866. #endif
  183867. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183868. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  183869. #endif
  183870. #if defined(PNG_WRITE_PACK_SUPPORTED)
  183871. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  183872. png_bytep row, png_uint_32 bit_depth));
  183873. #endif
  183874. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  183875. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  183876. png_color_8p bit_depth));
  183877. #endif
  183878. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183879. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183880. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183881. png_color_16p trans_values, png_color_16p background,
  183882. png_color_16p background_1,
  183883. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  183884. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  183885. png_uint_16pp gamma_16_to_1, int gamma_shift));
  183886. #else
  183887. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183888. png_color_16p trans_values, png_color_16p background));
  183889. #endif
  183890. #endif
  183891. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183892. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  183893. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  183894. int gamma_shift));
  183895. #endif
  183896. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183897. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  183898. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  183899. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  183900. png_bytep row, png_color_16p trans_value));
  183901. #endif
  183902. /* The following decodes the appropriate chunks, and does error correction,
  183903. * then calls the appropriate callback for the chunk if it is valid.
  183904. */
  183905. /* decode the IHDR chunk */
  183906. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  183907. png_uint_32 length));
  183908. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  183909. png_uint_32 length));
  183910. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  183911. png_uint_32 length));
  183912. #if defined(PNG_READ_bKGD_SUPPORTED)
  183913. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  183914. png_uint_32 length));
  183915. #endif
  183916. #if defined(PNG_READ_cHRM_SUPPORTED)
  183917. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  183918. png_uint_32 length));
  183919. #endif
  183920. #if defined(PNG_READ_gAMA_SUPPORTED)
  183921. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  183922. png_uint_32 length));
  183923. #endif
  183924. #if defined(PNG_READ_hIST_SUPPORTED)
  183925. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  183926. png_uint_32 length));
  183927. #endif
  183928. #if defined(PNG_READ_iCCP_SUPPORTED)
  183929. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  183930. png_uint_32 length));
  183931. #endif /* PNG_READ_iCCP_SUPPORTED */
  183932. #if defined(PNG_READ_iTXt_SUPPORTED)
  183933. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183934. png_uint_32 length));
  183935. #endif
  183936. #if defined(PNG_READ_oFFs_SUPPORTED)
  183937. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183938. png_uint_32 length));
  183939. #endif
  183940. #if defined(PNG_READ_pCAL_SUPPORTED)
  183941. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183942. png_uint_32 length));
  183943. #endif
  183944. #if defined(PNG_READ_pHYs_SUPPORTED)
  183945. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183946. png_uint_32 length));
  183947. #endif
  183948. #if defined(PNG_READ_sBIT_SUPPORTED)
  183949. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183950. png_uint_32 length));
  183951. #endif
  183952. #if defined(PNG_READ_sCAL_SUPPORTED)
  183953. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183954. png_uint_32 length));
  183955. #endif
  183956. #if defined(PNG_READ_sPLT_SUPPORTED)
  183957. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183958. png_uint_32 length));
  183959. #endif /* PNG_READ_sPLT_SUPPORTED */
  183960. #if defined(PNG_READ_sRGB_SUPPORTED)
  183961. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  183962. png_uint_32 length));
  183963. #endif
  183964. #if defined(PNG_READ_tEXt_SUPPORTED)
  183965. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183966. png_uint_32 length));
  183967. #endif
  183968. #if defined(PNG_READ_tIME_SUPPORTED)
  183969. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  183970. png_uint_32 length));
  183971. #endif
  183972. #if defined(PNG_READ_tRNS_SUPPORTED)
  183973. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  183974. png_uint_32 length));
  183975. #endif
  183976. #if defined(PNG_READ_zTXt_SUPPORTED)
  183977. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183978. png_uint_32 length));
  183979. #endif
  183980. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  183981. png_infop info_ptr, png_uint_32 length));
  183982. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  183983. png_bytep chunk_name));
  183984. /* handle the transformations for reading and writing */
  183985. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  183986. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  183987. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  183988. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183989. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  183990. png_infop info_ptr));
  183991. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  183992. png_infop info_ptr));
  183993. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  183994. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  183995. png_uint_32 length));
  183996. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  183997. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  183998. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  183999. png_bytep buffer, png_size_t buffer_length));
  184000. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184001. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184002. png_bytep buffer, png_size_t buffer_length));
  184003. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184004. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184005. png_infop info_ptr, png_uint_32 length));
  184006. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184007. png_infop info_ptr));
  184008. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184009. png_infop info_ptr));
  184010. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184011. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184012. png_infop info_ptr));
  184013. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184014. png_infop info_ptr));
  184015. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184016. #if defined(PNG_READ_tEXt_SUPPORTED)
  184017. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184018. png_infop info_ptr, png_uint_32 length));
  184019. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184020. png_infop info_ptr));
  184021. #endif
  184022. #if defined(PNG_READ_zTXt_SUPPORTED)
  184023. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184024. png_infop info_ptr, png_uint_32 length));
  184025. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184026. png_infop info_ptr));
  184027. #endif
  184028. #if defined(PNG_READ_iTXt_SUPPORTED)
  184029. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184030. png_infop info_ptr, png_uint_32 length));
  184031. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184032. png_infop info_ptr));
  184033. #endif
  184034. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184035. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184036. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184037. png_bytep row));
  184038. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184039. png_bytep row));
  184040. #endif
  184041. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184042. #if defined(PNG_MMX_CODE_SUPPORTED)
  184043. /* png.c */ /* PRIVATE */
  184044. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184045. #endif
  184046. #endif
  184047. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184048. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184049. png_infop info_ptr));
  184050. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184051. png_infop info_ptr));
  184052. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184053. png_infop info_ptr));
  184054. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184055. png_infop info_ptr));
  184056. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184057. png_infop info_ptr));
  184058. #if defined(PNG_pHYs_SUPPORTED)
  184059. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184060. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184061. #endif /* PNG_pHYs_SUPPORTED */
  184062. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184063. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184064. #endif /* PNG_INTERNAL */
  184065. #ifdef __cplusplus
  184066. }
  184067. #endif
  184068. #endif /* PNG_VERSION_INFO_ONLY */
  184069. /* do not put anything past this line */
  184070. #endif /* PNG_H */
  184071. /*** End of inlined file: png.h ***/
  184072. #define PNG_NO_EXTERN
  184073. /*** Start of inlined file: png.c ***/
  184074. /* png.c - location for general purpose libpng functions
  184075. *
  184076. * Last changed in libpng 1.2.21 [October 4, 2007]
  184077. * For conditions of distribution and use, see copyright notice in png.h
  184078. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184079. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184080. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184081. */
  184082. #define PNG_INTERNAL
  184083. #define PNG_NO_EXTERN
  184084. /* Generate a compiler error if there is an old png.h in the search path. */
  184085. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184086. /* Version information for C files. This had better match the version
  184087. * string defined in png.h. */
  184088. #ifdef PNG_USE_GLOBAL_ARRAYS
  184089. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184090. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184091. #ifdef PNG_READ_SUPPORTED
  184092. /* png_sig was changed to a function in version 1.0.5c */
  184093. /* Place to hold the signature string for a PNG file. */
  184094. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184095. #endif /* PNG_READ_SUPPORTED */
  184096. /* Invoke global declarations for constant strings for known chunk types */
  184097. PNG_IHDR;
  184098. PNG_IDAT;
  184099. PNG_IEND;
  184100. PNG_PLTE;
  184101. PNG_bKGD;
  184102. PNG_cHRM;
  184103. PNG_gAMA;
  184104. PNG_hIST;
  184105. PNG_iCCP;
  184106. PNG_iTXt;
  184107. PNG_oFFs;
  184108. PNG_pCAL;
  184109. PNG_sCAL;
  184110. PNG_pHYs;
  184111. PNG_sBIT;
  184112. PNG_sPLT;
  184113. PNG_sRGB;
  184114. PNG_tEXt;
  184115. PNG_tIME;
  184116. PNG_tRNS;
  184117. PNG_zTXt;
  184118. #ifdef PNG_READ_SUPPORTED
  184119. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184120. /* start of interlace block */
  184121. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184122. /* offset to next interlace block */
  184123. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184124. /* start of interlace block in the y direction */
  184125. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184126. /* offset to next interlace block in the y direction */
  184127. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184128. /* Height of interlace block. This is not currently used - if you need
  184129. * it, uncomment it here and in png.h
  184130. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184131. */
  184132. /* Mask to determine which pixels are valid in a pass */
  184133. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184134. /* Mask to determine which pixels to overwrite while displaying */
  184135. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184136. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184137. #endif /* PNG_READ_SUPPORTED */
  184138. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184139. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184140. * of the PNG file signature. If the PNG data is embedded into another
  184141. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184142. * or write any of the magic bytes before it starts on the IHDR.
  184143. */
  184144. #ifdef PNG_READ_SUPPORTED
  184145. void PNGAPI
  184146. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184147. {
  184148. if(png_ptr == NULL) return;
  184149. png_debug(1, "in png_set_sig_bytes\n");
  184150. if (num_bytes > 8)
  184151. png_error(png_ptr, "Too many bytes for PNG signature.");
  184152. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184153. }
  184154. /* Checks whether the supplied bytes match the PNG signature. We allow
  184155. * checking less than the full 8-byte signature so that those apps that
  184156. * already read the first few bytes of a file to determine the file type
  184157. * can simply check the remaining bytes for extra assurance. Returns
  184158. * an integer less than, equal to, or greater than zero if sig is found,
  184159. * respectively, to be less than, to match, or be greater than the correct
  184160. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184161. */
  184162. int PNGAPI
  184163. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184164. {
  184165. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184166. if (num_to_check > 8)
  184167. num_to_check = 8;
  184168. else if (num_to_check < 1)
  184169. return (-1);
  184170. if (start > 7)
  184171. return (-1);
  184172. if (start + num_to_check > 8)
  184173. num_to_check = 8 - start;
  184174. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184175. }
  184176. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184177. /* (Obsolete) function to check signature bytes. It does not allow one
  184178. * to check a partial signature. This function might be removed in the
  184179. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184180. */
  184181. int PNGAPI
  184182. png_check_sig(png_bytep sig, int num)
  184183. {
  184184. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184185. }
  184186. #endif
  184187. #endif /* PNG_READ_SUPPORTED */
  184188. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184189. /* Function to allocate memory for zlib and clear it to 0. */
  184190. #ifdef PNG_1_0_X
  184191. voidpf PNGAPI
  184192. #else
  184193. voidpf /* private */
  184194. #endif
  184195. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184196. {
  184197. png_voidp ptr;
  184198. png_structp p=(png_structp)png_ptr;
  184199. png_uint_32 save_flags=p->flags;
  184200. png_uint_32 num_bytes;
  184201. if(png_ptr == NULL) return (NULL);
  184202. if (items > PNG_UINT_32_MAX/size)
  184203. {
  184204. png_warning (p, "Potential overflow in png_zalloc()");
  184205. return (NULL);
  184206. }
  184207. num_bytes = (png_uint_32)items * size;
  184208. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184209. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184210. p->flags=save_flags;
  184211. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184212. if (ptr == NULL)
  184213. return ((voidpf)ptr);
  184214. if (num_bytes > (png_uint_32)0x8000L)
  184215. {
  184216. png_memset(ptr, 0, (png_size_t)0x8000L);
  184217. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184218. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184219. }
  184220. else
  184221. {
  184222. png_memset(ptr, 0, (png_size_t)num_bytes);
  184223. }
  184224. #endif
  184225. return ((voidpf)ptr);
  184226. }
  184227. /* function to free memory for zlib */
  184228. #ifdef PNG_1_0_X
  184229. void PNGAPI
  184230. #else
  184231. void /* private */
  184232. #endif
  184233. png_zfree(voidpf png_ptr, voidpf ptr)
  184234. {
  184235. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184236. }
  184237. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184238. * in case CRC is > 32 bits to leave the top bits 0.
  184239. */
  184240. void /* PRIVATE */
  184241. png_reset_crc(png_structp png_ptr)
  184242. {
  184243. png_ptr->crc = crc32(0, Z_NULL, 0);
  184244. }
  184245. /* Calculate the CRC over a section of data. We can only pass as
  184246. * much data to this routine as the largest single buffer size. We
  184247. * also check that this data will actually be used before going to the
  184248. * trouble of calculating it.
  184249. */
  184250. void /* PRIVATE */
  184251. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184252. {
  184253. int need_crc = 1;
  184254. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184255. {
  184256. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184257. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184258. need_crc = 0;
  184259. }
  184260. else /* critical */
  184261. {
  184262. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184263. need_crc = 0;
  184264. }
  184265. if (need_crc)
  184266. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184267. }
  184268. /* Allocate the memory for an info_struct for the application. We don't
  184269. * really need the png_ptr, but it could potentially be useful in the
  184270. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184271. * and png_info_init() so that applications that want to use a shared
  184272. * libpng don't have to be recompiled if png_info changes size.
  184273. */
  184274. png_infop PNGAPI
  184275. png_create_info_struct(png_structp png_ptr)
  184276. {
  184277. png_infop info_ptr;
  184278. png_debug(1, "in png_create_info_struct\n");
  184279. if(png_ptr == NULL) return (NULL);
  184280. #ifdef PNG_USER_MEM_SUPPORTED
  184281. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184282. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184283. #else
  184284. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184285. #endif
  184286. if (info_ptr != NULL)
  184287. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184288. return (info_ptr);
  184289. }
  184290. /* This function frees the memory associated with a single info struct.
  184291. * Normally, one would use either png_destroy_read_struct() or
  184292. * png_destroy_write_struct() to free an info struct, but this may be
  184293. * useful for some applications.
  184294. */
  184295. void PNGAPI
  184296. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184297. {
  184298. png_infop info_ptr = NULL;
  184299. if(png_ptr == NULL) return;
  184300. png_debug(1, "in png_destroy_info_struct\n");
  184301. if (info_ptr_ptr != NULL)
  184302. info_ptr = *info_ptr_ptr;
  184303. if (info_ptr != NULL)
  184304. {
  184305. png_info_destroy(png_ptr, info_ptr);
  184306. #ifdef PNG_USER_MEM_SUPPORTED
  184307. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184308. png_ptr->mem_ptr);
  184309. #else
  184310. png_destroy_struct((png_voidp)info_ptr);
  184311. #endif
  184312. *info_ptr_ptr = NULL;
  184313. }
  184314. }
  184315. /* Initialize the info structure. This is now an internal function (0.89)
  184316. * and applications using it are urged to use png_create_info_struct()
  184317. * instead.
  184318. */
  184319. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184320. #undef png_info_init
  184321. void PNGAPI
  184322. png_info_init(png_infop info_ptr)
  184323. {
  184324. /* We only come here via pre-1.0.12-compiled applications */
  184325. png_info_init_3(&info_ptr, 0);
  184326. }
  184327. #endif
  184328. void PNGAPI
  184329. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184330. {
  184331. png_infop info_ptr = *ptr_ptr;
  184332. if(info_ptr == NULL) return;
  184333. png_debug(1, "in png_info_init_3\n");
  184334. if(png_sizeof(png_info) > png_info_struct_size)
  184335. {
  184336. png_destroy_struct(info_ptr);
  184337. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184338. *ptr_ptr = info_ptr;
  184339. }
  184340. /* set everything to 0 */
  184341. png_memset(info_ptr, 0, png_sizeof (png_info));
  184342. }
  184343. #ifdef PNG_FREE_ME_SUPPORTED
  184344. void PNGAPI
  184345. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184346. int freer, png_uint_32 mask)
  184347. {
  184348. png_debug(1, "in png_data_freer\n");
  184349. if (png_ptr == NULL || info_ptr == NULL)
  184350. return;
  184351. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184352. info_ptr->free_me |= mask;
  184353. else if(freer == PNG_USER_WILL_FREE_DATA)
  184354. info_ptr->free_me &= ~mask;
  184355. else
  184356. png_warning(png_ptr,
  184357. "Unknown freer parameter in png_data_freer.");
  184358. }
  184359. #endif
  184360. void PNGAPI
  184361. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184362. int num)
  184363. {
  184364. png_debug(1, "in png_free_data\n");
  184365. if (png_ptr == NULL || info_ptr == NULL)
  184366. return;
  184367. #if defined(PNG_TEXT_SUPPORTED)
  184368. /* free text item num or (if num == -1) all text items */
  184369. #ifdef PNG_FREE_ME_SUPPORTED
  184370. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184371. #else
  184372. if (mask & PNG_FREE_TEXT)
  184373. #endif
  184374. {
  184375. if (num != -1)
  184376. {
  184377. if (info_ptr->text && info_ptr->text[num].key)
  184378. {
  184379. png_free(png_ptr, info_ptr->text[num].key);
  184380. info_ptr->text[num].key = NULL;
  184381. }
  184382. }
  184383. else
  184384. {
  184385. int i;
  184386. for (i = 0; i < info_ptr->num_text; i++)
  184387. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184388. png_free(png_ptr, info_ptr->text);
  184389. info_ptr->text = NULL;
  184390. info_ptr->num_text=0;
  184391. }
  184392. }
  184393. #endif
  184394. #if defined(PNG_tRNS_SUPPORTED)
  184395. /* free any tRNS entry */
  184396. #ifdef PNG_FREE_ME_SUPPORTED
  184397. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184398. #else
  184399. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184400. #endif
  184401. {
  184402. png_free(png_ptr, info_ptr->trans);
  184403. info_ptr->valid &= ~PNG_INFO_tRNS;
  184404. #ifndef PNG_FREE_ME_SUPPORTED
  184405. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184406. #endif
  184407. info_ptr->trans = NULL;
  184408. }
  184409. #endif
  184410. #if defined(PNG_sCAL_SUPPORTED)
  184411. /* free any sCAL entry */
  184412. #ifdef PNG_FREE_ME_SUPPORTED
  184413. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184414. #else
  184415. if (mask & PNG_FREE_SCAL)
  184416. #endif
  184417. {
  184418. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184419. png_free(png_ptr, info_ptr->scal_s_width);
  184420. png_free(png_ptr, info_ptr->scal_s_height);
  184421. info_ptr->scal_s_width = NULL;
  184422. info_ptr->scal_s_height = NULL;
  184423. #endif
  184424. info_ptr->valid &= ~PNG_INFO_sCAL;
  184425. }
  184426. #endif
  184427. #if defined(PNG_pCAL_SUPPORTED)
  184428. /* free any pCAL entry */
  184429. #ifdef PNG_FREE_ME_SUPPORTED
  184430. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184431. #else
  184432. if (mask & PNG_FREE_PCAL)
  184433. #endif
  184434. {
  184435. png_free(png_ptr, info_ptr->pcal_purpose);
  184436. png_free(png_ptr, info_ptr->pcal_units);
  184437. info_ptr->pcal_purpose = NULL;
  184438. info_ptr->pcal_units = NULL;
  184439. if (info_ptr->pcal_params != NULL)
  184440. {
  184441. int i;
  184442. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184443. {
  184444. png_free(png_ptr, info_ptr->pcal_params[i]);
  184445. info_ptr->pcal_params[i]=NULL;
  184446. }
  184447. png_free(png_ptr, info_ptr->pcal_params);
  184448. info_ptr->pcal_params = NULL;
  184449. }
  184450. info_ptr->valid &= ~PNG_INFO_pCAL;
  184451. }
  184452. #endif
  184453. #if defined(PNG_iCCP_SUPPORTED)
  184454. /* free any iCCP entry */
  184455. #ifdef PNG_FREE_ME_SUPPORTED
  184456. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184457. #else
  184458. if (mask & PNG_FREE_ICCP)
  184459. #endif
  184460. {
  184461. png_free(png_ptr, info_ptr->iccp_name);
  184462. png_free(png_ptr, info_ptr->iccp_profile);
  184463. info_ptr->iccp_name = NULL;
  184464. info_ptr->iccp_profile = NULL;
  184465. info_ptr->valid &= ~PNG_INFO_iCCP;
  184466. }
  184467. #endif
  184468. #if defined(PNG_sPLT_SUPPORTED)
  184469. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184470. #ifdef PNG_FREE_ME_SUPPORTED
  184471. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184472. #else
  184473. if (mask & PNG_FREE_SPLT)
  184474. #endif
  184475. {
  184476. if (num != -1)
  184477. {
  184478. if(info_ptr->splt_palettes)
  184479. {
  184480. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184481. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184482. info_ptr->splt_palettes[num].name = NULL;
  184483. info_ptr->splt_palettes[num].entries = NULL;
  184484. }
  184485. }
  184486. else
  184487. {
  184488. if(info_ptr->splt_palettes_num)
  184489. {
  184490. int i;
  184491. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184492. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184493. png_free(png_ptr, info_ptr->splt_palettes);
  184494. info_ptr->splt_palettes = NULL;
  184495. info_ptr->splt_palettes_num = 0;
  184496. }
  184497. info_ptr->valid &= ~PNG_INFO_sPLT;
  184498. }
  184499. }
  184500. #endif
  184501. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184502. if(png_ptr->unknown_chunk.data)
  184503. {
  184504. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184505. png_ptr->unknown_chunk.data = NULL;
  184506. }
  184507. #ifdef PNG_FREE_ME_SUPPORTED
  184508. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184509. #else
  184510. if (mask & PNG_FREE_UNKN)
  184511. #endif
  184512. {
  184513. if (num != -1)
  184514. {
  184515. if(info_ptr->unknown_chunks)
  184516. {
  184517. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184518. info_ptr->unknown_chunks[num].data = NULL;
  184519. }
  184520. }
  184521. else
  184522. {
  184523. int i;
  184524. if(info_ptr->unknown_chunks_num)
  184525. {
  184526. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184527. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184528. png_free(png_ptr, info_ptr->unknown_chunks);
  184529. info_ptr->unknown_chunks = NULL;
  184530. info_ptr->unknown_chunks_num = 0;
  184531. }
  184532. }
  184533. }
  184534. #endif
  184535. #if defined(PNG_hIST_SUPPORTED)
  184536. /* free any hIST entry */
  184537. #ifdef PNG_FREE_ME_SUPPORTED
  184538. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184539. #else
  184540. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184541. #endif
  184542. {
  184543. png_free(png_ptr, info_ptr->hist);
  184544. info_ptr->hist = NULL;
  184545. info_ptr->valid &= ~PNG_INFO_hIST;
  184546. #ifndef PNG_FREE_ME_SUPPORTED
  184547. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184548. #endif
  184549. }
  184550. #endif
  184551. /* free any PLTE entry that was internally allocated */
  184552. #ifdef PNG_FREE_ME_SUPPORTED
  184553. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184554. #else
  184555. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184556. #endif
  184557. {
  184558. png_zfree(png_ptr, info_ptr->palette);
  184559. info_ptr->palette = NULL;
  184560. info_ptr->valid &= ~PNG_INFO_PLTE;
  184561. #ifndef PNG_FREE_ME_SUPPORTED
  184562. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184563. #endif
  184564. info_ptr->num_palette = 0;
  184565. }
  184566. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184567. /* free any image bits attached to the info structure */
  184568. #ifdef PNG_FREE_ME_SUPPORTED
  184569. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184570. #else
  184571. if (mask & PNG_FREE_ROWS)
  184572. #endif
  184573. {
  184574. if(info_ptr->row_pointers)
  184575. {
  184576. int row;
  184577. for (row = 0; row < (int)info_ptr->height; row++)
  184578. {
  184579. png_free(png_ptr, info_ptr->row_pointers[row]);
  184580. info_ptr->row_pointers[row]=NULL;
  184581. }
  184582. png_free(png_ptr, info_ptr->row_pointers);
  184583. info_ptr->row_pointers=NULL;
  184584. }
  184585. info_ptr->valid &= ~PNG_INFO_IDAT;
  184586. }
  184587. #endif
  184588. #ifdef PNG_FREE_ME_SUPPORTED
  184589. if(num == -1)
  184590. info_ptr->free_me &= ~mask;
  184591. else
  184592. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184593. #endif
  184594. }
  184595. /* This is an internal routine to free any memory that the info struct is
  184596. * pointing to before re-using it or freeing the struct itself. Recall
  184597. * that png_free() checks for NULL pointers for us.
  184598. */
  184599. void /* PRIVATE */
  184600. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184601. {
  184602. png_debug(1, "in png_info_destroy\n");
  184603. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184604. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184605. if (png_ptr->num_chunk_list)
  184606. {
  184607. png_free(png_ptr, png_ptr->chunk_list);
  184608. png_ptr->chunk_list=NULL;
  184609. png_ptr->num_chunk_list=0;
  184610. }
  184611. #endif
  184612. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184613. }
  184614. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184615. /* This function returns a pointer to the io_ptr associated with the user
  184616. * functions. The application should free any memory associated with this
  184617. * pointer before png_write_destroy() or png_read_destroy() are called.
  184618. */
  184619. png_voidp PNGAPI
  184620. png_get_io_ptr(png_structp png_ptr)
  184621. {
  184622. if(png_ptr == NULL) return (NULL);
  184623. return (png_ptr->io_ptr);
  184624. }
  184625. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184626. #if !defined(PNG_NO_STDIO)
  184627. /* Initialize the default input/output functions for the PNG file. If you
  184628. * use your own read or write routines, you can call either png_set_read_fn()
  184629. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184630. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184631. * necessarily available.
  184632. */
  184633. void PNGAPI
  184634. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184635. {
  184636. png_debug(1, "in png_init_io\n");
  184637. if(png_ptr == NULL) return;
  184638. png_ptr->io_ptr = (png_voidp)fp;
  184639. }
  184640. #endif
  184641. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184642. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184643. * a "Creation Time" or other text-based time string.
  184644. */
  184645. png_charp PNGAPI
  184646. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184647. {
  184648. static PNG_CONST char short_months[12][4] =
  184649. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184650. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184651. if(png_ptr == NULL) return (NULL);
  184652. if (png_ptr->time_buffer == NULL)
  184653. {
  184654. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184655. png_sizeof(char)));
  184656. }
  184657. #if defined(_WIN32_WCE)
  184658. {
  184659. wchar_t time_buf[29];
  184660. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184661. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184662. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184663. ptime->second % 61);
  184664. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184665. NULL, NULL);
  184666. }
  184667. #else
  184668. #ifdef USE_FAR_KEYWORD
  184669. {
  184670. char near_time_buf[29];
  184671. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184672. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184673. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184674. ptime->second % 61);
  184675. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184676. 29*png_sizeof(char));
  184677. }
  184678. #else
  184679. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184680. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184681. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184682. ptime->second % 61);
  184683. #endif
  184684. #endif /* _WIN32_WCE */
  184685. return ((png_charp)png_ptr->time_buffer);
  184686. }
  184687. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184688. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184689. png_charp PNGAPI
  184690. png_get_copyright(png_structp png_ptr)
  184691. {
  184692. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184693. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184694. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184695. Copyright (c) 1996-1997 Andreas Dilger\n\
  184696. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184697. }
  184698. /* The following return the library version as a short string in the
  184699. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184700. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184701. * is defined in png.h.
  184702. * Note: now there is no difference between png_get_libpng_ver() and
  184703. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184704. * it is guaranteed that png.c uses the correct version of png.h.
  184705. */
  184706. png_charp PNGAPI
  184707. png_get_libpng_ver(png_structp png_ptr)
  184708. {
  184709. /* Version of *.c files used when building libpng */
  184710. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184711. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184712. }
  184713. png_charp PNGAPI
  184714. png_get_header_ver(png_structp png_ptr)
  184715. {
  184716. /* Version of *.h files used when building libpng */
  184717. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184718. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184719. }
  184720. png_charp PNGAPI
  184721. png_get_header_version(png_structp png_ptr)
  184722. {
  184723. /* Returns longer string containing both version and date */
  184724. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184725. return ((png_charp) PNG_HEADER_VERSION_STRING
  184726. #ifndef PNG_READ_SUPPORTED
  184727. " (NO READ SUPPORT)"
  184728. #endif
  184729. "\n");
  184730. }
  184731. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184732. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184733. int PNGAPI
  184734. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184735. {
  184736. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184737. int i;
  184738. png_bytep p;
  184739. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184740. return 0;
  184741. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184742. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184743. if (!png_memcmp(chunk_name, p, 4))
  184744. return ((int)*(p+4));
  184745. return 0;
  184746. }
  184747. #endif
  184748. /* This function, added to libpng-1.0.6g, is untested. */
  184749. int PNGAPI
  184750. png_reset_zstream(png_structp png_ptr)
  184751. {
  184752. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184753. return (inflateReset(&png_ptr->zstream));
  184754. }
  184755. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184756. /* This function was added to libpng-1.0.7 */
  184757. png_uint_32 PNGAPI
  184758. png_access_version_number(void)
  184759. {
  184760. /* Version of *.c files used when building libpng */
  184761. return((png_uint_32) PNG_LIBPNG_VER);
  184762. }
  184763. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184764. #if !defined(PNG_1_0_X)
  184765. /* this function was added to libpng 1.2.0 */
  184766. int PNGAPI
  184767. png_mmx_support(void)
  184768. {
  184769. /* obsolete, to be removed from libpng-1.4.0 */
  184770. return -1;
  184771. }
  184772. #endif /* PNG_1_0_X */
  184773. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184774. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184775. #ifdef PNG_SIZE_T
  184776. /* Added at libpng version 1.2.6 */
  184777. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184778. png_size_t PNGAPI
  184779. png_convert_size(size_t size)
  184780. {
  184781. if (size > (png_size_t)-1)
  184782. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184783. return ((png_size_t)size);
  184784. }
  184785. #endif /* PNG_SIZE_T */
  184786. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184787. /*** End of inlined file: png.c ***/
  184788. /*** Start of inlined file: pngerror.c ***/
  184789. /* pngerror.c - stub functions for i/o and memory allocation
  184790. *
  184791. * Last changed in libpng 1.2.20 October 4, 2007
  184792. * For conditions of distribution and use, see copyright notice in png.h
  184793. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184794. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184795. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184796. *
  184797. * This file provides a location for all error handling. Users who
  184798. * need special error handling are expected to write replacement functions
  184799. * and use png_set_error_fn() to use those functions. See the instructions
  184800. * at each function.
  184801. */
  184802. #define PNG_INTERNAL
  184803. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184804. static void /* PRIVATE */
  184805. png_default_error PNGARG((png_structp png_ptr,
  184806. png_const_charp error_message));
  184807. #ifndef PNG_NO_WARNINGS
  184808. static void /* PRIVATE */
  184809. png_default_warning PNGARG((png_structp png_ptr,
  184810. png_const_charp warning_message));
  184811. #endif /* PNG_NO_WARNINGS */
  184812. /* This function is called whenever there is a fatal error. This function
  184813. * should not be changed. If there is a need to handle errors differently,
  184814. * you should supply a replacement error function and use png_set_error_fn()
  184815. * to replace the error function at run-time.
  184816. */
  184817. #ifndef PNG_NO_ERROR_TEXT
  184818. void PNGAPI
  184819. png_error(png_structp png_ptr, png_const_charp error_message)
  184820. {
  184821. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184822. char msg[16];
  184823. if (png_ptr != NULL)
  184824. {
  184825. if (png_ptr->flags&
  184826. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184827. {
  184828. if (*error_message == '#')
  184829. {
  184830. int offset;
  184831. for (offset=1; offset<15; offset++)
  184832. if (*(error_message+offset) == ' ')
  184833. break;
  184834. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184835. {
  184836. int i;
  184837. for (i=0; i<offset-1; i++)
  184838. msg[i]=error_message[i+1];
  184839. msg[i]='\0';
  184840. error_message=msg;
  184841. }
  184842. else
  184843. error_message+=offset;
  184844. }
  184845. else
  184846. {
  184847. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184848. {
  184849. msg[0]='0';
  184850. msg[1]='\0';
  184851. error_message=msg;
  184852. }
  184853. }
  184854. }
  184855. }
  184856. #endif
  184857. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184858. (*(png_ptr->error_fn))(png_ptr, error_message);
  184859. /* If the custom handler doesn't exist, or if it returns,
  184860. use the default handler, which will not return. */
  184861. png_default_error(png_ptr, error_message);
  184862. }
  184863. #else
  184864. void PNGAPI
  184865. png_err(png_structp png_ptr)
  184866. {
  184867. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184868. (*(png_ptr->error_fn))(png_ptr, '\0');
  184869. /* If the custom handler doesn't exist, or if it returns,
  184870. use the default handler, which will not return. */
  184871. png_default_error(png_ptr, '\0');
  184872. }
  184873. #endif /* PNG_NO_ERROR_TEXT */
  184874. #ifndef PNG_NO_WARNINGS
  184875. /* This function is called whenever there is a non-fatal error. This function
  184876. * should not be changed. If there is a need to handle warnings differently,
  184877. * you should supply a replacement warning function and use
  184878. * png_set_error_fn() to replace the warning function at run-time.
  184879. */
  184880. void PNGAPI
  184881. png_warning(png_structp png_ptr, png_const_charp warning_message)
  184882. {
  184883. int offset = 0;
  184884. if (png_ptr != NULL)
  184885. {
  184886. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184887. if (png_ptr->flags&
  184888. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184889. #endif
  184890. {
  184891. if (*warning_message == '#')
  184892. {
  184893. for (offset=1; offset<15; offset++)
  184894. if (*(warning_message+offset) == ' ')
  184895. break;
  184896. }
  184897. }
  184898. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  184899. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  184900. }
  184901. else
  184902. png_default_warning(png_ptr, warning_message+offset);
  184903. }
  184904. #endif /* PNG_NO_WARNINGS */
  184905. /* These utilities are used internally to build an error message that relates
  184906. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  184907. * this is used to prefix the message. The message is limited in length
  184908. * to 63 bytes, the name characters are output as hex digits wrapped in []
  184909. * if the character is invalid.
  184910. */
  184911. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  184912. /*static PNG_CONST char png_digit[16] = {
  184913. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  184914. 'A', 'B', 'C', 'D', 'E', 'F'
  184915. };*/
  184916. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  184917. static void /* PRIVATE */
  184918. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  184919. error_message)
  184920. {
  184921. int iout = 0, iin = 0;
  184922. while (iin < 4)
  184923. {
  184924. int c = png_ptr->chunk_name[iin++];
  184925. if (isnonalpha(c))
  184926. {
  184927. buffer[iout++] = '[';
  184928. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  184929. buffer[iout++] = png_digit[c & 0x0f];
  184930. buffer[iout++] = ']';
  184931. }
  184932. else
  184933. {
  184934. buffer[iout++] = (png_byte)c;
  184935. }
  184936. }
  184937. if (error_message == NULL)
  184938. buffer[iout] = 0;
  184939. else
  184940. {
  184941. buffer[iout++] = ':';
  184942. buffer[iout++] = ' ';
  184943. png_strncpy(buffer+iout, error_message, 63);
  184944. buffer[iout+63] = 0;
  184945. }
  184946. }
  184947. #ifdef PNG_READ_SUPPORTED
  184948. void PNGAPI
  184949. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  184950. {
  184951. char msg[18+64];
  184952. if (png_ptr == NULL)
  184953. png_error(png_ptr, error_message);
  184954. else
  184955. {
  184956. png_format_buffer(png_ptr, msg, error_message);
  184957. png_error(png_ptr, msg);
  184958. }
  184959. }
  184960. #endif /* PNG_READ_SUPPORTED */
  184961. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  184962. #ifndef PNG_NO_WARNINGS
  184963. void PNGAPI
  184964. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  184965. {
  184966. char msg[18+64];
  184967. if (png_ptr == NULL)
  184968. png_warning(png_ptr, warning_message);
  184969. else
  184970. {
  184971. png_format_buffer(png_ptr, msg, warning_message);
  184972. png_warning(png_ptr, msg);
  184973. }
  184974. }
  184975. #endif /* PNG_NO_WARNINGS */
  184976. /* This is the default error handling function. Note that replacements for
  184977. * this function MUST NOT RETURN, or the program will likely crash. This
  184978. * function is used by default, or if the program supplies NULL for the
  184979. * error function pointer in png_set_error_fn().
  184980. */
  184981. static void /* PRIVATE */
  184982. png_default_error(png_structp, png_const_charp error_message)
  184983. {
  184984. #ifndef PNG_NO_CONSOLE_IO
  184985. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184986. if (*error_message == '#')
  184987. {
  184988. int offset;
  184989. char error_number[16];
  184990. for (offset=0; offset<15; offset++)
  184991. {
  184992. error_number[offset] = *(error_message+offset+1);
  184993. if (*(error_message+offset) == ' ')
  184994. break;
  184995. }
  184996. if((offset > 1) && (offset < 15))
  184997. {
  184998. error_number[offset-1]='\0';
  184999. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185000. error_message+offset);
  185001. }
  185002. else
  185003. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185004. }
  185005. else
  185006. #endif
  185007. fprintf(stderr, "libpng error: %s\n", error_message);
  185008. #endif
  185009. #ifdef PNG_SETJMP_SUPPORTED
  185010. if (png_ptr)
  185011. {
  185012. # ifdef USE_FAR_KEYWORD
  185013. {
  185014. jmp_buf jmpbuf;
  185015. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185016. longjmp(jmpbuf, 1);
  185017. }
  185018. # else
  185019. longjmp(png_ptr->jmpbuf, 1);
  185020. # endif
  185021. }
  185022. #else
  185023. PNG_ABORT();
  185024. #endif
  185025. #ifdef PNG_NO_CONSOLE_IO
  185026. error_message = error_message; /* make compiler happy */
  185027. #endif
  185028. }
  185029. #ifndef PNG_NO_WARNINGS
  185030. /* This function is called when there is a warning, but the library thinks
  185031. * it can continue anyway. Replacement functions don't have to do anything
  185032. * here if you don't want them to. In the default configuration, png_ptr is
  185033. * not used, but it is passed in case it may be useful.
  185034. */
  185035. static void /* PRIVATE */
  185036. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185037. {
  185038. #ifndef PNG_NO_CONSOLE_IO
  185039. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185040. if (*warning_message == '#')
  185041. {
  185042. int offset;
  185043. char warning_number[16];
  185044. for (offset=0; offset<15; offset++)
  185045. {
  185046. warning_number[offset]=*(warning_message+offset+1);
  185047. if (*(warning_message+offset) == ' ')
  185048. break;
  185049. }
  185050. if((offset > 1) && (offset < 15))
  185051. {
  185052. warning_number[offset-1]='\0';
  185053. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185054. warning_message+offset);
  185055. }
  185056. else
  185057. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185058. }
  185059. else
  185060. # endif
  185061. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185062. #else
  185063. warning_message = warning_message; /* make compiler happy */
  185064. #endif
  185065. png_ptr = png_ptr; /* make compiler happy */
  185066. }
  185067. #endif /* PNG_NO_WARNINGS */
  185068. /* This function is called when the application wants to use another method
  185069. * of handling errors and warnings. Note that the error function MUST NOT
  185070. * return to the calling routine or serious problems will occur. The return
  185071. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185072. */
  185073. void PNGAPI
  185074. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185075. png_error_ptr error_fn, png_error_ptr warning_fn)
  185076. {
  185077. if (png_ptr == NULL)
  185078. return;
  185079. png_ptr->error_ptr = error_ptr;
  185080. png_ptr->error_fn = error_fn;
  185081. png_ptr->warning_fn = warning_fn;
  185082. }
  185083. /* This function returns a pointer to the error_ptr associated with the user
  185084. * functions. The application should free any memory associated with this
  185085. * pointer before png_write_destroy and png_read_destroy are called.
  185086. */
  185087. png_voidp PNGAPI
  185088. png_get_error_ptr(png_structp png_ptr)
  185089. {
  185090. if (png_ptr == NULL)
  185091. return NULL;
  185092. return ((png_voidp)png_ptr->error_ptr);
  185093. }
  185094. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185095. void PNGAPI
  185096. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185097. {
  185098. if(png_ptr != NULL)
  185099. {
  185100. png_ptr->flags &=
  185101. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185102. }
  185103. }
  185104. #endif
  185105. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185106. /*** End of inlined file: pngerror.c ***/
  185107. /*** Start of inlined file: pngget.c ***/
  185108. /* pngget.c - retrieval of values from info struct
  185109. *
  185110. * Last changed in libpng 1.2.15 January 5, 2007
  185111. * For conditions of distribution and use, see copyright notice in png.h
  185112. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185113. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185114. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185115. */
  185116. #define PNG_INTERNAL
  185117. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185118. png_uint_32 PNGAPI
  185119. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185120. {
  185121. if (png_ptr != NULL && info_ptr != NULL)
  185122. return(info_ptr->valid & flag);
  185123. else
  185124. return(0);
  185125. }
  185126. png_uint_32 PNGAPI
  185127. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185128. {
  185129. if (png_ptr != NULL && info_ptr != NULL)
  185130. return(info_ptr->rowbytes);
  185131. else
  185132. return(0);
  185133. }
  185134. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185135. png_bytepp PNGAPI
  185136. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185137. {
  185138. if (png_ptr != NULL && info_ptr != NULL)
  185139. return(info_ptr->row_pointers);
  185140. else
  185141. return(0);
  185142. }
  185143. #endif
  185144. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185145. /* easy access to info, added in libpng-0.99 */
  185146. png_uint_32 PNGAPI
  185147. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185148. {
  185149. if (png_ptr != NULL && info_ptr != NULL)
  185150. {
  185151. return info_ptr->width;
  185152. }
  185153. return (0);
  185154. }
  185155. png_uint_32 PNGAPI
  185156. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185157. {
  185158. if (png_ptr != NULL && info_ptr != NULL)
  185159. {
  185160. return info_ptr->height;
  185161. }
  185162. return (0);
  185163. }
  185164. png_byte PNGAPI
  185165. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185166. {
  185167. if (png_ptr != NULL && info_ptr != NULL)
  185168. {
  185169. return info_ptr->bit_depth;
  185170. }
  185171. return (0);
  185172. }
  185173. png_byte PNGAPI
  185174. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185175. {
  185176. if (png_ptr != NULL && info_ptr != NULL)
  185177. {
  185178. return info_ptr->color_type;
  185179. }
  185180. return (0);
  185181. }
  185182. png_byte PNGAPI
  185183. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185184. {
  185185. if (png_ptr != NULL && info_ptr != NULL)
  185186. {
  185187. return info_ptr->filter_type;
  185188. }
  185189. return (0);
  185190. }
  185191. png_byte PNGAPI
  185192. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185193. {
  185194. if (png_ptr != NULL && info_ptr != NULL)
  185195. {
  185196. return info_ptr->interlace_type;
  185197. }
  185198. return (0);
  185199. }
  185200. png_byte PNGAPI
  185201. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185202. {
  185203. if (png_ptr != NULL && info_ptr != NULL)
  185204. {
  185205. return info_ptr->compression_type;
  185206. }
  185207. return (0);
  185208. }
  185209. png_uint_32 PNGAPI
  185210. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185211. {
  185212. if (png_ptr != NULL && info_ptr != NULL)
  185213. #if defined(PNG_pHYs_SUPPORTED)
  185214. if (info_ptr->valid & PNG_INFO_pHYs)
  185215. {
  185216. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185217. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185218. return (0);
  185219. else return (info_ptr->x_pixels_per_unit);
  185220. }
  185221. #else
  185222. return (0);
  185223. #endif
  185224. return (0);
  185225. }
  185226. png_uint_32 PNGAPI
  185227. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185228. {
  185229. if (png_ptr != NULL && info_ptr != NULL)
  185230. #if defined(PNG_pHYs_SUPPORTED)
  185231. if (info_ptr->valid & PNG_INFO_pHYs)
  185232. {
  185233. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185234. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185235. return (0);
  185236. else return (info_ptr->y_pixels_per_unit);
  185237. }
  185238. #else
  185239. return (0);
  185240. #endif
  185241. return (0);
  185242. }
  185243. png_uint_32 PNGAPI
  185244. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185245. {
  185246. if (png_ptr != NULL && info_ptr != NULL)
  185247. #if defined(PNG_pHYs_SUPPORTED)
  185248. if (info_ptr->valid & PNG_INFO_pHYs)
  185249. {
  185250. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185251. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185252. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185253. return (0);
  185254. else return (info_ptr->x_pixels_per_unit);
  185255. }
  185256. #else
  185257. return (0);
  185258. #endif
  185259. return (0);
  185260. }
  185261. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185262. float PNGAPI
  185263. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185264. {
  185265. if (png_ptr != NULL && info_ptr != NULL)
  185266. #if defined(PNG_pHYs_SUPPORTED)
  185267. if (info_ptr->valid & PNG_INFO_pHYs)
  185268. {
  185269. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185270. if (info_ptr->x_pixels_per_unit == 0)
  185271. return ((float)0.0);
  185272. else
  185273. return ((float)((float)info_ptr->y_pixels_per_unit
  185274. /(float)info_ptr->x_pixels_per_unit));
  185275. }
  185276. #else
  185277. return (0.0);
  185278. #endif
  185279. return ((float)0.0);
  185280. }
  185281. #endif
  185282. png_int_32 PNGAPI
  185283. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185284. {
  185285. if (png_ptr != NULL && info_ptr != NULL)
  185286. #if defined(PNG_oFFs_SUPPORTED)
  185287. if (info_ptr->valid & PNG_INFO_oFFs)
  185288. {
  185289. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185290. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185291. return (0);
  185292. else return (info_ptr->x_offset);
  185293. }
  185294. #else
  185295. return (0);
  185296. #endif
  185297. return (0);
  185298. }
  185299. png_int_32 PNGAPI
  185300. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185301. {
  185302. if (png_ptr != NULL && info_ptr != NULL)
  185303. #if defined(PNG_oFFs_SUPPORTED)
  185304. if (info_ptr->valid & PNG_INFO_oFFs)
  185305. {
  185306. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185307. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185308. return (0);
  185309. else return (info_ptr->y_offset);
  185310. }
  185311. #else
  185312. return (0);
  185313. #endif
  185314. return (0);
  185315. }
  185316. png_int_32 PNGAPI
  185317. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185318. {
  185319. if (png_ptr != NULL && info_ptr != NULL)
  185320. #if defined(PNG_oFFs_SUPPORTED)
  185321. if (info_ptr->valid & PNG_INFO_oFFs)
  185322. {
  185323. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185324. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185325. return (0);
  185326. else return (info_ptr->x_offset);
  185327. }
  185328. #else
  185329. return (0);
  185330. #endif
  185331. return (0);
  185332. }
  185333. png_int_32 PNGAPI
  185334. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185335. {
  185336. if (png_ptr != NULL && info_ptr != NULL)
  185337. #if defined(PNG_oFFs_SUPPORTED)
  185338. if (info_ptr->valid & PNG_INFO_oFFs)
  185339. {
  185340. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185341. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185342. return (0);
  185343. else return (info_ptr->y_offset);
  185344. }
  185345. #else
  185346. return (0);
  185347. #endif
  185348. return (0);
  185349. }
  185350. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185351. png_uint_32 PNGAPI
  185352. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185353. {
  185354. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185355. *.0254 +.5));
  185356. }
  185357. png_uint_32 PNGAPI
  185358. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185359. {
  185360. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185361. *.0254 +.5));
  185362. }
  185363. png_uint_32 PNGAPI
  185364. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185365. {
  185366. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185367. *.0254 +.5));
  185368. }
  185369. float PNGAPI
  185370. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185371. {
  185372. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185373. *.00003937);
  185374. }
  185375. float PNGAPI
  185376. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185377. {
  185378. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185379. *.00003937);
  185380. }
  185381. #if defined(PNG_pHYs_SUPPORTED)
  185382. png_uint_32 PNGAPI
  185383. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185384. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185385. {
  185386. png_uint_32 retval = 0;
  185387. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185388. {
  185389. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185390. if (res_x != NULL)
  185391. {
  185392. *res_x = info_ptr->x_pixels_per_unit;
  185393. retval |= PNG_INFO_pHYs;
  185394. }
  185395. if (res_y != NULL)
  185396. {
  185397. *res_y = info_ptr->y_pixels_per_unit;
  185398. retval |= PNG_INFO_pHYs;
  185399. }
  185400. if (unit_type != NULL)
  185401. {
  185402. *unit_type = (int)info_ptr->phys_unit_type;
  185403. retval |= PNG_INFO_pHYs;
  185404. if(*unit_type == 1)
  185405. {
  185406. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185407. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185408. }
  185409. }
  185410. }
  185411. return (retval);
  185412. }
  185413. #endif /* PNG_pHYs_SUPPORTED */
  185414. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185415. /* png_get_channels really belongs in here, too, but it's been around longer */
  185416. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185417. png_byte PNGAPI
  185418. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185419. {
  185420. if (png_ptr != NULL && info_ptr != NULL)
  185421. return(info_ptr->channels);
  185422. else
  185423. return (0);
  185424. }
  185425. png_bytep PNGAPI
  185426. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185427. {
  185428. if (png_ptr != NULL && info_ptr != NULL)
  185429. return(info_ptr->signature);
  185430. else
  185431. return (NULL);
  185432. }
  185433. #if defined(PNG_bKGD_SUPPORTED)
  185434. png_uint_32 PNGAPI
  185435. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185436. png_color_16p *background)
  185437. {
  185438. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185439. && background != NULL)
  185440. {
  185441. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185442. *background = &(info_ptr->background);
  185443. return (PNG_INFO_bKGD);
  185444. }
  185445. return (0);
  185446. }
  185447. #endif
  185448. #if defined(PNG_cHRM_SUPPORTED)
  185449. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185450. png_uint_32 PNGAPI
  185451. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185452. double *white_x, double *white_y, double *red_x, double *red_y,
  185453. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185454. {
  185455. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185456. {
  185457. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185458. if (white_x != NULL)
  185459. *white_x = (double)info_ptr->x_white;
  185460. if (white_y != NULL)
  185461. *white_y = (double)info_ptr->y_white;
  185462. if (red_x != NULL)
  185463. *red_x = (double)info_ptr->x_red;
  185464. if (red_y != NULL)
  185465. *red_y = (double)info_ptr->y_red;
  185466. if (green_x != NULL)
  185467. *green_x = (double)info_ptr->x_green;
  185468. if (green_y != NULL)
  185469. *green_y = (double)info_ptr->y_green;
  185470. if (blue_x != NULL)
  185471. *blue_x = (double)info_ptr->x_blue;
  185472. if (blue_y != NULL)
  185473. *blue_y = (double)info_ptr->y_blue;
  185474. return (PNG_INFO_cHRM);
  185475. }
  185476. return (0);
  185477. }
  185478. #endif
  185479. #ifdef PNG_FIXED_POINT_SUPPORTED
  185480. png_uint_32 PNGAPI
  185481. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185482. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185483. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185484. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185485. {
  185486. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185487. {
  185488. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185489. if (white_x != NULL)
  185490. *white_x = info_ptr->int_x_white;
  185491. if (white_y != NULL)
  185492. *white_y = info_ptr->int_y_white;
  185493. if (red_x != NULL)
  185494. *red_x = info_ptr->int_x_red;
  185495. if (red_y != NULL)
  185496. *red_y = info_ptr->int_y_red;
  185497. if (green_x != NULL)
  185498. *green_x = info_ptr->int_x_green;
  185499. if (green_y != NULL)
  185500. *green_y = info_ptr->int_y_green;
  185501. if (blue_x != NULL)
  185502. *blue_x = info_ptr->int_x_blue;
  185503. if (blue_y != NULL)
  185504. *blue_y = info_ptr->int_y_blue;
  185505. return (PNG_INFO_cHRM);
  185506. }
  185507. return (0);
  185508. }
  185509. #endif
  185510. #endif
  185511. #if defined(PNG_gAMA_SUPPORTED)
  185512. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185513. png_uint_32 PNGAPI
  185514. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185515. {
  185516. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185517. && file_gamma != NULL)
  185518. {
  185519. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185520. *file_gamma = (double)info_ptr->gamma;
  185521. return (PNG_INFO_gAMA);
  185522. }
  185523. return (0);
  185524. }
  185525. #endif
  185526. #ifdef PNG_FIXED_POINT_SUPPORTED
  185527. png_uint_32 PNGAPI
  185528. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185529. png_fixed_point *int_file_gamma)
  185530. {
  185531. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185532. && int_file_gamma != NULL)
  185533. {
  185534. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185535. *int_file_gamma = info_ptr->int_gamma;
  185536. return (PNG_INFO_gAMA);
  185537. }
  185538. return (0);
  185539. }
  185540. #endif
  185541. #endif
  185542. #if defined(PNG_sRGB_SUPPORTED)
  185543. png_uint_32 PNGAPI
  185544. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185545. {
  185546. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185547. && file_srgb_intent != NULL)
  185548. {
  185549. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185550. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185551. return (PNG_INFO_sRGB);
  185552. }
  185553. return (0);
  185554. }
  185555. #endif
  185556. #if defined(PNG_iCCP_SUPPORTED)
  185557. png_uint_32 PNGAPI
  185558. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185559. png_charpp name, int *compression_type,
  185560. png_charpp profile, png_uint_32 *proflen)
  185561. {
  185562. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185563. && name != NULL && profile != NULL && proflen != NULL)
  185564. {
  185565. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185566. *name = info_ptr->iccp_name;
  185567. *profile = info_ptr->iccp_profile;
  185568. /* compression_type is a dummy so the API won't have to change
  185569. if we introduce multiple compression types later. */
  185570. *proflen = (int)info_ptr->iccp_proflen;
  185571. *compression_type = (int)info_ptr->iccp_compression;
  185572. return (PNG_INFO_iCCP);
  185573. }
  185574. return (0);
  185575. }
  185576. #endif
  185577. #if defined(PNG_sPLT_SUPPORTED)
  185578. png_uint_32 PNGAPI
  185579. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185580. png_sPLT_tpp spalettes)
  185581. {
  185582. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185583. {
  185584. *spalettes = info_ptr->splt_palettes;
  185585. return ((png_uint_32)info_ptr->splt_palettes_num);
  185586. }
  185587. return (0);
  185588. }
  185589. #endif
  185590. #if defined(PNG_hIST_SUPPORTED)
  185591. png_uint_32 PNGAPI
  185592. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185593. {
  185594. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185595. && hist != NULL)
  185596. {
  185597. png_debug1(1, "in %s retrieval function\n", "hIST");
  185598. *hist = info_ptr->hist;
  185599. return (PNG_INFO_hIST);
  185600. }
  185601. return (0);
  185602. }
  185603. #endif
  185604. png_uint_32 PNGAPI
  185605. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185606. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185607. int *color_type, int *interlace_type, int *compression_type,
  185608. int *filter_type)
  185609. {
  185610. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185611. bit_depth != NULL && color_type != NULL)
  185612. {
  185613. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185614. *width = info_ptr->width;
  185615. *height = info_ptr->height;
  185616. *bit_depth = info_ptr->bit_depth;
  185617. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185618. png_error(png_ptr, "Invalid bit depth");
  185619. *color_type = info_ptr->color_type;
  185620. if (info_ptr->color_type > 6)
  185621. png_error(png_ptr, "Invalid color type");
  185622. if (compression_type != NULL)
  185623. *compression_type = info_ptr->compression_type;
  185624. if (filter_type != NULL)
  185625. *filter_type = info_ptr->filter_type;
  185626. if (interlace_type != NULL)
  185627. *interlace_type = info_ptr->interlace_type;
  185628. /* check for potential overflow of rowbytes */
  185629. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185630. png_error(png_ptr, "Invalid image width");
  185631. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185632. png_error(png_ptr, "Invalid image height");
  185633. if (info_ptr->width > (PNG_UINT_32_MAX
  185634. >> 3) /* 8-byte RGBA pixels */
  185635. - 64 /* bigrowbuf hack */
  185636. - 1 /* filter byte */
  185637. - 7*8 /* rounding of width to multiple of 8 pixels */
  185638. - 8) /* extra max_pixel_depth pad */
  185639. {
  185640. png_warning(png_ptr,
  185641. "Width too large for libpng to process image data.");
  185642. }
  185643. return (1);
  185644. }
  185645. return (0);
  185646. }
  185647. #if defined(PNG_oFFs_SUPPORTED)
  185648. png_uint_32 PNGAPI
  185649. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185650. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185651. {
  185652. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185653. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185654. {
  185655. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185656. *offset_x = info_ptr->x_offset;
  185657. *offset_y = info_ptr->y_offset;
  185658. *unit_type = (int)info_ptr->offset_unit_type;
  185659. return (PNG_INFO_oFFs);
  185660. }
  185661. return (0);
  185662. }
  185663. #endif
  185664. #if defined(PNG_pCAL_SUPPORTED)
  185665. png_uint_32 PNGAPI
  185666. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185667. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185668. png_charp *units, png_charpp *params)
  185669. {
  185670. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185671. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185672. nparams != NULL && units != NULL && params != NULL)
  185673. {
  185674. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185675. *purpose = info_ptr->pcal_purpose;
  185676. *X0 = info_ptr->pcal_X0;
  185677. *X1 = info_ptr->pcal_X1;
  185678. *type = (int)info_ptr->pcal_type;
  185679. *nparams = (int)info_ptr->pcal_nparams;
  185680. *units = info_ptr->pcal_units;
  185681. *params = info_ptr->pcal_params;
  185682. return (PNG_INFO_pCAL);
  185683. }
  185684. return (0);
  185685. }
  185686. #endif
  185687. #if defined(PNG_sCAL_SUPPORTED)
  185688. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185689. png_uint_32 PNGAPI
  185690. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185691. int *unit, double *width, double *height)
  185692. {
  185693. if (png_ptr != NULL && info_ptr != NULL &&
  185694. (info_ptr->valid & PNG_INFO_sCAL))
  185695. {
  185696. *unit = info_ptr->scal_unit;
  185697. *width = info_ptr->scal_pixel_width;
  185698. *height = info_ptr->scal_pixel_height;
  185699. return (PNG_INFO_sCAL);
  185700. }
  185701. return(0);
  185702. }
  185703. #else
  185704. #ifdef PNG_FIXED_POINT_SUPPORTED
  185705. png_uint_32 PNGAPI
  185706. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185707. int *unit, png_charpp width, png_charpp height)
  185708. {
  185709. if (png_ptr != NULL && info_ptr != NULL &&
  185710. (info_ptr->valid & PNG_INFO_sCAL))
  185711. {
  185712. *unit = info_ptr->scal_unit;
  185713. *width = info_ptr->scal_s_width;
  185714. *height = info_ptr->scal_s_height;
  185715. return (PNG_INFO_sCAL);
  185716. }
  185717. return(0);
  185718. }
  185719. #endif
  185720. #endif
  185721. #endif
  185722. #if defined(PNG_pHYs_SUPPORTED)
  185723. png_uint_32 PNGAPI
  185724. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185725. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185726. {
  185727. png_uint_32 retval = 0;
  185728. if (png_ptr != NULL && info_ptr != NULL &&
  185729. (info_ptr->valid & PNG_INFO_pHYs))
  185730. {
  185731. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185732. if (res_x != NULL)
  185733. {
  185734. *res_x = info_ptr->x_pixels_per_unit;
  185735. retval |= PNG_INFO_pHYs;
  185736. }
  185737. if (res_y != NULL)
  185738. {
  185739. *res_y = info_ptr->y_pixels_per_unit;
  185740. retval |= PNG_INFO_pHYs;
  185741. }
  185742. if (unit_type != NULL)
  185743. {
  185744. *unit_type = (int)info_ptr->phys_unit_type;
  185745. retval |= PNG_INFO_pHYs;
  185746. }
  185747. }
  185748. return (retval);
  185749. }
  185750. #endif
  185751. png_uint_32 PNGAPI
  185752. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185753. int *num_palette)
  185754. {
  185755. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185756. && palette != NULL)
  185757. {
  185758. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185759. *palette = info_ptr->palette;
  185760. *num_palette = info_ptr->num_palette;
  185761. png_debug1(3, "num_palette = %d\n", *num_palette);
  185762. return (PNG_INFO_PLTE);
  185763. }
  185764. return (0);
  185765. }
  185766. #if defined(PNG_sBIT_SUPPORTED)
  185767. png_uint_32 PNGAPI
  185768. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185769. {
  185770. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185771. && sig_bit != NULL)
  185772. {
  185773. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185774. *sig_bit = &(info_ptr->sig_bit);
  185775. return (PNG_INFO_sBIT);
  185776. }
  185777. return (0);
  185778. }
  185779. #endif
  185780. #if defined(PNG_TEXT_SUPPORTED)
  185781. png_uint_32 PNGAPI
  185782. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185783. int *num_text)
  185784. {
  185785. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185786. {
  185787. png_debug1(1, "in %s retrieval function\n",
  185788. (png_ptr->chunk_name[0] == '\0' ? "text"
  185789. : (png_const_charp)png_ptr->chunk_name));
  185790. if (text_ptr != NULL)
  185791. *text_ptr = info_ptr->text;
  185792. if (num_text != NULL)
  185793. *num_text = info_ptr->num_text;
  185794. return ((png_uint_32)info_ptr->num_text);
  185795. }
  185796. if (num_text != NULL)
  185797. *num_text = 0;
  185798. return(0);
  185799. }
  185800. #endif
  185801. #if defined(PNG_tIME_SUPPORTED)
  185802. png_uint_32 PNGAPI
  185803. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185804. {
  185805. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185806. && mod_time != NULL)
  185807. {
  185808. png_debug1(1, "in %s retrieval function\n", "tIME");
  185809. *mod_time = &(info_ptr->mod_time);
  185810. return (PNG_INFO_tIME);
  185811. }
  185812. return (0);
  185813. }
  185814. #endif
  185815. #if defined(PNG_tRNS_SUPPORTED)
  185816. png_uint_32 PNGAPI
  185817. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  185818. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  185819. {
  185820. png_uint_32 retval = 0;
  185821. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  185822. {
  185823. png_debug1(1, "in %s retrieval function\n", "tRNS");
  185824. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185825. {
  185826. if (trans != NULL)
  185827. {
  185828. *trans = info_ptr->trans;
  185829. retval |= PNG_INFO_tRNS;
  185830. }
  185831. if (trans_values != NULL)
  185832. *trans_values = &(info_ptr->trans_values);
  185833. }
  185834. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  185835. {
  185836. if (trans_values != NULL)
  185837. {
  185838. *trans_values = &(info_ptr->trans_values);
  185839. retval |= PNG_INFO_tRNS;
  185840. }
  185841. if(trans != NULL)
  185842. *trans = NULL;
  185843. }
  185844. if(num_trans != NULL)
  185845. {
  185846. *num_trans = info_ptr->num_trans;
  185847. retval |= PNG_INFO_tRNS;
  185848. }
  185849. }
  185850. return (retval);
  185851. }
  185852. #endif
  185853. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185854. png_uint_32 PNGAPI
  185855. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  185856. png_unknown_chunkpp unknowns)
  185857. {
  185858. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  185859. {
  185860. *unknowns = info_ptr->unknown_chunks;
  185861. return ((png_uint_32)info_ptr->unknown_chunks_num);
  185862. }
  185863. return (0);
  185864. }
  185865. #endif
  185866. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185867. png_byte PNGAPI
  185868. png_get_rgb_to_gray_status (png_structp png_ptr)
  185869. {
  185870. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  185871. }
  185872. #endif
  185873. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  185874. png_voidp PNGAPI
  185875. png_get_user_chunk_ptr(png_structp png_ptr)
  185876. {
  185877. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  185878. }
  185879. #endif
  185880. #ifdef PNG_WRITE_SUPPORTED
  185881. png_uint_32 PNGAPI
  185882. png_get_compression_buffer_size(png_structp png_ptr)
  185883. {
  185884. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  185885. }
  185886. #endif
  185887. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  185888. #ifndef PNG_1_0_X
  185889. /* this function was added to libpng 1.2.0 and should exist by default */
  185890. png_uint_32 PNGAPI
  185891. png_get_asm_flags (png_structp png_ptr)
  185892. {
  185893. /* obsolete, to be removed from libpng-1.4.0 */
  185894. return (png_ptr? 0L: 0L);
  185895. }
  185896. /* this function was added to libpng 1.2.0 and should exist by default */
  185897. png_uint_32 PNGAPI
  185898. png_get_asm_flagmask (int flag_select)
  185899. {
  185900. /* obsolete, to be removed from libpng-1.4.0 */
  185901. flag_select=flag_select;
  185902. return 0L;
  185903. }
  185904. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  185905. /* this function was added to libpng 1.2.0 */
  185906. png_uint_32 PNGAPI
  185907. png_get_mmx_flagmask (int flag_select, int *compilerID)
  185908. {
  185909. /* obsolete, to be removed from libpng-1.4.0 */
  185910. flag_select=flag_select;
  185911. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  185912. return 0L;
  185913. }
  185914. /* this function was added to libpng 1.2.0 */
  185915. png_byte PNGAPI
  185916. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  185917. {
  185918. /* obsolete, to be removed from libpng-1.4.0 */
  185919. return (png_ptr? 0: 0);
  185920. }
  185921. /* this function was added to libpng 1.2.0 */
  185922. png_uint_32 PNGAPI
  185923. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  185924. {
  185925. /* obsolete, to be removed from libpng-1.4.0 */
  185926. return (png_ptr? 0L: 0L);
  185927. }
  185928. #endif /* ?PNG_1_0_X */
  185929. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  185930. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185931. /* these functions were added to libpng 1.2.6 */
  185932. png_uint_32 PNGAPI
  185933. png_get_user_width_max (png_structp png_ptr)
  185934. {
  185935. return (png_ptr? png_ptr->user_width_max : 0);
  185936. }
  185937. png_uint_32 PNGAPI
  185938. png_get_user_height_max (png_structp png_ptr)
  185939. {
  185940. return (png_ptr? png_ptr->user_height_max : 0);
  185941. }
  185942. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  185943. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185944. /*** End of inlined file: pngget.c ***/
  185945. /*** Start of inlined file: pngmem.c ***/
  185946. /* pngmem.c - stub functions for memory allocation
  185947. *
  185948. * Last changed in libpng 1.2.13 November 13, 2006
  185949. * For conditions of distribution and use, see copyright notice in png.h
  185950. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185951. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185952. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185953. *
  185954. * This file provides a location for all memory allocation. Users who
  185955. * need special memory handling are expected to supply replacement
  185956. * functions for png_malloc() and png_free(), and to use
  185957. * png_create_read_struct_2() and png_create_write_struct_2() to
  185958. * identify the replacement functions.
  185959. */
  185960. #define PNG_INTERNAL
  185961. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185962. /* Borland DOS special memory handler */
  185963. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  185964. /* if you change this, be sure to change the one in png.h also */
  185965. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  185966. by a single call to calloc() if this is thought to improve performance. */
  185967. png_voidp /* PRIVATE */
  185968. png_create_struct(int type)
  185969. {
  185970. #ifdef PNG_USER_MEM_SUPPORTED
  185971. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185972. }
  185973. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  185974. png_voidp /* PRIVATE */
  185975. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185976. {
  185977. #endif /* PNG_USER_MEM_SUPPORTED */
  185978. png_size_t size;
  185979. png_voidp struct_ptr;
  185980. if (type == PNG_STRUCT_INFO)
  185981. size = png_sizeof(png_info);
  185982. else if (type == PNG_STRUCT_PNG)
  185983. size = png_sizeof(png_struct);
  185984. else
  185985. return (png_get_copyright(NULL));
  185986. #ifdef PNG_USER_MEM_SUPPORTED
  185987. if(malloc_fn != NULL)
  185988. {
  185989. png_struct dummy_struct;
  185990. png_structp png_ptr = &dummy_struct;
  185991. png_ptr->mem_ptr=mem_ptr;
  185992. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  185993. }
  185994. else
  185995. #endif /* PNG_USER_MEM_SUPPORTED */
  185996. struct_ptr = (png_voidp)farmalloc(size);
  185997. if (struct_ptr != NULL)
  185998. png_memset(struct_ptr, 0, size);
  185999. return (struct_ptr);
  186000. }
  186001. /* Free memory allocated by a png_create_struct() call */
  186002. void /* PRIVATE */
  186003. png_destroy_struct(png_voidp struct_ptr)
  186004. {
  186005. #ifdef PNG_USER_MEM_SUPPORTED
  186006. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186007. }
  186008. /* Free memory allocated by a png_create_struct() call */
  186009. void /* PRIVATE */
  186010. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186011. png_voidp mem_ptr)
  186012. {
  186013. #endif
  186014. if (struct_ptr != NULL)
  186015. {
  186016. #ifdef PNG_USER_MEM_SUPPORTED
  186017. if(free_fn != NULL)
  186018. {
  186019. png_struct dummy_struct;
  186020. png_structp png_ptr = &dummy_struct;
  186021. png_ptr->mem_ptr=mem_ptr;
  186022. (*(free_fn))(png_ptr, struct_ptr);
  186023. return;
  186024. }
  186025. #endif /* PNG_USER_MEM_SUPPORTED */
  186026. farfree (struct_ptr);
  186027. }
  186028. }
  186029. /* Allocate memory. For reasonable files, size should never exceed
  186030. * 64K. However, zlib may allocate more then 64K if you don't tell
  186031. * it not to. See zconf.h and png.h for more information. zlib does
  186032. * need to allocate exactly 64K, so whatever you call here must
  186033. * have the ability to do that.
  186034. *
  186035. * Borland seems to have a problem in DOS mode for exactly 64K.
  186036. * It gives you a segment with an offset of 8 (perhaps to store its
  186037. * memory stuff). zlib doesn't like this at all, so we have to
  186038. * detect and deal with it. This code should not be needed in
  186039. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186040. * been updated by Alexander Lehmann for version 0.89 to waste less
  186041. * memory.
  186042. *
  186043. * Note that we can't use png_size_t for the "size" declaration,
  186044. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186045. * result, we would be truncating potentially larger memory requests
  186046. * (which should cause a fatal error) and introducing major problems.
  186047. */
  186048. png_voidp PNGAPI
  186049. png_malloc(png_structp png_ptr, png_uint_32 size)
  186050. {
  186051. png_voidp ret;
  186052. if (png_ptr == NULL || size == 0)
  186053. return (NULL);
  186054. #ifdef PNG_USER_MEM_SUPPORTED
  186055. if(png_ptr->malloc_fn != NULL)
  186056. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186057. else
  186058. ret = (png_malloc_default(png_ptr, size));
  186059. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186060. png_error(png_ptr, "Out of memory!");
  186061. return (ret);
  186062. }
  186063. png_voidp PNGAPI
  186064. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186065. {
  186066. png_voidp ret;
  186067. #endif /* PNG_USER_MEM_SUPPORTED */
  186068. if (png_ptr == NULL || size == 0)
  186069. return (NULL);
  186070. #ifdef PNG_MAX_MALLOC_64K
  186071. if (size > (png_uint_32)65536L)
  186072. {
  186073. png_warning(png_ptr, "Cannot Allocate > 64K");
  186074. ret = NULL;
  186075. }
  186076. else
  186077. #endif
  186078. if (size != (size_t)size)
  186079. ret = NULL;
  186080. else if (size == (png_uint_32)65536L)
  186081. {
  186082. if (png_ptr->offset_table == NULL)
  186083. {
  186084. /* try to see if we need to do any of this fancy stuff */
  186085. ret = farmalloc(size);
  186086. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186087. {
  186088. int num_blocks;
  186089. png_uint_32 total_size;
  186090. png_bytep table;
  186091. int i;
  186092. png_byte huge * hptr;
  186093. if (ret != NULL)
  186094. {
  186095. farfree(ret);
  186096. ret = NULL;
  186097. }
  186098. if(png_ptr->zlib_window_bits > 14)
  186099. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186100. else
  186101. num_blocks = 1;
  186102. if (png_ptr->zlib_mem_level >= 7)
  186103. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186104. else
  186105. num_blocks++;
  186106. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186107. table = farmalloc(total_size);
  186108. if (table == NULL)
  186109. {
  186110. #ifndef PNG_USER_MEM_SUPPORTED
  186111. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186112. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186113. else
  186114. png_warning(png_ptr, "Out Of Memory.");
  186115. #endif
  186116. return (NULL);
  186117. }
  186118. if ((png_size_t)table & 0xfff0)
  186119. {
  186120. #ifndef PNG_USER_MEM_SUPPORTED
  186121. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186122. png_error(png_ptr,
  186123. "Farmalloc didn't return normalized pointer");
  186124. else
  186125. png_warning(png_ptr,
  186126. "Farmalloc didn't return normalized pointer");
  186127. #endif
  186128. return (NULL);
  186129. }
  186130. png_ptr->offset_table = table;
  186131. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186132. png_sizeof (png_bytep));
  186133. if (png_ptr->offset_table_ptr == NULL)
  186134. {
  186135. #ifndef PNG_USER_MEM_SUPPORTED
  186136. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186137. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186138. else
  186139. png_warning(png_ptr, "Out Of memory.");
  186140. #endif
  186141. return (NULL);
  186142. }
  186143. hptr = (png_byte huge *)table;
  186144. if ((png_size_t)hptr & 0xf)
  186145. {
  186146. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186147. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186148. }
  186149. for (i = 0; i < num_blocks; i++)
  186150. {
  186151. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186152. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186153. }
  186154. png_ptr->offset_table_number = num_blocks;
  186155. png_ptr->offset_table_count = 0;
  186156. png_ptr->offset_table_count_free = 0;
  186157. }
  186158. }
  186159. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186160. {
  186161. #ifndef PNG_USER_MEM_SUPPORTED
  186162. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186163. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186164. else
  186165. png_warning(png_ptr, "Out of Memory.");
  186166. #endif
  186167. return (NULL);
  186168. }
  186169. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186170. }
  186171. else
  186172. ret = farmalloc(size);
  186173. #ifndef PNG_USER_MEM_SUPPORTED
  186174. if (ret == NULL)
  186175. {
  186176. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186177. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186178. else
  186179. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186180. }
  186181. #endif
  186182. return (ret);
  186183. }
  186184. /* free a pointer allocated by png_malloc(). In the default
  186185. configuration, png_ptr is not used, but is passed in case it
  186186. is needed. If ptr is NULL, return without taking any action. */
  186187. void PNGAPI
  186188. png_free(png_structp png_ptr, png_voidp ptr)
  186189. {
  186190. if (png_ptr == NULL || ptr == NULL)
  186191. return;
  186192. #ifdef PNG_USER_MEM_SUPPORTED
  186193. if (png_ptr->free_fn != NULL)
  186194. {
  186195. (*(png_ptr->free_fn))(png_ptr, ptr);
  186196. return;
  186197. }
  186198. else png_free_default(png_ptr, ptr);
  186199. }
  186200. void PNGAPI
  186201. png_free_default(png_structp png_ptr, png_voidp ptr)
  186202. {
  186203. #endif /* PNG_USER_MEM_SUPPORTED */
  186204. if(png_ptr == NULL) return;
  186205. if (png_ptr->offset_table != NULL)
  186206. {
  186207. int i;
  186208. for (i = 0; i < png_ptr->offset_table_count; i++)
  186209. {
  186210. if (ptr == png_ptr->offset_table_ptr[i])
  186211. {
  186212. ptr = NULL;
  186213. png_ptr->offset_table_count_free++;
  186214. break;
  186215. }
  186216. }
  186217. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186218. {
  186219. farfree(png_ptr->offset_table);
  186220. farfree(png_ptr->offset_table_ptr);
  186221. png_ptr->offset_table = NULL;
  186222. png_ptr->offset_table_ptr = NULL;
  186223. }
  186224. }
  186225. if (ptr != NULL)
  186226. {
  186227. farfree(ptr);
  186228. }
  186229. }
  186230. #else /* Not the Borland DOS special memory handler */
  186231. /* Allocate memory for a png_struct or a png_info. The malloc and
  186232. memset can be replaced by a single call to calloc() if this is thought
  186233. to improve performance noticably. */
  186234. png_voidp /* PRIVATE */
  186235. png_create_struct(int type)
  186236. {
  186237. #ifdef PNG_USER_MEM_SUPPORTED
  186238. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186239. }
  186240. /* Allocate memory for a png_struct or a png_info. The malloc and
  186241. memset can be replaced by a single call to calloc() if this is thought
  186242. to improve performance noticably. */
  186243. png_voidp /* PRIVATE */
  186244. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186245. {
  186246. #endif /* PNG_USER_MEM_SUPPORTED */
  186247. png_size_t size;
  186248. png_voidp struct_ptr;
  186249. if (type == PNG_STRUCT_INFO)
  186250. size = png_sizeof(png_info);
  186251. else if (type == PNG_STRUCT_PNG)
  186252. size = png_sizeof(png_struct);
  186253. else
  186254. return (NULL);
  186255. #ifdef PNG_USER_MEM_SUPPORTED
  186256. if(malloc_fn != NULL)
  186257. {
  186258. png_struct dummy_struct;
  186259. png_structp png_ptr = &dummy_struct;
  186260. png_ptr->mem_ptr=mem_ptr;
  186261. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186262. if (struct_ptr != NULL)
  186263. png_memset(struct_ptr, 0, size);
  186264. return (struct_ptr);
  186265. }
  186266. #endif /* PNG_USER_MEM_SUPPORTED */
  186267. #if defined(__TURBOC__) && !defined(__FLAT__)
  186268. struct_ptr = (png_voidp)farmalloc(size);
  186269. #else
  186270. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186271. struct_ptr = (png_voidp)halloc(size,1);
  186272. # else
  186273. struct_ptr = (png_voidp)malloc(size);
  186274. # endif
  186275. #endif
  186276. if (struct_ptr != NULL)
  186277. png_memset(struct_ptr, 0, size);
  186278. return (struct_ptr);
  186279. }
  186280. /* Free memory allocated by a png_create_struct() call */
  186281. void /* PRIVATE */
  186282. png_destroy_struct(png_voidp struct_ptr)
  186283. {
  186284. #ifdef PNG_USER_MEM_SUPPORTED
  186285. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186286. }
  186287. /* Free memory allocated by a png_create_struct() call */
  186288. void /* PRIVATE */
  186289. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186290. png_voidp mem_ptr)
  186291. {
  186292. #endif /* PNG_USER_MEM_SUPPORTED */
  186293. if (struct_ptr != NULL)
  186294. {
  186295. #ifdef PNG_USER_MEM_SUPPORTED
  186296. if(free_fn != NULL)
  186297. {
  186298. png_struct dummy_struct;
  186299. png_structp png_ptr = &dummy_struct;
  186300. png_ptr->mem_ptr=mem_ptr;
  186301. (*(free_fn))(png_ptr, struct_ptr);
  186302. return;
  186303. }
  186304. #endif /* PNG_USER_MEM_SUPPORTED */
  186305. #if defined(__TURBOC__) && !defined(__FLAT__)
  186306. farfree(struct_ptr);
  186307. #else
  186308. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186309. hfree(struct_ptr);
  186310. # else
  186311. free(struct_ptr);
  186312. # endif
  186313. #endif
  186314. }
  186315. }
  186316. /* Allocate memory. For reasonable files, size should never exceed
  186317. 64K. However, zlib may allocate more then 64K if you don't tell
  186318. it not to. See zconf.h and png.h for more information. zlib does
  186319. need to allocate exactly 64K, so whatever you call here must
  186320. have the ability to do that. */
  186321. png_voidp PNGAPI
  186322. png_malloc(png_structp png_ptr, png_uint_32 size)
  186323. {
  186324. png_voidp ret;
  186325. #ifdef PNG_USER_MEM_SUPPORTED
  186326. if (png_ptr == NULL || size == 0)
  186327. return (NULL);
  186328. if(png_ptr->malloc_fn != NULL)
  186329. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186330. else
  186331. ret = (png_malloc_default(png_ptr, size));
  186332. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186333. png_error(png_ptr, "Out of Memory!");
  186334. return (ret);
  186335. }
  186336. png_voidp PNGAPI
  186337. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186338. {
  186339. png_voidp ret;
  186340. #endif /* PNG_USER_MEM_SUPPORTED */
  186341. if (png_ptr == NULL || size == 0)
  186342. return (NULL);
  186343. #ifdef PNG_MAX_MALLOC_64K
  186344. if (size > (png_uint_32)65536L)
  186345. {
  186346. #ifndef PNG_USER_MEM_SUPPORTED
  186347. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186348. png_error(png_ptr, "Cannot Allocate > 64K");
  186349. else
  186350. #endif
  186351. return NULL;
  186352. }
  186353. #endif
  186354. /* Check for overflow */
  186355. #if defined(__TURBOC__) && !defined(__FLAT__)
  186356. if (size != (unsigned long)size)
  186357. ret = NULL;
  186358. else
  186359. ret = farmalloc(size);
  186360. #else
  186361. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186362. if (size != (unsigned long)size)
  186363. ret = NULL;
  186364. else
  186365. ret = halloc(size, 1);
  186366. # else
  186367. if (size != (size_t)size)
  186368. ret = NULL;
  186369. else
  186370. ret = malloc((size_t)size);
  186371. # endif
  186372. #endif
  186373. #ifndef PNG_USER_MEM_SUPPORTED
  186374. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186375. png_error(png_ptr, "Out of Memory");
  186376. #endif
  186377. return (ret);
  186378. }
  186379. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186380. without taking any action. */
  186381. void PNGAPI
  186382. png_free(png_structp png_ptr, png_voidp ptr)
  186383. {
  186384. if (png_ptr == NULL || ptr == NULL)
  186385. return;
  186386. #ifdef PNG_USER_MEM_SUPPORTED
  186387. if (png_ptr->free_fn != NULL)
  186388. {
  186389. (*(png_ptr->free_fn))(png_ptr, ptr);
  186390. return;
  186391. }
  186392. else png_free_default(png_ptr, ptr);
  186393. }
  186394. void PNGAPI
  186395. png_free_default(png_structp png_ptr, png_voidp ptr)
  186396. {
  186397. if (png_ptr == NULL || ptr == NULL)
  186398. return;
  186399. #endif /* PNG_USER_MEM_SUPPORTED */
  186400. #if defined(__TURBOC__) && !defined(__FLAT__)
  186401. farfree(ptr);
  186402. #else
  186403. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186404. hfree(ptr);
  186405. # else
  186406. free(ptr);
  186407. # endif
  186408. #endif
  186409. }
  186410. #endif /* Not Borland DOS special memory handler */
  186411. #if defined(PNG_1_0_X)
  186412. # define png_malloc_warn png_malloc
  186413. #else
  186414. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186415. * function will set up png_malloc() to issue a png_warning and return NULL
  186416. * instead of issuing a png_error, if it fails to allocate the requested
  186417. * memory.
  186418. */
  186419. png_voidp PNGAPI
  186420. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186421. {
  186422. png_voidp ptr;
  186423. png_uint_32 save_flags;
  186424. if(png_ptr == NULL) return (NULL);
  186425. save_flags=png_ptr->flags;
  186426. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186427. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186428. png_ptr->flags=save_flags;
  186429. return(ptr);
  186430. }
  186431. #endif
  186432. png_voidp PNGAPI
  186433. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186434. png_uint_32 length)
  186435. {
  186436. png_size_t size;
  186437. size = (png_size_t)length;
  186438. if ((png_uint_32)size != length)
  186439. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186440. return(png_memcpy (s1, s2, size));
  186441. }
  186442. png_voidp PNGAPI
  186443. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186444. png_uint_32 length)
  186445. {
  186446. png_size_t size;
  186447. size = (png_size_t)length;
  186448. if ((png_uint_32)size != length)
  186449. png_error(png_ptr,"Overflow in png_memset_check.");
  186450. return (png_memset (s1, value, size));
  186451. }
  186452. #ifdef PNG_USER_MEM_SUPPORTED
  186453. /* This function is called when the application wants to use another method
  186454. * of allocating and freeing memory.
  186455. */
  186456. void PNGAPI
  186457. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186458. malloc_fn, png_free_ptr free_fn)
  186459. {
  186460. if(png_ptr != NULL) {
  186461. png_ptr->mem_ptr = mem_ptr;
  186462. png_ptr->malloc_fn = malloc_fn;
  186463. png_ptr->free_fn = free_fn;
  186464. }
  186465. }
  186466. /* This function returns a pointer to the mem_ptr associated with the user
  186467. * functions. The application should free any memory associated with this
  186468. * pointer before png_write_destroy and png_read_destroy are called.
  186469. */
  186470. png_voidp PNGAPI
  186471. png_get_mem_ptr(png_structp png_ptr)
  186472. {
  186473. if(png_ptr == NULL) return (NULL);
  186474. return ((png_voidp)png_ptr->mem_ptr);
  186475. }
  186476. #endif /* PNG_USER_MEM_SUPPORTED */
  186477. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186478. /*** End of inlined file: pngmem.c ***/
  186479. /*** Start of inlined file: pngread.c ***/
  186480. /* pngread.c - read a PNG file
  186481. *
  186482. * Last changed in libpng 1.2.20 September 7, 2007
  186483. * For conditions of distribution and use, see copyright notice in png.h
  186484. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186485. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186486. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186487. *
  186488. * This file contains routines that an application calls directly to
  186489. * read a PNG file or stream.
  186490. */
  186491. #define PNG_INTERNAL
  186492. #if defined(PNG_READ_SUPPORTED)
  186493. /* Create a PNG structure for reading, and allocate any memory needed. */
  186494. png_structp PNGAPI
  186495. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186496. png_error_ptr error_fn, png_error_ptr warn_fn)
  186497. {
  186498. #ifdef PNG_USER_MEM_SUPPORTED
  186499. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186500. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186501. }
  186502. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186503. png_structp PNGAPI
  186504. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186505. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186506. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186507. {
  186508. #endif /* PNG_USER_MEM_SUPPORTED */
  186509. png_structp png_ptr;
  186510. #ifdef PNG_SETJMP_SUPPORTED
  186511. #ifdef USE_FAR_KEYWORD
  186512. jmp_buf jmpbuf;
  186513. #endif
  186514. #endif
  186515. int i;
  186516. png_debug(1, "in png_create_read_struct\n");
  186517. #ifdef PNG_USER_MEM_SUPPORTED
  186518. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186519. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186520. #else
  186521. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186522. #endif
  186523. if (png_ptr == NULL)
  186524. return (NULL);
  186525. /* added at libpng-1.2.6 */
  186526. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186527. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186528. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186529. #endif
  186530. #ifdef PNG_SETJMP_SUPPORTED
  186531. #ifdef USE_FAR_KEYWORD
  186532. if (setjmp(jmpbuf))
  186533. #else
  186534. if (setjmp(png_ptr->jmpbuf))
  186535. #endif
  186536. {
  186537. png_free(png_ptr, png_ptr->zbuf);
  186538. png_ptr->zbuf=NULL;
  186539. #ifdef PNG_USER_MEM_SUPPORTED
  186540. png_destroy_struct_2((png_voidp)png_ptr,
  186541. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186542. #else
  186543. png_destroy_struct((png_voidp)png_ptr);
  186544. #endif
  186545. return (NULL);
  186546. }
  186547. #ifdef USE_FAR_KEYWORD
  186548. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186549. #endif
  186550. #endif
  186551. #ifdef PNG_USER_MEM_SUPPORTED
  186552. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186553. #endif
  186554. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186555. i=0;
  186556. do
  186557. {
  186558. if(user_png_ver[i] != png_libpng_ver[i])
  186559. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186560. } while (png_libpng_ver[i++]);
  186561. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186562. {
  186563. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186564. * we must recompile any applications that use any older library version.
  186565. * For versions after libpng 1.0, we will be compatible, so we need
  186566. * only check the first digit.
  186567. */
  186568. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186569. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186570. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186571. {
  186572. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186573. char msg[80];
  186574. if (user_png_ver)
  186575. {
  186576. png_snprintf(msg, 80,
  186577. "Application was compiled with png.h from libpng-%.20s",
  186578. user_png_ver);
  186579. png_warning(png_ptr, msg);
  186580. }
  186581. png_snprintf(msg, 80,
  186582. "Application is running with png.c from libpng-%.20s",
  186583. png_libpng_ver);
  186584. png_warning(png_ptr, msg);
  186585. #endif
  186586. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186587. png_ptr->flags=0;
  186588. #endif
  186589. png_error(png_ptr,
  186590. "Incompatible libpng version in application and library");
  186591. }
  186592. }
  186593. /* initialize zbuf - compression buffer */
  186594. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186595. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186596. (png_uint_32)png_ptr->zbuf_size);
  186597. png_ptr->zstream.zalloc = png_zalloc;
  186598. png_ptr->zstream.zfree = png_zfree;
  186599. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186600. switch (inflateInit(&png_ptr->zstream))
  186601. {
  186602. case Z_OK: /* Do nothing */ break;
  186603. case Z_MEM_ERROR:
  186604. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186605. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186606. default: png_error(png_ptr, "Unknown zlib error");
  186607. }
  186608. png_ptr->zstream.next_out = png_ptr->zbuf;
  186609. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186610. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186611. #ifdef PNG_SETJMP_SUPPORTED
  186612. /* Applications that neglect to set up their own setjmp() and then encounter
  186613. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186614. abort instead of returning. */
  186615. #ifdef USE_FAR_KEYWORD
  186616. if (setjmp(jmpbuf))
  186617. PNG_ABORT();
  186618. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186619. #else
  186620. if (setjmp(png_ptr->jmpbuf))
  186621. PNG_ABORT();
  186622. #endif
  186623. #endif
  186624. return (png_ptr);
  186625. }
  186626. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186627. /* Initialize PNG structure for reading, and allocate any memory needed.
  186628. This interface is deprecated in favour of the png_create_read_struct(),
  186629. and it will disappear as of libpng-1.3.0. */
  186630. #undef png_read_init
  186631. void PNGAPI
  186632. png_read_init(png_structp png_ptr)
  186633. {
  186634. /* We only come here via pre-1.0.7-compiled applications */
  186635. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186636. }
  186637. void PNGAPI
  186638. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186639. png_size_t png_struct_size, png_size_t png_info_size)
  186640. {
  186641. /* We only come here via pre-1.0.12-compiled applications */
  186642. if(png_ptr == NULL) return;
  186643. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186644. if(png_sizeof(png_struct) > png_struct_size ||
  186645. png_sizeof(png_info) > png_info_size)
  186646. {
  186647. char msg[80];
  186648. png_ptr->warning_fn=NULL;
  186649. if (user_png_ver)
  186650. {
  186651. png_snprintf(msg, 80,
  186652. "Application was compiled with png.h from libpng-%.20s",
  186653. user_png_ver);
  186654. png_warning(png_ptr, msg);
  186655. }
  186656. png_snprintf(msg, 80,
  186657. "Application is running with png.c from libpng-%.20s",
  186658. png_libpng_ver);
  186659. png_warning(png_ptr, msg);
  186660. }
  186661. #endif
  186662. if(png_sizeof(png_struct) > png_struct_size)
  186663. {
  186664. png_ptr->error_fn=NULL;
  186665. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186666. png_ptr->flags=0;
  186667. #endif
  186668. png_error(png_ptr,
  186669. "The png struct allocated by the application for reading is too small.");
  186670. }
  186671. if(png_sizeof(png_info) > png_info_size)
  186672. {
  186673. png_ptr->error_fn=NULL;
  186674. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186675. png_ptr->flags=0;
  186676. #endif
  186677. png_error(png_ptr,
  186678. "The info struct allocated by application for reading is too small.");
  186679. }
  186680. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186681. }
  186682. #endif /* PNG_1_0_X || PNG_1_2_X */
  186683. void PNGAPI
  186684. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186685. png_size_t png_struct_size)
  186686. {
  186687. #ifdef PNG_SETJMP_SUPPORTED
  186688. jmp_buf tmp_jmp; /* to save current jump buffer */
  186689. #endif
  186690. int i=0;
  186691. png_structp png_ptr=*ptr_ptr;
  186692. if(png_ptr == NULL) return;
  186693. do
  186694. {
  186695. if(user_png_ver[i] != png_libpng_ver[i])
  186696. {
  186697. #ifdef PNG_LEGACY_SUPPORTED
  186698. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186699. #else
  186700. png_ptr->warning_fn=NULL;
  186701. png_warning(png_ptr,
  186702. "Application uses deprecated png_read_init() and should be recompiled.");
  186703. break;
  186704. #endif
  186705. }
  186706. } while (png_libpng_ver[i++]);
  186707. png_debug(1, "in png_read_init_3\n");
  186708. #ifdef PNG_SETJMP_SUPPORTED
  186709. /* save jump buffer and error functions */
  186710. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186711. #endif
  186712. if(png_sizeof(png_struct) > png_struct_size)
  186713. {
  186714. png_destroy_struct(png_ptr);
  186715. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186716. png_ptr = *ptr_ptr;
  186717. }
  186718. /* reset all variables to 0 */
  186719. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186720. #ifdef PNG_SETJMP_SUPPORTED
  186721. /* restore jump buffer */
  186722. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186723. #endif
  186724. /* added at libpng-1.2.6 */
  186725. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186726. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186727. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186728. #endif
  186729. /* initialize zbuf - compression buffer */
  186730. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186731. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186732. (png_uint_32)png_ptr->zbuf_size);
  186733. png_ptr->zstream.zalloc = png_zalloc;
  186734. png_ptr->zstream.zfree = png_zfree;
  186735. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186736. switch (inflateInit(&png_ptr->zstream))
  186737. {
  186738. case Z_OK: /* Do nothing */ break;
  186739. case Z_MEM_ERROR:
  186740. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186741. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186742. default: png_error(png_ptr, "Unknown zlib error");
  186743. }
  186744. png_ptr->zstream.next_out = png_ptr->zbuf;
  186745. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186746. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186747. }
  186748. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186749. /* Read the information before the actual image data. This has been
  186750. * changed in v0.90 to allow reading a file that already has the magic
  186751. * bytes read from the stream. You can tell libpng how many bytes have
  186752. * been read from the beginning of the stream (up to the maximum of 8)
  186753. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186754. * here. The application can then have access to the signature bytes we
  186755. * read if it is determined that this isn't a valid PNG file.
  186756. */
  186757. void PNGAPI
  186758. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186759. {
  186760. if(png_ptr == NULL) return;
  186761. png_debug(1, "in png_read_info\n");
  186762. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186763. if (png_ptr->sig_bytes < 8)
  186764. {
  186765. png_size_t num_checked = png_ptr->sig_bytes,
  186766. num_to_check = 8 - num_checked;
  186767. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186768. png_ptr->sig_bytes = 8;
  186769. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186770. {
  186771. if (num_checked < 4 &&
  186772. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186773. png_error(png_ptr, "Not a PNG file");
  186774. else
  186775. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186776. }
  186777. if (num_checked < 3)
  186778. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186779. }
  186780. for(;;)
  186781. {
  186782. #ifdef PNG_USE_LOCAL_ARRAYS
  186783. PNG_CONST PNG_IHDR;
  186784. PNG_CONST PNG_IDAT;
  186785. PNG_CONST PNG_IEND;
  186786. PNG_CONST PNG_PLTE;
  186787. #if defined(PNG_READ_bKGD_SUPPORTED)
  186788. PNG_CONST PNG_bKGD;
  186789. #endif
  186790. #if defined(PNG_READ_cHRM_SUPPORTED)
  186791. PNG_CONST PNG_cHRM;
  186792. #endif
  186793. #if defined(PNG_READ_gAMA_SUPPORTED)
  186794. PNG_CONST PNG_gAMA;
  186795. #endif
  186796. #if defined(PNG_READ_hIST_SUPPORTED)
  186797. PNG_CONST PNG_hIST;
  186798. #endif
  186799. #if defined(PNG_READ_iCCP_SUPPORTED)
  186800. PNG_CONST PNG_iCCP;
  186801. #endif
  186802. #if defined(PNG_READ_iTXt_SUPPORTED)
  186803. PNG_CONST PNG_iTXt;
  186804. #endif
  186805. #if defined(PNG_READ_oFFs_SUPPORTED)
  186806. PNG_CONST PNG_oFFs;
  186807. #endif
  186808. #if defined(PNG_READ_pCAL_SUPPORTED)
  186809. PNG_CONST PNG_pCAL;
  186810. #endif
  186811. #if defined(PNG_READ_pHYs_SUPPORTED)
  186812. PNG_CONST PNG_pHYs;
  186813. #endif
  186814. #if defined(PNG_READ_sBIT_SUPPORTED)
  186815. PNG_CONST PNG_sBIT;
  186816. #endif
  186817. #if defined(PNG_READ_sCAL_SUPPORTED)
  186818. PNG_CONST PNG_sCAL;
  186819. #endif
  186820. #if defined(PNG_READ_sPLT_SUPPORTED)
  186821. PNG_CONST PNG_sPLT;
  186822. #endif
  186823. #if defined(PNG_READ_sRGB_SUPPORTED)
  186824. PNG_CONST PNG_sRGB;
  186825. #endif
  186826. #if defined(PNG_READ_tEXt_SUPPORTED)
  186827. PNG_CONST PNG_tEXt;
  186828. #endif
  186829. #if defined(PNG_READ_tIME_SUPPORTED)
  186830. PNG_CONST PNG_tIME;
  186831. #endif
  186832. #if defined(PNG_READ_tRNS_SUPPORTED)
  186833. PNG_CONST PNG_tRNS;
  186834. #endif
  186835. #if defined(PNG_READ_zTXt_SUPPORTED)
  186836. PNG_CONST PNG_zTXt;
  186837. #endif
  186838. #endif /* PNG_USE_LOCAL_ARRAYS */
  186839. png_byte chunk_length[4];
  186840. png_uint_32 length;
  186841. png_read_data(png_ptr, chunk_length, 4);
  186842. length = png_get_uint_31(png_ptr,chunk_length);
  186843. png_reset_crc(png_ptr);
  186844. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186845. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  186846. length);
  186847. /* This should be a binary subdivision search or a hash for
  186848. * matching the chunk name rather than a linear search.
  186849. */
  186850. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186851. if(png_ptr->mode & PNG_AFTER_IDAT)
  186852. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  186853. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186854. png_handle_IHDR(png_ptr, info_ptr, length);
  186855. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186856. png_handle_IEND(png_ptr, info_ptr, length);
  186857. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186858. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186859. {
  186860. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186861. png_ptr->mode |= PNG_HAVE_IDAT;
  186862. png_handle_unknown(png_ptr, info_ptr, length);
  186863. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186864. png_ptr->mode |= PNG_HAVE_PLTE;
  186865. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186866. {
  186867. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186868. png_error(png_ptr, "Missing IHDR before IDAT");
  186869. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186870. !(png_ptr->mode & PNG_HAVE_PLTE))
  186871. png_error(png_ptr, "Missing PLTE before IDAT");
  186872. break;
  186873. }
  186874. }
  186875. #endif
  186876. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186877. png_handle_PLTE(png_ptr, info_ptr, length);
  186878. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186879. {
  186880. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186881. png_error(png_ptr, "Missing IHDR before IDAT");
  186882. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186883. !(png_ptr->mode & PNG_HAVE_PLTE))
  186884. png_error(png_ptr, "Missing PLTE before IDAT");
  186885. png_ptr->idat_size = length;
  186886. png_ptr->mode |= PNG_HAVE_IDAT;
  186887. break;
  186888. }
  186889. #if defined(PNG_READ_bKGD_SUPPORTED)
  186890. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186891. png_handle_bKGD(png_ptr, info_ptr, length);
  186892. #endif
  186893. #if defined(PNG_READ_cHRM_SUPPORTED)
  186894. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186895. png_handle_cHRM(png_ptr, info_ptr, length);
  186896. #endif
  186897. #if defined(PNG_READ_gAMA_SUPPORTED)
  186898. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186899. png_handle_gAMA(png_ptr, info_ptr, length);
  186900. #endif
  186901. #if defined(PNG_READ_hIST_SUPPORTED)
  186902. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186903. png_handle_hIST(png_ptr, info_ptr, length);
  186904. #endif
  186905. #if defined(PNG_READ_oFFs_SUPPORTED)
  186906. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186907. png_handle_oFFs(png_ptr, info_ptr, length);
  186908. #endif
  186909. #if defined(PNG_READ_pCAL_SUPPORTED)
  186910. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186911. png_handle_pCAL(png_ptr, info_ptr, length);
  186912. #endif
  186913. #if defined(PNG_READ_sCAL_SUPPORTED)
  186914. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186915. png_handle_sCAL(png_ptr, info_ptr, length);
  186916. #endif
  186917. #if defined(PNG_READ_pHYs_SUPPORTED)
  186918. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186919. png_handle_pHYs(png_ptr, info_ptr, length);
  186920. #endif
  186921. #if defined(PNG_READ_sBIT_SUPPORTED)
  186922. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186923. png_handle_sBIT(png_ptr, info_ptr, length);
  186924. #endif
  186925. #if defined(PNG_READ_sRGB_SUPPORTED)
  186926. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186927. png_handle_sRGB(png_ptr, info_ptr, length);
  186928. #endif
  186929. #if defined(PNG_READ_iCCP_SUPPORTED)
  186930. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186931. png_handle_iCCP(png_ptr, info_ptr, length);
  186932. #endif
  186933. #if defined(PNG_READ_sPLT_SUPPORTED)
  186934. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186935. png_handle_sPLT(png_ptr, info_ptr, length);
  186936. #endif
  186937. #if defined(PNG_READ_tEXt_SUPPORTED)
  186938. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186939. png_handle_tEXt(png_ptr, info_ptr, length);
  186940. #endif
  186941. #if defined(PNG_READ_tIME_SUPPORTED)
  186942. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186943. png_handle_tIME(png_ptr, info_ptr, length);
  186944. #endif
  186945. #if defined(PNG_READ_tRNS_SUPPORTED)
  186946. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186947. png_handle_tRNS(png_ptr, info_ptr, length);
  186948. #endif
  186949. #if defined(PNG_READ_zTXt_SUPPORTED)
  186950. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186951. png_handle_zTXt(png_ptr, info_ptr, length);
  186952. #endif
  186953. #if defined(PNG_READ_iTXt_SUPPORTED)
  186954. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186955. png_handle_iTXt(png_ptr, info_ptr, length);
  186956. #endif
  186957. else
  186958. png_handle_unknown(png_ptr, info_ptr, length);
  186959. }
  186960. }
  186961. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186962. /* optional call to update the users info_ptr structure */
  186963. void PNGAPI
  186964. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  186965. {
  186966. png_debug(1, "in png_read_update_info\n");
  186967. if(png_ptr == NULL) return;
  186968. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186969. png_read_start_row(png_ptr);
  186970. else
  186971. png_warning(png_ptr,
  186972. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  186973. png_read_transform_info(png_ptr, info_ptr);
  186974. }
  186975. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186976. /* Initialize palette, background, etc, after transformations
  186977. * are set, but before any reading takes place. This allows
  186978. * the user to obtain a gamma-corrected palette, for example.
  186979. * If the user doesn't call this, we will do it ourselves.
  186980. */
  186981. void PNGAPI
  186982. png_start_read_image(png_structp png_ptr)
  186983. {
  186984. png_debug(1, "in png_start_read_image\n");
  186985. if(png_ptr == NULL) return;
  186986. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186987. png_read_start_row(png_ptr);
  186988. }
  186989. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186990. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186991. void PNGAPI
  186992. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  186993. {
  186994. #ifdef PNG_USE_LOCAL_ARRAYS
  186995. PNG_CONST PNG_IDAT;
  186996. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  186997. 0xff};
  186998. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  186999. #endif
  187000. int ret;
  187001. if(png_ptr == NULL) return;
  187002. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187003. png_ptr->row_number, png_ptr->pass);
  187004. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187005. png_read_start_row(png_ptr);
  187006. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187007. {
  187008. /* check for transforms that have been set but were defined out */
  187009. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187010. if (png_ptr->transformations & PNG_INVERT_MONO)
  187011. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187012. #endif
  187013. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187014. if (png_ptr->transformations & PNG_FILLER)
  187015. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187016. #endif
  187017. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187018. if (png_ptr->transformations & PNG_PACKSWAP)
  187019. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187020. #endif
  187021. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187022. if (png_ptr->transformations & PNG_PACK)
  187023. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187024. #endif
  187025. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187026. if (png_ptr->transformations & PNG_SHIFT)
  187027. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187028. #endif
  187029. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187030. if (png_ptr->transformations & PNG_BGR)
  187031. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187032. #endif
  187033. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187034. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187035. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187036. #endif
  187037. }
  187038. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187039. /* if interlaced and we do not need a new row, combine row and return */
  187040. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187041. {
  187042. switch (png_ptr->pass)
  187043. {
  187044. case 0:
  187045. if (png_ptr->row_number & 0x07)
  187046. {
  187047. if (dsp_row != NULL)
  187048. png_combine_row(png_ptr, dsp_row,
  187049. png_pass_dsp_mask[png_ptr->pass]);
  187050. png_read_finish_row(png_ptr);
  187051. return;
  187052. }
  187053. break;
  187054. case 1:
  187055. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187056. {
  187057. if (dsp_row != NULL)
  187058. png_combine_row(png_ptr, dsp_row,
  187059. png_pass_dsp_mask[png_ptr->pass]);
  187060. png_read_finish_row(png_ptr);
  187061. return;
  187062. }
  187063. break;
  187064. case 2:
  187065. if ((png_ptr->row_number & 0x07) != 4)
  187066. {
  187067. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187068. png_combine_row(png_ptr, dsp_row,
  187069. png_pass_dsp_mask[png_ptr->pass]);
  187070. png_read_finish_row(png_ptr);
  187071. return;
  187072. }
  187073. break;
  187074. case 3:
  187075. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187076. {
  187077. if (dsp_row != NULL)
  187078. png_combine_row(png_ptr, dsp_row,
  187079. png_pass_dsp_mask[png_ptr->pass]);
  187080. png_read_finish_row(png_ptr);
  187081. return;
  187082. }
  187083. break;
  187084. case 4:
  187085. if ((png_ptr->row_number & 3) != 2)
  187086. {
  187087. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187088. png_combine_row(png_ptr, dsp_row,
  187089. png_pass_dsp_mask[png_ptr->pass]);
  187090. png_read_finish_row(png_ptr);
  187091. return;
  187092. }
  187093. break;
  187094. case 5:
  187095. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187096. {
  187097. if (dsp_row != NULL)
  187098. png_combine_row(png_ptr, dsp_row,
  187099. png_pass_dsp_mask[png_ptr->pass]);
  187100. png_read_finish_row(png_ptr);
  187101. return;
  187102. }
  187103. break;
  187104. case 6:
  187105. if (!(png_ptr->row_number & 1))
  187106. {
  187107. png_read_finish_row(png_ptr);
  187108. return;
  187109. }
  187110. break;
  187111. }
  187112. }
  187113. #endif
  187114. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187115. png_error(png_ptr, "Invalid attempt to read row data");
  187116. png_ptr->zstream.next_out = png_ptr->row_buf;
  187117. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187118. do
  187119. {
  187120. if (!(png_ptr->zstream.avail_in))
  187121. {
  187122. while (!png_ptr->idat_size)
  187123. {
  187124. png_byte chunk_length[4];
  187125. png_crc_finish(png_ptr, 0);
  187126. png_read_data(png_ptr, chunk_length, 4);
  187127. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187128. png_reset_crc(png_ptr);
  187129. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187130. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187131. png_error(png_ptr, "Not enough image data");
  187132. }
  187133. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187134. png_ptr->zstream.next_in = png_ptr->zbuf;
  187135. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187136. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187137. png_crc_read(png_ptr, png_ptr->zbuf,
  187138. (png_size_t)png_ptr->zstream.avail_in);
  187139. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187140. }
  187141. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187142. if (ret == Z_STREAM_END)
  187143. {
  187144. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187145. png_ptr->idat_size)
  187146. png_error(png_ptr, "Extra compressed data");
  187147. png_ptr->mode |= PNG_AFTER_IDAT;
  187148. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187149. break;
  187150. }
  187151. if (ret != Z_OK)
  187152. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187153. "Decompression error");
  187154. } while (png_ptr->zstream.avail_out);
  187155. png_ptr->row_info.color_type = png_ptr->color_type;
  187156. png_ptr->row_info.width = png_ptr->iwidth;
  187157. png_ptr->row_info.channels = png_ptr->channels;
  187158. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187159. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187160. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187161. png_ptr->row_info.width);
  187162. if(png_ptr->row_buf[0])
  187163. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187164. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187165. (int)(png_ptr->row_buf[0]));
  187166. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187167. png_ptr->rowbytes + 1);
  187168. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187169. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187170. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187171. {
  187172. /* Intrapixel differencing */
  187173. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187174. }
  187175. #endif
  187176. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187177. png_do_read_transformations(png_ptr);
  187178. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187179. /* blow up interlaced rows to full size */
  187180. if (png_ptr->interlaced &&
  187181. (png_ptr->transformations & PNG_INTERLACE))
  187182. {
  187183. if (png_ptr->pass < 6)
  187184. /* old interface (pre-1.0.9):
  187185. png_do_read_interlace(&(png_ptr->row_info),
  187186. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187187. */
  187188. png_do_read_interlace(png_ptr);
  187189. if (dsp_row != NULL)
  187190. png_combine_row(png_ptr, dsp_row,
  187191. png_pass_dsp_mask[png_ptr->pass]);
  187192. if (row != NULL)
  187193. png_combine_row(png_ptr, row,
  187194. png_pass_mask[png_ptr->pass]);
  187195. }
  187196. else
  187197. #endif
  187198. {
  187199. if (row != NULL)
  187200. png_combine_row(png_ptr, row, 0xff);
  187201. if (dsp_row != NULL)
  187202. png_combine_row(png_ptr, dsp_row, 0xff);
  187203. }
  187204. png_read_finish_row(png_ptr);
  187205. if (png_ptr->read_row_fn != NULL)
  187206. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187207. }
  187208. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187209. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187210. /* Read one or more rows of image data. If the image is interlaced,
  187211. * and png_set_interlace_handling() has been called, the rows need to
  187212. * contain the contents of the rows from the previous pass. If the
  187213. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187214. * called, the rows contents must be initialized to the contents of the
  187215. * screen.
  187216. *
  187217. * "row" holds the actual image, and pixels are placed in it
  187218. * as they arrive. If the image is displayed after each pass, it will
  187219. * appear to "sparkle" in. "display_row" can be used to display a
  187220. * "chunky" progressive image, with finer detail added as it becomes
  187221. * available. If you do not want this "chunky" display, you may pass
  187222. * NULL for display_row. If you do not want the sparkle display, and
  187223. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187224. * If you have called png_handle_alpha(), and the image has either an
  187225. * alpha channel or a transparency chunk, you must provide a buffer for
  187226. * rows. In this case, you do not have to provide a display_row buffer
  187227. * also, but you may. If the image is not interlaced, or if you have
  187228. * not called png_set_interlace_handling(), the display_row buffer will
  187229. * be ignored, so pass NULL to it.
  187230. *
  187231. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187232. */
  187233. void PNGAPI
  187234. png_read_rows(png_structp png_ptr, png_bytepp row,
  187235. png_bytepp display_row, png_uint_32 num_rows)
  187236. {
  187237. png_uint_32 i;
  187238. png_bytepp rp;
  187239. png_bytepp dp;
  187240. png_debug(1, "in png_read_rows\n");
  187241. if(png_ptr == NULL) return;
  187242. rp = row;
  187243. dp = display_row;
  187244. if (rp != NULL && dp != NULL)
  187245. for (i = 0; i < num_rows; i++)
  187246. {
  187247. png_bytep rptr = *rp++;
  187248. png_bytep dptr = *dp++;
  187249. png_read_row(png_ptr, rptr, dptr);
  187250. }
  187251. else if(rp != NULL)
  187252. for (i = 0; i < num_rows; i++)
  187253. {
  187254. png_bytep rptr = *rp;
  187255. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187256. rp++;
  187257. }
  187258. else if(dp != NULL)
  187259. for (i = 0; i < num_rows; i++)
  187260. {
  187261. png_bytep dptr = *dp;
  187262. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187263. dp++;
  187264. }
  187265. }
  187266. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187267. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187268. /* Read the entire image. If the image has an alpha channel or a tRNS
  187269. * chunk, and you have called png_handle_alpha()[*], you will need to
  187270. * initialize the image to the current image that PNG will be overlaying.
  187271. * We set the num_rows again here, in case it was incorrectly set in
  187272. * png_read_start_row() by a call to png_read_update_info() or
  187273. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187274. * prior to either of these functions like it should have been. You can
  187275. * only call this function once. If you desire to have an image for
  187276. * each pass of a interlaced image, use png_read_rows() instead.
  187277. *
  187278. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187279. */
  187280. void PNGAPI
  187281. png_read_image(png_structp png_ptr, png_bytepp image)
  187282. {
  187283. png_uint_32 i,image_height;
  187284. int pass, j;
  187285. png_bytepp rp;
  187286. png_debug(1, "in png_read_image\n");
  187287. if(png_ptr == NULL) return;
  187288. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187289. pass = png_set_interlace_handling(png_ptr);
  187290. #else
  187291. if (png_ptr->interlaced)
  187292. png_error(png_ptr,
  187293. "Cannot read interlaced image -- interlace handler disabled.");
  187294. pass = 1;
  187295. #endif
  187296. image_height=png_ptr->height;
  187297. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187298. for (j = 0; j < pass; j++)
  187299. {
  187300. rp = image;
  187301. for (i = 0; i < image_height; i++)
  187302. {
  187303. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187304. rp++;
  187305. }
  187306. }
  187307. }
  187308. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187309. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187310. /* Read the end of the PNG file. Will not read past the end of the
  187311. * file, will verify the end is accurate, and will read any comments
  187312. * or time information at the end of the file, if info is not NULL.
  187313. */
  187314. void PNGAPI
  187315. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187316. {
  187317. png_byte chunk_length[4];
  187318. png_uint_32 length;
  187319. png_debug(1, "in png_read_end\n");
  187320. if(png_ptr == NULL) return;
  187321. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187322. do
  187323. {
  187324. #ifdef PNG_USE_LOCAL_ARRAYS
  187325. PNG_CONST PNG_IHDR;
  187326. PNG_CONST PNG_IDAT;
  187327. PNG_CONST PNG_IEND;
  187328. PNG_CONST PNG_PLTE;
  187329. #if defined(PNG_READ_bKGD_SUPPORTED)
  187330. PNG_CONST PNG_bKGD;
  187331. #endif
  187332. #if defined(PNG_READ_cHRM_SUPPORTED)
  187333. PNG_CONST PNG_cHRM;
  187334. #endif
  187335. #if defined(PNG_READ_gAMA_SUPPORTED)
  187336. PNG_CONST PNG_gAMA;
  187337. #endif
  187338. #if defined(PNG_READ_hIST_SUPPORTED)
  187339. PNG_CONST PNG_hIST;
  187340. #endif
  187341. #if defined(PNG_READ_iCCP_SUPPORTED)
  187342. PNG_CONST PNG_iCCP;
  187343. #endif
  187344. #if defined(PNG_READ_iTXt_SUPPORTED)
  187345. PNG_CONST PNG_iTXt;
  187346. #endif
  187347. #if defined(PNG_READ_oFFs_SUPPORTED)
  187348. PNG_CONST PNG_oFFs;
  187349. #endif
  187350. #if defined(PNG_READ_pCAL_SUPPORTED)
  187351. PNG_CONST PNG_pCAL;
  187352. #endif
  187353. #if defined(PNG_READ_pHYs_SUPPORTED)
  187354. PNG_CONST PNG_pHYs;
  187355. #endif
  187356. #if defined(PNG_READ_sBIT_SUPPORTED)
  187357. PNG_CONST PNG_sBIT;
  187358. #endif
  187359. #if defined(PNG_READ_sCAL_SUPPORTED)
  187360. PNG_CONST PNG_sCAL;
  187361. #endif
  187362. #if defined(PNG_READ_sPLT_SUPPORTED)
  187363. PNG_CONST PNG_sPLT;
  187364. #endif
  187365. #if defined(PNG_READ_sRGB_SUPPORTED)
  187366. PNG_CONST PNG_sRGB;
  187367. #endif
  187368. #if defined(PNG_READ_tEXt_SUPPORTED)
  187369. PNG_CONST PNG_tEXt;
  187370. #endif
  187371. #if defined(PNG_READ_tIME_SUPPORTED)
  187372. PNG_CONST PNG_tIME;
  187373. #endif
  187374. #if defined(PNG_READ_tRNS_SUPPORTED)
  187375. PNG_CONST PNG_tRNS;
  187376. #endif
  187377. #if defined(PNG_READ_zTXt_SUPPORTED)
  187378. PNG_CONST PNG_zTXt;
  187379. #endif
  187380. #endif /* PNG_USE_LOCAL_ARRAYS */
  187381. png_read_data(png_ptr, chunk_length, 4);
  187382. length = png_get_uint_31(png_ptr,chunk_length);
  187383. png_reset_crc(png_ptr);
  187384. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187385. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187386. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187387. png_handle_IHDR(png_ptr, info_ptr, length);
  187388. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187389. png_handle_IEND(png_ptr, info_ptr, length);
  187390. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187391. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187392. {
  187393. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187394. {
  187395. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187396. png_error(png_ptr, "Too many IDAT's found");
  187397. }
  187398. png_handle_unknown(png_ptr, info_ptr, length);
  187399. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187400. png_ptr->mode |= PNG_HAVE_PLTE;
  187401. }
  187402. #endif
  187403. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187404. {
  187405. /* Zero length IDATs are legal after the last IDAT has been
  187406. * read, but not after other chunks have been read.
  187407. */
  187408. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187409. png_error(png_ptr, "Too many IDAT's found");
  187410. png_crc_finish(png_ptr, length);
  187411. }
  187412. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187413. png_handle_PLTE(png_ptr, info_ptr, length);
  187414. #if defined(PNG_READ_bKGD_SUPPORTED)
  187415. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187416. png_handle_bKGD(png_ptr, info_ptr, length);
  187417. #endif
  187418. #if defined(PNG_READ_cHRM_SUPPORTED)
  187419. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187420. png_handle_cHRM(png_ptr, info_ptr, length);
  187421. #endif
  187422. #if defined(PNG_READ_gAMA_SUPPORTED)
  187423. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187424. png_handle_gAMA(png_ptr, info_ptr, length);
  187425. #endif
  187426. #if defined(PNG_READ_hIST_SUPPORTED)
  187427. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187428. png_handle_hIST(png_ptr, info_ptr, length);
  187429. #endif
  187430. #if defined(PNG_READ_oFFs_SUPPORTED)
  187431. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187432. png_handle_oFFs(png_ptr, info_ptr, length);
  187433. #endif
  187434. #if defined(PNG_READ_pCAL_SUPPORTED)
  187435. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187436. png_handle_pCAL(png_ptr, info_ptr, length);
  187437. #endif
  187438. #if defined(PNG_READ_sCAL_SUPPORTED)
  187439. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187440. png_handle_sCAL(png_ptr, info_ptr, length);
  187441. #endif
  187442. #if defined(PNG_READ_pHYs_SUPPORTED)
  187443. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187444. png_handle_pHYs(png_ptr, info_ptr, length);
  187445. #endif
  187446. #if defined(PNG_READ_sBIT_SUPPORTED)
  187447. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187448. png_handle_sBIT(png_ptr, info_ptr, length);
  187449. #endif
  187450. #if defined(PNG_READ_sRGB_SUPPORTED)
  187451. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187452. png_handle_sRGB(png_ptr, info_ptr, length);
  187453. #endif
  187454. #if defined(PNG_READ_iCCP_SUPPORTED)
  187455. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187456. png_handle_iCCP(png_ptr, info_ptr, length);
  187457. #endif
  187458. #if defined(PNG_READ_sPLT_SUPPORTED)
  187459. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187460. png_handle_sPLT(png_ptr, info_ptr, length);
  187461. #endif
  187462. #if defined(PNG_READ_tEXt_SUPPORTED)
  187463. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187464. png_handle_tEXt(png_ptr, info_ptr, length);
  187465. #endif
  187466. #if defined(PNG_READ_tIME_SUPPORTED)
  187467. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187468. png_handle_tIME(png_ptr, info_ptr, length);
  187469. #endif
  187470. #if defined(PNG_READ_tRNS_SUPPORTED)
  187471. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187472. png_handle_tRNS(png_ptr, info_ptr, length);
  187473. #endif
  187474. #if defined(PNG_READ_zTXt_SUPPORTED)
  187475. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187476. png_handle_zTXt(png_ptr, info_ptr, length);
  187477. #endif
  187478. #if defined(PNG_READ_iTXt_SUPPORTED)
  187479. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187480. png_handle_iTXt(png_ptr, info_ptr, length);
  187481. #endif
  187482. else
  187483. png_handle_unknown(png_ptr, info_ptr, length);
  187484. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187485. }
  187486. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187487. /* free all memory used by the read */
  187488. void PNGAPI
  187489. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187490. png_infopp end_info_ptr_ptr)
  187491. {
  187492. png_structp png_ptr = NULL;
  187493. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187494. #ifdef PNG_USER_MEM_SUPPORTED
  187495. png_free_ptr free_fn;
  187496. png_voidp mem_ptr;
  187497. #endif
  187498. png_debug(1, "in png_destroy_read_struct\n");
  187499. if (png_ptr_ptr != NULL)
  187500. png_ptr = *png_ptr_ptr;
  187501. if (info_ptr_ptr != NULL)
  187502. info_ptr = *info_ptr_ptr;
  187503. if (end_info_ptr_ptr != NULL)
  187504. end_info_ptr = *end_info_ptr_ptr;
  187505. #ifdef PNG_USER_MEM_SUPPORTED
  187506. free_fn = png_ptr->free_fn;
  187507. mem_ptr = png_ptr->mem_ptr;
  187508. #endif
  187509. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187510. if (info_ptr != NULL)
  187511. {
  187512. #if defined(PNG_TEXT_SUPPORTED)
  187513. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187514. #endif
  187515. #ifdef PNG_USER_MEM_SUPPORTED
  187516. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187517. (png_voidp)mem_ptr);
  187518. #else
  187519. png_destroy_struct((png_voidp)info_ptr);
  187520. #endif
  187521. *info_ptr_ptr = NULL;
  187522. }
  187523. if (end_info_ptr != NULL)
  187524. {
  187525. #if defined(PNG_READ_TEXT_SUPPORTED)
  187526. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187527. #endif
  187528. #ifdef PNG_USER_MEM_SUPPORTED
  187529. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187530. (png_voidp)mem_ptr);
  187531. #else
  187532. png_destroy_struct((png_voidp)end_info_ptr);
  187533. #endif
  187534. *end_info_ptr_ptr = NULL;
  187535. }
  187536. if (png_ptr != NULL)
  187537. {
  187538. #ifdef PNG_USER_MEM_SUPPORTED
  187539. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187540. (png_voidp)mem_ptr);
  187541. #else
  187542. png_destroy_struct((png_voidp)png_ptr);
  187543. #endif
  187544. *png_ptr_ptr = NULL;
  187545. }
  187546. }
  187547. /* free all memory used by the read (old method) */
  187548. void /* PRIVATE */
  187549. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187550. {
  187551. #ifdef PNG_SETJMP_SUPPORTED
  187552. jmp_buf tmp_jmp;
  187553. #endif
  187554. png_error_ptr error_fn;
  187555. png_error_ptr warning_fn;
  187556. png_voidp error_ptr;
  187557. #ifdef PNG_USER_MEM_SUPPORTED
  187558. png_free_ptr free_fn;
  187559. #endif
  187560. png_debug(1, "in png_read_destroy\n");
  187561. if (info_ptr != NULL)
  187562. png_info_destroy(png_ptr, info_ptr);
  187563. if (end_info_ptr != NULL)
  187564. png_info_destroy(png_ptr, end_info_ptr);
  187565. png_free(png_ptr, png_ptr->zbuf);
  187566. png_free(png_ptr, png_ptr->big_row_buf);
  187567. png_free(png_ptr, png_ptr->prev_row);
  187568. #if defined(PNG_READ_DITHER_SUPPORTED)
  187569. png_free(png_ptr, png_ptr->palette_lookup);
  187570. png_free(png_ptr, png_ptr->dither_index);
  187571. #endif
  187572. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187573. png_free(png_ptr, png_ptr->gamma_table);
  187574. #endif
  187575. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187576. png_free(png_ptr, png_ptr->gamma_from_1);
  187577. png_free(png_ptr, png_ptr->gamma_to_1);
  187578. #endif
  187579. #ifdef PNG_FREE_ME_SUPPORTED
  187580. if (png_ptr->free_me & PNG_FREE_PLTE)
  187581. png_zfree(png_ptr, png_ptr->palette);
  187582. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187583. #else
  187584. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187585. png_zfree(png_ptr, png_ptr->palette);
  187586. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187587. #endif
  187588. #if defined(PNG_tRNS_SUPPORTED) || \
  187589. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187590. #ifdef PNG_FREE_ME_SUPPORTED
  187591. if (png_ptr->free_me & PNG_FREE_TRNS)
  187592. png_free(png_ptr, png_ptr->trans);
  187593. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187594. #else
  187595. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187596. png_free(png_ptr, png_ptr->trans);
  187597. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187598. #endif
  187599. #endif
  187600. #if defined(PNG_READ_hIST_SUPPORTED)
  187601. #ifdef PNG_FREE_ME_SUPPORTED
  187602. if (png_ptr->free_me & PNG_FREE_HIST)
  187603. png_free(png_ptr, png_ptr->hist);
  187604. png_ptr->free_me &= ~PNG_FREE_HIST;
  187605. #else
  187606. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187607. png_free(png_ptr, png_ptr->hist);
  187608. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187609. #endif
  187610. #endif
  187611. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187612. if (png_ptr->gamma_16_table != NULL)
  187613. {
  187614. int i;
  187615. int istop = (1 << (8 - png_ptr->gamma_shift));
  187616. for (i = 0; i < istop; i++)
  187617. {
  187618. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187619. }
  187620. png_free(png_ptr, png_ptr->gamma_16_table);
  187621. }
  187622. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187623. if (png_ptr->gamma_16_from_1 != NULL)
  187624. {
  187625. int i;
  187626. int istop = (1 << (8 - png_ptr->gamma_shift));
  187627. for (i = 0; i < istop; i++)
  187628. {
  187629. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187630. }
  187631. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187632. }
  187633. if (png_ptr->gamma_16_to_1 != NULL)
  187634. {
  187635. int i;
  187636. int istop = (1 << (8 - png_ptr->gamma_shift));
  187637. for (i = 0; i < istop; i++)
  187638. {
  187639. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187640. }
  187641. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187642. }
  187643. #endif
  187644. #endif
  187645. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187646. png_free(png_ptr, png_ptr->time_buffer);
  187647. #endif
  187648. inflateEnd(&png_ptr->zstream);
  187649. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187650. png_free(png_ptr, png_ptr->save_buffer);
  187651. #endif
  187652. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187653. #ifdef PNG_TEXT_SUPPORTED
  187654. png_free(png_ptr, png_ptr->current_text);
  187655. #endif /* PNG_TEXT_SUPPORTED */
  187656. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187657. /* Save the important info out of the png_struct, in case it is
  187658. * being used again.
  187659. */
  187660. #ifdef PNG_SETJMP_SUPPORTED
  187661. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187662. #endif
  187663. error_fn = png_ptr->error_fn;
  187664. warning_fn = png_ptr->warning_fn;
  187665. error_ptr = png_ptr->error_ptr;
  187666. #ifdef PNG_USER_MEM_SUPPORTED
  187667. free_fn = png_ptr->free_fn;
  187668. #endif
  187669. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187670. png_ptr->error_fn = error_fn;
  187671. png_ptr->warning_fn = warning_fn;
  187672. png_ptr->error_ptr = error_ptr;
  187673. #ifdef PNG_USER_MEM_SUPPORTED
  187674. png_ptr->free_fn = free_fn;
  187675. #endif
  187676. #ifdef PNG_SETJMP_SUPPORTED
  187677. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187678. #endif
  187679. }
  187680. void PNGAPI
  187681. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187682. {
  187683. if(png_ptr == NULL) return;
  187684. png_ptr->read_row_fn = read_row_fn;
  187685. }
  187686. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187687. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187688. void PNGAPI
  187689. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187690. int transforms,
  187691. voidp params)
  187692. {
  187693. int row;
  187694. if(png_ptr == NULL) return;
  187695. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187696. /* invert the alpha channel from opacity to transparency
  187697. */
  187698. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187699. png_set_invert_alpha(png_ptr);
  187700. #endif
  187701. /* png_read_info() gives us all of the information from the
  187702. * PNG file before the first IDAT (image data chunk).
  187703. */
  187704. png_read_info(png_ptr, info_ptr);
  187705. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187706. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187707. /* -------------- image transformations start here ------------------- */
  187708. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187709. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187710. */
  187711. if (transforms & PNG_TRANSFORM_STRIP_16)
  187712. png_set_strip_16(png_ptr);
  187713. #endif
  187714. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187715. /* Strip alpha bytes from the input data without combining with
  187716. * the background (not recommended).
  187717. */
  187718. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187719. png_set_strip_alpha(png_ptr);
  187720. #endif
  187721. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187722. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187723. * byte into separate bytes (useful for paletted and grayscale images).
  187724. */
  187725. if (transforms & PNG_TRANSFORM_PACKING)
  187726. png_set_packing(png_ptr);
  187727. #endif
  187728. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187729. /* Change the order of packed pixels to least significant bit first
  187730. * (not useful if you are using png_set_packing).
  187731. */
  187732. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187733. png_set_packswap(png_ptr);
  187734. #endif
  187735. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187736. /* Expand paletted colors into true RGB triplets
  187737. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187738. * Expand paletted or RGB images with transparency to full alpha
  187739. * channels so the data will be available as RGBA quartets.
  187740. */
  187741. if (transforms & PNG_TRANSFORM_EXPAND)
  187742. if ((png_ptr->bit_depth < 8) ||
  187743. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187744. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187745. png_set_expand(png_ptr);
  187746. #endif
  187747. /* We don't handle background color or gamma transformation or dithering.
  187748. */
  187749. #if defined(PNG_READ_INVERT_SUPPORTED)
  187750. /* invert monochrome files to have 0 as white and 1 as black
  187751. */
  187752. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187753. png_set_invert_mono(png_ptr);
  187754. #endif
  187755. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187756. /* If you want to shift the pixel values from the range [0,255] or
  187757. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187758. * colors were originally in:
  187759. */
  187760. if ((transforms & PNG_TRANSFORM_SHIFT)
  187761. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187762. {
  187763. png_color_8p sig_bit;
  187764. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187765. png_set_shift(png_ptr, sig_bit);
  187766. }
  187767. #endif
  187768. #if defined(PNG_READ_BGR_SUPPORTED)
  187769. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187770. */
  187771. if (transforms & PNG_TRANSFORM_BGR)
  187772. png_set_bgr(png_ptr);
  187773. #endif
  187774. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187775. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187776. */
  187777. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187778. png_set_swap_alpha(png_ptr);
  187779. #endif
  187780. #if defined(PNG_READ_SWAP_SUPPORTED)
  187781. /* swap bytes of 16 bit files to least significant byte first
  187782. */
  187783. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187784. png_set_swap(png_ptr);
  187785. #endif
  187786. /* We don't handle adding filler bytes */
  187787. /* Optional call to gamma correct and add the background to the palette
  187788. * and update info structure. REQUIRED if you are expecting libpng to
  187789. * update the palette for you (i.e., you selected such a transform above).
  187790. */
  187791. png_read_update_info(png_ptr, info_ptr);
  187792. /* -------------- image transformations end here ------------------- */
  187793. #ifdef PNG_FREE_ME_SUPPORTED
  187794. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187795. #endif
  187796. if(info_ptr->row_pointers == NULL)
  187797. {
  187798. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187799. info_ptr->height * png_sizeof(png_bytep));
  187800. #ifdef PNG_FREE_ME_SUPPORTED
  187801. info_ptr->free_me |= PNG_FREE_ROWS;
  187802. #endif
  187803. for (row = 0; row < (int)info_ptr->height; row++)
  187804. {
  187805. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187806. png_get_rowbytes(png_ptr, info_ptr));
  187807. }
  187808. }
  187809. png_read_image(png_ptr, info_ptr->row_pointers);
  187810. info_ptr->valid |= PNG_INFO_IDAT;
  187811. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187812. png_read_end(png_ptr, info_ptr);
  187813. transforms = transforms; /* quiet compiler warnings */
  187814. params = params;
  187815. }
  187816. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  187817. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187818. #endif /* PNG_READ_SUPPORTED */
  187819. /*** End of inlined file: pngread.c ***/
  187820. /*** Start of inlined file: pngpread.c ***/
  187821. /* pngpread.c - read a png file in push mode
  187822. *
  187823. * Last changed in libpng 1.2.21 October 4, 2007
  187824. * For conditions of distribution and use, see copyright notice in png.h
  187825. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187826. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187827. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187828. */
  187829. #define PNG_INTERNAL
  187830. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187831. /* push model modes */
  187832. #define PNG_READ_SIG_MODE 0
  187833. #define PNG_READ_CHUNK_MODE 1
  187834. #define PNG_READ_IDAT_MODE 2
  187835. #define PNG_SKIP_MODE 3
  187836. #define PNG_READ_tEXt_MODE 4
  187837. #define PNG_READ_zTXt_MODE 5
  187838. #define PNG_READ_DONE_MODE 6
  187839. #define PNG_READ_iTXt_MODE 7
  187840. #define PNG_ERROR_MODE 8
  187841. void PNGAPI
  187842. png_process_data(png_structp png_ptr, png_infop info_ptr,
  187843. png_bytep buffer, png_size_t buffer_size)
  187844. {
  187845. if(png_ptr == NULL) return;
  187846. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  187847. while (png_ptr->buffer_size)
  187848. {
  187849. png_process_some_data(png_ptr, info_ptr);
  187850. }
  187851. }
  187852. /* What we do with the incoming data depends on what we were previously
  187853. * doing before we ran out of data...
  187854. */
  187855. void /* PRIVATE */
  187856. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  187857. {
  187858. if(png_ptr == NULL) return;
  187859. switch (png_ptr->process_mode)
  187860. {
  187861. case PNG_READ_SIG_MODE:
  187862. {
  187863. png_push_read_sig(png_ptr, info_ptr);
  187864. break;
  187865. }
  187866. case PNG_READ_CHUNK_MODE:
  187867. {
  187868. png_push_read_chunk(png_ptr, info_ptr);
  187869. break;
  187870. }
  187871. case PNG_READ_IDAT_MODE:
  187872. {
  187873. png_push_read_IDAT(png_ptr);
  187874. break;
  187875. }
  187876. #if defined(PNG_READ_tEXt_SUPPORTED)
  187877. case PNG_READ_tEXt_MODE:
  187878. {
  187879. png_push_read_tEXt(png_ptr, info_ptr);
  187880. break;
  187881. }
  187882. #endif
  187883. #if defined(PNG_READ_zTXt_SUPPORTED)
  187884. case PNG_READ_zTXt_MODE:
  187885. {
  187886. png_push_read_zTXt(png_ptr, info_ptr);
  187887. break;
  187888. }
  187889. #endif
  187890. #if defined(PNG_READ_iTXt_SUPPORTED)
  187891. case PNG_READ_iTXt_MODE:
  187892. {
  187893. png_push_read_iTXt(png_ptr, info_ptr);
  187894. break;
  187895. }
  187896. #endif
  187897. case PNG_SKIP_MODE:
  187898. {
  187899. png_push_crc_finish(png_ptr);
  187900. break;
  187901. }
  187902. default:
  187903. {
  187904. png_ptr->buffer_size = 0;
  187905. break;
  187906. }
  187907. }
  187908. }
  187909. /* Read any remaining signature bytes from the stream and compare them with
  187910. * the correct PNG signature. It is possible that this routine is called
  187911. * with bytes already read from the signature, either because they have been
  187912. * checked by the calling application, or because of multiple calls to this
  187913. * routine.
  187914. */
  187915. void /* PRIVATE */
  187916. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  187917. {
  187918. png_size_t num_checked = png_ptr->sig_bytes,
  187919. num_to_check = 8 - num_checked;
  187920. if (png_ptr->buffer_size < num_to_check)
  187921. {
  187922. num_to_check = png_ptr->buffer_size;
  187923. }
  187924. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  187925. num_to_check);
  187926. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  187927. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187928. {
  187929. if (num_checked < 4 &&
  187930. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187931. png_error(png_ptr, "Not a PNG file");
  187932. else
  187933. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187934. }
  187935. else
  187936. {
  187937. if (png_ptr->sig_bytes >= 8)
  187938. {
  187939. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187940. }
  187941. }
  187942. }
  187943. void /* PRIVATE */
  187944. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  187945. {
  187946. #ifdef PNG_USE_LOCAL_ARRAYS
  187947. PNG_CONST PNG_IHDR;
  187948. PNG_CONST PNG_IDAT;
  187949. PNG_CONST PNG_IEND;
  187950. PNG_CONST PNG_PLTE;
  187951. #if defined(PNG_READ_bKGD_SUPPORTED)
  187952. PNG_CONST PNG_bKGD;
  187953. #endif
  187954. #if defined(PNG_READ_cHRM_SUPPORTED)
  187955. PNG_CONST PNG_cHRM;
  187956. #endif
  187957. #if defined(PNG_READ_gAMA_SUPPORTED)
  187958. PNG_CONST PNG_gAMA;
  187959. #endif
  187960. #if defined(PNG_READ_hIST_SUPPORTED)
  187961. PNG_CONST PNG_hIST;
  187962. #endif
  187963. #if defined(PNG_READ_iCCP_SUPPORTED)
  187964. PNG_CONST PNG_iCCP;
  187965. #endif
  187966. #if defined(PNG_READ_iTXt_SUPPORTED)
  187967. PNG_CONST PNG_iTXt;
  187968. #endif
  187969. #if defined(PNG_READ_oFFs_SUPPORTED)
  187970. PNG_CONST PNG_oFFs;
  187971. #endif
  187972. #if defined(PNG_READ_pCAL_SUPPORTED)
  187973. PNG_CONST PNG_pCAL;
  187974. #endif
  187975. #if defined(PNG_READ_pHYs_SUPPORTED)
  187976. PNG_CONST PNG_pHYs;
  187977. #endif
  187978. #if defined(PNG_READ_sBIT_SUPPORTED)
  187979. PNG_CONST PNG_sBIT;
  187980. #endif
  187981. #if defined(PNG_READ_sCAL_SUPPORTED)
  187982. PNG_CONST PNG_sCAL;
  187983. #endif
  187984. #if defined(PNG_READ_sRGB_SUPPORTED)
  187985. PNG_CONST PNG_sRGB;
  187986. #endif
  187987. #if defined(PNG_READ_sPLT_SUPPORTED)
  187988. PNG_CONST PNG_sPLT;
  187989. #endif
  187990. #if defined(PNG_READ_tEXt_SUPPORTED)
  187991. PNG_CONST PNG_tEXt;
  187992. #endif
  187993. #if defined(PNG_READ_tIME_SUPPORTED)
  187994. PNG_CONST PNG_tIME;
  187995. #endif
  187996. #if defined(PNG_READ_tRNS_SUPPORTED)
  187997. PNG_CONST PNG_tRNS;
  187998. #endif
  187999. #if defined(PNG_READ_zTXt_SUPPORTED)
  188000. PNG_CONST PNG_zTXt;
  188001. #endif
  188002. #endif /* PNG_USE_LOCAL_ARRAYS */
  188003. /* First we make sure we have enough data for the 4 byte chunk name
  188004. * and the 4 byte chunk length before proceeding with decoding the
  188005. * chunk data. To fully decode each of these chunks, we also make
  188006. * sure we have enough data in the buffer for the 4 byte CRC at the
  188007. * end of every chunk (except IDAT, which is handled separately).
  188008. */
  188009. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188010. {
  188011. png_byte chunk_length[4];
  188012. if (png_ptr->buffer_size < 8)
  188013. {
  188014. png_push_save_buffer(png_ptr);
  188015. return;
  188016. }
  188017. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188018. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188019. png_reset_crc(png_ptr);
  188020. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188021. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188022. }
  188023. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188024. if(png_ptr->mode & PNG_AFTER_IDAT)
  188025. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188026. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188027. {
  188028. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188029. {
  188030. png_push_save_buffer(png_ptr);
  188031. return;
  188032. }
  188033. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188034. }
  188035. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188036. {
  188037. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188038. {
  188039. png_push_save_buffer(png_ptr);
  188040. return;
  188041. }
  188042. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188043. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188044. png_push_have_end(png_ptr, info_ptr);
  188045. }
  188046. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188047. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188048. {
  188049. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188050. {
  188051. png_push_save_buffer(png_ptr);
  188052. return;
  188053. }
  188054. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188055. png_ptr->mode |= PNG_HAVE_IDAT;
  188056. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188057. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188058. png_ptr->mode |= PNG_HAVE_PLTE;
  188059. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188060. {
  188061. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188062. png_error(png_ptr, "Missing IHDR before IDAT");
  188063. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188064. !(png_ptr->mode & PNG_HAVE_PLTE))
  188065. png_error(png_ptr, "Missing PLTE before IDAT");
  188066. }
  188067. }
  188068. #endif
  188069. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188070. {
  188071. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188072. {
  188073. png_push_save_buffer(png_ptr);
  188074. return;
  188075. }
  188076. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188077. }
  188078. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188079. {
  188080. /* If we reach an IDAT chunk, this means we have read all of the
  188081. * header chunks, and we can start reading the image (or if this
  188082. * is called after the image has been read - we have an error).
  188083. */
  188084. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188085. png_error(png_ptr, "Missing IHDR before IDAT");
  188086. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188087. !(png_ptr->mode & PNG_HAVE_PLTE))
  188088. png_error(png_ptr, "Missing PLTE before IDAT");
  188089. if (png_ptr->mode & PNG_HAVE_IDAT)
  188090. {
  188091. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188092. if (png_ptr->push_length == 0)
  188093. return;
  188094. if (png_ptr->mode & PNG_AFTER_IDAT)
  188095. png_error(png_ptr, "Too many IDAT's found");
  188096. }
  188097. png_ptr->idat_size = png_ptr->push_length;
  188098. png_ptr->mode |= PNG_HAVE_IDAT;
  188099. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188100. png_push_have_info(png_ptr, info_ptr);
  188101. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188102. png_ptr->zstream.next_out = png_ptr->row_buf;
  188103. return;
  188104. }
  188105. #if defined(PNG_READ_gAMA_SUPPORTED)
  188106. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188107. {
  188108. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188109. {
  188110. png_push_save_buffer(png_ptr);
  188111. return;
  188112. }
  188113. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188114. }
  188115. #endif
  188116. #if defined(PNG_READ_sBIT_SUPPORTED)
  188117. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188118. {
  188119. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188120. {
  188121. png_push_save_buffer(png_ptr);
  188122. return;
  188123. }
  188124. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188125. }
  188126. #endif
  188127. #if defined(PNG_READ_cHRM_SUPPORTED)
  188128. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188129. {
  188130. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188131. {
  188132. png_push_save_buffer(png_ptr);
  188133. return;
  188134. }
  188135. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188136. }
  188137. #endif
  188138. #if defined(PNG_READ_sRGB_SUPPORTED)
  188139. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188140. {
  188141. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188142. {
  188143. png_push_save_buffer(png_ptr);
  188144. return;
  188145. }
  188146. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188147. }
  188148. #endif
  188149. #if defined(PNG_READ_iCCP_SUPPORTED)
  188150. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188151. {
  188152. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188153. {
  188154. png_push_save_buffer(png_ptr);
  188155. return;
  188156. }
  188157. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188158. }
  188159. #endif
  188160. #if defined(PNG_READ_sPLT_SUPPORTED)
  188161. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188162. {
  188163. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188164. {
  188165. png_push_save_buffer(png_ptr);
  188166. return;
  188167. }
  188168. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188169. }
  188170. #endif
  188171. #if defined(PNG_READ_tRNS_SUPPORTED)
  188172. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188173. {
  188174. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188175. {
  188176. png_push_save_buffer(png_ptr);
  188177. return;
  188178. }
  188179. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188180. }
  188181. #endif
  188182. #if defined(PNG_READ_bKGD_SUPPORTED)
  188183. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188184. {
  188185. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188186. {
  188187. png_push_save_buffer(png_ptr);
  188188. return;
  188189. }
  188190. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188191. }
  188192. #endif
  188193. #if defined(PNG_READ_hIST_SUPPORTED)
  188194. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188195. {
  188196. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188197. {
  188198. png_push_save_buffer(png_ptr);
  188199. return;
  188200. }
  188201. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188202. }
  188203. #endif
  188204. #if defined(PNG_READ_pHYs_SUPPORTED)
  188205. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188206. {
  188207. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188208. {
  188209. png_push_save_buffer(png_ptr);
  188210. return;
  188211. }
  188212. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188213. }
  188214. #endif
  188215. #if defined(PNG_READ_oFFs_SUPPORTED)
  188216. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188217. {
  188218. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188219. {
  188220. png_push_save_buffer(png_ptr);
  188221. return;
  188222. }
  188223. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188224. }
  188225. #endif
  188226. #if defined(PNG_READ_pCAL_SUPPORTED)
  188227. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188228. {
  188229. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188230. {
  188231. png_push_save_buffer(png_ptr);
  188232. return;
  188233. }
  188234. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188235. }
  188236. #endif
  188237. #if defined(PNG_READ_sCAL_SUPPORTED)
  188238. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188239. {
  188240. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188241. {
  188242. png_push_save_buffer(png_ptr);
  188243. return;
  188244. }
  188245. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188246. }
  188247. #endif
  188248. #if defined(PNG_READ_tIME_SUPPORTED)
  188249. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188250. {
  188251. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188252. {
  188253. png_push_save_buffer(png_ptr);
  188254. return;
  188255. }
  188256. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188257. }
  188258. #endif
  188259. #if defined(PNG_READ_tEXt_SUPPORTED)
  188260. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188261. {
  188262. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188263. {
  188264. png_push_save_buffer(png_ptr);
  188265. return;
  188266. }
  188267. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188268. }
  188269. #endif
  188270. #if defined(PNG_READ_zTXt_SUPPORTED)
  188271. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188272. {
  188273. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188274. {
  188275. png_push_save_buffer(png_ptr);
  188276. return;
  188277. }
  188278. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188279. }
  188280. #endif
  188281. #if defined(PNG_READ_iTXt_SUPPORTED)
  188282. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188283. {
  188284. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188285. {
  188286. png_push_save_buffer(png_ptr);
  188287. return;
  188288. }
  188289. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188290. }
  188291. #endif
  188292. else
  188293. {
  188294. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188295. {
  188296. png_push_save_buffer(png_ptr);
  188297. return;
  188298. }
  188299. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188300. }
  188301. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188302. }
  188303. void /* PRIVATE */
  188304. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188305. {
  188306. png_ptr->process_mode = PNG_SKIP_MODE;
  188307. png_ptr->skip_length = skip;
  188308. }
  188309. void /* PRIVATE */
  188310. png_push_crc_finish(png_structp png_ptr)
  188311. {
  188312. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188313. {
  188314. png_size_t save_size;
  188315. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188316. save_size = (png_size_t)png_ptr->skip_length;
  188317. else
  188318. save_size = png_ptr->save_buffer_size;
  188319. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188320. png_ptr->skip_length -= save_size;
  188321. png_ptr->buffer_size -= save_size;
  188322. png_ptr->save_buffer_size -= save_size;
  188323. png_ptr->save_buffer_ptr += save_size;
  188324. }
  188325. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188326. {
  188327. png_size_t save_size;
  188328. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188329. save_size = (png_size_t)png_ptr->skip_length;
  188330. else
  188331. save_size = png_ptr->current_buffer_size;
  188332. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188333. png_ptr->skip_length -= save_size;
  188334. png_ptr->buffer_size -= save_size;
  188335. png_ptr->current_buffer_size -= save_size;
  188336. png_ptr->current_buffer_ptr += save_size;
  188337. }
  188338. if (!png_ptr->skip_length)
  188339. {
  188340. if (png_ptr->buffer_size < 4)
  188341. {
  188342. png_push_save_buffer(png_ptr);
  188343. return;
  188344. }
  188345. png_crc_finish(png_ptr, 0);
  188346. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188347. }
  188348. }
  188349. void PNGAPI
  188350. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188351. {
  188352. png_bytep ptr;
  188353. if(png_ptr == NULL) return;
  188354. ptr = buffer;
  188355. if (png_ptr->save_buffer_size)
  188356. {
  188357. png_size_t save_size;
  188358. if (length < png_ptr->save_buffer_size)
  188359. save_size = length;
  188360. else
  188361. save_size = png_ptr->save_buffer_size;
  188362. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188363. length -= save_size;
  188364. ptr += save_size;
  188365. png_ptr->buffer_size -= save_size;
  188366. png_ptr->save_buffer_size -= save_size;
  188367. png_ptr->save_buffer_ptr += save_size;
  188368. }
  188369. if (length && png_ptr->current_buffer_size)
  188370. {
  188371. png_size_t save_size;
  188372. if (length < png_ptr->current_buffer_size)
  188373. save_size = length;
  188374. else
  188375. save_size = png_ptr->current_buffer_size;
  188376. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188377. png_ptr->buffer_size -= save_size;
  188378. png_ptr->current_buffer_size -= save_size;
  188379. png_ptr->current_buffer_ptr += save_size;
  188380. }
  188381. }
  188382. void /* PRIVATE */
  188383. png_push_save_buffer(png_structp png_ptr)
  188384. {
  188385. if (png_ptr->save_buffer_size)
  188386. {
  188387. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188388. {
  188389. png_size_t i,istop;
  188390. png_bytep sp;
  188391. png_bytep dp;
  188392. istop = png_ptr->save_buffer_size;
  188393. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188394. i < istop; i++, sp++, dp++)
  188395. {
  188396. *dp = *sp;
  188397. }
  188398. }
  188399. }
  188400. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188401. png_ptr->save_buffer_max)
  188402. {
  188403. png_size_t new_max;
  188404. png_bytep old_buffer;
  188405. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188406. (png_ptr->current_buffer_size + 256))
  188407. {
  188408. png_error(png_ptr, "Potential overflow of save_buffer");
  188409. }
  188410. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188411. old_buffer = png_ptr->save_buffer;
  188412. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188413. (png_uint_32)new_max);
  188414. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188415. png_free(png_ptr, old_buffer);
  188416. png_ptr->save_buffer_max = new_max;
  188417. }
  188418. if (png_ptr->current_buffer_size)
  188419. {
  188420. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188421. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188422. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188423. png_ptr->current_buffer_size = 0;
  188424. }
  188425. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188426. png_ptr->buffer_size = 0;
  188427. }
  188428. void /* PRIVATE */
  188429. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188430. png_size_t buffer_length)
  188431. {
  188432. png_ptr->current_buffer = buffer;
  188433. png_ptr->current_buffer_size = buffer_length;
  188434. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188435. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188436. }
  188437. void /* PRIVATE */
  188438. png_push_read_IDAT(png_structp png_ptr)
  188439. {
  188440. #ifdef PNG_USE_LOCAL_ARRAYS
  188441. PNG_CONST PNG_IDAT;
  188442. #endif
  188443. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188444. {
  188445. png_byte chunk_length[4];
  188446. if (png_ptr->buffer_size < 8)
  188447. {
  188448. png_push_save_buffer(png_ptr);
  188449. return;
  188450. }
  188451. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188452. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188453. png_reset_crc(png_ptr);
  188454. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188455. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188456. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188457. {
  188458. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188459. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188460. png_error(png_ptr, "Not enough compressed data");
  188461. return;
  188462. }
  188463. png_ptr->idat_size = png_ptr->push_length;
  188464. }
  188465. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188466. {
  188467. png_size_t save_size;
  188468. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188469. {
  188470. save_size = (png_size_t)png_ptr->idat_size;
  188471. /* check for overflow */
  188472. if((png_uint_32)save_size != png_ptr->idat_size)
  188473. png_error(png_ptr, "save_size overflowed in pngpread");
  188474. }
  188475. else
  188476. save_size = png_ptr->save_buffer_size;
  188477. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188478. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188479. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188480. png_ptr->idat_size -= save_size;
  188481. png_ptr->buffer_size -= save_size;
  188482. png_ptr->save_buffer_size -= save_size;
  188483. png_ptr->save_buffer_ptr += save_size;
  188484. }
  188485. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188486. {
  188487. png_size_t save_size;
  188488. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188489. {
  188490. save_size = (png_size_t)png_ptr->idat_size;
  188491. /* check for overflow */
  188492. if((png_uint_32)save_size != png_ptr->idat_size)
  188493. png_error(png_ptr, "save_size overflowed in pngpread");
  188494. }
  188495. else
  188496. save_size = png_ptr->current_buffer_size;
  188497. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188498. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188499. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188500. png_ptr->idat_size -= save_size;
  188501. png_ptr->buffer_size -= save_size;
  188502. png_ptr->current_buffer_size -= save_size;
  188503. png_ptr->current_buffer_ptr += save_size;
  188504. }
  188505. if (!png_ptr->idat_size)
  188506. {
  188507. if (png_ptr->buffer_size < 4)
  188508. {
  188509. png_push_save_buffer(png_ptr);
  188510. return;
  188511. }
  188512. png_crc_finish(png_ptr, 0);
  188513. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188514. png_ptr->mode |= PNG_AFTER_IDAT;
  188515. }
  188516. }
  188517. void /* PRIVATE */
  188518. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188519. png_size_t buffer_length)
  188520. {
  188521. int ret;
  188522. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188523. png_error(png_ptr, "Extra compression data");
  188524. png_ptr->zstream.next_in = buffer;
  188525. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188526. for(;;)
  188527. {
  188528. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188529. if (ret != Z_OK)
  188530. {
  188531. if (ret == Z_STREAM_END)
  188532. {
  188533. if (png_ptr->zstream.avail_in)
  188534. png_error(png_ptr, "Extra compressed data");
  188535. if (!(png_ptr->zstream.avail_out))
  188536. {
  188537. png_push_process_row(png_ptr);
  188538. }
  188539. png_ptr->mode |= PNG_AFTER_IDAT;
  188540. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188541. break;
  188542. }
  188543. else if (ret == Z_BUF_ERROR)
  188544. break;
  188545. else
  188546. png_error(png_ptr, "Decompression Error");
  188547. }
  188548. if (!(png_ptr->zstream.avail_out))
  188549. {
  188550. if ((
  188551. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188552. png_ptr->interlaced && png_ptr->pass > 6) ||
  188553. (!png_ptr->interlaced &&
  188554. #endif
  188555. png_ptr->row_number == png_ptr->num_rows))
  188556. {
  188557. if (png_ptr->zstream.avail_in)
  188558. {
  188559. png_warning(png_ptr, "Too much data in IDAT chunks");
  188560. }
  188561. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188562. break;
  188563. }
  188564. png_push_process_row(png_ptr);
  188565. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188566. png_ptr->zstream.next_out = png_ptr->row_buf;
  188567. }
  188568. else
  188569. break;
  188570. }
  188571. }
  188572. void /* PRIVATE */
  188573. png_push_process_row(png_structp png_ptr)
  188574. {
  188575. png_ptr->row_info.color_type = png_ptr->color_type;
  188576. png_ptr->row_info.width = png_ptr->iwidth;
  188577. png_ptr->row_info.channels = png_ptr->channels;
  188578. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188579. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188580. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188581. png_ptr->row_info.width);
  188582. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188583. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188584. (int)(png_ptr->row_buf[0]));
  188585. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188586. png_ptr->rowbytes + 1);
  188587. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188588. png_do_read_transformations(png_ptr);
  188589. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188590. /* blow up interlaced rows to full size */
  188591. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188592. {
  188593. if (png_ptr->pass < 6)
  188594. /* old interface (pre-1.0.9):
  188595. png_do_read_interlace(&(png_ptr->row_info),
  188596. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188597. */
  188598. png_do_read_interlace(png_ptr);
  188599. switch (png_ptr->pass)
  188600. {
  188601. case 0:
  188602. {
  188603. int i;
  188604. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188605. {
  188606. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188607. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188608. }
  188609. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188610. {
  188611. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188612. {
  188613. png_push_have_row(png_ptr, png_bytep_NULL);
  188614. png_read_push_finish_row(png_ptr);
  188615. }
  188616. }
  188617. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188618. {
  188619. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188620. {
  188621. png_push_have_row(png_ptr, png_bytep_NULL);
  188622. png_read_push_finish_row(png_ptr);
  188623. }
  188624. }
  188625. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188626. {
  188627. png_push_have_row(png_ptr, png_bytep_NULL);
  188628. png_read_push_finish_row(png_ptr);
  188629. }
  188630. break;
  188631. }
  188632. case 1:
  188633. {
  188634. int i;
  188635. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188636. {
  188637. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188638. png_read_push_finish_row(png_ptr);
  188639. }
  188640. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188641. {
  188642. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188643. {
  188644. png_push_have_row(png_ptr, png_bytep_NULL);
  188645. png_read_push_finish_row(png_ptr);
  188646. }
  188647. }
  188648. break;
  188649. }
  188650. case 2:
  188651. {
  188652. int i;
  188653. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188654. {
  188655. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188656. png_read_push_finish_row(png_ptr);
  188657. }
  188658. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188659. {
  188660. png_push_have_row(png_ptr, png_bytep_NULL);
  188661. png_read_push_finish_row(png_ptr);
  188662. }
  188663. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188664. {
  188665. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188666. {
  188667. png_push_have_row(png_ptr, png_bytep_NULL);
  188668. png_read_push_finish_row(png_ptr);
  188669. }
  188670. }
  188671. break;
  188672. }
  188673. case 3:
  188674. {
  188675. int i;
  188676. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188677. {
  188678. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188679. png_read_push_finish_row(png_ptr);
  188680. }
  188681. if (png_ptr->pass == 4) /* skip top two generated rows */
  188682. {
  188683. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188684. {
  188685. png_push_have_row(png_ptr, png_bytep_NULL);
  188686. png_read_push_finish_row(png_ptr);
  188687. }
  188688. }
  188689. break;
  188690. }
  188691. case 4:
  188692. {
  188693. int i;
  188694. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188695. {
  188696. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188697. png_read_push_finish_row(png_ptr);
  188698. }
  188699. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188700. {
  188701. png_push_have_row(png_ptr, png_bytep_NULL);
  188702. png_read_push_finish_row(png_ptr);
  188703. }
  188704. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188705. {
  188706. png_push_have_row(png_ptr, png_bytep_NULL);
  188707. png_read_push_finish_row(png_ptr);
  188708. }
  188709. break;
  188710. }
  188711. case 5:
  188712. {
  188713. int i;
  188714. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188715. {
  188716. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188717. png_read_push_finish_row(png_ptr);
  188718. }
  188719. if (png_ptr->pass == 6) /* skip top generated row */
  188720. {
  188721. png_push_have_row(png_ptr, png_bytep_NULL);
  188722. png_read_push_finish_row(png_ptr);
  188723. }
  188724. break;
  188725. }
  188726. case 6:
  188727. {
  188728. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188729. png_read_push_finish_row(png_ptr);
  188730. if (png_ptr->pass != 6)
  188731. break;
  188732. png_push_have_row(png_ptr, png_bytep_NULL);
  188733. png_read_push_finish_row(png_ptr);
  188734. }
  188735. }
  188736. }
  188737. else
  188738. #endif
  188739. {
  188740. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188741. png_read_push_finish_row(png_ptr);
  188742. }
  188743. }
  188744. void /* PRIVATE */
  188745. png_read_push_finish_row(png_structp png_ptr)
  188746. {
  188747. #ifdef PNG_USE_LOCAL_ARRAYS
  188748. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188749. /* start of interlace block */
  188750. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188751. /* offset to next interlace block */
  188752. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188753. /* start of interlace block in the y direction */
  188754. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188755. /* offset to next interlace block in the y direction */
  188756. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188757. /* Height of interlace block. This is not currently used - if you need
  188758. * it, uncomment it here and in png.h
  188759. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188760. */
  188761. #endif
  188762. png_ptr->row_number++;
  188763. if (png_ptr->row_number < png_ptr->num_rows)
  188764. return;
  188765. if (png_ptr->interlaced)
  188766. {
  188767. png_ptr->row_number = 0;
  188768. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188769. png_ptr->rowbytes + 1);
  188770. do
  188771. {
  188772. png_ptr->pass++;
  188773. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188774. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188775. (png_ptr->pass == 5 && png_ptr->width < 2))
  188776. png_ptr->pass++;
  188777. if (png_ptr->pass > 7)
  188778. png_ptr->pass--;
  188779. if (png_ptr->pass >= 7)
  188780. break;
  188781. png_ptr->iwidth = (png_ptr->width +
  188782. png_pass_inc[png_ptr->pass] - 1 -
  188783. png_pass_start[png_ptr->pass]) /
  188784. png_pass_inc[png_ptr->pass];
  188785. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188786. png_ptr->iwidth) + 1;
  188787. if (png_ptr->transformations & PNG_INTERLACE)
  188788. break;
  188789. png_ptr->num_rows = (png_ptr->height +
  188790. png_pass_yinc[png_ptr->pass] - 1 -
  188791. png_pass_ystart[png_ptr->pass]) /
  188792. png_pass_yinc[png_ptr->pass];
  188793. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188794. }
  188795. }
  188796. #if defined(PNG_READ_tEXt_SUPPORTED)
  188797. void /* PRIVATE */
  188798. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188799. length)
  188800. {
  188801. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188802. {
  188803. png_error(png_ptr, "Out of place tEXt");
  188804. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188805. }
  188806. #ifdef PNG_MAX_MALLOC_64K
  188807. png_ptr->skip_length = 0; /* This may not be necessary */
  188808. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188809. {
  188810. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188811. png_ptr->skip_length = length - (png_uint_32)65535L;
  188812. length = (png_uint_32)65535L;
  188813. }
  188814. #endif
  188815. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188816. (png_uint_32)(length+1));
  188817. png_ptr->current_text[length] = '\0';
  188818. png_ptr->current_text_ptr = png_ptr->current_text;
  188819. png_ptr->current_text_size = (png_size_t)length;
  188820. png_ptr->current_text_left = (png_size_t)length;
  188821. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  188822. }
  188823. void /* PRIVATE */
  188824. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  188825. {
  188826. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188827. {
  188828. png_size_t text_size;
  188829. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188830. text_size = png_ptr->buffer_size;
  188831. else
  188832. text_size = png_ptr->current_text_left;
  188833. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188834. png_ptr->current_text_left -= text_size;
  188835. png_ptr->current_text_ptr += text_size;
  188836. }
  188837. if (!(png_ptr->current_text_left))
  188838. {
  188839. png_textp text_ptr;
  188840. png_charp text;
  188841. png_charp key;
  188842. int ret;
  188843. if (png_ptr->buffer_size < 4)
  188844. {
  188845. png_push_save_buffer(png_ptr);
  188846. return;
  188847. }
  188848. png_push_crc_finish(png_ptr);
  188849. #if defined(PNG_MAX_MALLOC_64K)
  188850. if (png_ptr->skip_length)
  188851. return;
  188852. #endif
  188853. key = png_ptr->current_text;
  188854. for (text = key; *text; text++)
  188855. /* empty loop */ ;
  188856. if (text < key + png_ptr->current_text_size)
  188857. text++;
  188858. text_ptr = (png_textp)png_malloc(png_ptr,
  188859. (png_uint_32)png_sizeof(png_text));
  188860. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188861. text_ptr->key = key;
  188862. #ifdef PNG_iTXt_SUPPORTED
  188863. text_ptr->lang = NULL;
  188864. text_ptr->lang_key = NULL;
  188865. #endif
  188866. text_ptr->text = text;
  188867. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188868. png_free(png_ptr, key);
  188869. png_free(png_ptr, text_ptr);
  188870. png_ptr->current_text = NULL;
  188871. if (ret)
  188872. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188873. }
  188874. }
  188875. #endif
  188876. #if defined(PNG_READ_zTXt_SUPPORTED)
  188877. void /* PRIVATE */
  188878. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188879. length)
  188880. {
  188881. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188882. {
  188883. png_error(png_ptr, "Out of place zTXt");
  188884. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188885. }
  188886. #ifdef PNG_MAX_MALLOC_64K
  188887. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  188888. * to be able to store the uncompressed data. Actually, the threshold
  188889. * is probably around 32K, but it isn't as definite as 64K is.
  188890. */
  188891. if (length > (png_uint_32)65535L)
  188892. {
  188893. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  188894. png_push_crc_skip(png_ptr, length);
  188895. return;
  188896. }
  188897. #endif
  188898. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188899. (png_uint_32)(length+1));
  188900. png_ptr->current_text[length] = '\0';
  188901. png_ptr->current_text_ptr = png_ptr->current_text;
  188902. png_ptr->current_text_size = (png_size_t)length;
  188903. png_ptr->current_text_left = (png_size_t)length;
  188904. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  188905. }
  188906. void /* PRIVATE */
  188907. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  188908. {
  188909. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188910. {
  188911. png_size_t text_size;
  188912. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  188913. text_size = png_ptr->buffer_size;
  188914. else
  188915. text_size = png_ptr->current_text_left;
  188916. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188917. png_ptr->current_text_left -= text_size;
  188918. png_ptr->current_text_ptr += text_size;
  188919. }
  188920. if (!(png_ptr->current_text_left))
  188921. {
  188922. png_textp text_ptr;
  188923. png_charp text;
  188924. png_charp key;
  188925. int ret;
  188926. png_size_t text_size, key_size;
  188927. if (png_ptr->buffer_size < 4)
  188928. {
  188929. png_push_save_buffer(png_ptr);
  188930. return;
  188931. }
  188932. png_push_crc_finish(png_ptr);
  188933. key = png_ptr->current_text;
  188934. for (text = key; *text; text++)
  188935. /* empty loop */ ;
  188936. /* zTXt can't have zero text */
  188937. if (text >= key + png_ptr->current_text_size)
  188938. {
  188939. png_ptr->current_text = NULL;
  188940. png_free(png_ptr, key);
  188941. return;
  188942. }
  188943. text++;
  188944. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  188945. {
  188946. png_ptr->current_text = NULL;
  188947. png_free(png_ptr, key);
  188948. return;
  188949. }
  188950. text++;
  188951. png_ptr->zstream.next_in = (png_bytep )text;
  188952. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  188953. (text - key));
  188954. png_ptr->zstream.next_out = png_ptr->zbuf;
  188955. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188956. key_size = text - key;
  188957. text_size = 0;
  188958. text = NULL;
  188959. ret = Z_STREAM_END;
  188960. while (png_ptr->zstream.avail_in)
  188961. {
  188962. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188963. if (ret != Z_OK && ret != Z_STREAM_END)
  188964. {
  188965. inflateReset(&png_ptr->zstream);
  188966. png_ptr->zstream.avail_in = 0;
  188967. png_ptr->current_text = NULL;
  188968. png_free(png_ptr, key);
  188969. png_free(png_ptr, text);
  188970. return;
  188971. }
  188972. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  188973. {
  188974. if (text == NULL)
  188975. {
  188976. text = (png_charp)png_malloc(png_ptr,
  188977. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188978. + key_size + 1));
  188979. png_memcpy(text + key_size, png_ptr->zbuf,
  188980. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188981. png_memcpy(text, key, key_size);
  188982. text_size = key_size + png_ptr->zbuf_size -
  188983. png_ptr->zstream.avail_out;
  188984. *(text + text_size) = '\0';
  188985. }
  188986. else
  188987. {
  188988. png_charp tmp;
  188989. tmp = text;
  188990. text = (png_charp)png_malloc(png_ptr, text_size +
  188991. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188992. + 1));
  188993. png_memcpy(text, tmp, text_size);
  188994. png_free(png_ptr, tmp);
  188995. png_memcpy(text + text_size, png_ptr->zbuf,
  188996. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188997. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188998. *(text + text_size) = '\0';
  188999. }
  189000. if (ret != Z_STREAM_END)
  189001. {
  189002. png_ptr->zstream.next_out = png_ptr->zbuf;
  189003. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189004. }
  189005. }
  189006. else
  189007. {
  189008. break;
  189009. }
  189010. if (ret == Z_STREAM_END)
  189011. break;
  189012. }
  189013. inflateReset(&png_ptr->zstream);
  189014. png_ptr->zstream.avail_in = 0;
  189015. if (ret != Z_STREAM_END)
  189016. {
  189017. png_ptr->current_text = NULL;
  189018. png_free(png_ptr, key);
  189019. png_free(png_ptr, text);
  189020. return;
  189021. }
  189022. png_ptr->current_text = NULL;
  189023. png_free(png_ptr, key);
  189024. key = text;
  189025. text += key_size;
  189026. text_ptr = (png_textp)png_malloc(png_ptr,
  189027. (png_uint_32)png_sizeof(png_text));
  189028. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189029. text_ptr->key = key;
  189030. #ifdef PNG_iTXt_SUPPORTED
  189031. text_ptr->lang = NULL;
  189032. text_ptr->lang_key = NULL;
  189033. #endif
  189034. text_ptr->text = text;
  189035. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189036. png_free(png_ptr, key);
  189037. png_free(png_ptr, text_ptr);
  189038. if (ret)
  189039. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189040. }
  189041. }
  189042. #endif
  189043. #if defined(PNG_READ_iTXt_SUPPORTED)
  189044. void /* PRIVATE */
  189045. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189046. length)
  189047. {
  189048. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189049. {
  189050. png_error(png_ptr, "Out of place iTXt");
  189051. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189052. }
  189053. #ifdef PNG_MAX_MALLOC_64K
  189054. png_ptr->skip_length = 0; /* This may not be necessary */
  189055. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189056. {
  189057. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189058. png_ptr->skip_length = length - (png_uint_32)65535L;
  189059. length = (png_uint_32)65535L;
  189060. }
  189061. #endif
  189062. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189063. (png_uint_32)(length+1));
  189064. png_ptr->current_text[length] = '\0';
  189065. png_ptr->current_text_ptr = png_ptr->current_text;
  189066. png_ptr->current_text_size = (png_size_t)length;
  189067. png_ptr->current_text_left = (png_size_t)length;
  189068. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189069. }
  189070. void /* PRIVATE */
  189071. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189072. {
  189073. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189074. {
  189075. png_size_t text_size;
  189076. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189077. text_size = png_ptr->buffer_size;
  189078. else
  189079. text_size = png_ptr->current_text_left;
  189080. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189081. png_ptr->current_text_left -= text_size;
  189082. png_ptr->current_text_ptr += text_size;
  189083. }
  189084. if (!(png_ptr->current_text_left))
  189085. {
  189086. png_textp text_ptr;
  189087. png_charp key;
  189088. int comp_flag;
  189089. png_charp lang;
  189090. png_charp lang_key;
  189091. png_charp text;
  189092. int ret;
  189093. if (png_ptr->buffer_size < 4)
  189094. {
  189095. png_push_save_buffer(png_ptr);
  189096. return;
  189097. }
  189098. png_push_crc_finish(png_ptr);
  189099. #if defined(PNG_MAX_MALLOC_64K)
  189100. if (png_ptr->skip_length)
  189101. return;
  189102. #endif
  189103. key = png_ptr->current_text;
  189104. for (lang = key; *lang; lang++)
  189105. /* empty loop */ ;
  189106. if (lang < key + png_ptr->current_text_size - 3)
  189107. lang++;
  189108. comp_flag = *lang++;
  189109. lang++; /* skip comp_type, always zero */
  189110. for (lang_key = lang; *lang_key; lang_key++)
  189111. /* empty loop */ ;
  189112. lang_key++; /* skip NUL separator */
  189113. text=lang_key;
  189114. if (lang_key < key + png_ptr->current_text_size - 1)
  189115. {
  189116. for (; *text; text++)
  189117. /* empty loop */ ;
  189118. }
  189119. if (text < key + png_ptr->current_text_size)
  189120. text++;
  189121. text_ptr = (png_textp)png_malloc(png_ptr,
  189122. (png_uint_32)png_sizeof(png_text));
  189123. text_ptr->compression = comp_flag + 2;
  189124. text_ptr->key = key;
  189125. text_ptr->lang = lang;
  189126. text_ptr->lang_key = lang_key;
  189127. text_ptr->text = text;
  189128. text_ptr->text_length = 0;
  189129. text_ptr->itxt_length = png_strlen(text);
  189130. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189131. png_ptr->current_text = NULL;
  189132. png_free(png_ptr, text_ptr);
  189133. if (ret)
  189134. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189135. }
  189136. }
  189137. #endif
  189138. /* This function is called when we haven't found a handler for this
  189139. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189140. * name or a critical chunk), the chunk is (currently) silently ignored.
  189141. */
  189142. void /* PRIVATE */
  189143. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189144. length)
  189145. {
  189146. png_uint_32 skip=0;
  189147. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189148. if (!(png_ptr->chunk_name[0] & 0x20))
  189149. {
  189150. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189151. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189152. PNG_HANDLE_CHUNK_ALWAYS
  189153. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189154. && png_ptr->read_user_chunk_fn == NULL
  189155. #endif
  189156. )
  189157. #endif
  189158. png_chunk_error(png_ptr, "unknown critical chunk");
  189159. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189160. }
  189161. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189162. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189163. {
  189164. #ifdef PNG_MAX_MALLOC_64K
  189165. if (length > (png_uint_32)65535L)
  189166. {
  189167. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189168. skip = length - (png_uint_32)65535L;
  189169. length = (png_uint_32)65535L;
  189170. }
  189171. #endif
  189172. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189173. (png_charp)png_ptr->chunk_name, 5);
  189174. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189175. png_ptr->unknown_chunk.size = (png_size_t)length;
  189176. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189177. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189178. if(png_ptr->read_user_chunk_fn != NULL)
  189179. {
  189180. /* callback to user unknown chunk handler */
  189181. int ret;
  189182. ret = (*(png_ptr->read_user_chunk_fn))
  189183. (png_ptr, &png_ptr->unknown_chunk);
  189184. if (ret < 0)
  189185. png_chunk_error(png_ptr, "error in user chunk");
  189186. if (ret == 0)
  189187. {
  189188. if (!(png_ptr->chunk_name[0] & 0x20))
  189189. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189190. PNG_HANDLE_CHUNK_ALWAYS)
  189191. png_chunk_error(png_ptr, "unknown critical chunk");
  189192. png_set_unknown_chunks(png_ptr, info_ptr,
  189193. &png_ptr->unknown_chunk, 1);
  189194. }
  189195. }
  189196. #else
  189197. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189198. #endif
  189199. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189200. png_ptr->unknown_chunk.data = NULL;
  189201. }
  189202. else
  189203. #endif
  189204. skip=length;
  189205. png_push_crc_skip(png_ptr, skip);
  189206. }
  189207. void /* PRIVATE */
  189208. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189209. {
  189210. if (png_ptr->info_fn != NULL)
  189211. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189212. }
  189213. void /* PRIVATE */
  189214. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189215. {
  189216. if (png_ptr->end_fn != NULL)
  189217. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189218. }
  189219. void /* PRIVATE */
  189220. png_push_have_row(png_structp png_ptr, png_bytep row)
  189221. {
  189222. if (png_ptr->row_fn != NULL)
  189223. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189224. (int)png_ptr->pass);
  189225. }
  189226. void PNGAPI
  189227. png_progressive_combine_row (png_structp png_ptr,
  189228. png_bytep old_row, png_bytep new_row)
  189229. {
  189230. #ifdef PNG_USE_LOCAL_ARRAYS
  189231. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189232. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189233. #endif
  189234. if(png_ptr == NULL) return;
  189235. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189236. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189237. }
  189238. void PNGAPI
  189239. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189240. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189241. png_progressive_end_ptr end_fn)
  189242. {
  189243. if(png_ptr == NULL) return;
  189244. png_ptr->info_fn = info_fn;
  189245. png_ptr->row_fn = row_fn;
  189246. png_ptr->end_fn = end_fn;
  189247. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189248. }
  189249. png_voidp PNGAPI
  189250. png_get_progressive_ptr(png_structp png_ptr)
  189251. {
  189252. if(png_ptr == NULL) return (NULL);
  189253. return png_ptr->io_ptr;
  189254. }
  189255. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189256. /*** End of inlined file: pngpread.c ***/
  189257. /*** Start of inlined file: pngrio.c ***/
  189258. /* pngrio.c - functions for data input
  189259. *
  189260. * Last changed in libpng 1.2.13 November 13, 2006
  189261. * For conditions of distribution and use, see copyright notice in png.h
  189262. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189263. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189264. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189265. *
  189266. * This file provides a location for all input. Users who need
  189267. * special handling are expected to write a function that has the same
  189268. * arguments as this and performs a similar function, but that possibly
  189269. * has a different input method. Note that you shouldn't change this
  189270. * function, but rather write a replacement function and then make
  189271. * libpng use it at run time with png_set_read_fn(...).
  189272. */
  189273. #define PNG_INTERNAL
  189274. #if defined(PNG_READ_SUPPORTED)
  189275. /* Read the data from whatever input you are using. The default routine
  189276. reads from a file pointer. Note that this routine sometimes gets called
  189277. with very small lengths, so you should implement some kind of simple
  189278. buffering if you are using unbuffered reads. This should never be asked
  189279. to read more then 64K on a 16 bit machine. */
  189280. void /* PRIVATE */
  189281. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189282. {
  189283. png_debug1(4,"reading %d bytes\n", (int)length);
  189284. if (png_ptr->read_data_fn != NULL)
  189285. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189286. else
  189287. png_error(png_ptr, "Call to NULL read function");
  189288. }
  189289. #if !defined(PNG_NO_STDIO)
  189290. /* This is the function that does the actual reading of data. If you are
  189291. not reading from a standard C stream, you should create a replacement
  189292. read_data function and use it at run time with png_set_read_fn(), rather
  189293. than changing the library. */
  189294. #ifndef USE_FAR_KEYWORD
  189295. void PNGAPI
  189296. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189297. {
  189298. png_size_t check;
  189299. if(png_ptr == NULL) return;
  189300. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189301. * instead of an int, which is what fread() actually returns.
  189302. */
  189303. #if defined(_WIN32_WCE)
  189304. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189305. check = 0;
  189306. #else
  189307. check = (png_size_t)fread(data, (png_size_t)1, length,
  189308. (png_FILE_p)png_ptr->io_ptr);
  189309. #endif
  189310. if (check != length)
  189311. png_error(png_ptr, "Read Error");
  189312. }
  189313. #else
  189314. /* this is the model-independent version. Since the standard I/O library
  189315. can't handle far buffers in the medium and small models, we have to copy
  189316. the data.
  189317. */
  189318. #define NEAR_BUF_SIZE 1024
  189319. #define MIN(a,b) (a <= b ? a : b)
  189320. static void PNGAPI
  189321. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189322. {
  189323. int check;
  189324. png_byte *n_data;
  189325. png_FILE_p io_ptr;
  189326. if(png_ptr == NULL) return;
  189327. /* Check if data really is near. If so, use usual code. */
  189328. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189329. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189330. if ((png_bytep)n_data == data)
  189331. {
  189332. #if defined(_WIN32_WCE)
  189333. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189334. check = 0;
  189335. #else
  189336. check = fread(n_data, 1, length, io_ptr);
  189337. #endif
  189338. }
  189339. else
  189340. {
  189341. png_byte buf[NEAR_BUF_SIZE];
  189342. png_size_t read, remaining, err;
  189343. check = 0;
  189344. remaining = length;
  189345. do
  189346. {
  189347. read = MIN(NEAR_BUF_SIZE, remaining);
  189348. #if defined(_WIN32_WCE)
  189349. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189350. err = 0;
  189351. #else
  189352. err = fread(buf, (png_size_t)1, read, io_ptr);
  189353. #endif
  189354. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189355. if(err != read)
  189356. break;
  189357. else
  189358. check += err;
  189359. data += read;
  189360. remaining -= read;
  189361. }
  189362. while (remaining != 0);
  189363. }
  189364. if ((png_uint_32)check != (png_uint_32)length)
  189365. png_error(png_ptr, "read Error");
  189366. }
  189367. #endif
  189368. #endif
  189369. /* This function allows the application to supply a new input function
  189370. for libpng if standard C streams aren't being used.
  189371. This function takes as its arguments:
  189372. png_ptr - pointer to a png input data structure
  189373. io_ptr - pointer to user supplied structure containing info about
  189374. the input functions. May be NULL.
  189375. read_data_fn - pointer to a new input function that takes as its
  189376. arguments a pointer to a png_struct, a pointer to
  189377. a location where input data can be stored, and a 32-bit
  189378. unsigned int that is the number of bytes to be read.
  189379. To exit and output any fatal error messages the new write
  189380. function should call png_error(png_ptr, "Error msg"). */
  189381. void PNGAPI
  189382. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189383. png_rw_ptr read_data_fn)
  189384. {
  189385. if(png_ptr == NULL) return;
  189386. png_ptr->io_ptr = io_ptr;
  189387. #if !defined(PNG_NO_STDIO)
  189388. if (read_data_fn != NULL)
  189389. png_ptr->read_data_fn = read_data_fn;
  189390. else
  189391. png_ptr->read_data_fn = png_default_read_data;
  189392. #else
  189393. png_ptr->read_data_fn = read_data_fn;
  189394. #endif
  189395. /* It is an error to write to a read device */
  189396. if (png_ptr->write_data_fn != NULL)
  189397. {
  189398. png_ptr->write_data_fn = NULL;
  189399. png_warning(png_ptr,
  189400. "It's an error to set both read_data_fn and write_data_fn in the ");
  189401. png_warning(png_ptr,
  189402. "same structure. Resetting write_data_fn to NULL.");
  189403. }
  189404. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189405. png_ptr->output_flush_fn = NULL;
  189406. #endif
  189407. }
  189408. #endif /* PNG_READ_SUPPORTED */
  189409. /*** End of inlined file: pngrio.c ***/
  189410. /*** Start of inlined file: pngrtran.c ***/
  189411. /* pngrtran.c - transforms the data in a row for PNG readers
  189412. *
  189413. * Last changed in libpng 1.2.21 [October 4, 2007]
  189414. * For conditions of distribution and use, see copyright notice in png.h
  189415. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189416. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189417. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189418. *
  189419. * This file contains functions optionally called by an application
  189420. * in order to tell libpng how to handle data when reading a PNG.
  189421. * Transformations that are used in both reading and writing are
  189422. * in pngtrans.c.
  189423. */
  189424. #define PNG_INTERNAL
  189425. #if defined(PNG_READ_SUPPORTED)
  189426. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189427. void PNGAPI
  189428. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189429. {
  189430. png_debug(1, "in png_set_crc_action\n");
  189431. /* Tell libpng how we react to CRC errors in critical chunks */
  189432. if(png_ptr == NULL) return;
  189433. switch (crit_action)
  189434. {
  189435. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189436. break;
  189437. case PNG_CRC_WARN_USE: /* warn/use data */
  189438. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189439. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189440. break;
  189441. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189442. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189443. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189444. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189445. break;
  189446. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189447. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189448. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189449. case PNG_CRC_DEFAULT:
  189450. default:
  189451. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189452. break;
  189453. }
  189454. switch (ancil_action)
  189455. {
  189456. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189457. break;
  189458. case PNG_CRC_WARN_USE: /* warn/use data */
  189459. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189460. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189461. break;
  189462. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189463. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189464. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189465. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189466. break;
  189467. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189468. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189469. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189470. break;
  189471. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189472. case PNG_CRC_DEFAULT:
  189473. default:
  189474. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189475. break;
  189476. }
  189477. }
  189478. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189479. defined(PNG_FLOATING_POINT_SUPPORTED)
  189480. /* handle alpha and tRNS via a background color */
  189481. void PNGAPI
  189482. png_set_background(png_structp png_ptr,
  189483. png_color_16p background_color, int background_gamma_code,
  189484. int need_expand, double background_gamma)
  189485. {
  189486. png_debug(1, "in png_set_background\n");
  189487. if(png_ptr == NULL) return;
  189488. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189489. {
  189490. png_warning(png_ptr, "Application must supply a known background gamma");
  189491. return;
  189492. }
  189493. png_ptr->transformations |= PNG_BACKGROUND;
  189494. png_memcpy(&(png_ptr->background), background_color,
  189495. png_sizeof(png_color_16));
  189496. png_ptr->background_gamma = (float)background_gamma;
  189497. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189498. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189499. }
  189500. #endif
  189501. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189502. /* strip 16 bit depth files to 8 bit depth */
  189503. void PNGAPI
  189504. png_set_strip_16(png_structp png_ptr)
  189505. {
  189506. png_debug(1, "in png_set_strip_16\n");
  189507. if(png_ptr == NULL) return;
  189508. png_ptr->transformations |= PNG_16_TO_8;
  189509. }
  189510. #endif
  189511. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189512. void PNGAPI
  189513. png_set_strip_alpha(png_structp png_ptr)
  189514. {
  189515. png_debug(1, "in png_set_strip_alpha\n");
  189516. if(png_ptr == NULL) return;
  189517. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189518. }
  189519. #endif
  189520. #if defined(PNG_READ_DITHER_SUPPORTED)
  189521. /* Dither file to 8 bit. Supply a palette, the current number
  189522. * of elements in the palette, the maximum number of elements
  189523. * allowed, and a histogram if possible. If the current number
  189524. * of colors is greater then the maximum number, the palette will be
  189525. * modified to fit in the maximum number. "full_dither" indicates
  189526. * whether we need a dithering cube set up for RGB images, or if we
  189527. * simply are reducing the number of colors in a paletted image.
  189528. */
  189529. typedef struct png_dsort_struct
  189530. {
  189531. struct png_dsort_struct FAR * next;
  189532. png_byte left;
  189533. png_byte right;
  189534. } png_dsort;
  189535. typedef png_dsort FAR * png_dsortp;
  189536. typedef png_dsort FAR * FAR * png_dsortpp;
  189537. void PNGAPI
  189538. png_set_dither(png_structp png_ptr, png_colorp palette,
  189539. int num_palette, int maximum_colors, png_uint_16p histogram,
  189540. int full_dither)
  189541. {
  189542. png_debug(1, "in png_set_dither\n");
  189543. if(png_ptr == NULL) return;
  189544. png_ptr->transformations |= PNG_DITHER;
  189545. if (!full_dither)
  189546. {
  189547. int i;
  189548. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189549. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189550. for (i = 0; i < num_palette; i++)
  189551. png_ptr->dither_index[i] = (png_byte)i;
  189552. }
  189553. if (num_palette > maximum_colors)
  189554. {
  189555. if (histogram != NULL)
  189556. {
  189557. /* This is easy enough, just throw out the least used colors.
  189558. Perhaps not the best solution, but good enough. */
  189559. int i;
  189560. /* initialize an array to sort colors */
  189561. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189562. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189563. /* initialize the dither_sort array */
  189564. for (i = 0; i < num_palette; i++)
  189565. png_ptr->dither_sort[i] = (png_byte)i;
  189566. /* Find the least used palette entries by starting a
  189567. bubble sort, and running it until we have sorted
  189568. out enough colors. Note that we don't care about
  189569. sorting all the colors, just finding which are
  189570. least used. */
  189571. for (i = num_palette - 1; i >= maximum_colors; i--)
  189572. {
  189573. int done; /* to stop early if the list is pre-sorted */
  189574. int j;
  189575. done = 1;
  189576. for (j = 0; j < i; j++)
  189577. {
  189578. if (histogram[png_ptr->dither_sort[j]]
  189579. < histogram[png_ptr->dither_sort[j + 1]])
  189580. {
  189581. png_byte t;
  189582. t = png_ptr->dither_sort[j];
  189583. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189584. png_ptr->dither_sort[j + 1] = t;
  189585. done = 0;
  189586. }
  189587. }
  189588. if (done)
  189589. break;
  189590. }
  189591. /* swap the palette around, and set up a table, if necessary */
  189592. if (full_dither)
  189593. {
  189594. int j = num_palette;
  189595. /* put all the useful colors within the max, but don't
  189596. move the others */
  189597. for (i = 0; i < maximum_colors; i++)
  189598. {
  189599. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189600. {
  189601. do
  189602. j--;
  189603. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189604. palette[i] = palette[j];
  189605. }
  189606. }
  189607. }
  189608. else
  189609. {
  189610. int j = num_palette;
  189611. /* move all the used colors inside the max limit, and
  189612. develop a translation table */
  189613. for (i = 0; i < maximum_colors; i++)
  189614. {
  189615. /* only move the colors we need to */
  189616. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189617. {
  189618. png_color tmp_color;
  189619. do
  189620. j--;
  189621. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189622. tmp_color = palette[j];
  189623. palette[j] = palette[i];
  189624. palette[i] = tmp_color;
  189625. /* indicate where the color went */
  189626. png_ptr->dither_index[j] = (png_byte)i;
  189627. png_ptr->dither_index[i] = (png_byte)j;
  189628. }
  189629. }
  189630. /* find closest color for those colors we are not using */
  189631. for (i = 0; i < num_palette; i++)
  189632. {
  189633. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189634. {
  189635. int min_d, k, min_k, d_index;
  189636. /* find the closest color to one we threw out */
  189637. d_index = png_ptr->dither_index[i];
  189638. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189639. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189640. {
  189641. int d;
  189642. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189643. if (d < min_d)
  189644. {
  189645. min_d = d;
  189646. min_k = k;
  189647. }
  189648. }
  189649. /* point to closest color */
  189650. png_ptr->dither_index[i] = (png_byte)min_k;
  189651. }
  189652. }
  189653. }
  189654. png_free(png_ptr, png_ptr->dither_sort);
  189655. png_ptr->dither_sort=NULL;
  189656. }
  189657. else
  189658. {
  189659. /* This is much harder to do simply (and quickly). Perhaps
  189660. we need to go through a median cut routine, but those
  189661. don't always behave themselves with only a few colors
  189662. as input. So we will just find the closest two colors,
  189663. and throw out one of them (chosen somewhat randomly).
  189664. [We don't understand this at all, so if someone wants to
  189665. work on improving it, be our guest - AED, GRP]
  189666. */
  189667. int i;
  189668. int max_d;
  189669. int num_new_palette;
  189670. png_dsortp t;
  189671. png_dsortpp hash;
  189672. t=NULL;
  189673. /* initialize palette index arrays */
  189674. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189675. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189676. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189677. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189678. /* initialize the sort array */
  189679. for (i = 0; i < num_palette; i++)
  189680. {
  189681. png_ptr->index_to_palette[i] = (png_byte)i;
  189682. png_ptr->palette_to_index[i] = (png_byte)i;
  189683. }
  189684. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189685. png_sizeof (png_dsortp)));
  189686. for (i = 0; i < 769; i++)
  189687. hash[i] = NULL;
  189688. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189689. num_new_palette = num_palette;
  189690. /* initial wild guess at how far apart the farthest pixel
  189691. pair we will be eliminating will be. Larger
  189692. numbers mean more areas will be allocated, Smaller
  189693. numbers run the risk of not saving enough data, and
  189694. having to do this all over again.
  189695. I have not done extensive checking on this number.
  189696. */
  189697. max_d = 96;
  189698. while (num_new_palette > maximum_colors)
  189699. {
  189700. for (i = 0; i < num_new_palette - 1; i++)
  189701. {
  189702. int j;
  189703. for (j = i + 1; j < num_new_palette; j++)
  189704. {
  189705. int d;
  189706. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189707. if (d <= max_d)
  189708. {
  189709. t = (png_dsortp)png_malloc_warn(png_ptr,
  189710. (png_uint_32)(png_sizeof(png_dsort)));
  189711. if (t == NULL)
  189712. break;
  189713. t->next = hash[d];
  189714. t->left = (png_byte)i;
  189715. t->right = (png_byte)j;
  189716. hash[d] = t;
  189717. }
  189718. }
  189719. if (t == NULL)
  189720. break;
  189721. }
  189722. if (t != NULL)
  189723. for (i = 0; i <= max_d; i++)
  189724. {
  189725. if (hash[i] != NULL)
  189726. {
  189727. png_dsortp p;
  189728. for (p = hash[i]; p; p = p->next)
  189729. {
  189730. if ((int)png_ptr->index_to_palette[p->left]
  189731. < num_new_palette &&
  189732. (int)png_ptr->index_to_palette[p->right]
  189733. < num_new_palette)
  189734. {
  189735. int j, next_j;
  189736. if (num_new_palette & 0x01)
  189737. {
  189738. j = p->left;
  189739. next_j = p->right;
  189740. }
  189741. else
  189742. {
  189743. j = p->right;
  189744. next_j = p->left;
  189745. }
  189746. num_new_palette--;
  189747. palette[png_ptr->index_to_palette[j]]
  189748. = palette[num_new_palette];
  189749. if (!full_dither)
  189750. {
  189751. int k;
  189752. for (k = 0; k < num_palette; k++)
  189753. {
  189754. if (png_ptr->dither_index[k] ==
  189755. png_ptr->index_to_palette[j])
  189756. png_ptr->dither_index[k] =
  189757. png_ptr->index_to_palette[next_j];
  189758. if ((int)png_ptr->dither_index[k] ==
  189759. num_new_palette)
  189760. png_ptr->dither_index[k] =
  189761. png_ptr->index_to_palette[j];
  189762. }
  189763. }
  189764. png_ptr->index_to_palette[png_ptr->palette_to_index
  189765. [num_new_palette]] = png_ptr->index_to_palette[j];
  189766. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189767. = png_ptr->palette_to_index[num_new_palette];
  189768. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189769. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189770. }
  189771. if (num_new_palette <= maximum_colors)
  189772. break;
  189773. }
  189774. if (num_new_palette <= maximum_colors)
  189775. break;
  189776. }
  189777. }
  189778. for (i = 0; i < 769; i++)
  189779. {
  189780. if (hash[i] != NULL)
  189781. {
  189782. png_dsortp p = hash[i];
  189783. while (p)
  189784. {
  189785. t = p->next;
  189786. png_free(png_ptr, p);
  189787. p = t;
  189788. }
  189789. }
  189790. hash[i] = 0;
  189791. }
  189792. max_d += 96;
  189793. }
  189794. png_free(png_ptr, hash);
  189795. png_free(png_ptr, png_ptr->palette_to_index);
  189796. png_free(png_ptr, png_ptr->index_to_palette);
  189797. png_ptr->palette_to_index=NULL;
  189798. png_ptr->index_to_palette=NULL;
  189799. }
  189800. num_palette = maximum_colors;
  189801. }
  189802. if (png_ptr->palette == NULL)
  189803. {
  189804. png_ptr->palette = palette;
  189805. }
  189806. png_ptr->num_palette = (png_uint_16)num_palette;
  189807. if (full_dither)
  189808. {
  189809. int i;
  189810. png_bytep distance;
  189811. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189812. PNG_DITHER_BLUE_BITS;
  189813. int num_red = (1 << PNG_DITHER_RED_BITS);
  189814. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189815. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  189816. png_size_t num_entries = ((png_size_t)1 << total_bits);
  189817. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  189818. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  189819. png_memset(png_ptr->palette_lookup, 0, num_entries *
  189820. png_sizeof (png_byte));
  189821. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  189822. png_sizeof(png_byte)));
  189823. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  189824. for (i = 0; i < num_palette; i++)
  189825. {
  189826. int ir, ig, ib;
  189827. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  189828. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  189829. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  189830. for (ir = 0; ir < num_red; ir++)
  189831. {
  189832. /* int dr = abs(ir - r); */
  189833. int dr = ((ir > r) ? ir - r : r - ir);
  189834. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  189835. for (ig = 0; ig < num_green; ig++)
  189836. {
  189837. /* int dg = abs(ig - g); */
  189838. int dg = ((ig > g) ? ig - g : g - ig);
  189839. int dt = dr + dg;
  189840. int dm = ((dr > dg) ? dr : dg);
  189841. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  189842. for (ib = 0; ib < num_blue; ib++)
  189843. {
  189844. int d_index = index_g | ib;
  189845. /* int db = abs(ib - b); */
  189846. int db = ((ib > b) ? ib - b : b - ib);
  189847. int dmax = ((dm > db) ? dm : db);
  189848. int d = dmax + dt + db;
  189849. if (d < (int)distance[d_index])
  189850. {
  189851. distance[d_index] = (png_byte)d;
  189852. png_ptr->palette_lookup[d_index] = (png_byte)i;
  189853. }
  189854. }
  189855. }
  189856. }
  189857. }
  189858. png_free(png_ptr, distance);
  189859. }
  189860. }
  189861. #endif
  189862. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189863. /* Transform the image from the file_gamma to the screen_gamma. We
  189864. * only do transformations on images where the file_gamma and screen_gamma
  189865. * are not close reciprocals, otherwise it slows things down slightly, and
  189866. * also needlessly introduces small errors.
  189867. *
  189868. * We will turn off gamma transformation later if no semitransparent entries
  189869. * are present in the tRNS array for palette images. We can't do it here
  189870. * because we don't necessarily have the tRNS chunk yet.
  189871. */
  189872. void PNGAPI
  189873. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  189874. {
  189875. png_debug(1, "in png_set_gamma\n");
  189876. if(png_ptr == NULL) return;
  189877. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  189878. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  189879. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  189880. png_ptr->transformations |= PNG_GAMMA;
  189881. png_ptr->gamma = (float)file_gamma;
  189882. png_ptr->screen_gamma = (float)scrn_gamma;
  189883. }
  189884. #endif
  189885. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189886. /* Expand paletted images to RGB, expand grayscale images of
  189887. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  189888. * to alpha channels.
  189889. */
  189890. void PNGAPI
  189891. png_set_expand(png_structp png_ptr)
  189892. {
  189893. png_debug(1, "in png_set_expand\n");
  189894. if(png_ptr == NULL) return;
  189895. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189896. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189897. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189898. #endif
  189899. }
  189900. /* GRR 19990627: the following three functions currently are identical
  189901. * to png_set_expand(). However, it is entirely reasonable that someone
  189902. * might wish to expand an indexed image to RGB but *not* expand a single,
  189903. * fully transparent palette entry to a full alpha channel--perhaps instead
  189904. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  189905. * the transparent color with a particular RGB value, or drop tRNS entirely.
  189906. * IOW, a future version of the library may make the transformations flag
  189907. * a bit more fine-grained, with separate bits for each of these three
  189908. * functions.
  189909. *
  189910. * More to the point, these functions make it obvious what libpng will be
  189911. * doing, whereas "expand" can (and does) mean any number of things.
  189912. *
  189913. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  189914. * to expand only the sample depth but not to expand the tRNS to alpha.
  189915. */
  189916. /* Expand paletted images to RGB. */
  189917. void PNGAPI
  189918. png_set_palette_to_rgb(png_structp png_ptr)
  189919. {
  189920. png_debug(1, "in png_set_palette_to_rgb\n");
  189921. if(png_ptr == NULL) return;
  189922. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189923. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189924. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  189925. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189926. #endif
  189927. }
  189928. #if !defined(PNG_1_0_X)
  189929. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189930. void PNGAPI
  189931. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  189932. {
  189933. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  189934. if(png_ptr == NULL) return;
  189935. png_ptr->transformations |= PNG_EXPAND;
  189936. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189937. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189938. #endif
  189939. }
  189940. #endif
  189941. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  189942. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189943. /* Deprecated as of libpng-1.2.9 */
  189944. void PNGAPI
  189945. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  189946. {
  189947. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  189948. if(png_ptr == NULL) return;
  189949. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189950. }
  189951. #endif
  189952. /* Expand tRNS chunks to alpha channels. */
  189953. void PNGAPI
  189954. png_set_tRNS_to_alpha(png_structp png_ptr)
  189955. {
  189956. png_debug(1, "in png_set_tRNS_to_alpha\n");
  189957. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189958. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189959. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189960. #endif
  189961. }
  189962. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  189963. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189964. void PNGAPI
  189965. png_set_gray_to_rgb(png_structp png_ptr)
  189966. {
  189967. png_debug(1, "in png_set_gray_to_rgb\n");
  189968. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  189969. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189970. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189971. #endif
  189972. }
  189973. #endif
  189974. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189975. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  189976. /* Convert a RGB image to a grayscale of the same width. This allows us,
  189977. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  189978. */
  189979. void PNGAPI
  189980. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  189981. double green)
  189982. {
  189983. int red_fixed = (int)((float)red*100000.0 + 0.5);
  189984. int green_fixed = (int)((float)green*100000.0 + 0.5);
  189985. if(png_ptr == NULL) return;
  189986. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  189987. }
  189988. #endif
  189989. void PNGAPI
  189990. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  189991. png_fixed_point red, png_fixed_point green)
  189992. {
  189993. png_debug(1, "in png_set_rgb_to_gray\n");
  189994. if(png_ptr == NULL) return;
  189995. switch(error_action)
  189996. {
  189997. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  189998. break;
  189999. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190000. break;
  190001. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190002. }
  190003. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190004. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190005. png_ptr->transformations |= PNG_EXPAND;
  190006. #else
  190007. {
  190008. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190009. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190010. }
  190011. #endif
  190012. {
  190013. png_uint_16 red_int, green_int;
  190014. if(red < 0 || green < 0)
  190015. {
  190016. red_int = 6968; /* .212671 * 32768 + .5 */
  190017. green_int = 23434; /* .715160 * 32768 + .5 */
  190018. }
  190019. else if(red + green < 100000L)
  190020. {
  190021. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190022. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190023. }
  190024. else
  190025. {
  190026. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190027. red_int = 6968;
  190028. green_int = 23434;
  190029. }
  190030. png_ptr->rgb_to_gray_red_coeff = red_int;
  190031. png_ptr->rgb_to_gray_green_coeff = green_int;
  190032. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190033. }
  190034. }
  190035. #endif
  190036. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190037. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190038. defined(PNG_LEGACY_SUPPORTED)
  190039. void PNGAPI
  190040. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190041. read_user_transform_fn)
  190042. {
  190043. png_debug(1, "in png_set_read_user_transform_fn\n");
  190044. if(png_ptr == NULL) return;
  190045. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190046. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190047. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190048. #endif
  190049. #ifdef PNG_LEGACY_SUPPORTED
  190050. if(read_user_transform_fn)
  190051. png_warning(png_ptr,
  190052. "This version of libpng does not support user transforms");
  190053. #endif
  190054. }
  190055. #endif
  190056. /* Initialize everything needed for the read. This includes modifying
  190057. * the palette.
  190058. */
  190059. void /* PRIVATE */
  190060. png_init_read_transformations(png_structp png_ptr)
  190061. {
  190062. png_debug(1, "in png_init_read_transformations\n");
  190063. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190064. if(png_ptr != NULL)
  190065. #endif
  190066. {
  190067. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190068. || defined(PNG_READ_GAMMA_SUPPORTED)
  190069. int color_type = png_ptr->color_type;
  190070. #endif
  190071. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190072. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190073. /* Detect gray background and attempt to enable optimization
  190074. * for gray --> RGB case */
  190075. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190076. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190077. * background color might actually be gray yet not be flagged as such.
  190078. * This is not a problem for the current code, which uses
  190079. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190080. * png_do_gray_to_rgb() transformation.
  190081. */
  190082. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190083. !(color_type & PNG_COLOR_MASK_COLOR))
  190084. {
  190085. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190086. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190087. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190088. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190089. png_ptr->background.red == png_ptr->background.green &&
  190090. png_ptr->background.red == png_ptr->background.blue)
  190091. {
  190092. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190093. png_ptr->background.gray = png_ptr->background.red;
  190094. }
  190095. #endif
  190096. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190097. (png_ptr->transformations & PNG_EXPAND))
  190098. {
  190099. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190100. {
  190101. /* expand background and tRNS chunks */
  190102. switch (png_ptr->bit_depth)
  190103. {
  190104. case 1:
  190105. png_ptr->background.gray *= (png_uint_16)0xff;
  190106. png_ptr->background.red = png_ptr->background.green
  190107. = png_ptr->background.blue = png_ptr->background.gray;
  190108. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190109. {
  190110. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190111. png_ptr->trans_values.red = png_ptr->trans_values.green
  190112. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190113. }
  190114. break;
  190115. case 2:
  190116. png_ptr->background.gray *= (png_uint_16)0x55;
  190117. png_ptr->background.red = png_ptr->background.green
  190118. = png_ptr->background.blue = png_ptr->background.gray;
  190119. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190120. {
  190121. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190122. png_ptr->trans_values.red = png_ptr->trans_values.green
  190123. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190124. }
  190125. break;
  190126. case 4:
  190127. png_ptr->background.gray *= (png_uint_16)0x11;
  190128. png_ptr->background.red = png_ptr->background.green
  190129. = png_ptr->background.blue = png_ptr->background.gray;
  190130. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190131. {
  190132. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190133. png_ptr->trans_values.red = png_ptr->trans_values.green
  190134. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190135. }
  190136. break;
  190137. case 8:
  190138. case 16:
  190139. png_ptr->background.red = png_ptr->background.green
  190140. = png_ptr->background.blue = png_ptr->background.gray;
  190141. break;
  190142. }
  190143. }
  190144. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190145. {
  190146. png_ptr->background.red =
  190147. png_ptr->palette[png_ptr->background.index].red;
  190148. png_ptr->background.green =
  190149. png_ptr->palette[png_ptr->background.index].green;
  190150. png_ptr->background.blue =
  190151. png_ptr->palette[png_ptr->background.index].blue;
  190152. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190153. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190154. {
  190155. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190156. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190157. #endif
  190158. {
  190159. /* invert the alpha channel (in tRNS) unless the pixels are
  190160. going to be expanded, in which case leave it for later */
  190161. int i,istop;
  190162. istop=(int)png_ptr->num_trans;
  190163. for (i=0; i<istop; i++)
  190164. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190165. }
  190166. }
  190167. #endif
  190168. }
  190169. }
  190170. #endif
  190171. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190172. png_ptr->background_1 = png_ptr->background;
  190173. #endif
  190174. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190175. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190176. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190177. < PNG_GAMMA_THRESHOLD))
  190178. {
  190179. int i,k;
  190180. k=0;
  190181. for (i=0; i<png_ptr->num_trans; i++)
  190182. {
  190183. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190184. k=1; /* partial transparency is present */
  190185. }
  190186. if (k == 0)
  190187. png_ptr->transformations &= (~PNG_GAMMA);
  190188. }
  190189. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190190. png_ptr->gamma != 0.0)
  190191. {
  190192. png_build_gamma_table(png_ptr);
  190193. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190194. if (png_ptr->transformations & PNG_BACKGROUND)
  190195. {
  190196. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190197. {
  190198. /* could skip if no transparency and
  190199. */
  190200. png_color back, back_1;
  190201. png_colorp palette = png_ptr->palette;
  190202. int num_palette = png_ptr->num_palette;
  190203. int i;
  190204. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190205. {
  190206. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190207. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190208. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190209. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190210. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190211. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190212. }
  190213. else
  190214. {
  190215. double g, gs;
  190216. switch (png_ptr->background_gamma_type)
  190217. {
  190218. case PNG_BACKGROUND_GAMMA_SCREEN:
  190219. g = (png_ptr->screen_gamma);
  190220. gs = 1.0;
  190221. break;
  190222. case PNG_BACKGROUND_GAMMA_FILE:
  190223. g = 1.0 / (png_ptr->gamma);
  190224. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190225. break;
  190226. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190227. g = 1.0 / (png_ptr->background_gamma);
  190228. gs = 1.0 / (png_ptr->background_gamma *
  190229. png_ptr->screen_gamma);
  190230. break;
  190231. default:
  190232. g = 1.0; /* back_1 */
  190233. gs = 1.0; /* back */
  190234. }
  190235. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190236. {
  190237. back.red = (png_byte)png_ptr->background.red;
  190238. back.green = (png_byte)png_ptr->background.green;
  190239. back.blue = (png_byte)png_ptr->background.blue;
  190240. }
  190241. else
  190242. {
  190243. back.red = (png_byte)(pow(
  190244. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190245. back.green = (png_byte)(pow(
  190246. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190247. back.blue = (png_byte)(pow(
  190248. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190249. }
  190250. back_1.red = (png_byte)(pow(
  190251. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190252. back_1.green = (png_byte)(pow(
  190253. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190254. back_1.blue = (png_byte)(pow(
  190255. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190256. }
  190257. for (i = 0; i < num_palette; i++)
  190258. {
  190259. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190260. {
  190261. if (png_ptr->trans[i] == 0)
  190262. {
  190263. palette[i] = back;
  190264. }
  190265. else /* if (png_ptr->trans[i] != 0xff) */
  190266. {
  190267. png_byte v, w;
  190268. v = png_ptr->gamma_to_1[palette[i].red];
  190269. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190270. palette[i].red = png_ptr->gamma_from_1[w];
  190271. v = png_ptr->gamma_to_1[palette[i].green];
  190272. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190273. palette[i].green = png_ptr->gamma_from_1[w];
  190274. v = png_ptr->gamma_to_1[palette[i].blue];
  190275. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190276. palette[i].blue = png_ptr->gamma_from_1[w];
  190277. }
  190278. }
  190279. else
  190280. {
  190281. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190282. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190283. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190284. }
  190285. }
  190286. }
  190287. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190288. else
  190289. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190290. {
  190291. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190292. double g = 1.0;
  190293. double gs = 1.0;
  190294. switch (png_ptr->background_gamma_type)
  190295. {
  190296. case PNG_BACKGROUND_GAMMA_SCREEN:
  190297. g = (png_ptr->screen_gamma);
  190298. gs = 1.0;
  190299. break;
  190300. case PNG_BACKGROUND_GAMMA_FILE:
  190301. g = 1.0 / (png_ptr->gamma);
  190302. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190303. break;
  190304. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190305. g = 1.0 / (png_ptr->background_gamma);
  190306. gs = 1.0 / (png_ptr->background_gamma *
  190307. png_ptr->screen_gamma);
  190308. break;
  190309. }
  190310. png_ptr->background_1.gray = (png_uint_16)(pow(
  190311. (double)png_ptr->background.gray / m, g) * m + .5);
  190312. png_ptr->background.gray = (png_uint_16)(pow(
  190313. (double)png_ptr->background.gray / m, gs) * m + .5);
  190314. if ((png_ptr->background.red != png_ptr->background.green) ||
  190315. (png_ptr->background.red != png_ptr->background.blue) ||
  190316. (png_ptr->background.red != png_ptr->background.gray))
  190317. {
  190318. /* RGB or RGBA with color background */
  190319. png_ptr->background_1.red = (png_uint_16)(pow(
  190320. (double)png_ptr->background.red / m, g) * m + .5);
  190321. png_ptr->background_1.green = (png_uint_16)(pow(
  190322. (double)png_ptr->background.green / m, g) * m + .5);
  190323. png_ptr->background_1.blue = (png_uint_16)(pow(
  190324. (double)png_ptr->background.blue / m, g) * m + .5);
  190325. png_ptr->background.red = (png_uint_16)(pow(
  190326. (double)png_ptr->background.red / m, gs) * m + .5);
  190327. png_ptr->background.green = (png_uint_16)(pow(
  190328. (double)png_ptr->background.green / m, gs) * m + .5);
  190329. png_ptr->background.blue = (png_uint_16)(pow(
  190330. (double)png_ptr->background.blue / m, gs) * m + .5);
  190331. }
  190332. else
  190333. {
  190334. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190335. png_ptr->background_1.red = png_ptr->background_1.green
  190336. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190337. png_ptr->background.red = png_ptr->background.green
  190338. = png_ptr->background.blue = png_ptr->background.gray;
  190339. }
  190340. }
  190341. }
  190342. else
  190343. /* transformation does not include PNG_BACKGROUND */
  190344. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190345. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190346. {
  190347. png_colorp palette = png_ptr->palette;
  190348. int num_palette = png_ptr->num_palette;
  190349. int i;
  190350. for (i = 0; i < num_palette; i++)
  190351. {
  190352. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190353. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190354. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190355. }
  190356. }
  190357. }
  190358. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190359. else
  190360. #endif
  190361. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190362. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190363. /* No GAMMA transformation */
  190364. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190365. (color_type == PNG_COLOR_TYPE_PALETTE))
  190366. {
  190367. int i;
  190368. int istop = (int)png_ptr->num_trans;
  190369. png_color back;
  190370. png_colorp palette = png_ptr->palette;
  190371. back.red = (png_byte)png_ptr->background.red;
  190372. back.green = (png_byte)png_ptr->background.green;
  190373. back.blue = (png_byte)png_ptr->background.blue;
  190374. for (i = 0; i < istop; i++)
  190375. {
  190376. if (png_ptr->trans[i] == 0)
  190377. {
  190378. palette[i] = back;
  190379. }
  190380. else if (png_ptr->trans[i] != 0xff)
  190381. {
  190382. /* The png_composite() macro is defined in png.h */
  190383. png_composite(palette[i].red, palette[i].red,
  190384. png_ptr->trans[i], back.red);
  190385. png_composite(palette[i].green, palette[i].green,
  190386. png_ptr->trans[i], back.green);
  190387. png_composite(palette[i].blue, palette[i].blue,
  190388. png_ptr->trans[i], back.blue);
  190389. }
  190390. }
  190391. }
  190392. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190393. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190394. if ((png_ptr->transformations & PNG_SHIFT) &&
  190395. (color_type == PNG_COLOR_TYPE_PALETTE))
  190396. {
  190397. png_uint_16 i;
  190398. png_uint_16 istop = png_ptr->num_palette;
  190399. int sr = 8 - png_ptr->sig_bit.red;
  190400. int sg = 8 - png_ptr->sig_bit.green;
  190401. int sb = 8 - png_ptr->sig_bit.blue;
  190402. if (sr < 0 || sr > 8)
  190403. sr = 0;
  190404. if (sg < 0 || sg > 8)
  190405. sg = 0;
  190406. if (sb < 0 || sb > 8)
  190407. sb = 0;
  190408. for (i = 0; i < istop; i++)
  190409. {
  190410. png_ptr->palette[i].red >>= sr;
  190411. png_ptr->palette[i].green >>= sg;
  190412. png_ptr->palette[i].blue >>= sb;
  190413. }
  190414. }
  190415. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190416. }
  190417. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190418. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190419. if(png_ptr)
  190420. return;
  190421. #endif
  190422. }
  190423. /* Modify the info structure to reflect the transformations. The
  190424. * info should be updated so a PNG file could be written with it,
  190425. * assuming the transformations result in valid PNG data.
  190426. */
  190427. void /* PRIVATE */
  190428. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190429. {
  190430. png_debug(1, "in png_read_transform_info\n");
  190431. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190432. if (png_ptr->transformations & PNG_EXPAND)
  190433. {
  190434. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190435. {
  190436. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190437. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190438. else
  190439. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190440. info_ptr->bit_depth = 8;
  190441. info_ptr->num_trans = 0;
  190442. }
  190443. else
  190444. {
  190445. if (png_ptr->num_trans)
  190446. {
  190447. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190448. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190449. else
  190450. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190451. }
  190452. if (info_ptr->bit_depth < 8)
  190453. info_ptr->bit_depth = 8;
  190454. info_ptr->num_trans = 0;
  190455. }
  190456. }
  190457. #endif
  190458. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190459. if (png_ptr->transformations & PNG_BACKGROUND)
  190460. {
  190461. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190462. info_ptr->num_trans = 0;
  190463. info_ptr->background = png_ptr->background;
  190464. }
  190465. #endif
  190466. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190467. if (png_ptr->transformations & PNG_GAMMA)
  190468. {
  190469. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190470. info_ptr->gamma = png_ptr->gamma;
  190471. #endif
  190472. #ifdef PNG_FIXED_POINT_SUPPORTED
  190473. info_ptr->int_gamma = png_ptr->int_gamma;
  190474. #endif
  190475. }
  190476. #endif
  190477. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190478. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190479. info_ptr->bit_depth = 8;
  190480. #endif
  190481. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190482. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190483. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190484. #endif
  190485. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190486. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190487. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190488. #endif
  190489. #if defined(PNG_READ_DITHER_SUPPORTED)
  190490. if (png_ptr->transformations & PNG_DITHER)
  190491. {
  190492. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190493. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190494. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190495. {
  190496. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190497. }
  190498. }
  190499. #endif
  190500. #if defined(PNG_READ_PACK_SUPPORTED)
  190501. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190502. info_ptr->bit_depth = 8;
  190503. #endif
  190504. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190505. info_ptr->channels = 1;
  190506. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190507. info_ptr->channels = 3;
  190508. else
  190509. info_ptr->channels = 1;
  190510. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190511. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190512. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190513. #endif
  190514. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190515. info_ptr->channels++;
  190516. #if defined(PNG_READ_FILLER_SUPPORTED)
  190517. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190518. if ((png_ptr->transformations & PNG_FILLER) &&
  190519. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190520. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190521. {
  190522. info_ptr->channels++;
  190523. /* if adding a true alpha channel not just filler */
  190524. #if !defined(PNG_1_0_X)
  190525. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190526. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190527. #endif
  190528. }
  190529. #endif
  190530. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190531. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190532. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190533. {
  190534. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190535. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190536. if(info_ptr->channels < png_ptr->user_transform_channels)
  190537. info_ptr->channels = png_ptr->user_transform_channels;
  190538. }
  190539. #endif
  190540. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190541. info_ptr->bit_depth);
  190542. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190543. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190544. if(png_ptr)
  190545. return;
  190546. #endif
  190547. }
  190548. /* Transform the row. The order of transformations is significant,
  190549. * and is very touchy. If you add a transformation, take care to
  190550. * decide how it fits in with the other transformations here.
  190551. */
  190552. void /* PRIVATE */
  190553. png_do_read_transformations(png_structp png_ptr)
  190554. {
  190555. png_debug(1, "in png_do_read_transformations\n");
  190556. if (png_ptr->row_buf == NULL)
  190557. {
  190558. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190559. char msg[50];
  190560. png_snprintf2(msg, 50,
  190561. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190562. png_ptr->pass);
  190563. png_error(png_ptr, msg);
  190564. #else
  190565. png_error(png_ptr, "NULL row buffer");
  190566. #endif
  190567. }
  190568. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190569. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190570. /* Application has failed to call either png_read_start_image()
  190571. * or png_read_update_info() after setting transforms that expand
  190572. * pixels. This check added to libpng-1.2.19 */
  190573. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190574. png_error(png_ptr, "Uninitialized row");
  190575. #else
  190576. png_warning(png_ptr, "Uninitialized row");
  190577. #endif
  190578. #endif
  190579. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190580. if (png_ptr->transformations & PNG_EXPAND)
  190581. {
  190582. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190583. {
  190584. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190585. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190586. }
  190587. else
  190588. {
  190589. if (png_ptr->num_trans &&
  190590. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190591. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190592. &(png_ptr->trans_values));
  190593. else
  190594. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190595. NULL);
  190596. }
  190597. }
  190598. #endif
  190599. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190600. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190601. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190602. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190603. #endif
  190604. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190605. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190606. {
  190607. int rgb_error =
  190608. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190609. if(rgb_error)
  190610. {
  190611. png_ptr->rgb_to_gray_status=1;
  190612. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190613. PNG_RGB_TO_GRAY_WARN)
  190614. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190615. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190616. PNG_RGB_TO_GRAY_ERR)
  190617. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190618. }
  190619. }
  190620. #endif
  190621. /*
  190622. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190623. In most cases, the "simple transparency" should be done prior to doing
  190624. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190625. pixel is transparent. You would also need to make sure that the
  190626. transparency information is upgraded to RGB.
  190627. To summarize, the current flow is:
  190628. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190629. with background "in place" if transparent,
  190630. convert to RGB if necessary
  190631. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190632. convert to RGB if necessary
  190633. To support RGB backgrounds for gray images we need:
  190634. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190635. 3 or 6 bytes and composite with background
  190636. "in place" if transparent (3x compare/pixel
  190637. compared to doing composite with gray bkgrnd)
  190638. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190639. remove alpha bytes (3x float operations/pixel
  190640. compared with composite on gray background)
  190641. Greg's change will do this. The reason it wasn't done before is for
  190642. performance, as this increases the per-pixel operations. If we would check
  190643. in advance if the background was gray or RGB, and position the gray-to-RGB
  190644. transform appropriately, then it would save a lot of work/time.
  190645. */
  190646. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190647. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190648. * for performance reasons */
  190649. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190650. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190651. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190652. #endif
  190653. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190654. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190655. ((png_ptr->num_trans != 0 ) ||
  190656. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190657. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190658. &(png_ptr->trans_values), &(png_ptr->background)
  190659. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190660. , &(png_ptr->background_1),
  190661. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190662. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190663. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190664. png_ptr->gamma_shift
  190665. #endif
  190666. );
  190667. #endif
  190668. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190669. if ((png_ptr->transformations & PNG_GAMMA) &&
  190670. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190671. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190672. ((png_ptr->num_trans != 0) ||
  190673. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190674. #endif
  190675. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190676. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190677. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190678. png_ptr->gamma_shift);
  190679. #endif
  190680. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190681. if (png_ptr->transformations & PNG_16_TO_8)
  190682. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190683. #endif
  190684. #if defined(PNG_READ_DITHER_SUPPORTED)
  190685. if (png_ptr->transformations & PNG_DITHER)
  190686. {
  190687. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190688. png_ptr->palette_lookup, png_ptr->dither_index);
  190689. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190690. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190691. }
  190692. #endif
  190693. #if defined(PNG_READ_INVERT_SUPPORTED)
  190694. if (png_ptr->transformations & PNG_INVERT_MONO)
  190695. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190696. #endif
  190697. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190698. if (png_ptr->transformations & PNG_SHIFT)
  190699. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190700. &(png_ptr->shift));
  190701. #endif
  190702. #if defined(PNG_READ_PACK_SUPPORTED)
  190703. if (png_ptr->transformations & PNG_PACK)
  190704. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190705. #endif
  190706. #if defined(PNG_READ_BGR_SUPPORTED)
  190707. if (png_ptr->transformations & PNG_BGR)
  190708. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190709. #endif
  190710. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190711. if (png_ptr->transformations & PNG_PACKSWAP)
  190712. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190713. #endif
  190714. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190715. /* if gray -> RGB, do so now only if we did not do so above */
  190716. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190717. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190718. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190719. #endif
  190720. #if defined(PNG_READ_FILLER_SUPPORTED)
  190721. if (png_ptr->transformations & PNG_FILLER)
  190722. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190723. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190724. #endif
  190725. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190726. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190727. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190728. #endif
  190729. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190730. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190731. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190732. #endif
  190733. #if defined(PNG_READ_SWAP_SUPPORTED)
  190734. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190735. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190736. #endif
  190737. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190738. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190739. {
  190740. if(png_ptr->read_user_transform_fn != NULL)
  190741. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190742. (png_ptr, /* png_ptr */
  190743. &(png_ptr->row_info), /* row_info: */
  190744. /* png_uint_32 width; width of row */
  190745. /* png_uint_32 rowbytes; number of bytes in row */
  190746. /* png_byte color_type; color type of pixels */
  190747. /* png_byte bit_depth; bit depth of samples */
  190748. /* png_byte channels; number of channels (1-4) */
  190749. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190750. png_ptr->row_buf + 1); /* start of pixel data for row */
  190751. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190752. if(png_ptr->user_transform_depth)
  190753. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190754. if(png_ptr->user_transform_channels)
  190755. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190756. #endif
  190757. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190758. png_ptr->row_info.channels);
  190759. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190760. png_ptr->row_info.width);
  190761. }
  190762. #endif
  190763. }
  190764. #if defined(PNG_READ_PACK_SUPPORTED)
  190765. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190766. * without changing the actual values. Thus, if you had a row with
  190767. * a bit depth of 1, you would end up with bytes that only contained
  190768. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190769. * png_do_shift() after this.
  190770. */
  190771. void /* PRIVATE */
  190772. png_do_unpack(png_row_infop row_info, png_bytep row)
  190773. {
  190774. png_debug(1, "in png_do_unpack\n");
  190775. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190776. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190777. #else
  190778. if (row_info->bit_depth < 8)
  190779. #endif
  190780. {
  190781. png_uint_32 i;
  190782. png_uint_32 row_width=row_info->width;
  190783. switch (row_info->bit_depth)
  190784. {
  190785. case 1:
  190786. {
  190787. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190788. png_bytep dp = row + (png_size_t)row_width - 1;
  190789. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190790. for (i = 0; i < row_width; i++)
  190791. {
  190792. *dp = (png_byte)((*sp >> shift) & 0x01);
  190793. if (shift == 7)
  190794. {
  190795. shift = 0;
  190796. sp--;
  190797. }
  190798. else
  190799. shift++;
  190800. dp--;
  190801. }
  190802. break;
  190803. }
  190804. case 2:
  190805. {
  190806. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190807. png_bytep dp = row + (png_size_t)row_width - 1;
  190808. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190809. for (i = 0; i < row_width; i++)
  190810. {
  190811. *dp = (png_byte)((*sp >> shift) & 0x03);
  190812. if (shift == 6)
  190813. {
  190814. shift = 0;
  190815. sp--;
  190816. }
  190817. else
  190818. shift += 2;
  190819. dp--;
  190820. }
  190821. break;
  190822. }
  190823. case 4:
  190824. {
  190825. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  190826. png_bytep dp = row + (png_size_t)row_width - 1;
  190827. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190828. for (i = 0; i < row_width; i++)
  190829. {
  190830. *dp = (png_byte)((*sp >> shift) & 0x0f);
  190831. if (shift == 4)
  190832. {
  190833. shift = 0;
  190834. sp--;
  190835. }
  190836. else
  190837. shift = 4;
  190838. dp--;
  190839. }
  190840. break;
  190841. }
  190842. }
  190843. row_info->bit_depth = 8;
  190844. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190845. row_info->rowbytes = row_width * row_info->channels;
  190846. }
  190847. }
  190848. #endif
  190849. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190850. /* Reverse the effects of png_do_shift. This routine merely shifts the
  190851. * pixels back to their significant bits values. Thus, if you have
  190852. * a row of bit depth 8, but only 5 are significant, this will shift
  190853. * the values back to 0 through 31.
  190854. */
  190855. void /* PRIVATE */
  190856. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  190857. {
  190858. png_debug(1, "in png_do_unshift\n");
  190859. if (
  190860. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190861. row != NULL && row_info != NULL && sig_bits != NULL &&
  190862. #endif
  190863. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  190864. {
  190865. int shift[4];
  190866. int channels = 0;
  190867. int c;
  190868. png_uint_16 value = 0;
  190869. png_uint_32 row_width = row_info->width;
  190870. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  190871. {
  190872. shift[channels++] = row_info->bit_depth - sig_bits->red;
  190873. shift[channels++] = row_info->bit_depth - sig_bits->green;
  190874. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  190875. }
  190876. else
  190877. {
  190878. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  190879. }
  190880. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190881. {
  190882. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  190883. }
  190884. for (c = 0; c < channels; c++)
  190885. {
  190886. if (shift[c] <= 0)
  190887. shift[c] = 0;
  190888. else
  190889. value = 1;
  190890. }
  190891. if (!value)
  190892. return;
  190893. switch (row_info->bit_depth)
  190894. {
  190895. case 2:
  190896. {
  190897. png_bytep bp;
  190898. png_uint_32 i;
  190899. png_uint_32 istop = row_info->rowbytes;
  190900. for (bp = row, i = 0; i < istop; i++)
  190901. {
  190902. *bp >>= 1;
  190903. *bp++ &= 0x55;
  190904. }
  190905. break;
  190906. }
  190907. case 4:
  190908. {
  190909. png_bytep bp = row;
  190910. png_uint_32 i;
  190911. png_uint_32 istop = row_info->rowbytes;
  190912. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  190913. (png_byte)((int)0xf >> shift[0]));
  190914. for (i = 0; i < istop; i++)
  190915. {
  190916. *bp >>= shift[0];
  190917. *bp++ &= mask;
  190918. }
  190919. break;
  190920. }
  190921. case 8:
  190922. {
  190923. png_bytep bp = row;
  190924. png_uint_32 i;
  190925. png_uint_32 istop = row_width * channels;
  190926. for (i = 0; i < istop; i++)
  190927. {
  190928. *bp++ >>= shift[i%channels];
  190929. }
  190930. break;
  190931. }
  190932. case 16:
  190933. {
  190934. png_bytep bp = row;
  190935. png_uint_32 i;
  190936. png_uint_32 istop = channels * row_width;
  190937. for (i = 0; i < istop; i++)
  190938. {
  190939. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  190940. value >>= shift[i%channels];
  190941. *bp++ = (png_byte)(value >> 8);
  190942. *bp++ = (png_byte)(value & 0xff);
  190943. }
  190944. break;
  190945. }
  190946. }
  190947. }
  190948. }
  190949. #endif
  190950. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190951. /* chop rows of bit depth 16 down to 8 */
  190952. void /* PRIVATE */
  190953. png_do_chop(png_row_infop row_info, png_bytep row)
  190954. {
  190955. png_debug(1, "in png_do_chop\n");
  190956. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190957. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  190958. #else
  190959. if (row_info->bit_depth == 16)
  190960. #endif
  190961. {
  190962. png_bytep sp = row;
  190963. png_bytep dp = row;
  190964. png_uint_32 i;
  190965. png_uint_32 istop = row_info->width * row_info->channels;
  190966. for (i = 0; i<istop; i++, sp += 2, dp++)
  190967. {
  190968. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  190969. /* This does a more accurate scaling of the 16-bit color
  190970. * value, rather than a simple low-byte truncation.
  190971. *
  190972. * What the ideal calculation should be:
  190973. * *dp = (((((png_uint_32)(*sp) << 8) |
  190974. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  190975. *
  190976. * GRR: no, I think this is what it really should be:
  190977. * *dp = (((((png_uint_32)(*sp) << 8) |
  190978. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  190979. *
  190980. * GRR: here's the exact calculation with shifts:
  190981. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  190982. * *dp = (temp - (temp >> 8)) >> 8;
  190983. *
  190984. * Approximate calculation with shift/add instead of multiply/divide:
  190985. * *dp = ((((png_uint_32)(*sp) << 8) |
  190986. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  190987. *
  190988. * What we actually do to avoid extra shifting and conversion:
  190989. */
  190990. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  190991. #else
  190992. /* Simply discard the low order byte */
  190993. *dp = *sp;
  190994. #endif
  190995. }
  190996. row_info->bit_depth = 8;
  190997. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190998. row_info->rowbytes = row_info->width * row_info->channels;
  190999. }
  191000. }
  191001. #endif
  191002. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191003. void /* PRIVATE */
  191004. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191005. {
  191006. png_debug(1, "in png_do_read_swap_alpha\n");
  191007. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191008. if (row != NULL && row_info != NULL)
  191009. #endif
  191010. {
  191011. png_uint_32 row_width = row_info->width;
  191012. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191013. {
  191014. /* This converts from RGBA to ARGB */
  191015. if (row_info->bit_depth == 8)
  191016. {
  191017. png_bytep sp = row + row_info->rowbytes;
  191018. png_bytep dp = sp;
  191019. png_byte save;
  191020. png_uint_32 i;
  191021. for (i = 0; i < row_width; i++)
  191022. {
  191023. save = *(--sp);
  191024. *(--dp) = *(--sp);
  191025. *(--dp) = *(--sp);
  191026. *(--dp) = *(--sp);
  191027. *(--dp) = save;
  191028. }
  191029. }
  191030. /* This converts from RRGGBBAA to AARRGGBB */
  191031. else
  191032. {
  191033. png_bytep sp = row + row_info->rowbytes;
  191034. png_bytep dp = sp;
  191035. png_byte save[2];
  191036. png_uint_32 i;
  191037. for (i = 0; i < row_width; i++)
  191038. {
  191039. save[0] = *(--sp);
  191040. save[1] = *(--sp);
  191041. *(--dp) = *(--sp);
  191042. *(--dp) = *(--sp);
  191043. *(--dp) = *(--sp);
  191044. *(--dp) = *(--sp);
  191045. *(--dp) = *(--sp);
  191046. *(--dp) = *(--sp);
  191047. *(--dp) = save[0];
  191048. *(--dp) = save[1];
  191049. }
  191050. }
  191051. }
  191052. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191053. {
  191054. /* This converts from GA to AG */
  191055. if (row_info->bit_depth == 8)
  191056. {
  191057. png_bytep sp = row + row_info->rowbytes;
  191058. png_bytep dp = sp;
  191059. png_byte save;
  191060. png_uint_32 i;
  191061. for (i = 0; i < row_width; i++)
  191062. {
  191063. save = *(--sp);
  191064. *(--dp) = *(--sp);
  191065. *(--dp) = save;
  191066. }
  191067. }
  191068. /* This converts from GGAA to AAGG */
  191069. else
  191070. {
  191071. png_bytep sp = row + row_info->rowbytes;
  191072. png_bytep dp = sp;
  191073. png_byte save[2];
  191074. png_uint_32 i;
  191075. for (i = 0; i < row_width; i++)
  191076. {
  191077. save[0] = *(--sp);
  191078. save[1] = *(--sp);
  191079. *(--dp) = *(--sp);
  191080. *(--dp) = *(--sp);
  191081. *(--dp) = save[0];
  191082. *(--dp) = save[1];
  191083. }
  191084. }
  191085. }
  191086. }
  191087. }
  191088. #endif
  191089. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191090. void /* PRIVATE */
  191091. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191092. {
  191093. png_debug(1, "in png_do_read_invert_alpha\n");
  191094. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191095. if (row != NULL && row_info != NULL)
  191096. #endif
  191097. {
  191098. png_uint_32 row_width = row_info->width;
  191099. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191100. {
  191101. /* This inverts the alpha channel in RGBA */
  191102. if (row_info->bit_depth == 8)
  191103. {
  191104. png_bytep sp = row + row_info->rowbytes;
  191105. png_bytep dp = sp;
  191106. png_uint_32 i;
  191107. for (i = 0; i < row_width; i++)
  191108. {
  191109. *(--dp) = (png_byte)(255 - *(--sp));
  191110. /* This does nothing:
  191111. *(--dp) = *(--sp);
  191112. *(--dp) = *(--sp);
  191113. *(--dp) = *(--sp);
  191114. We can replace it with:
  191115. */
  191116. sp-=3;
  191117. dp=sp;
  191118. }
  191119. }
  191120. /* This inverts the alpha channel in RRGGBBAA */
  191121. else
  191122. {
  191123. png_bytep sp = row + row_info->rowbytes;
  191124. png_bytep dp = sp;
  191125. png_uint_32 i;
  191126. for (i = 0; i < row_width; i++)
  191127. {
  191128. *(--dp) = (png_byte)(255 - *(--sp));
  191129. *(--dp) = (png_byte)(255 - *(--sp));
  191130. /* This does nothing:
  191131. *(--dp) = *(--sp);
  191132. *(--dp) = *(--sp);
  191133. *(--dp) = *(--sp);
  191134. *(--dp) = *(--sp);
  191135. *(--dp) = *(--sp);
  191136. *(--dp) = *(--sp);
  191137. We can replace it with:
  191138. */
  191139. sp-=6;
  191140. dp=sp;
  191141. }
  191142. }
  191143. }
  191144. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191145. {
  191146. /* This inverts the alpha channel in GA */
  191147. if (row_info->bit_depth == 8)
  191148. {
  191149. png_bytep sp = row + row_info->rowbytes;
  191150. png_bytep dp = sp;
  191151. png_uint_32 i;
  191152. for (i = 0; i < row_width; i++)
  191153. {
  191154. *(--dp) = (png_byte)(255 - *(--sp));
  191155. *(--dp) = *(--sp);
  191156. }
  191157. }
  191158. /* This inverts the alpha channel in GGAA */
  191159. else
  191160. {
  191161. png_bytep sp = row + row_info->rowbytes;
  191162. png_bytep dp = sp;
  191163. png_uint_32 i;
  191164. for (i = 0; i < row_width; i++)
  191165. {
  191166. *(--dp) = (png_byte)(255 - *(--sp));
  191167. *(--dp) = (png_byte)(255 - *(--sp));
  191168. /*
  191169. *(--dp) = *(--sp);
  191170. *(--dp) = *(--sp);
  191171. */
  191172. sp-=2;
  191173. dp=sp;
  191174. }
  191175. }
  191176. }
  191177. }
  191178. }
  191179. #endif
  191180. #if defined(PNG_READ_FILLER_SUPPORTED)
  191181. /* Add filler channel if we have RGB color */
  191182. void /* PRIVATE */
  191183. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191184. png_uint_32 filler, png_uint_32 flags)
  191185. {
  191186. png_uint_32 i;
  191187. png_uint_32 row_width = row_info->width;
  191188. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191189. png_byte lo_filler = (png_byte)(filler & 0xff);
  191190. png_debug(1, "in png_do_read_filler\n");
  191191. if (
  191192. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191193. row != NULL && row_info != NULL &&
  191194. #endif
  191195. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191196. {
  191197. if(row_info->bit_depth == 8)
  191198. {
  191199. /* This changes the data from G to GX */
  191200. if (flags & PNG_FLAG_FILLER_AFTER)
  191201. {
  191202. png_bytep sp = row + (png_size_t)row_width;
  191203. png_bytep dp = sp + (png_size_t)row_width;
  191204. for (i = 1; i < row_width; i++)
  191205. {
  191206. *(--dp) = lo_filler;
  191207. *(--dp) = *(--sp);
  191208. }
  191209. *(--dp) = lo_filler;
  191210. row_info->channels = 2;
  191211. row_info->pixel_depth = 16;
  191212. row_info->rowbytes = row_width * 2;
  191213. }
  191214. /* This changes the data from G to XG */
  191215. else
  191216. {
  191217. png_bytep sp = row + (png_size_t)row_width;
  191218. png_bytep dp = sp + (png_size_t)row_width;
  191219. for (i = 0; i < row_width; i++)
  191220. {
  191221. *(--dp) = *(--sp);
  191222. *(--dp) = lo_filler;
  191223. }
  191224. row_info->channels = 2;
  191225. row_info->pixel_depth = 16;
  191226. row_info->rowbytes = row_width * 2;
  191227. }
  191228. }
  191229. else if(row_info->bit_depth == 16)
  191230. {
  191231. /* This changes the data from GG to GGXX */
  191232. if (flags & PNG_FLAG_FILLER_AFTER)
  191233. {
  191234. png_bytep sp = row + (png_size_t)row_width * 2;
  191235. png_bytep dp = sp + (png_size_t)row_width * 2;
  191236. for (i = 1; i < row_width; i++)
  191237. {
  191238. *(--dp) = hi_filler;
  191239. *(--dp) = lo_filler;
  191240. *(--dp) = *(--sp);
  191241. *(--dp) = *(--sp);
  191242. }
  191243. *(--dp) = hi_filler;
  191244. *(--dp) = lo_filler;
  191245. row_info->channels = 2;
  191246. row_info->pixel_depth = 32;
  191247. row_info->rowbytes = row_width * 4;
  191248. }
  191249. /* This changes the data from GG to XXGG */
  191250. else
  191251. {
  191252. png_bytep sp = row + (png_size_t)row_width * 2;
  191253. png_bytep dp = sp + (png_size_t)row_width * 2;
  191254. for (i = 0; i < row_width; i++)
  191255. {
  191256. *(--dp) = *(--sp);
  191257. *(--dp) = *(--sp);
  191258. *(--dp) = hi_filler;
  191259. *(--dp) = lo_filler;
  191260. }
  191261. row_info->channels = 2;
  191262. row_info->pixel_depth = 32;
  191263. row_info->rowbytes = row_width * 4;
  191264. }
  191265. }
  191266. } /* COLOR_TYPE == GRAY */
  191267. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191268. {
  191269. if(row_info->bit_depth == 8)
  191270. {
  191271. /* This changes the data from RGB to RGBX */
  191272. if (flags & PNG_FLAG_FILLER_AFTER)
  191273. {
  191274. png_bytep sp = row + (png_size_t)row_width * 3;
  191275. png_bytep dp = sp + (png_size_t)row_width;
  191276. for (i = 1; i < row_width; i++)
  191277. {
  191278. *(--dp) = lo_filler;
  191279. *(--dp) = *(--sp);
  191280. *(--dp) = *(--sp);
  191281. *(--dp) = *(--sp);
  191282. }
  191283. *(--dp) = lo_filler;
  191284. row_info->channels = 4;
  191285. row_info->pixel_depth = 32;
  191286. row_info->rowbytes = row_width * 4;
  191287. }
  191288. /* This changes the data from RGB to XRGB */
  191289. else
  191290. {
  191291. png_bytep sp = row + (png_size_t)row_width * 3;
  191292. png_bytep dp = sp + (png_size_t)row_width;
  191293. for (i = 0; i < row_width; i++)
  191294. {
  191295. *(--dp) = *(--sp);
  191296. *(--dp) = *(--sp);
  191297. *(--dp) = *(--sp);
  191298. *(--dp) = lo_filler;
  191299. }
  191300. row_info->channels = 4;
  191301. row_info->pixel_depth = 32;
  191302. row_info->rowbytes = row_width * 4;
  191303. }
  191304. }
  191305. else if(row_info->bit_depth == 16)
  191306. {
  191307. /* This changes the data from RRGGBB to RRGGBBXX */
  191308. if (flags & PNG_FLAG_FILLER_AFTER)
  191309. {
  191310. png_bytep sp = row + (png_size_t)row_width * 6;
  191311. png_bytep dp = sp + (png_size_t)row_width * 2;
  191312. for (i = 1; i < row_width; i++)
  191313. {
  191314. *(--dp) = hi_filler;
  191315. *(--dp) = lo_filler;
  191316. *(--dp) = *(--sp);
  191317. *(--dp) = *(--sp);
  191318. *(--dp) = *(--sp);
  191319. *(--dp) = *(--sp);
  191320. *(--dp) = *(--sp);
  191321. *(--dp) = *(--sp);
  191322. }
  191323. *(--dp) = hi_filler;
  191324. *(--dp) = lo_filler;
  191325. row_info->channels = 4;
  191326. row_info->pixel_depth = 64;
  191327. row_info->rowbytes = row_width * 8;
  191328. }
  191329. /* This changes the data from RRGGBB to XXRRGGBB */
  191330. else
  191331. {
  191332. png_bytep sp = row + (png_size_t)row_width * 6;
  191333. png_bytep dp = sp + (png_size_t)row_width * 2;
  191334. for (i = 0; i < row_width; i++)
  191335. {
  191336. *(--dp) = *(--sp);
  191337. *(--dp) = *(--sp);
  191338. *(--dp) = *(--sp);
  191339. *(--dp) = *(--sp);
  191340. *(--dp) = *(--sp);
  191341. *(--dp) = *(--sp);
  191342. *(--dp) = hi_filler;
  191343. *(--dp) = lo_filler;
  191344. }
  191345. row_info->channels = 4;
  191346. row_info->pixel_depth = 64;
  191347. row_info->rowbytes = row_width * 8;
  191348. }
  191349. }
  191350. } /* COLOR_TYPE == RGB */
  191351. }
  191352. #endif
  191353. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191354. /* expand grayscale files to RGB, with or without alpha */
  191355. void /* PRIVATE */
  191356. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191357. {
  191358. png_uint_32 i;
  191359. png_uint_32 row_width = row_info->width;
  191360. png_debug(1, "in png_do_gray_to_rgb\n");
  191361. if (row_info->bit_depth >= 8 &&
  191362. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191363. row != NULL && row_info != NULL &&
  191364. #endif
  191365. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191366. {
  191367. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191368. {
  191369. if (row_info->bit_depth == 8)
  191370. {
  191371. png_bytep sp = row + (png_size_t)row_width - 1;
  191372. png_bytep dp = sp + (png_size_t)row_width * 2;
  191373. for (i = 0; i < row_width; i++)
  191374. {
  191375. *(dp--) = *sp;
  191376. *(dp--) = *sp;
  191377. *(dp--) = *(sp--);
  191378. }
  191379. }
  191380. else
  191381. {
  191382. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191383. png_bytep dp = sp + (png_size_t)row_width * 4;
  191384. for (i = 0; i < row_width; i++)
  191385. {
  191386. *(dp--) = *sp;
  191387. *(dp--) = *(sp - 1);
  191388. *(dp--) = *sp;
  191389. *(dp--) = *(sp - 1);
  191390. *(dp--) = *(sp--);
  191391. *(dp--) = *(sp--);
  191392. }
  191393. }
  191394. }
  191395. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191396. {
  191397. if (row_info->bit_depth == 8)
  191398. {
  191399. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191400. png_bytep dp = sp + (png_size_t)row_width * 2;
  191401. for (i = 0; i < row_width; i++)
  191402. {
  191403. *(dp--) = *(sp--);
  191404. *(dp--) = *sp;
  191405. *(dp--) = *sp;
  191406. *(dp--) = *(sp--);
  191407. }
  191408. }
  191409. else
  191410. {
  191411. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191412. png_bytep dp = sp + (png_size_t)row_width * 4;
  191413. for (i = 0; i < row_width; i++)
  191414. {
  191415. *(dp--) = *(sp--);
  191416. *(dp--) = *(sp--);
  191417. *(dp--) = *sp;
  191418. *(dp--) = *(sp - 1);
  191419. *(dp--) = *sp;
  191420. *(dp--) = *(sp - 1);
  191421. *(dp--) = *(sp--);
  191422. *(dp--) = *(sp--);
  191423. }
  191424. }
  191425. }
  191426. row_info->channels += (png_byte)2;
  191427. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191428. row_info->pixel_depth = (png_byte)(row_info->channels *
  191429. row_info->bit_depth);
  191430. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191431. }
  191432. }
  191433. #endif
  191434. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191435. /* reduce RGB files to grayscale, with or without alpha
  191436. * using the equation given in Poynton's ColorFAQ at
  191437. * <http://www.inforamp.net/~poynton/>
  191438. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191439. *
  191440. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191441. *
  191442. * We approximate this with
  191443. *
  191444. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191445. *
  191446. * which can be expressed with integers as
  191447. *
  191448. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191449. *
  191450. * The calculation is to be done in a linear colorspace.
  191451. *
  191452. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191453. */
  191454. int /* PRIVATE */
  191455. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191456. {
  191457. png_uint_32 i;
  191458. png_uint_32 row_width = row_info->width;
  191459. int rgb_error = 0;
  191460. png_debug(1, "in png_do_rgb_to_gray\n");
  191461. if (
  191462. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191463. row != NULL && row_info != NULL &&
  191464. #endif
  191465. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191466. {
  191467. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191468. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191469. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191470. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191471. {
  191472. if (row_info->bit_depth == 8)
  191473. {
  191474. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191475. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191476. {
  191477. png_bytep sp = row;
  191478. png_bytep dp = row;
  191479. for (i = 0; i < row_width; i++)
  191480. {
  191481. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191482. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191483. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191484. if(red != green || red != blue)
  191485. {
  191486. rgb_error |= 1;
  191487. *(dp++) = png_ptr->gamma_from_1[
  191488. (rc*red+gc*green+bc*blue)>>15];
  191489. }
  191490. else
  191491. *(dp++) = *(sp-1);
  191492. }
  191493. }
  191494. else
  191495. #endif
  191496. {
  191497. png_bytep sp = row;
  191498. png_bytep dp = row;
  191499. for (i = 0; i < row_width; i++)
  191500. {
  191501. png_byte red = *(sp++);
  191502. png_byte green = *(sp++);
  191503. png_byte blue = *(sp++);
  191504. if(red != green || red != blue)
  191505. {
  191506. rgb_error |= 1;
  191507. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191508. }
  191509. else
  191510. *(dp++) = *(sp-1);
  191511. }
  191512. }
  191513. }
  191514. else /* RGB bit_depth == 16 */
  191515. {
  191516. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191517. if (png_ptr->gamma_16_to_1 != NULL &&
  191518. png_ptr->gamma_16_from_1 != NULL)
  191519. {
  191520. png_bytep sp = row;
  191521. png_bytep dp = row;
  191522. for (i = 0; i < row_width; i++)
  191523. {
  191524. png_uint_16 red, green, blue, w;
  191525. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191526. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191527. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191528. if(red == green && red == blue)
  191529. w = red;
  191530. else
  191531. {
  191532. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191533. png_ptr->gamma_shift][red>>8];
  191534. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191535. png_ptr->gamma_shift][green>>8];
  191536. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191537. png_ptr->gamma_shift][blue>>8];
  191538. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191539. + bc*blue_1)>>15);
  191540. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191541. png_ptr->gamma_shift][gray16 >> 8];
  191542. rgb_error |= 1;
  191543. }
  191544. *(dp++) = (png_byte)((w>>8) & 0xff);
  191545. *(dp++) = (png_byte)(w & 0xff);
  191546. }
  191547. }
  191548. else
  191549. #endif
  191550. {
  191551. png_bytep sp = row;
  191552. png_bytep dp = row;
  191553. for (i = 0; i < row_width; i++)
  191554. {
  191555. png_uint_16 red, green, blue, gray16;
  191556. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191557. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191558. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191559. if(red != green || red != blue)
  191560. rgb_error |= 1;
  191561. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191562. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191563. *(dp++) = (png_byte)(gray16 & 0xff);
  191564. }
  191565. }
  191566. }
  191567. }
  191568. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191569. {
  191570. if (row_info->bit_depth == 8)
  191571. {
  191572. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191573. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191574. {
  191575. png_bytep sp = row;
  191576. png_bytep dp = row;
  191577. for (i = 0; i < row_width; i++)
  191578. {
  191579. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191580. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191581. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191582. if(red != green || red != blue)
  191583. rgb_error |= 1;
  191584. *(dp++) = png_ptr->gamma_from_1
  191585. [(rc*red + gc*green + bc*blue)>>15];
  191586. *(dp++) = *(sp++); /* alpha */
  191587. }
  191588. }
  191589. else
  191590. #endif
  191591. {
  191592. png_bytep sp = row;
  191593. png_bytep dp = row;
  191594. for (i = 0; i < row_width; i++)
  191595. {
  191596. png_byte red = *(sp++);
  191597. png_byte green = *(sp++);
  191598. png_byte blue = *(sp++);
  191599. if(red != green || red != blue)
  191600. rgb_error |= 1;
  191601. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191602. *(dp++) = *(sp++); /* alpha */
  191603. }
  191604. }
  191605. }
  191606. else /* RGBA bit_depth == 16 */
  191607. {
  191608. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191609. if (png_ptr->gamma_16_to_1 != NULL &&
  191610. png_ptr->gamma_16_from_1 != NULL)
  191611. {
  191612. png_bytep sp = row;
  191613. png_bytep dp = row;
  191614. for (i = 0; i < row_width; i++)
  191615. {
  191616. png_uint_16 red, green, blue, w;
  191617. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191618. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191619. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191620. if(red == green && red == blue)
  191621. w = red;
  191622. else
  191623. {
  191624. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191625. png_ptr->gamma_shift][red>>8];
  191626. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191627. png_ptr->gamma_shift][green>>8];
  191628. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191629. png_ptr->gamma_shift][blue>>8];
  191630. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191631. + gc * green_1 + bc * blue_1)>>15);
  191632. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191633. png_ptr->gamma_shift][gray16 >> 8];
  191634. rgb_error |= 1;
  191635. }
  191636. *(dp++) = (png_byte)((w>>8) & 0xff);
  191637. *(dp++) = (png_byte)(w & 0xff);
  191638. *(dp++) = *(sp++); /* alpha */
  191639. *(dp++) = *(sp++);
  191640. }
  191641. }
  191642. else
  191643. #endif
  191644. {
  191645. png_bytep sp = row;
  191646. png_bytep dp = row;
  191647. for (i = 0; i < row_width; i++)
  191648. {
  191649. png_uint_16 red, green, blue, gray16;
  191650. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191651. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191652. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191653. if(red != green || red != blue)
  191654. rgb_error |= 1;
  191655. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191656. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191657. *(dp++) = (png_byte)(gray16 & 0xff);
  191658. *(dp++) = *(sp++); /* alpha */
  191659. *(dp++) = *(sp++);
  191660. }
  191661. }
  191662. }
  191663. }
  191664. row_info->channels -= (png_byte)2;
  191665. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191666. row_info->pixel_depth = (png_byte)(row_info->channels *
  191667. row_info->bit_depth);
  191668. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191669. }
  191670. return rgb_error;
  191671. }
  191672. #endif
  191673. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191674. * large of png_color. This lets grayscale images be treated as
  191675. * paletted. Most useful for gamma correction and simplification
  191676. * of code.
  191677. */
  191678. void PNGAPI
  191679. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191680. {
  191681. int num_palette;
  191682. int color_inc;
  191683. int i;
  191684. int v;
  191685. png_debug(1, "in png_do_build_grayscale_palette\n");
  191686. if (palette == NULL)
  191687. return;
  191688. switch (bit_depth)
  191689. {
  191690. case 1:
  191691. num_palette = 2;
  191692. color_inc = 0xff;
  191693. break;
  191694. case 2:
  191695. num_palette = 4;
  191696. color_inc = 0x55;
  191697. break;
  191698. case 4:
  191699. num_palette = 16;
  191700. color_inc = 0x11;
  191701. break;
  191702. case 8:
  191703. num_palette = 256;
  191704. color_inc = 1;
  191705. break;
  191706. default:
  191707. num_palette = 0;
  191708. color_inc = 0;
  191709. break;
  191710. }
  191711. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191712. {
  191713. palette[i].red = (png_byte)v;
  191714. palette[i].green = (png_byte)v;
  191715. palette[i].blue = (png_byte)v;
  191716. }
  191717. }
  191718. /* This function is currently unused. Do we really need it? */
  191719. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191720. void /* PRIVATE */
  191721. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191722. int num_palette)
  191723. {
  191724. png_debug(1, "in png_correct_palette\n");
  191725. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191726. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191727. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191728. {
  191729. png_color back, back_1;
  191730. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191731. {
  191732. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191733. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191734. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191735. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191736. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191737. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191738. }
  191739. else
  191740. {
  191741. double g;
  191742. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191743. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191744. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191745. {
  191746. back.red = png_ptr->background.red;
  191747. back.green = png_ptr->background.green;
  191748. back.blue = png_ptr->background.blue;
  191749. }
  191750. else
  191751. {
  191752. back.red =
  191753. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191754. 255.0 + 0.5);
  191755. back.green =
  191756. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191757. 255.0 + 0.5);
  191758. back.blue =
  191759. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191760. 255.0 + 0.5);
  191761. }
  191762. g = 1.0 / png_ptr->background_gamma;
  191763. back_1.red =
  191764. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191765. 255.0 + 0.5);
  191766. back_1.green =
  191767. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191768. 255.0 + 0.5);
  191769. back_1.blue =
  191770. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191771. 255.0 + 0.5);
  191772. }
  191773. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191774. {
  191775. png_uint_32 i;
  191776. for (i = 0; i < (png_uint_32)num_palette; i++)
  191777. {
  191778. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191779. {
  191780. palette[i] = back;
  191781. }
  191782. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191783. {
  191784. png_byte v, w;
  191785. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191786. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191787. palette[i].red = png_ptr->gamma_from_1[w];
  191788. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191789. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191790. palette[i].green = png_ptr->gamma_from_1[w];
  191791. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191792. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191793. palette[i].blue = png_ptr->gamma_from_1[w];
  191794. }
  191795. else
  191796. {
  191797. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191798. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191799. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191800. }
  191801. }
  191802. }
  191803. else
  191804. {
  191805. int i;
  191806. for (i = 0; i < num_palette; i++)
  191807. {
  191808. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191809. {
  191810. palette[i] = back;
  191811. }
  191812. else
  191813. {
  191814. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191815. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191816. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191817. }
  191818. }
  191819. }
  191820. }
  191821. else
  191822. #endif
  191823. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191824. if (png_ptr->transformations & PNG_GAMMA)
  191825. {
  191826. int i;
  191827. for (i = 0; i < num_palette; i++)
  191828. {
  191829. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191830. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191831. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191832. }
  191833. }
  191834. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191835. else
  191836. #endif
  191837. #endif
  191838. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191839. if (png_ptr->transformations & PNG_BACKGROUND)
  191840. {
  191841. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191842. {
  191843. png_color back;
  191844. back.red = (png_byte)png_ptr->background.red;
  191845. back.green = (png_byte)png_ptr->background.green;
  191846. back.blue = (png_byte)png_ptr->background.blue;
  191847. for (i = 0; i < (int)png_ptr->num_trans; i++)
  191848. {
  191849. if (png_ptr->trans[i] == 0)
  191850. {
  191851. palette[i].red = back.red;
  191852. palette[i].green = back.green;
  191853. palette[i].blue = back.blue;
  191854. }
  191855. else if (png_ptr->trans[i] != 0xff)
  191856. {
  191857. png_composite(palette[i].red, png_ptr->palette[i].red,
  191858. png_ptr->trans[i], back.red);
  191859. png_composite(palette[i].green, png_ptr->palette[i].green,
  191860. png_ptr->trans[i], back.green);
  191861. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  191862. png_ptr->trans[i], back.blue);
  191863. }
  191864. }
  191865. }
  191866. else /* assume grayscale palette (what else could it be?) */
  191867. {
  191868. int i;
  191869. for (i = 0; i < num_palette; i++)
  191870. {
  191871. if (i == (png_byte)png_ptr->trans_values.gray)
  191872. {
  191873. palette[i].red = (png_byte)png_ptr->background.red;
  191874. palette[i].green = (png_byte)png_ptr->background.green;
  191875. palette[i].blue = (png_byte)png_ptr->background.blue;
  191876. }
  191877. }
  191878. }
  191879. }
  191880. #endif
  191881. }
  191882. #endif
  191883. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191884. /* Replace any alpha or transparency with the supplied background color.
  191885. * "background" is already in the screen gamma, while "background_1" is
  191886. * at a gamma of 1.0. Paletted files have already been taken care of.
  191887. */
  191888. void /* PRIVATE */
  191889. png_do_background(png_row_infop row_info, png_bytep row,
  191890. png_color_16p trans_values, png_color_16p background
  191891. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191892. , png_color_16p background_1,
  191893. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  191894. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  191895. png_uint_16pp gamma_16_to_1, int gamma_shift
  191896. #endif
  191897. )
  191898. {
  191899. png_bytep sp, dp;
  191900. png_uint_32 i;
  191901. png_uint_32 row_width=row_info->width;
  191902. int shift;
  191903. png_debug(1, "in png_do_background\n");
  191904. if (background != NULL &&
  191905. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191906. row != NULL && row_info != NULL &&
  191907. #endif
  191908. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  191909. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  191910. {
  191911. switch (row_info->color_type)
  191912. {
  191913. case PNG_COLOR_TYPE_GRAY:
  191914. {
  191915. switch (row_info->bit_depth)
  191916. {
  191917. case 1:
  191918. {
  191919. sp = row;
  191920. shift = 7;
  191921. for (i = 0; i < row_width; i++)
  191922. {
  191923. if ((png_uint_16)((*sp >> shift) & 0x01)
  191924. == trans_values->gray)
  191925. {
  191926. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191927. *sp |= (png_byte)(background->gray << shift);
  191928. }
  191929. if (!shift)
  191930. {
  191931. shift = 7;
  191932. sp++;
  191933. }
  191934. else
  191935. shift--;
  191936. }
  191937. break;
  191938. }
  191939. case 2:
  191940. {
  191941. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191942. if (gamma_table != NULL)
  191943. {
  191944. sp = row;
  191945. shift = 6;
  191946. for (i = 0; i < row_width; i++)
  191947. {
  191948. if ((png_uint_16)((*sp >> shift) & 0x03)
  191949. == trans_values->gray)
  191950. {
  191951. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191952. *sp |= (png_byte)(background->gray << shift);
  191953. }
  191954. else
  191955. {
  191956. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  191957. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  191958. (p << 4) | (p << 6)] >> 6) & 0x03);
  191959. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191960. *sp |= (png_byte)(g << shift);
  191961. }
  191962. if (!shift)
  191963. {
  191964. shift = 6;
  191965. sp++;
  191966. }
  191967. else
  191968. shift -= 2;
  191969. }
  191970. }
  191971. else
  191972. #endif
  191973. {
  191974. sp = row;
  191975. shift = 6;
  191976. for (i = 0; i < row_width; i++)
  191977. {
  191978. if ((png_uint_16)((*sp >> shift) & 0x03)
  191979. == trans_values->gray)
  191980. {
  191981. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191982. *sp |= (png_byte)(background->gray << shift);
  191983. }
  191984. if (!shift)
  191985. {
  191986. shift = 6;
  191987. sp++;
  191988. }
  191989. else
  191990. shift -= 2;
  191991. }
  191992. }
  191993. break;
  191994. }
  191995. case 4:
  191996. {
  191997. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191998. if (gamma_table != NULL)
  191999. {
  192000. sp = row;
  192001. shift = 4;
  192002. for (i = 0; i < row_width; i++)
  192003. {
  192004. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192005. == trans_values->gray)
  192006. {
  192007. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192008. *sp |= (png_byte)(background->gray << shift);
  192009. }
  192010. else
  192011. {
  192012. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192013. png_byte g = (png_byte)((gamma_table[p |
  192014. (p << 4)] >> 4) & 0x0f);
  192015. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192016. *sp |= (png_byte)(g << shift);
  192017. }
  192018. if (!shift)
  192019. {
  192020. shift = 4;
  192021. sp++;
  192022. }
  192023. else
  192024. shift -= 4;
  192025. }
  192026. }
  192027. else
  192028. #endif
  192029. {
  192030. sp = row;
  192031. shift = 4;
  192032. for (i = 0; i < row_width; i++)
  192033. {
  192034. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192035. == trans_values->gray)
  192036. {
  192037. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192038. *sp |= (png_byte)(background->gray << shift);
  192039. }
  192040. if (!shift)
  192041. {
  192042. shift = 4;
  192043. sp++;
  192044. }
  192045. else
  192046. shift -= 4;
  192047. }
  192048. }
  192049. break;
  192050. }
  192051. case 8:
  192052. {
  192053. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192054. if (gamma_table != NULL)
  192055. {
  192056. sp = row;
  192057. for (i = 0; i < row_width; i++, sp++)
  192058. {
  192059. if (*sp == trans_values->gray)
  192060. {
  192061. *sp = (png_byte)background->gray;
  192062. }
  192063. else
  192064. {
  192065. *sp = gamma_table[*sp];
  192066. }
  192067. }
  192068. }
  192069. else
  192070. #endif
  192071. {
  192072. sp = row;
  192073. for (i = 0; i < row_width; i++, sp++)
  192074. {
  192075. if (*sp == trans_values->gray)
  192076. {
  192077. *sp = (png_byte)background->gray;
  192078. }
  192079. }
  192080. }
  192081. break;
  192082. }
  192083. case 16:
  192084. {
  192085. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192086. if (gamma_16 != NULL)
  192087. {
  192088. sp = row;
  192089. for (i = 0; i < row_width; i++, sp += 2)
  192090. {
  192091. png_uint_16 v;
  192092. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192093. if (v == trans_values->gray)
  192094. {
  192095. /* background is already in screen gamma */
  192096. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192097. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192098. }
  192099. else
  192100. {
  192101. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192102. *sp = (png_byte)((v >> 8) & 0xff);
  192103. *(sp + 1) = (png_byte)(v & 0xff);
  192104. }
  192105. }
  192106. }
  192107. else
  192108. #endif
  192109. {
  192110. sp = row;
  192111. for (i = 0; i < row_width; i++, sp += 2)
  192112. {
  192113. png_uint_16 v;
  192114. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192115. if (v == trans_values->gray)
  192116. {
  192117. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192118. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192119. }
  192120. }
  192121. }
  192122. break;
  192123. }
  192124. }
  192125. break;
  192126. }
  192127. case PNG_COLOR_TYPE_RGB:
  192128. {
  192129. if (row_info->bit_depth == 8)
  192130. {
  192131. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192132. if (gamma_table != NULL)
  192133. {
  192134. sp = row;
  192135. for (i = 0; i < row_width; i++, sp += 3)
  192136. {
  192137. if (*sp == trans_values->red &&
  192138. *(sp + 1) == trans_values->green &&
  192139. *(sp + 2) == trans_values->blue)
  192140. {
  192141. *sp = (png_byte)background->red;
  192142. *(sp + 1) = (png_byte)background->green;
  192143. *(sp + 2) = (png_byte)background->blue;
  192144. }
  192145. else
  192146. {
  192147. *sp = gamma_table[*sp];
  192148. *(sp + 1) = gamma_table[*(sp + 1)];
  192149. *(sp + 2) = gamma_table[*(sp + 2)];
  192150. }
  192151. }
  192152. }
  192153. else
  192154. #endif
  192155. {
  192156. sp = row;
  192157. for (i = 0; i < row_width; i++, sp += 3)
  192158. {
  192159. if (*sp == trans_values->red &&
  192160. *(sp + 1) == trans_values->green &&
  192161. *(sp + 2) == trans_values->blue)
  192162. {
  192163. *sp = (png_byte)background->red;
  192164. *(sp + 1) = (png_byte)background->green;
  192165. *(sp + 2) = (png_byte)background->blue;
  192166. }
  192167. }
  192168. }
  192169. }
  192170. else /* if (row_info->bit_depth == 16) */
  192171. {
  192172. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192173. if (gamma_16 != NULL)
  192174. {
  192175. sp = row;
  192176. for (i = 0; i < row_width; i++, sp += 6)
  192177. {
  192178. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192179. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192180. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192181. if (r == trans_values->red && g == trans_values->green &&
  192182. b == trans_values->blue)
  192183. {
  192184. /* background is already in screen gamma */
  192185. *sp = (png_byte)((background->red >> 8) & 0xff);
  192186. *(sp + 1) = (png_byte)(background->red & 0xff);
  192187. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192188. *(sp + 3) = (png_byte)(background->green & 0xff);
  192189. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192190. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192191. }
  192192. else
  192193. {
  192194. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192195. *sp = (png_byte)((v >> 8) & 0xff);
  192196. *(sp + 1) = (png_byte)(v & 0xff);
  192197. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192198. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192199. *(sp + 3) = (png_byte)(v & 0xff);
  192200. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192201. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192202. *(sp + 5) = (png_byte)(v & 0xff);
  192203. }
  192204. }
  192205. }
  192206. else
  192207. #endif
  192208. {
  192209. sp = row;
  192210. for (i = 0; i < row_width; i++, sp += 6)
  192211. {
  192212. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192213. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192214. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192215. if (r == trans_values->red && g == trans_values->green &&
  192216. b == trans_values->blue)
  192217. {
  192218. *sp = (png_byte)((background->red >> 8) & 0xff);
  192219. *(sp + 1) = (png_byte)(background->red & 0xff);
  192220. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192221. *(sp + 3) = (png_byte)(background->green & 0xff);
  192222. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192223. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192224. }
  192225. }
  192226. }
  192227. }
  192228. break;
  192229. }
  192230. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192231. {
  192232. if (row_info->bit_depth == 8)
  192233. {
  192234. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192235. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192236. gamma_table != NULL)
  192237. {
  192238. sp = row;
  192239. dp = row;
  192240. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192241. {
  192242. png_uint_16 a = *(sp + 1);
  192243. if (a == 0xff)
  192244. {
  192245. *dp = gamma_table[*sp];
  192246. }
  192247. else if (a == 0)
  192248. {
  192249. /* background is already in screen gamma */
  192250. *dp = (png_byte)background->gray;
  192251. }
  192252. else
  192253. {
  192254. png_byte v, w;
  192255. v = gamma_to_1[*sp];
  192256. png_composite(w, v, a, background_1->gray);
  192257. *dp = gamma_from_1[w];
  192258. }
  192259. }
  192260. }
  192261. else
  192262. #endif
  192263. {
  192264. sp = row;
  192265. dp = row;
  192266. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192267. {
  192268. png_byte a = *(sp + 1);
  192269. if (a == 0xff)
  192270. {
  192271. *dp = *sp;
  192272. }
  192273. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192274. else if (a == 0)
  192275. {
  192276. *dp = (png_byte)background->gray;
  192277. }
  192278. else
  192279. {
  192280. png_composite(*dp, *sp, a, background_1->gray);
  192281. }
  192282. #else
  192283. *dp = (png_byte)background->gray;
  192284. #endif
  192285. }
  192286. }
  192287. }
  192288. else /* if (png_ptr->bit_depth == 16) */
  192289. {
  192290. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192291. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192292. gamma_16_to_1 != NULL)
  192293. {
  192294. sp = row;
  192295. dp = row;
  192296. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192297. {
  192298. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192299. if (a == (png_uint_16)0xffff)
  192300. {
  192301. png_uint_16 v;
  192302. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192303. *dp = (png_byte)((v >> 8) & 0xff);
  192304. *(dp + 1) = (png_byte)(v & 0xff);
  192305. }
  192306. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192307. else if (a == 0)
  192308. #else
  192309. else
  192310. #endif
  192311. {
  192312. /* background is already in screen gamma */
  192313. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192314. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192315. }
  192316. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192317. else
  192318. {
  192319. png_uint_16 g, v, w;
  192320. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192321. png_composite_16(v, g, a, background_1->gray);
  192322. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192323. *dp = (png_byte)((w >> 8) & 0xff);
  192324. *(dp + 1) = (png_byte)(w & 0xff);
  192325. }
  192326. #endif
  192327. }
  192328. }
  192329. else
  192330. #endif
  192331. {
  192332. sp = row;
  192333. dp = row;
  192334. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192335. {
  192336. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192337. if (a == (png_uint_16)0xffff)
  192338. {
  192339. png_memcpy(dp, sp, 2);
  192340. }
  192341. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192342. else if (a == 0)
  192343. #else
  192344. else
  192345. #endif
  192346. {
  192347. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192348. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192349. }
  192350. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192351. else
  192352. {
  192353. png_uint_16 g, v;
  192354. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192355. png_composite_16(v, g, a, background_1->gray);
  192356. *dp = (png_byte)((v >> 8) & 0xff);
  192357. *(dp + 1) = (png_byte)(v & 0xff);
  192358. }
  192359. #endif
  192360. }
  192361. }
  192362. }
  192363. break;
  192364. }
  192365. case PNG_COLOR_TYPE_RGB_ALPHA:
  192366. {
  192367. if (row_info->bit_depth == 8)
  192368. {
  192369. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192370. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192371. gamma_table != NULL)
  192372. {
  192373. sp = row;
  192374. dp = row;
  192375. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192376. {
  192377. png_byte a = *(sp + 3);
  192378. if (a == 0xff)
  192379. {
  192380. *dp = gamma_table[*sp];
  192381. *(dp + 1) = gamma_table[*(sp + 1)];
  192382. *(dp + 2) = gamma_table[*(sp + 2)];
  192383. }
  192384. else if (a == 0)
  192385. {
  192386. /* background is already in screen gamma */
  192387. *dp = (png_byte)background->red;
  192388. *(dp + 1) = (png_byte)background->green;
  192389. *(dp + 2) = (png_byte)background->blue;
  192390. }
  192391. else
  192392. {
  192393. png_byte v, w;
  192394. v = gamma_to_1[*sp];
  192395. png_composite(w, v, a, background_1->red);
  192396. *dp = gamma_from_1[w];
  192397. v = gamma_to_1[*(sp + 1)];
  192398. png_composite(w, v, a, background_1->green);
  192399. *(dp + 1) = gamma_from_1[w];
  192400. v = gamma_to_1[*(sp + 2)];
  192401. png_composite(w, v, a, background_1->blue);
  192402. *(dp + 2) = gamma_from_1[w];
  192403. }
  192404. }
  192405. }
  192406. else
  192407. #endif
  192408. {
  192409. sp = row;
  192410. dp = row;
  192411. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192412. {
  192413. png_byte a = *(sp + 3);
  192414. if (a == 0xff)
  192415. {
  192416. *dp = *sp;
  192417. *(dp + 1) = *(sp + 1);
  192418. *(dp + 2) = *(sp + 2);
  192419. }
  192420. else if (a == 0)
  192421. {
  192422. *dp = (png_byte)background->red;
  192423. *(dp + 1) = (png_byte)background->green;
  192424. *(dp + 2) = (png_byte)background->blue;
  192425. }
  192426. else
  192427. {
  192428. png_composite(*dp, *sp, a, background->red);
  192429. png_composite(*(dp + 1), *(sp + 1), a,
  192430. background->green);
  192431. png_composite(*(dp + 2), *(sp + 2), a,
  192432. background->blue);
  192433. }
  192434. }
  192435. }
  192436. }
  192437. else /* if (row_info->bit_depth == 16) */
  192438. {
  192439. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192440. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192441. gamma_16_to_1 != NULL)
  192442. {
  192443. sp = row;
  192444. dp = row;
  192445. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192446. {
  192447. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192448. << 8) + (png_uint_16)(*(sp + 7)));
  192449. if (a == (png_uint_16)0xffff)
  192450. {
  192451. png_uint_16 v;
  192452. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192453. *dp = (png_byte)((v >> 8) & 0xff);
  192454. *(dp + 1) = (png_byte)(v & 0xff);
  192455. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192456. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192457. *(dp + 3) = (png_byte)(v & 0xff);
  192458. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192459. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192460. *(dp + 5) = (png_byte)(v & 0xff);
  192461. }
  192462. else if (a == 0)
  192463. {
  192464. /* background is already in screen gamma */
  192465. *dp = (png_byte)((background->red >> 8) & 0xff);
  192466. *(dp + 1) = (png_byte)(background->red & 0xff);
  192467. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192468. *(dp + 3) = (png_byte)(background->green & 0xff);
  192469. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192470. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192471. }
  192472. else
  192473. {
  192474. png_uint_16 v, w, x;
  192475. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192476. png_composite_16(w, v, a, background_1->red);
  192477. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192478. *dp = (png_byte)((x >> 8) & 0xff);
  192479. *(dp + 1) = (png_byte)(x & 0xff);
  192480. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192481. png_composite_16(w, v, a, background_1->green);
  192482. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192483. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192484. *(dp + 3) = (png_byte)(x & 0xff);
  192485. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192486. png_composite_16(w, v, a, background_1->blue);
  192487. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192488. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192489. *(dp + 5) = (png_byte)(x & 0xff);
  192490. }
  192491. }
  192492. }
  192493. else
  192494. #endif
  192495. {
  192496. sp = row;
  192497. dp = row;
  192498. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192499. {
  192500. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192501. << 8) + (png_uint_16)(*(sp + 7)));
  192502. if (a == (png_uint_16)0xffff)
  192503. {
  192504. png_memcpy(dp, sp, 6);
  192505. }
  192506. else if (a == 0)
  192507. {
  192508. *dp = (png_byte)((background->red >> 8) & 0xff);
  192509. *(dp + 1) = (png_byte)(background->red & 0xff);
  192510. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192511. *(dp + 3) = (png_byte)(background->green & 0xff);
  192512. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192513. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192514. }
  192515. else
  192516. {
  192517. png_uint_16 v;
  192518. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192519. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192520. + *(sp + 3));
  192521. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192522. + *(sp + 5));
  192523. png_composite_16(v, r, a, background->red);
  192524. *dp = (png_byte)((v >> 8) & 0xff);
  192525. *(dp + 1) = (png_byte)(v & 0xff);
  192526. png_composite_16(v, g, a, background->green);
  192527. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192528. *(dp + 3) = (png_byte)(v & 0xff);
  192529. png_composite_16(v, b, a, background->blue);
  192530. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192531. *(dp + 5) = (png_byte)(v & 0xff);
  192532. }
  192533. }
  192534. }
  192535. }
  192536. break;
  192537. }
  192538. }
  192539. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192540. {
  192541. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192542. row_info->channels--;
  192543. row_info->pixel_depth = (png_byte)(row_info->channels *
  192544. row_info->bit_depth);
  192545. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192546. }
  192547. }
  192548. }
  192549. #endif
  192550. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192551. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192552. * you do this after you deal with the transparency issue on grayscale
  192553. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192554. * is 16, use gamma_16_table and gamma_shift. Build these with
  192555. * build_gamma_table().
  192556. */
  192557. void /* PRIVATE */
  192558. png_do_gamma(png_row_infop row_info, png_bytep row,
  192559. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192560. int gamma_shift)
  192561. {
  192562. png_bytep sp;
  192563. png_uint_32 i;
  192564. png_uint_32 row_width=row_info->width;
  192565. png_debug(1, "in png_do_gamma\n");
  192566. if (
  192567. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192568. row != NULL && row_info != NULL &&
  192569. #endif
  192570. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192571. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192572. {
  192573. switch (row_info->color_type)
  192574. {
  192575. case PNG_COLOR_TYPE_RGB:
  192576. {
  192577. if (row_info->bit_depth == 8)
  192578. {
  192579. sp = row;
  192580. for (i = 0; i < row_width; i++)
  192581. {
  192582. *sp = gamma_table[*sp];
  192583. sp++;
  192584. *sp = gamma_table[*sp];
  192585. sp++;
  192586. *sp = gamma_table[*sp];
  192587. sp++;
  192588. }
  192589. }
  192590. else /* if (row_info->bit_depth == 16) */
  192591. {
  192592. sp = row;
  192593. for (i = 0; i < row_width; i++)
  192594. {
  192595. png_uint_16 v;
  192596. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192597. *sp = (png_byte)((v >> 8) & 0xff);
  192598. *(sp + 1) = (png_byte)(v & 0xff);
  192599. sp += 2;
  192600. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192601. *sp = (png_byte)((v >> 8) & 0xff);
  192602. *(sp + 1) = (png_byte)(v & 0xff);
  192603. sp += 2;
  192604. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192605. *sp = (png_byte)((v >> 8) & 0xff);
  192606. *(sp + 1) = (png_byte)(v & 0xff);
  192607. sp += 2;
  192608. }
  192609. }
  192610. break;
  192611. }
  192612. case PNG_COLOR_TYPE_RGB_ALPHA:
  192613. {
  192614. if (row_info->bit_depth == 8)
  192615. {
  192616. sp = row;
  192617. for (i = 0; i < row_width; i++)
  192618. {
  192619. *sp = gamma_table[*sp];
  192620. sp++;
  192621. *sp = gamma_table[*sp];
  192622. sp++;
  192623. *sp = gamma_table[*sp];
  192624. sp++;
  192625. sp++;
  192626. }
  192627. }
  192628. else /* if (row_info->bit_depth == 16) */
  192629. {
  192630. sp = row;
  192631. for (i = 0; i < row_width; i++)
  192632. {
  192633. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192634. *sp = (png_byte)((v >> 8) & 0xff);
  192635. *(sp + 1) = (png_byte)(v & 0xff);
  192636. sp += 2;
  192637. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192638. *sp = (png_byte)((v >> 8) & 0xff);
  192639. *(sp + 1) = (png_byte)(v & 0xff);
  192640. sp += 2;
  192641. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192642. *sp = (png_byte)((v >> 8) & 0xff);
  192643. *(sp + 1) = (png_byte)(v & 0xff);
  192644. sp += 4;
  192645. }
  192646. }
  192647. break;
  192648. }
  192649. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192650. {
  192651. if (row_info->bit_depth == 8)
  192652. {
  192653. sp = row;
  192654. for (i = 0; i < row_width; i++)
  192655. {
  192656. *sp = gamma_table[*sp];
  192657. sp += 2;
  192658. }
  192659. }
  192660. else /* if (row_info->bit_depth == 16) */
  192661. {
  192662. sp = row;
  192663. for (i = 0; i < row_width; i++)
  192664. {
  192665. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192666. *sp = (png_byte)((v >> 8) & 0xff);
  192667. *(sp + 1) = (png_byte)(v & 0xff);
  192668. sp += 4;
  192669. }
  192670. }
  192671. break;
  192672. }
  192673. case PNG_COLOR_TYPE_GRAY:
  192674. {
  192675. if (row_info->bit_depth == 2)
  192676. {
  192677. sp = row;
  192678. for (i = 0; i < row_width; i += 4)
  192679. {
  192680. int a = *sp & 0xc0;
  192681. int b = *sp & 0x30;
  192682. int c = *sp & 0x0c;
  192683. int d = *sp & 0x03;
  192684. *sp = (png_byte)(
  192685. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192686. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192687. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192688. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192689. sp++;
  192690. }
  192691. }
  192692. if (row_info->bit_depth == 4)
  192693. {
  192694. sp = row;
  192695. for (i = 0; i < row_width; i += 2)
  192696. {
  192697. int msb = *sp & 0xf0;
  192698. int lsb = *sp & 0x0f;
  192699. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192700. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192701. sp++;
  192702. }
  192703. }
  192704. else if (row_info->bit_depth == 8)
  192705. {
  192706. sp = row;
  192707. for (i = 0; i < row_width; i++)
  192708. {
  192709. *sp = gamma_table[*sp];
  192710. sp++;
  192711. }
  192712. }
  192713. else if (row_info->bit_depth == 16)
  192714. {
  192715. sp = row;
  192716. for (i = 0; i < row_width; i++)
  192717. {
  192718. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192719. *sp = (png_byte)((v >> 8) & 0xff);
  192720. *(sp + 1) = (png_byte)(v & 0xff);
  192721. sp += 2;
  192722. }
  192723. }
  192724. break;
  192725. }
  192726. }
  192727. }
  192728. }
  192729. #endif
  192730. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192731. /* Expands a palette row to an RGB or RGBA row depending
  192732. * upon whether you supply trans and num_trans.
  192733. */
  192734. void /* PRIVATE */
  192735. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192736. png_colorp palette, png_bytep trans, int num_trans)
  192737. {
  192738. int shift, value;
  192739. png_bytep sp, dp;
  192740. png_uint_32 i;
  192741. png_uint_32 row_width=row_info->width;
  192742. png_debug(1, "in png_do_expand_palette\n");
  192743. if (
  192744. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192745. row != NULL && row_info != NULL &&
  192746. #endif
  192747. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192748. {
  192749. if (row_info->bit_depth < 8)
  192750. {
  192751. switch (row_info->bit_depth)
  192752. {
  192753. case 1:
  192754. {
  192755. sp = row + (png_size_t)((row_width - 1) >> 3);
  192756. dp = row + (png_size_t)row_width - 1;
  192757. shift = 7 - (int)((row_width + 7) & 0x07);
  192758. for (i = 0; i < row_width; i++)
  192759. {
  192760. if ((*sp >> shift) & 0x01)
  192761. *dp = 1;
  192762. else
  192763. *dp = 0;
  192764. if (shift == 7)
  192765. {
  192766. shift = 0;
  192767. sp--;
  192768. }
  192769. else
  192770. shift++;
  192771. dp--;
  192772. }
  192773. break;
  192774. }
  192775. case 2:
  192776. {
  192777. sp = row + (png_size_t)((row_width - 1) >> 2);
  192778. dp = row + (png_size_t)row_width - 1;
  192779. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192780. for (i = 0; i < row_width; i++)
  192781. {
  192782. value = (*sp >> shift) & 0x03;
  192783. *dp = (png_byte)value;
  192784. if (shift == 6)
  192785. {
  192786. shift = 0;
  192787. sp--;
  192788. }
  192789. else
  192790. shift += 2;
  192791. dp--;
  192792. }
  192793. break;
  192794. }
  192795. case 4:
  192796. {
  192797. sp = row + (png_size_t)((row_width - 1) >> 1);
  192798. dp = row + (png_size_t)row_width - 1;
  192799. shift = (int)((row_width & 0x01) << 2);
  192800. for (i = 0; i < row_width; i++)
  192801. {
  192802. value = (*sp >> shift) & 0x0f;
  192803. *dp = (png_byte)value;
  192804. if (shift == 4)
  192805. {
  192806. shift = 0;
  192807. sp--;
  192808. }
  192809. else
  192810. shift += 4;
  192811. dp--;
  192812. }
  192813. break;
  192814. }
  192815. }
  192816. row_info->bit_depth = 8;
  192817. row_info->pixel_depth = 8;
  192818. row_info->rowbytes = row_width;
  192819. }
  192820. switch (row_info->bit_depth)
  192821. {
  192822. case 8:
  192823. {
  192824. if (trans != NULL)
  192825. {
  192826. sp = row + (png_size_t)row_width - 1;
  192827. dp = row + (png_size_t)(row_width << 2) - 1;
  192828. for (i = 0; i < row_width; i++)
  192829. {
  192830. if ((int)(*sp) >= num_trans)
  192831. *dp-- = 0xff;
  192832. else
  192833. *dp-- = trans[*sp];
  192834. *dp-- = palette[*sp].blue;
  192835. *dp-- = palette[*sp].green;
  192836. *dp-- = palette[*sp].red;
  192837. sp--;
  192838. }
  192839. row_info->bit_depth = 8;
  192840. row_info->pixel_depth = 32;
  192841. row_info->rowbytes = row_width * 4;
  192842. row_info->color_type = 6;
  192843. row_info->channels = 4;
  192844. }
  192845. else
  192846. {
  192847. sp = row + (png_size_t)row_width - 1;
  192848. dp = row + (png_size_t)(row_width * 3) - 1;
  192849. for (i = 0; i < row_width; i++)
  192850. {
  192851. *dp-- = palette[*sp].blue;
  192852. *dp-- = palette[*sp].green;
  192853. *dp-- = palette[*sp].red;
  192854. sp--;
  192855. }
  192856. row_info->bit_depth = 8;
  192857. row_info->pixel_depth = 24;
  192858. row_info->rowbytes = row_width * 3;
  192859. row_info->color_type = 2;
  192860. row_info->channels = 3;
  192861. }
  192862. break;
  192863. }
  192864. }
  192865. }
  192866. }
  192867. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  192868. * expanded transparency value is supplied, an alpha channel is built.
  192869. */
  192870. void /* PRIVATE */
  192871. png_do_expand(png_row_infop row_info, png_bytep row,
  192872. png_color_16p trans_value)
  192873. {
  192874. int shift, value;
  192875. png_bytep sp, dp;
  192876. png_uint_32 i;
  192877. png_uint_32 row_width=row_info->width;
  192878. png_debug(1, "in png_do_expand\n");
  192879. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192880. if (row != NULL && row_info != NULL)
  192881. #endif
  192882. {
  192883. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192884. {
  192885. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  192886. if (row_info->bit_depth < 8)
  192887. {
  192888. switch (row_info->bit_depth)
  192889. {
  192890. case 1:
  192891. {
  192892. gray = (png_uint_16)((gray&0x01)*0xff);
  192893. sp = row + (png_size_t)((row_width - 1) >> 3);
  192894. dp = row + (png_size_t)row_width - 1;
  192895. shift = 7 - (int)((row_width + 7) & 0x07);
  192896. for (i = 0; i < row_width; i++)
  192897. {
  192898. if ((*sp >> shift) & 0x01)
  192899. *dp = 0xff;
  192900. else
  192901. *dp = 0;
  192902. if (shift == 7)
  192903. {
  192904. shift = 0;
  192905. sp--;
  192906. }
  192907. else
  192908. shift++;
  192909. dp--;
  192910. }
  192911. break;
  192912. }
  192913. case 2:
  192914. {
  192915. gray = (png_uint_16)((gray&0x03)*0x55);
  192916. sp = row + (png_size_t)((row_width - 1) >> 2);
  192917. dp = row + (png_size_t)row_width - 1;
  192918. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192919. for (i = 0; i < row_width; i++)
  192920. {
  192921. value = (*sp >> shift) & 0x03;
  192922. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  192923. (value << 6));
  192924. if (shift == 6)
  192925. {
  192926. shift = 0;
  192927. sp--;
  192928. }
  192929. else
  192930. shift += 2;
  192931. dp--;
  192932. }
  192933. break;
  192934. }
  192935. case 4:
  192936. {
  192937. gray = (png_uint_16)((gray&0x0f)*0x11);
  192938. sp = row + (png_size_t)((row_width - 1) >> 1);
  192939. dp = row + (png_size_t)row_width - 1;
  192940. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192941. for (i = 0; i < row_width; i++)
  192942. {
  192943. value = (*sp >> shift) & 0x0f;
  192944. *dp = (png_byte)(value | (value << 4));
  192945. if (shift == 4)
  192946. {
  192947. shift = 0;
  192948. sp--;
  192949. }
  192950. else
  192951. shift = 4;
  192952. dp--;
  192953. }
  192954. break;
  192955. }
  192956. }
  192957. row_info->bit_depth = 8;
  192958. row_info->pixel_depth = 8;
  192959. row_info->rowbytes = row_width;
  192960. }
  192961. if (trans_value != NULL)
  192962. {
  192963. if (row_info->bit_depth == 8)
  192964. {
  192965. gray = gray & 0xff;
  192966. sp = row + (png_size_t)row_width - 1;
  192967. dp = row + (png_size_t)(row_width << 1) - 1;
  192968. for (i = 0; i < row_width; i++)
  192969. {
  192970. if (*sp == gray)
  192971. *dp-- = 0;
  192972. else
  192973. *dp-- = 0xff;
  192974. *dp-- = *sp--;
  192975. }
  192976. }
  192977. else if (row_info->bit_depth == 16)
  192978. {
  192979. png_byte gray_high = (gray >> 8) & 0xff;
  192980. png_byte gray_low = gray & 0xff;
  192981. sp = row + row_info->rowbytes - 1;
  192982. dp = row + (row_info->rowbytes << 1) - 1;
  192983. for (i = 0; i < row_width; i++)
  192984. {
  192985. if (*(sp-1) == gray_high && *(sp) == gray_low)
  192986. {
  192987. *dp-- = 0;
  192988. *dp-- = 0;
  192989. }
  192990. else
  192991. {
  192992. *dp-- = 0xff;
  192993. *dp-- = 0xff;
  192994. }
  192995. *dp-- = *sp--;
  192996. *dp-- = *sp--;
  192997. }
  192998. }
  192999. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193000. row_info->channels = 2;
  193001. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193002. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193003. row_width);
  193004. }
  193005. }
  193006. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193007. {
  193008. if (row_info->bit_depth == 8)
  193009. {
  193010. png_byte red = trans_value->red & 0xff;
  193011. png_byte green = trans_value->green & 0xff;
  193012. png_byte blue = trans_value->blue & 0xff;
  193013. sp = row + (png_size_t)row_info->rowbytes - 1;
  193014. dp = row + (png_size_t)(row_width << 2) - 1;
  193015. for (i = 0; i < row_width; i++)
  193016. {
  193017. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193018. *dp-- = 0;
  193019. else
  193020. *dp-- = 0xff;
  193021. *dp-- = *sp--;
  193022. *dp-- = *sp--;
  193023. *dp-- = *sp--;
  193024. }
  193025. }
  193026. else if (row_info->bit_depth == 16)
  193027. {
  193028. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193029. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193030. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193031. png_byte red_low = trans_value->red & 0xff;
  193032. png_byte green_low = trans_value->green & 0xff;
  193033. png_byte blue_low = trans_value->blue & 0xff;
  193034. sp = row + row_info->rowbytes - 1;
  193035. dp = row + (png_size_t)(row_width << 3) - 1;
  193036. for (i = 0; i < row_width; i++)
  193037. {
  193038. if (*(sp - 5) == red_high &&
  193039. *(sp - 4) == red_low &&
  193040. *(sp - 3) == green_high &&
  193041. *(sp - 2) == green_low &&
  193042. *(sp - 1) == blue_high &&
  193043. *(sp ) == blue_low)
  193044. {
  193045. *dp-- = 0;
  193046. *dp-- = 0;
  193047. }
  193048. else
  193049. {
  193050. *dp-- = 0xff;
  193051. *dp-- = 0xff;
  193052. }
  193053. *dp-- = *sp--;
  193054. *dp-- = *sp--;
  193055. *dp-- = *sp--;
  193056. *dp-- = *sp--;
  193057. *dp-- = *sp--;
  193058. *dp-- = *sp--;
  193059. }
  193060. }
  193061. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193062. row_info->channels = 4;
  193063. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193064. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193065. }
  193066. }
  193067. }
  193068. #endif
  193069. #if defined(PNG_READ_DITHER_SUPPORTED)
  193070. void /* PRIVATE */
  193071. png_do_dither(png_row_infop row_info, png_bytep row,
  193072. png_bytep palette_lookup, png_bytep dither_lookup)
  193073. {
  193074. png_bytep sp, dp;
  193075. png_uint_32 i;
  193076. png_uint_32 row_width=row_info->width;
  193077. png_debug(1, "in png_do_dither\n");
  193078. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193079. if (row != NULL && row_info != NULL)
  193080. #endif
  193081. {
  193082. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193083. palette_lookup && row_info->bit_depth == 8)
  193084. {
  193085. int r, g, b, p;
  193086. sp = row;
  193087. dp = row;
  193088. for (i = 0; i < row_width; i++)
  193089. {
  193090. r = *sp++;
  193091. g = *sp++;
  193092. b = *sp++;
  193093. /* this looks real messy, but the compiler will reduce
  193094. it down to a reasonable formula. For example, with
  193095. 5 bits per color, we get:
  193096. p = (((r >> 3) & 0x1f) << 10) |
  193097. (((g >> 3) & 0x1f) << 5) |
  193098. ((b >> 3) & 0x1f);
  193099. */
  193100. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193101. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193102. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193103. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193104. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193105. (PNG_DITHER_BLUE_BITS)) |
  193106. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193107. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193108. *dp++ = palette_lookup[p];
  193109. }
  193110. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193111. row_info->channels = 1;
  193112. row_info->pixel_depth = row_info->bit_depth;
  193113. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193114. }
  193115. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193116. palette_lookup != NULL && row_info->bit_depth == 8)
  193117. {
  193118. int r, g, b, p;
  193119. sp = row;
  193120. dp = row;
  193121. for (i = 0; i < row_width; i++)
  193122. {
  193123. r = *sp++;
  193124. g = *sp++;
  193125. b = *sp++;
  193126. sp++;
  193127. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193128. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193129. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193130. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193131. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193132. (PNG_DITHER_BLUE_BITS)) |
  193133. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193134. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193135. *dp++ = palette_lookup[p];
  193136. }
  193137. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193138. row_info->channels = 1;
  193139. row_info->pixel_depth = row_info->bit_depth;
  193140. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193141. }
  193142. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193143. dither_lookup && row_info->bit_depth == 8)
  193144. {
  193145. sp = row;
  193146. for (i = 0; i < row_width; i++, sp++)
  193147. {
  193148. *sp = dither_lookup[*sp];
  193149. }
  193150. }
  193151. }
  193152. }
  193153. #endif
  193154. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193155. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193156. static PNG_CONST int png_gamma_shift[] =
  193157. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193158. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193159. * tables, we don't make a full table if we are reducing to 8-bit in
  193160. * the future. Note also how the gamma_16 tables are segmented so that
  193161. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193162. */
  193163. void /* PRIVATE */
  193164. png_build_gamma_table(png_structp png_ptr)
  193165. {
  193166. png_debug(1, "in png_build_gamma_table\n");
  193167. if (png_ptr->bit_depth <= 8)
  193168. {
  193169. int i;
  193170. double g;
  193171. if (png_ptr->screen_gamma > .000001)
  193172. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193173. else
  193174. g = 1.0;
  193175. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193176. (png_uint_32)256);
  193177. for (i = 0; i < 256; i++)
  193178. {
  193179. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193180. g) * 255.0 + .5);
  193181. }
  193182. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193183. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193184. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193185. {
  193186. g = 1.0 / (png_ptr->gamma);
  193187. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193188. (png_uint_32)256);
  193189. for (i = 0; i < 256; i++)
  193190. {
  193191. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193192. g) * 255.0 + .5);
  193193. }
  193194. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193195. (png_uint_32)256);
  193196. if(png_ptr->screen_gamma > 0.000001)
  193197. g = 1.0 / png_ptr->screen_gamma;
  193198. else
  193199. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193200. for (i = 0; i < 256; i++)
  193201. {
  193202. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193203. g) * 255.0 + .5);
  193204. }
  193205. }
  193206. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193207. }
  193208. else
  193209. {
  193210. double g;
  193211. int i, j, shift, num;
  193212. int sig_bit;
  193213. png_uint_32 ig;
  193214. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193215. {
  193216. sig_bit = (int)png_ptr->sig_bit.red;
  193217. if ((int)png_ptr->sig_bit.green > sig_bit)
  193218. sig_bit = png_ptr->sig_bit.green;
  193219. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193220. sig_bit = png_ptr->sig_bit.blue;
  193221. }
  193222. else
  193223. {
  193224. sig_bit = (int)png_ptr->sig_bit.gray;
  193225. }
  193226. if (sig_bit > 0)
  193227. shift = 16 - sig_bit;
  193228. else
  193229. shift = 0;
  193230. if (png_ptr->transformations & PNG_16_TO_8)
  193231. {
  193232. if (shift < (16 - PNG_MAX_GAMMA_8))
  193233. shift = (16 - PNG_MAX_GAMMA_8);
  193234. }
  193235. if (shift > 8)
  193236. shift = 8;
  193237. if (shift < 0)
  193238. shift = 0;
  193239. png_ptr->gamma_shift = (png_byte)shift;
  193240. num = (1 << (8 - shift));
  193241. if (png_ptr->screen_gamma > .000001)
  193242. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193243. else
  193244. g = 1.0;
  193245. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193246. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193247. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193248. {
  193249. double fin, fout;
  193250. png_uint_32 last, max;
  193251. for (i = 0; i < num; i++)
  193252. {
  193253. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193254. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193255. }
  193256. g = 1.0 / g;
  193257. last = 0;
  193258. for (i = 0; i < 256; i++)
  193259. {
  193260. fout = ((double)i + 0.5) / 256.0;
  193261. fin = pow(fout, g);
  193262. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193263. while (last <= max)
  193264. {
  193265. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193266. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193267. (png_uint_16)i | ((png_uint_16)i << 8));
  193268. last++;
  193269. }
  193270. }
  193271. while (last < ((png_uint_32)num << 8))
  193272. {
  193273. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193274. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193275. last++;
  193276. }
  193277. }
  193278. else
  193279. {
  193280. for (i = 0; i < num; i++)
  193281. {
  193282. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193283. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193284. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193285. for (j = 0; j < 256; j++)
  193286. {
  193287. png_ptr->gamma_16_table[i][j] =
  193288. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193289. 65535.0, g) * 65535.0 + .5);
  193290. }
  193291. }
  193292. }
  193293. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193294. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193295. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193296. {
  193297. g = 1.0 / (png_ptr->gamma);
  193298. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193299. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193300. for (i = 0; i < num; i++)
  193301. {
  193302. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193303. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193304. ig = (((png_uint_32)i *
  193305. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193306. for (j = 0; j < 256; j++)
  193307. {
  193308. png_ptr->gamma_16_to_1[i][j] =
  193309. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193310. 65535.0, g) * 65535.0 + .5);
  193311. }
  193312. }
  193313. if(png_ptr->screen_gamma > 0.000001)
  193314. g = 1.0 / png_ptr->screen_gamma;
  193315. else
  193316. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193317. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193318. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193319. for (i = 0; i < num; i++)
  193320. {
  193321. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193322. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193323. ig = (((png_uint_32)i *
  193324. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193325. for (j = 0; j < 256; j++)
  193326. {
  193327. png_ptr->gamma_16_from_1[i][j] =
  193328. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193329. 65535.0, g) * 65535.0 + .5);
  193330. }
  193331. }
  193332. }
  193333. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193334. }
  193335. }
  193336. #endif
  193337. /* To do: install integer version of png_build_gamma_table here */
  193338. #endif
  193339. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193340. /* undoes intrapixel differencing */
  193341. void /* PRIVATE */
  193342. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193343. {
  193344. png_debug(1, "in png_do_read_intrapixel\n");
  193345. if (
  193346. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193347. row != NULL && row_info != NULL &&
  193348. #endif
  193349. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193350. {
  193351. int bytes_per_pixel;
  193352. png_uint_32 row_width = row_info->width;
  193353. if (row_info->bit_depth == 8)
  193354. {
  193355. png_bytep rp;
  193356. png_uint_32 i;
  193357. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193358. bytes_per_pixel = 3;
  193359. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193360. bytes_per_pixel = 4;
  193361. else
  193362. return;
  193363. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193364. {
  193365. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193366. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193367. }
  193368. }
  193369. else if (row_info->bit_depth == 16)
  193370. {
  193371. png_bytep rp;
  193372. png_uint_32 i;
  193373. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193374. bytes_per_pixel = 6;
  193375. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193376. bytes_per_pixel = 8;
  193377. else
  193378. return;
  193379. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193380. {
  193381. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193382. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193383. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193384. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193385. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193386. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193387. *(rp+1) = (png_byte)(red & 0xff);
  193388. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193389. *(rp+5) = (png_byte)(blue & 0xff);
  193390. }
  193391. }
  193392. }
  193393. }
  193394. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193395. #endif /* PNG_READ_SUPPORTED */
  193396. /*** End of inlined file: pngrtran.c ***/
  193397. /*** Start of inlined file: pngrutil.c ***/
  193398. /* pngrutil.c - utilities to read a PNG file
  193399. *
  193400. * Last changed in libpng 1.2.21 [October 4, 2007]
  193401. * For conditions of distribution and use, see copyright notice in png.h
  193402. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193403. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193404. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193405. *
  193406. * This file contains routines that are only called from within
  193407. * libpng itself during the course of reading an image.
  193408. */
  193409. #define PNG_INTERNAL
  193410. #if defined(PNG_READ_SUPPORTED)
  193411. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193412. # define WIN32_WCE_OLD
  193413. #endif
  193414. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193415. # if defined(WIN32_WCE_OLD)
  193416. /* strtod() function is not supported on WindowsCE */
  193417. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193418. {
  193419. double result = 0;
  193420. int len;
  193421. wchar_t *str, *end;
  193422. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193423. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193424. if ( NULL != str )
  193425. {
  193426. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193427. result = wcstod(str, &end);
  193428. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193429. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193430. png_free(png_ptr, str);
  193431. }
  193432. return result;
  193433. }
  193434. # else
  193435. # define png_strtod(p,a,b) strtod(a,b)
  193436. # endif
  193437. #endif
  193438. png_uint_32 PNGAPI
  193439. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193440. {
  193441. png_uint_32 i = png_get_uint_32(buf);
  193442. if (i > PNG_UINT_31_MAX)
  193443. png_error(png_ptr, "PNG unsigned integer out of range.");
  193444. return (i);
  193445. }
  193446. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193447. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193448. png_uint_32 PNGAPI
  193449. png_get_uint_32(png_bytep buf)
  193450. {
  193451. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193452. ((png_uint_32)(*(buf + 1)) << 16) +
  193453. ((png_uint_32)(*(buf + 2)) << 8) +
  193454. (png_uint_32)(*(buf + 3));
  193455. return (i);
  193456. }
  193457. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193458. * data is stored in the PNG file in two's complement format, and it is
  193459. * assumed that the machine format for signed integers is the same. */
  193460. png_int_32 PNGAPI
  193461. png_get_int_32(png_bytep buf)
  193462. {
  193463. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193464. ((png_int_32)(*(buf + 1)) << 16) +
  193465. ((png_int_32)(*(buf + 2)) << 8) +
  193466. (png_int_32)(*(buf + 3));
  193467. return (i);
  193468. }
  193469. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193470. png_uint_16 PNGAPI
  193471. png_get_uint_16(png_bytep buf)
  193472. {
  193473. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193474. (png_uint_16)(*(buf + 1)));
  193475. return (i);
  193476. }
  193477. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193478. /* Read data, and (optionally) run it through the CRC. */
  193479. void /* PRIVATE */
  193480. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193481. {
  193482. if(png_ptr == NULL) return;
  193483. png_read_data(png_ptr, buf, length);
  193484. png_calculate_crc(png_ptr, buf, length);
  193485. }
  193486. /* Optionally skip data and then check the CRC. Depending on whether we
  193487. are reading a ancillary or critical chunk, and how the program has set
  193488. things up, we may calculate the CRC on the data and print a message.
  193489. Returns '1' if there was a CRC error, '0' otherwise. */
  193490. int /* PRIVATE */
  193491. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193492. {
  193493. png_size_t i;
  193494. png_size_t istop = png_ptr->zbuf_size;
  193495. for (i = (png_size_t)skip; i > istop; i -= istop)
  193496. {
  193497. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193498. }
  193499. if (i)
  193500. {
  193501. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193502. }
  193503. if (png_crc_error(png_ptr))
  193504. {
  193505. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193506. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193507. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193508. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193509. {
  193510. png_chunk_warning(png_ptr, "CRC error");
  193511. }
  193512. else
  193513. {
  193514. png_chunk_error(png_ptr, "CRC error");
  193515. }
  193516. return (1);
  193517. }
  193518. return (0);
  193519. }
  193520. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193521. the data it has read thus far. */
  193522. int /* PRIVATE */
  193523. png_crc_error(png_structp png_ptr)
  193524. {
  193525. png_byte crc_bytes[4];
  193526. png_uint_32 crc;
  193527. int need_crc = 1;
  193528. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193529. {
  193530. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193531. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193532. need_crc = 0;
  193533. }
  193534. else /* critical */
  193535. {
  193536. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193537. need_crc = 0;
  193538. }
  193539. png_read_data(png_ptr, crc_bytes, 4);
  193540. if (need_crc)
  193541. {
  193542. crc = png_get_uint_32(crc_bytes);
  193543. return ((int)(crc != png_ptr->crc));
  193544. }
  193545. else
  193546. return (0);
  193547. }
  193548. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193549. defined(PNG_READ_iCCP_SUPPORTED)
  193550. /*
  193551. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193552. * points at an allocated area holding the contents of a chunk with a
  193553. * trailing compressed part. What we get back is an allocated area
  193554. * holding the original prefix part and an uncompressed version of the
  193555. * trailing part (the malloc area passed in is freed).
  193556. */
  193557. png_charp /* PRIVATE */
  193558. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193559. png_charp chunkdata, png_size_t chunklength,
  193560. png_size_t prefix_size, png_size_t *newlength)
  193561. {
  193562. static PNG_CONST char msg[] = "Error decoding compressed text";
  193563. png_charp text;
  193564. png_size_t text_size;
  193565. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193566. {
  193567. int ret = Z_OK;
  193568. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193569. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193570. png_ptr->zstream.next_out = png_ptr->zbuf;
  193571. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193572. text_size = 0;
  193573. text = NULL;
  193574. while (png_ptr->zstream.avail_in)
  193575. {
  193576. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193577. if (ret != Z_OK && ret != Z_STREAM_END)
  193578. {
  193579. if (png_ptr->zstream.msg != NULL)
  193580. png_warning(png_ptr, png_ptr->zstream.msg);
  193581. else
  193582. png_warning(png_ptr, msg);
  193583. inflateReset(&png_ptr->zstream);
  193584. png_ptr->zstream.avail_in = 0;
  193585. if (text == NULL)
  193586. {
  193587. text_size = prefix_size + png_sizeof(msg) + 1;
  193588. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193589. if (text == NULL)
  193590. {
  193591. png_free(png_ptr,chunkdata);
  193592. png_error(png_ptr,"Not enough memory to decompress chunk");
  193593. }
  193594. png_memcpy(text, chunkdata, prefix_size);
  193595. }
  193596. text[text_size - 1] = 0x00;
  193597. /* Copy what we can of the error message into the text chunk */
  193598. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193599. text_size = png_sizeof(msg) > text_size ? text_size :
  193600. png_sizeof(msg);
  193601. png_memcpy(text + prefix_size, msg, text_size + 1);
  193602. break;
  193603. }
  193604. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193605. {
  193606. if (text == NULL)
  193607. {
  193608. text_size = prefix_size +
  193609. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193610. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193611. if (text == NULL)
  193612. {
  193613. png_free(png_ptr,chunkdata);
  193614. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193615. }
  193616. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193617. text_size - prefix_size);
  193618. png_memcpy(text, chunkdata, prefix_size);
  193619. *(text + text_size) = 0x00;
  193620. }
  193621. else
  193622. {
  193623. png_charp tmp;
  193624. tmp = text;
  193625. text = (png_charp)png_malloc_warn(png_ptr,
  193626. (png_uint_32)(text_size +
  193627. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193628. if (text == NULL)
  193629. {
  193630. png_free(png_ptr, tmp);
  193631. png_free(png_ptr, chunkdata);
  193632. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193633. }
  193634. png_memcpy(text, tmp, text_size);
  193635. png_free(png_ptr, tmp);
  193636. png_memcpy(text + text_size, png_ptr->zbuf,
  193637. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193638. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193639. *(text + text_size) = 0x00;
  193640. }
  193641. if (ret == Z_STREAM_END)
  193642. break;
  193643. else
  193644. {
  193645. png_ptr->zstream.next_out = png_ptr->zbuf;
  193646. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193647. }
  193648. }
  193649. }
  193650. if (ret != Z_STREAM_END)
  193651. {
  193652. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193653. char umsg[52];
  193654. if (ret == Z_BUF_ERROR)
  193655. png_snprintf(umsg, 52,
  193656. "Buffer error in compressed datastream in %s chunk",
  193657. png_ptr->chunk_name);
  193658. else if (ret == Z_DATA_ERROR)
  193659. png_snprintf(umsg, 52,
  193660. "Data error in compressed datastream in %s chunk",
  193661. png_ptr->chunk_name);
  193662. else
  193663. png_snprintf(umsg, 52,
  193664. "Incomplete compressed datastream in %s chunk",
  193665. png_ptr->chunk_name);
  193666. png_warning(png_ptr, umsg);
  193667. #else
  193668. png_warning(png_ptr,
  193669. "Incomplete compressed datastream in chunk other than IDAT");
  193670. #endif
  193671. text_size=prefix_size;
  193672. if (text == NULL)
  193673. {
  193674. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193675. if (text == NULL)
  193676. {
  193677. png_free(png_ptr, chunkdata);
  193678. png_error(png_ptr,"Not enough memory for text.");
  193679. }
  193680. png_memcpy(text, chunkdata, prefix_size);
  193681. }
  193682. *(text + text_size) = 0x00;
  193683. }
  193684. inflateReset(&png_ptr->zstream);
  193685. png_ptr->zstream.avail_in = 0;
  193686. png_free(png_ptr, chunkdata);
  193687. chunkdata = text;
  193688. *newlength=text_size;
  193689. }
  193690. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193691. {
  193692. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193693. char umsg[50];
  193694. png_snprintf(umsg, 50,
  193695. "Unknown zTXt compression type %d", comp_type);
  193696. png_warning(png_ptr, umsg);
  193697. #else
  193698. png_warning(png_ptr, "Unknown zTXt compression type");
  193699. #endif
  193700. *(chunkdata + prefix_size) = 0x00;
  193701. *newlength=prefix_size;
  193702. }
  193703. return chunkdata;
  193704. }
  193705. #endif
  193706. /* read and check the IDHR chunk */
  193707. void /* PRIVATE */
  193708. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193709. {
  193710. png_byte buf[13];
  193711. png_uint_32 width, height;
  193712. int bit_depth, color_type, compression_type, filter_type;
  193713. int interlace_type;
  193714. png_debug(1, "in png_handle_IHDR\n");
  193715. if (png_ptr->mode & PNG_HAVE_IHDR)
  193716. png_error(png_ptr, "Out of place IHDR");
  193717. /* check the length */
  193718. if (length != 13)
  193719. png_error(png_ptr, "Invalid IHDR chunk");
  193720. png_ptr->mode |= PNG_HAVE_IHDR;
  193721. png_crc_read(png_ptr, buf, 13);
  193722. png_crc_finish(png_ptr, 0);
  193723. width = png_get_uint_31(png_ptr, buf);
  193724. height = png_get_uint_31(png_ptr, buf + 4);
  193725. bit_depth = buf[8];
  193726. color_type = buf[9];
  193727. compression_type = buf[10];
  193728. filter_type = buf[11];
  193729. interlace_type = buf[12];
  193730. /* set internal variables */
  193731. png_ptr->width = width;
  193732. png_ptr->height = height;
  193733. png_ptr->bit_depth = (png_byte)bit_depth;
  193734. png_ptr->interlaced = (png_byte)interlace_type;
  193735. png_ptr->color_type = (png_byte)color_type;
  193736. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193737. png_ptr->filter_type = (png_byte)filter_type;
  193738. #endif
  193739. png_ptr->compression_type = (png_byte)compression_type;
  193740. /* find number of channels */
  193741. switch (png_ptr->color_type)
  193742. {
  193743. case PNG_COLOR_TYPE_GRAY:
  193744. case PNG_COLOR_TYPE_PALETTE:
  193745. png_ptr->channels = 1;
  193746. break;
  193747. case PNG_COLOR_TYPE_RGB:
  193748. png_ptr->channels = 3;
  193749. break;
  193750. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193751. png_ptr->channels = 2;
  193752. break;
  193753. case PNG_COLOR_TYPE_RGB_ALPHA:
  193754. png_ptr->channels = 4;
  193755. break;
  193756. }
  193757. /* set up other useful info */
  193758. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193759. png_ptr->channels);
  193760. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193761. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193762. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193763. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193764. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193765. color_type, interlace_type, compression_type, filter_type);
  193766. }
  193767. /* read and check the palette */
  193768. void /* PRIVATE */
  193769. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193770. {
  193771. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193772. int num, i;
  193773. #ifndef PNG_NO_POINTER_INDEXING
  193774. png_colorp pal_ptr;
  193775. #endif
  193776. png_debug(1, "in png_handle_PLTE\n");
  193777. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193778. png_error(png_ptr, "Missing IHDR before PLTE");
  193779. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193780. {
  193781. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193782. png_crc_finish(png_ptr, length);
  193783. return;
  193784. }
  193785. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193786. png_error(png_ptr, "Duplicate PLTE chunk");
  193787. png_ptr->mode |= PNG_HAVE_PLTE;
  193788. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193789. {
  193790. png_warning(png_ptr,
  193791. "Ignoring PLTE chunk in grayscale PNG");
  193792. png_crc_finish(png_ptr, length);
  193793. return;
  193794. }
  193795. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193796. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193797. {
  193798. png_crc_finish(png_ptr, length);
  193799. return;
  193800. }
  193801. #endif
  193802. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193803. {
  193804. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193805. {
  193806. png_warning(png_ptr, "Invalid palette chunk");
  193807. png_crc_finish(png_ptr, length);
  193808. return;
  193809. }
  193810. else
  193811. {
  193812. png_error(png_ptr, "Invalid palette chunk");
  193813. }
  193814. }
  193815. num = (int)length / 3;
  193816. #ifndef PNG_NO_POINTER_INDEXING
  193817. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  193818. {
  193819. png_byte buf[3];
  193820. png_crc_read(png_ptr, buf, 3);
  193821. pal_ptr->red = buf[0];
  193822. pal_ptr->green = buf[1];
  193823. pal_ptr->blue = buf[2];
  193824. }
  193825. #else
  193826. for (i = 0; i < num; i++)
  193827. {
  193828. png_byte buf[3];
  193829. png_crc_read(png_ptr, buf, 3);
  193830. /* don't depend upon png_color being any order */
  193831. palette[i].red = buf[0];
  193832. palette[i].green = buf[1];
  193833. palette[i].blue = buf[2];
  193834. }
  193835. #endif
  193836. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  193837. whatever the normal CRC configuration tells us. However, if we
  193838. have an RGB image, the PLTE can be considered ancillary, so
  193839. we will act as though it is. */
  193840. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193841. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193842. #endif
  193843. {
  193844. png_crc_finish(png_ptr, 0);
  193845. }
  193846. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193847. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  193848. {
  193849. /* If we don't want to use the data from an ancillary chunk,
  193850. we have two options: an error abort, or a warning and we
  193851. ignore the data in this chunk (which should be OK, since
  193852. it's considered ancillary for a RGB or RGBA image). */
  193853. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  193854. {
  193855. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  193856. {
  193857. png_chunk_error(png_ptr, "CRC error");
  193858. }
  193859. else
  193860. {
  193861. png_chunk_warning(png_ptr, "CRC error");
  193862. return;
  193863. }
  193864. }
  193865. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  193866. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193867. {
  193868. png_chunk_warning(png_ptr, "CRC error");
  193869. }
  193870. }
  193871. #endif
  193872. png_set_PLTE(png_ptr, info_ptr, palette, num);
  193873. #if defined(PNG_READ_tRNS_SUPPORTED)
  193874. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193875. {
  193876. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193877. {
  193878. if (png_ptr->num_trans > (png_uint_16)num)
  193879. {
  193880. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  193881. png_ptr->num_trans = (png_uint_16)num;
  193882. }
  193883. if (info_ptr->num_trans > (png_uint_16)num)
  193884. {
  193885. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  193886. info_ptr->num_trans = (png_uint_16)num;
  193887. }
  193888. }
  193889. }
  193890. #endif
  193891. }
  193892. void /* PRIVATE */
  193893. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193894. {
  193895. png_debug(1, "in png_handle_IEND\n");
  193896. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  193897. {
  193898. png_error(png_ptr, "No image in file");
  193899. }
  193900. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  193901. if (length != 0)
  193902. {
  193903. png_warning(png_ptr, "Incorrect IEND chunk length");
  193904. }
  193905. png_crc_finish(png_ptr, length);
  193906. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  193907. }
  193908. #if defined(PNG_READ_gAMA_SUPPORTED)
  193909. void /* PRIVATE */
  193910. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193911. {
  193912. png_fixed_point igamma;
  193913. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193914. float file_gamma;
  193915. #endif
  193916. png_byte buf[4];
  193917. png_debug(1, "in png_handle_gAMA\n");
  193918. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193919. png_error(png_ptr, "Missing IHDR before gAMA");
  193920. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193921. {
  193922. png_warning(png_ptr, "Invalid gAMA after IDAT");
  193923. png_crc_finish(png_ptr, length);
  193924. return;
  193925. }
  193926. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193927. /* Should be an error, but we can cope with it */
  193928. png_warning(png_ptr, "Out of place gAMA chunk");
  193929. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  193930. #if defined(PNG_READ_sRGB_SUPPORTED)
  193931. && !(info_ptr->valid & PNG_INFO_sRGB)
  193932. #endif
  193933. )
  193934. {
  193935. png_warning(png_ptr, "Duplicate gAMA chunk");
  193936. png_crc_finish(png_ptr, length);
  193937. return;
  193938. }
  193939. if (length != 4)
  193940. {
  193941. png_warning(png_ptr, "Incorrect gAMA chunk length");
  193942. png_crc_finish(png_ptr, length);
  193943. return;
  193944. }
  193945. png_crc_read(png_ptr, buf, 4);
  193946. if (png_crc_finish(png_ptr, 0))
  193947. return;
  193948. igamma = (png_fixed_point)png_get_uint_32(buf);
  193949. /* check for zero gamma */
  193950. if (igamma == 0)
  193951. {
  193952. png_warning(png_ptr,
  193953. "Ignoring gAMA chunk with gamma=0");
  193954. return;
  193955. }
  193956. #if defined(PNG_READ_sRGB_SUPPORTED)
  193957. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193958. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193959. {
  193960. png_warning(png_ptr,
  193961. "Ignoring incorrect gAMA value when sRGB is also present");
  193962. #ifndef PNG_NO_CONSOLE_IO
  193963. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  193964. #endif
  193965. return;
  193966. }
  193967. #endif /* PNG_READ_sRGB_SUPPORTED */
  193968. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193969. file_gamma = (float)igamma / (float)100000.0;
  193970. # ifdef PNG_READ_GAMMA_SUPPORTED
  193971. png_ptr->gamma = file_gamma;
  193972. # endif
  193973. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193974. #endif
  193975. #ifdef PNG_FIXED_POINT_SUPPORTED
  193976. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  193977. #endif
  193978. }
  193979. #endif
  193980. #if defined(PNG_READ_sBIT_SUPPORTED)
  193981. void /* PRIVATE */
  193982. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193983. {
  193984. png_size_t truelen;
  193985. png_byte buf[4];
  193986. png_debug(1, "in png_handle_sBIT\n");
  193987. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  193988. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193989. png_error(png_ptr, "Missing IHDR before sBIT");
  193990. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193991. {
  193992. png_warning(png_ptr, "Invalid sBIT after IDAT");
  193993. png_crc_finish(png_ptr, length);
  193994. return;
  193995. }
  193996. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193997. {
  193998. /* Should be an error, but we can cope with it */
  193999. png_warning(png_ptr, "Out of place sBIT chunk");
  194000. }
  194001. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194002. {
  194003. png_warning(png_ptr, "Duplicate sBIT chunk");
  194004. png_crc_finish(png_ptr, length);
  194005. return;
  194006. }
  194007. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194008. truelen = 3;
  194009. else
  194010. truelen = (png_size_t)png_ptr->channels;
  194011. if (length != truelen || length > 4)
  194012. {
  194013. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194014. png_crc_finish(png_ptr, length);
  194015. return;
  194016. }
  194017. png_crc_read(png_ptr, buf, truelen);
  194018. if (png_crc_finish(png_ptr, 0))
  194019. return;
  194020. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194021. {
  194022. png_ptr->sig_bit.red = buf[0];
  194023. png_ptr->sig_bit.green = buf[1];
  194024. png_ptr->sig_bit.blue = buf[2];
  194025. png_ptr->sig_bit.alpha = buf[3];
  194026. }
  194027. else
  194028. {
  194029. png_ptr->sig_bit.gray = buf[0];
  194030. png_ptr->sig_bit.red = buf[0];
  194031. png_ptr->sig_bit.green = buf[0];
  194032. png_ptr->sig_bit.blue = buf[0];
  194033. png_ptr->sig_bit.alpha = buf[1];
  194034. }
  194035. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194036. }
  194037. #endif
  194038. #if defined(PNG_READ_cHRM_SUPPORTED)
  194039. void /* PRIVATE */
  194040. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194041. {
  194042. png_byte buf[4];
  194043. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194044. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194045. #endif
  194046. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194047. int_y_green, int_x_blue, int_y_blue;
  194048. png_uint_32 uint_x, uint_y;
  194049. png_debug(1, "in png_handle_cHRM\n");
  194050. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194051. png_error(png_ptr, "Missing IHDR before cHRM");
  194052. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194053. {
  194054. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194055. png_crc_finish(png_ptr, length);
  194056. return;
  194057. }
  194058. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194059. /* Should be an error, but we can cope with it */
  194060. png_warning(png_ptr, "Missing PLTE before cHRM");
  194061. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194062. #if defined(PNG_READ_sRGB_SUPPORTED)
  194063. && !(info_ptr->valid & PNG_INFO_sRGB)
  194064. #endif
  194065. )
  194066. {
  194067. png_warning(png_ptr, "Duplicate cHRM chunk");
  194068. png_crc_finish(png_ptr, length);
  194069. return;
  194070. }
  194071. if (length != 32)
  194072. {
  194073. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194074. png_crc_finish(png_ptr, length);
  194075. return;
  194076. }
  194077. png_crc_read(png_ptr, buf, 4);
  194078. uint_x = png_get_uint_32(buf);
  194079. png_crc_read(png_ptr, buf, 4);
  194080. uint_y = png_get_uint_32(buf);
  194081. if (uint_x > 80000L || uint_y > 80000L ||
  194082. uint_x + uint_y > 100000L)
  194083. {
  194084. png_warning(png_ptr, "Invalid cHRM white point");
  194085. png_crc_finish(png_ptr, 24);
  194086. return;
  194087. }
  194088. int_x_white = (png_fixed_point)uint_x;
  194089. int_y_white = (png_fixed_point)uint_y;
  194090. png_crc_read(png_ptr, buf, 4);
  194091. uint_x = png_get_uint_32(buf);
  194092. png_crc_read(png_ptr, buf, 4);
  194093. uint_y = png_get_uint_32(buf);
  194094. if (uint_x + uint_y > 100000L)
  194095. {
  194096. png_warning(png_ptr, "Invalid cHRM red point");
  194097. png_crc_finish(png_ptr, 16);
  194098. return;
  194099. }
  194100. int_x_red = (png_fixed_point)uint_x;
  194101. int_y_red = (png_fixed_point)uint_y;
  194102. png_crc_read(png_ptr, buf, 4);
  194103. uint_x = png_get_uint_32(buf);
  194104. png_crc_read(png_ptr, buf, 4);
  194105. uint_y = png_get_uint_32(buf);
  194106. if (uint_x + uint_y > 100000L)
  194107. {
  194108. png_warning(png_ptr, "Invalid cHRM green point");
  194109. png_crc_finish(png_ptr, 8);
  194110. return;
  194111. }
  194112. int_x_green = (png_fixed_point)uint_x;
  194113. int_y_green = (png_fixed_point)uint_y;
  194114. png_crc_read(png_ptr, buf, 4);
  194115. uint_x = png_get_uint_32(buf);
  194116. png_crc_read(png_ptr, buf, 4);
  194117. uint_y = png_get_uint_32(buf);
  194118. if (uint_x + uint_y > 100000L)
  194119. {
  194120. png_warning(png_ptr, "Invalid cHRM blue point");
  194121. png_crc_finish(png_ptr, 0);
  194122. return;
  194123. }
  194124. int_x_blue = (png_fixed_point)uint_x;
  194125. int_y_blue = (png_fixed_point)uint_y;
  194126. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194127. white_x = (float)int_x_white / (float)100000.0;
  194128. white_y = (float)int_y_white / (float)100000.0;
  194129. red_x = (float)int_x_red / (float)100000.0;
  194130. red_y = (float)int_y_red / (float)100000.0;
  194131. green_x = (float)int_x_green / (float)100000.0;
  194132. green_y = (float)int_y_green / (float)100000.0;
  194133. blue_x = (float)int_x_blue / (float)100000.0;
  194134. blue_y = (float)int_y_blue / (float)100000.0;
  194135. #endif
  194136. #if defined(PNG_READ_sRGB_SUPPORTED)
  194137. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194138. {
  194139. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194140. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194141. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194142. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194143. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194144. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194145. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194146. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194147. {
  194148. png_warning(png_ptr,
  194149. "Ignoring incorrect cHRM value when sRGB is also present");
  194150. #ifndef PNG_NO_CONSOLE_IO
  194151. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194152. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194153. white_x, white_y, red_x, red_y);
  194154. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194155. green_x, green_y, blue_x, blue_y);
  194156. #else
  194157. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194158. int_x_white, int_y_white, int_x_red, int_y_red);
  194159. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194160. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194161. #endif
  194162. #endif /* PNG_NO_CONSOLE_IO */
  194163. }
  194164. png_crc_finish(png_ptr, 0);
  194165. return;
  194166. }
  194167. #endif /* PNG_READ_sRGB_SUPPORTED */
  194168. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194169. png_set_cHRM(png_ptr, info_ptr,
  194170. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194171. #endif
  194172. #ifdef PNG_FIXED_POINT_SUPPORTED
  194173. png_set_cHRM_fixed(png_ptr, info_ptr,
  194174. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194175. int_y_green, int_x_blue, int_y_blue);
  194176. #endif
  194177. if (png_crc_finish(png_ptr, 0))
  194178. return;
  194179. }
  194180. #endif
  194181. #if defined(PNG_READ_sRGB_SUPPORTED)
  194182. void /* PRIVATE */
  194183. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194184. {
  194185. int intent;
  194186. png_byte buf[1];
  194187. png_debug(1, "in png_handle_sRGB\n");
  194188. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194189. png_error(png_ptr, "Missing IHDR before sRGB");
  194190. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194191. {
  194192. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194193. png_crc_finish(png_ptr, length);
  194194. return;
  194195. }
  194196. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194197. /* Should be an error, but we can cope with it */
  194198. png_warning(png_ptr, "Out of place sRGB chunk");
  194199. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194200. {
  194201. png_warning(png_ptr, "Duplicate sRGB chunk");
  194202. png_crc_finish(png_ptr, length);
  194203. return;
  194204. }
  194205. if (length != 1)
  194206. {
  194207. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194208. png_crc_finish(png_ptr, length);
  194209. return;
  194210. }
  194211. png_crc_read(png_ptr, buf, 1);
  194212. if (png_crc_finish(png_ptr, 0))
  194213. return;
  194214. intent = buf[0];
  194215. /* check for bad intent */
  194216. if (intent >= PNG_sRGB_INTENT_LAST)
  194217. {
  194218. png_warning(png_ptr, "Unknown sRGB intent");
  194219. return;
  194220. }
  194221. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194222. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194223. {
  194224. png_fixed_point igamma;
  194225. #ifdef PNG_FIXED_POINT_SUPPORTED
  194226. igamma=info_ptr->int_gamma;
  194227. #else
  194228. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194229. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194230. # endif
  194231. #endif
  194232. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194233. {
  194234. png_warning(png_ptr,
  194235. "Ignoring incorrect gAMA value when sRGB is also present");
  194236. #ifndef PNG_NO_CONSOLE_IO
  194237. # ifdef PNG_FIXED_POINT_SUPPORTED
  194238. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194239. # else
  194240. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194241. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194242. # endif
  194243. # endif
  194244. #endif
  194245. }
  194246. }
  194247. #endif /* PNG_READ_gAMA_SUPPORTED */
  194248. #ifdef PNG_READ_cHRM_SUPPORTED
  194249. #ifdef PNG_FIXED_POINT_SUPPORTED
  194250. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194251. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194252. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194253. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194254. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194255. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194256. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194257. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194258. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194259. {
  194260. png_warning(png_ptr,
  194261. "Ignoring incorrect cHRM value when sRGB is also present");
  194262. }
  194263. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194264. #endif /* PNG_READ_cHRM_SUPPORTED */
  194265. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194266. }
  194267. #endif /* PNG_READ_sRGB_SUPPORTED */
  194268. #if defined(PNG_READ_iCCP_SUPPORTED)
  194269. void /* PRIVATE */
  194270. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194271. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194272. {
  194273. png_charp chunkdata;
  194274. png_byte compression_type;
  194275. png_bytep pC;
  194276. png_charp profile;
  194277. png_uint_32 skip = 0;
  194278. png_uint_32 profile_size, profile_length;
  194279. png_size_t slength, prefix_length, data_length;
  194280. png_debug(1, "in png_handle_iCCP\n");
  194281. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194282. png_error(png_ptr, "Missing IHDR before iCCP");
  194283. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194284. {
  194285. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194286. png_crc_finish(png_ptr, length);
  194287. return;
  194288. }
  194289. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194290. /* Should be an error, but we can cope with it */
  194291. png_warning(png_ptr, "Out of place iCCP chunk");
  194292. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194293. {
  194294. png_warning(png_ptr, "Duplicate iCCP chunk");
  194295. png_crc_finish(png_ptr, length);
  194296. return;
  194297. }
  194298. #ifdef PNG_MAX_MALLOC_64K
  194299. if (length > (png_uint_32)65535L)
  194300. {
  194301. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194302. skip = length - (png_uint_32)65535L;
  194303. length = (png_uint_32)65535L;
  194304. }
  194305. #endif
  194306. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194307. slength = (png_size_t)length;
  194308. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194309. if (png_crc_finish(png_ptr, skip))
  194310. {
  194311. png_free(png_ptr, chunkdata);
  194312. return;
  194313. }
  194314. chunkdata[slength] = 0x00;
  194315. for (profile = chunkdata; *profile; profile++)
  194316. /* empty loop to find end of name */ ;
  194317. ++profile;
  194318. /* there should be at least one zero (the compression type byte)
  194319. following the separator, and we should be on it */
  194320. if ( profile >= chunkdata + slength - 1)
  194321. {
  194322. png_free(png_ptr, chunkdata);
  194323. png_warning(png_ptr, "Malformed iCCP chunk");
  194324. return;
  194325. }
  194326. /* compression_type should always be zero */
  194327. compression_type = *profile++;
  194328. if (compression_type)
  194329. {
  194330. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194331. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194332. wrote nonzero) */
  194333. }
  194334. prefix_length = profile - chunkdata;
  194335. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194336. slength, prefix_length, &data_length);
  194337. profile_length = data_length - prefix_length;
  194338. if ( prefix_length > data_length || profile_length < 4)
  194339. {
  194340. png_free(png_ptr, chunkdata);
  194341. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194342. return;
  194343. }
  194344. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194345. pC = (png_bytep)(chunkdata+prefix_length);
  194346. profile_size = ((*(pC ))<<24) |
  194347. ((*(pC+1))<<16) |
  194348. ((*(pC+2))<< 8) |
  194349. ((*(pC+3)) );
  194350. if(profile_size < profile_length)
  194351. profile_length = profile_size;
  194352. if(profile_size > profile_length)
  194353. {
  194354. png_free(png_ptr, chunkdata);
  194355. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194356. return;
  194357. }
  194358. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194359. chunkdata + prefix_length, profile_length);
  194360. png_free(png_ptr, chunkdata);
  194361. }
  194362. #endif /* PNG_READ_iCCP_SUPPORTED */
  194363. #if defined(PNG_READ_sPLT_SUPPORTED)
  194364. void /* PRIVATE */
  194365. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194366. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194367. {
  194368. png_bytep chunkdata;
  194369. png_bytep entry_start;
  194370. png_sPLT_t new_palette;
  194371. #ifdef PNG_NO_POINTER_INDEXING
  194372. png_sPLT_entryp pp;
  194373. #endif
  194374. int data_length, entry_size, i;
  194375. png_uint_32 skip = 0;
  194376. png_size_t slength;
  194377. png_debug(1, "in png_handle_sPLT\n");
  194378. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194379. png_error(png_ptr, "Missing IHDR before sPLT");
  194380. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194381. {
  194382. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194383. png_crc_finish(png_ptr, length);
  194384. return;
  194385. }
  194386. #ifdef PNG_MAX_MALLOC_64K
  194387. if (length > (png_uint_32)65535L)
  194388. {
  194389. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194390. skip = length - (png_uint_32)65535L;
  194391. length = (png_uint_32)65535L;
  194392. }
  194393. #endif
  194394. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194395. slength = (png_size_t)length;
  194396. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194397. if (png_crc_finish(png_ptr, skip))
  194398. {
  194399. png_free(png_ptr, chunkdata);
  194400. return;
  194401. }
  194402. chunkdata[slength] = 0x00;
  194403. for (entry_start = chunkdata; *entry_start; entry_start++)
  194404. /* empty loop to find end of name */ ;
  194405. ++entry_start;
  194406. /* a sample depth should follow the separator, and we should be on it */
  194407. if (entry_start > chunkdata + slength - 2)
  194408. {
  194409. png_free(png_ptr, chunkdata);
  194410. png_warning(png_ptr, "malformed sPLT chunk");
  194411. return;
  194412. }
  194413. new_palette.depth = *entry_start++;
  194414. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194415. data_length = (slength - (entry_start - chunkdata));
  194416. /* integrity-check the data length */
  194417. if (data_length % entry_size)
  194418. {
  194419. png_free(png_ptr, chunkdata);
  194420. png_warning(png_ptr, "sPLT chunk has bad length");
  194421. return;
  194422. }
  194423. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194424. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194425. png_sizeof(png_sPLT_entry)))
  194426. {
  194427. png_warning(png_ptr, "sPLT chunk too long");
  194428. return;
  194429. }
  194430. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194431. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194432. if (new_palette.entries == NULL)
  194433. {
  194434. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194435. return;
  194436. }
  194437. #ifndef PNG_NO_POINTER_INDEXING
  194438. for (i = 0; i < new_palette.nentries; i++)
  194439. {
  194440. png_sPLT_entryp pp = new_palette.entries + i;
  194441. if (new_palette.depth == 8)
  194442. {
  194443. pp->red = *entry_start++;
  194444. pp->green = *entry_start++;
  194445. pp->blue = *entry_start++;
  194446. pp->alpha = *entry_start++;
  194447. }
  194448. else
  194449. {
  194450. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194451. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194452. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194453. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194454. }
  194455. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194456. }
  194457. #else
  194458. pp = new_palette.entries;
  194459. for (i = 0; i < new_palette.nentries; i++)
  194460. {
  194461. if (new_palette.depth == 8)
  194462. {
  194463. pp[i].red = *entry_start++;
  194464. pp[i].green = *entry_start++;
  194465. pp[i].blue = *entry_start++;
  194466. pp[i].alpha = *entry_start++;
  194467. }
  194468. else
  194469. {
  194470. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194471. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194472. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194473. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194474. }
  194475. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194476. }
  194477. #endif
  194478. /* discard all chunk data except the name and stash that */
  194479. new_palette.name = (png_charp)chunkdata;
  194480. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194481. png_free(png_ptr, chunkdata);
  194482. png_free(png_ptr, new_palette.entries);
  194483. }
  194484. #endif /* PNG_READ_sPLT_SUPPORTED */
  194485. #if defined(PNG_READ_tRNS_SUPPORTED)
  194486. void /* PRIVATE */
  194487. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194488. {
  194489. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194490. int bit_mask;
  194491. png_debug(1, "in png_handle_tRNS\n");
  194492. /* For non-indexed color, mask off any bits in the tRNS value that
  194493. * exceed the bit depth. Some creators were writing extra bits there.
  194494. * This is not needed for indexed color. */
  194495. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194496. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194497. png_error(png_ptr, "Missing IHDR before tRNS");
  194498. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194499. {
  194500. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194501. png_crc_finish(png_ptr, length);
  194502. return;
  194503. }
  194504. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194505. {
  194506. png_warning(png_ptr, "Duplicate tRNS chunk");
  194507. png_crc_finish(png_ptr, length);
  194508. return;
  194509. }
  194510. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194511. {
  194512. png_byte buf[2];
  194513. if (length != 2)
  194514. {
  194515. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194516. png_crc_finish(png_ptr, length);
  194517. return;
  194518. }
  194519. png_crc_read(png_ptr, buf, 2);
  194520. png_ptr->num_trans = 1;
  194521. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194522. }
  194523. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194524. {
  194525. png_byte buf[6];
  194526. if (length != 6)
  194527. {
  194528. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194529. png_crc_finish(png_ptr, length);
  194530. return;
  194531. }
  194532. png_crc_read(png_ptr, buf, (png_size_t)length);
  194533. png_ptr->num_trans = 1;
  194534. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194535. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194536. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194537. }
  194538. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194539. {
  194540. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194541. {
  194542. /* Should be an error, but we can cope with it. */
  194543. png_warning(png_ptr, "Missing PLTE before tRNS");
  194544. }
  194545. if (length > (png_uint_32)png_ptr->num_palette ||
  194546. length > PNG_MAX_PALETTE_LENGTH)
  194547. {
  194548. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194549. png_crc_finish(png_ptr, length);
  194550. return;
  194551. }
  194552. if (length == 0)
  194553. {
  194554. png_warning(png_ptr, "Zero length tRNS chunk");
  194555. png_crc_finish(png_ptr, length);
  194556. return;
  194557. }
  194558. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194559. png_ptr->num_trans = (png_uint_16)length;
  194560. }
  194561. else
  194562. {
  194563. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194564. png_crc_finish(png_ptr, length);
  194565. return;
  194566. }
  194567. if (png_crc_finish(png_ptr, 0))
  194568. {
  194569. png_ptr->num_trans = 0;
  194570. return;
  194571. }
  194572. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194573. &(png_ptr->trans_values));
  194574. }
  194575. #endif
  194576. #if defined(PNG_READ_bKGD_SUPPORTED)
  194577. void /* PRIVATE */
  194578. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194579. {
  194580. png_size_t truelen;
  194581. png_byte buf[6];
  194582. png_debug(1, "in png_handle_bKGD\n");
  194583. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194584. png_error(png_ptr, "Missing IHDR before bKGD");
  194585. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194586. {
  194587. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194588. png_crc_finish(png_ptr, length);
  194589. return;
  194590. }
  194591. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194592. !(png_ptr->mode & PNG_HAVE_PLTE))
  194593. {
  194594. png_warning(png_ptr, "Missing PLTE before bKGD");
  194595. png_crc_finish(png_ptr, length);
  194596. return;
  194597. }
  194598. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194599. {
  194600. png_warning(png_ptr, "Duplicate bKGD chunk");
  194601. png_crc_finish(png_ptr, length);
  194602. return;
  194603. }
  194604. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194605. truelen = 1;
  194606. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194607. truelen = 6;
  194608. else
  194609. truelen = 2;
  194610. if (length != truelen)
  194611. {
  194612. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194613. png_crc_finish(png_ptr, length);
  194614. return;
  194615. }
  194616. png_crc_read(png_ptr, buf, truelen);
  194617. if (png_crc_finish(png_ptr, 0))
  194618. return;
  194619. /* We convert the index value into RGB components so that we can allow
  194620. * arbitrary RGB values for background when we have transparency, and
  194621. * so it is easy to determine the RGB values of the background color
  194622. * from the info_ptr struct. */
  194623. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194624. {
  194625. png_ptr->background.index = buf[0];
  194626. if(info_ptr->num_palette)
  194627. {
  194628. if(buf[0] > info_ptr->num_palette)
  194629. {
  194630. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194631. return;
  194632. }
  194633. png_ptr->background.red =
  194634. (png_uint_16)png_ptr->palette[buf[0]].red;
  194635. png_ptr->background.green =
  194636. (png_uint_16)png_ptr->palette[buf[0]].green;
  194637. png_ptr->background.blue =
  194638. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194639. }
  194640. }
  194641. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194642. {
  194643. png_ptr->background.red =
  194644. png_ptr->background.green =
  194645. png_ptr->background.blue =
  194646. png_ptr->background.gray = png_get_uint_16(buf);
  194647. }
  194648. else
  194649. {
  194650. png_ptr->background.red = png_get_uint_16(buf);
  194651. png_ptr->background.green = png_get_uint_16(buf + 2);
  194652. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194653. }
  194654. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194655. }
  194656. #endif
  194657. #if defined(PNG_READ_hIST_SUPPORTED)
  194658. void /* PRIVATE */
  194659. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194660. {
  194661. unsigned int num, i;
  194662. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194663. png_debug(1, "in png_handle_hIST\n");
  194664. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194665. png_error(png_ptr, "Missing IHDR before hIST");
  194666. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194667. {
  194668. png_warning(png_ptr, "Invalid hIST after IDAT");
  194669. png_crc_finish(png_ptr, length);
  194670. return;
  194671. }
  194672. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194673. {
  194674. png_warning(png_ptr, "Missing PLTE before hIST");
  194675. png_crc_finish(png_ptr, length);
  194676. return;
  194677. }
  194678. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194679. {
  194680. png_warning(png_ptr, "Duplicate hIST chunk");
  194681. png_crc_finish(png_ptr, length);
  194682. return;
  194683. }
  194684. num = length / 2 ;
  194685. if (num != (unsigned int) png_ptr->num_palette || num >
  194686. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194687. {
  194688. png_warning(png_ptr, "Incorrect hIST chunk length");
  194689. png_crc_finish(png_ptr, length);
  194690. return;
  194691. }
  194692. for (i = 0; i < num; i++)
  194693. {
  194694. png_byte buf[2];
  194695. png_crc_read(png_ptr, buf, 2);
  194696. readbuf[i] = png_get_uint_16(buf);
  194697. }
  194698. if (png_crc_finish(png_ptr, 0))
  194699. return;
  194700. png_set_hIST(png_ptr, info_ptr, readbuf);
  194701. }
  194702. #endif
  194703. #if defined(PNG_READ_pHYs_SUPPORTED)
  194704. void /* PRIVATE */
  194705. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194706. {
  194707. png_byte buf[9];
  194708. png_uint_32 res_x, res_y;
  194709. int unit_type;
  194710. png_debug(1, "in png_handle_pHYs\n");
  194711. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194712. png_error(png_ptr, "Missing IHDR before pHYs");
  194713. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194714. {
  194715. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194716. png_crc_finish(png_ptr, length);
  194717. return;
  194718. }
  194719. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194720. {
  194721. png_warning(png_ptr, "Duplicate pHYs chunk");
  194722. png_crc_finish(png_ptr, length);
  194723. return;
  194724. }
  194725. if (length != 9)
  194726. {
  194727. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194728. png_crc_finish(png_ptr, length);
  194729. return;
  194730. }
  194731. png_crc_read(png_ptr, buf, 9);
  194732. if (png_crc_finish(png_ptr, 0))
  194733. return;
  194734. res_x = png_get_uint_32(buf);
  194735. res_y = png_get_uint_32(buf + 4);
  194736. unit_type = buf[8];
  194737. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194738. }
  194739. #endif
  194740. #if defined(PNG_READ_oFFs_SUPPORTED)
  194741. void /* PRIVATE */
  194742. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194743. {
  194744. png_byte buf[9];
  194745. png_int_32 offset_x, offset_y;
  194746. int unit_type;
  194747. png_debug(1, "in png_handle_oFFs\n");
  194748. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194749. png_error(png_ptr, "Missing IHDR before oFFs");
  194750. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194751. {
  194752. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194753. png_crc_finish(png_ptr, length);
  194754. return;
  194755. }
  194756. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194757. {
  194758. png_warning(png_ptr, "Duplicate oFFs chunk");
  194759. png_crc_finish(png_ptr, length);
  194760. return;
  194761. }
  194762. if (length != 9)
  194763. {
  194764. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194765. png_crc_finish(png_ptr, length);
  194766. return;
  194767. }
  194768. png_crc_read(png_ptr, buf, 9);
  194769. if (png_crc_finish(png_ptr, 0))
  194770. return;
  194771. offset_x = png_get_int_32(buf);
  194772. offset_y = png_get_int_32(buf + 4);
  194773. unit_type = buf[8];
  194774. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194775. }
  194776. #endif
  194777. #if defined(PNG_READ_pCAL_SUPPORTED)
  194778. /* read the pCAL chunk (described in the PNG Extensions document) */
  194779. void /* PRIVATE */
  194780. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194781. {
  194782. png_charp purpose;
  194783. png_int_32 X0, X1;
  194784. png_byte type, nparams;
  194785. png_charp buf, units, endptr;
  194786. png_charpp params;
  194787. png_size_t slength;
  194788. int i;
  194789. png_debug(1, "in png_handle_pCAL\n");
  194790. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194791. png_error(png_ptr, "Missing IHDR before pCAL");
  194792. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194793. {
  194794. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194795. png_crc_finish(png_ptr, length);
  194796. return;
  194797. }
  194798. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194799. {
  194800. png_warning(png_ptr, "Duplicate pCAL chunk");
  194801. png_crc_finish(png_ptr, length);
  194802. return;
  194803. }
  194804. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194805. length + 1);
  194806. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194807. if (purpose == NULL)
  194808. {
  194809. png_warning(png_ptr, "No memory for pCAL purpose.");
  194810. return;
  194811. }
  194812. slength = (png_size_t)length;
  194813. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194814. if (png_crc_finish(png_ptr, 0))
  194815. {
  194816. png_free(png_ptr, purpose);
  194817. return;
  194818. }
  194819. purpose[slength] = 0x00; /* null terminate the last string */
  194820. png_debug(3, "Finding end of pCAL purpose string\n");
  194821. for (buf = purpose; *buf; buf++)
  194822. /* empty loop */ ;
  194823. endptr = purpose + slength;
  194824. /* We need to have at least 12 bytes after the purpose string
  194825. in order to get the parameter information. */
  194826. if (endptr <= buf + 12)
  194827. {
  194828. png_warning(png_ptr, "Invalid pCAL data");
  194829. png_free(png_ptr, purpose);
  194830. return;
  194831. }
  194832. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  194833. X0 = png_get_int_32((png_bytep)buf+1);
  194834. X1 = png_get_int_32((png_bytep)buf+5);
  194835. type = buf[9];
  194836. nparams = buf[10];
  194837. units = buf + 11;
  194838. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  194839. /* Check that we have the right number of parameters for known
  194840. equation types. */
  194841. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  194842. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  194843. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  194844. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  194845. {
  194846. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  194847. png_free(png_ptr, purpose);
  194848. return;
  194849. }
  194850. else if (type >= PNG_EQUATION_LAST)
  194851. {
  194852. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  194853. }
  194854. for (buf = units; *buf; buf++)
  194855. /* Empty loop to move past the units string. */ ;
  194856. png_debug(3, "Allocating pCAL parameters array\n");
  194857. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  194858. *png_sizeof(png_charp))) ;
  194859. if (params == NULL)
  194860. {
  194861. png_free(png_ptr, purpose);
  194862. png_warning(png_ptr, "No memory for pCAL params.");
  194863. return;
  194864. }
  194865. /* Get pointers to the start of each parameter string. */
  194866. for (i = 0; i < (int)nparams; i++)
  194867. {
  194868. buf++; /* Skip the null string terminator from previous parameter. */
  194869. png_debug1(3, "Reading pCAL parameter %d\n", i);
  194870. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  194871. /* Empty loop to move past each parameter string */ ;
  194872. /* Make sure we haven't run out of data yet */
  194873. if (buf > endptr)
  194874. {
  194875. png_warning(png_ptr, "Invalid pCAL data");
  194876. png_free(png_ptr, purpose);
  194877. png_free(png_ptr, params);
  194878. return;
  194879. }
  194880. }
  194881. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  194882. units, params);
  194883. png_free(png_ptr, purpose);
  194884. png_free(png_ptr, params);
  194885. }
  194886. #endif
  194887. #if defined(PNG_READ_sCAL_SUPPORTED)
  194888. /* read the sCAL chunk */
  194889. void /* PRIVATE */
  194890. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194891. {
  194892. png_charp buffer, ep;
  194893. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194894. double width, height;
  194895. png_charp vp;
  194896. #else
  194897. #ifdef PNG_FIXED_POINT_SUPPORTED
  194898. png_charp swidth, sheight;
  194899. #endif
  194900. #endif
  194901. png_size_t slength;
  194902. png_debug(1, "in png_handle_sCAL\n");
  194903. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194904. png_error(png_ptr, "Missing IHDR before sCAL");
  194905. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194906. {
  194907. png_warning(png_ptr, "Invalid sCAL after IDAT");
  194908. png_crc_finish(png_ptr, length);
  194909. return;
  194910. }
  194911. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  194912. {
  194913. png_warning(png_ptr, "Duplicate sCAL chunk");
  194914. png_crc_finish(png_ptr, length);
  194915. return;
  194916. }
  194917. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  194918. length + 1);
  194919. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194920. if (buffer == NULL)
  194921. {
  194922. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  194923. return;
  194924. }
  194925. slength = (png_size_t)length;
  194926. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  194927. if (png_crc_finish(png_ptr, 0))
  194928. {
  194929. png_free(png_ptr, buffer);
  194930. return;
  194931. }
  194932. buffer[slength] = 0x00; /* null terminate the last string */
  194933. ep = buffer + 1; /* skip unit byte */
  194934. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194935. width = png_strtod(png_ptr, ep, &vp);
  194936. if (*vp)
  194937. {
  194938. png_warning(png_ptr, "malformed width string in sCAL chunk");
  194939. return;
  194940. }
  194941. #else
  194942. #ifdef PNG_FIXED_POINT_SUPPORTED
  194943. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194944. if (swidth == NULL)
  194945. {
  194946. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  194947. return;
  194948. }
  194949. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  194950. #endif
  194951. #endif
  194952. for (ep = buffer; *ep; ep++)
  194953. /* empty loop */ ;
  194954. ep++;
  194955. if (buffer + slength < ep)
  194956. {
  194957. png_warning(png_ptr, "Truncated sCAL chunk");
  194958. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  194959. !defined(PNG_FLOATING_POINT_SUPPORTED)
  194960. png_free(png_ptr, swidth);
  194961. #endif
  194962. png_free(png_ptr, buffer);
  194963. return;
  194964. }
  194965. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194966. height = png_strtod(png_ptr, ep, &vp);
  194967. if (*vp)
  194968. {
  194969. png_warning(png_ptr, "malformed height string in sCAL chunk");
  194970. return;
  194971. }
  194972. #else
  194973. #ifdef PNG_FIXED_POINT_SUPPORTED
  194974. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194975. if (swidth == NULL)
  194976. {
  194977. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  194978. return;
  194979. }
  194980. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  194981. #endif
  194982. #endif
  194983. if (buffer + slength < ep
  194984. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194985. || width <= 0. || height <= 0.
  194986. #endif
  194987. )
  194988. {
  194989. png_warning(png_ptr, "Invalid sCAL data");
  194990. png_free(png_ptr, buffer);
  194991. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194992. png_free(png_ptr, swidth);
  194993. png_free(png_ptr, sheight);
  194994. #endif
  194995. return;
  194996. }
  194997. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194998. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  194999. #else
  195000. #ifdef PNG_FIXED_POINT_SUPPORTED
  195001. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195002. #endif
  195003. #endif
  195004. png_free(png_ptr, buffer);
  195005. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195006. png_free(png_ptr, swidth);
  195007. png_free(png_ptr, sheight);
  195008. #endif
  195009. }
  195010. #endif
  195011. #if defined(PNG_READ_tIME_SUPPORTED)
  195012. void /* PRIVATE */
  195013. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195014. {
  195015. png_byte buf[7];
  195016. png_time mod_time;
  195017. png_debug(1, "in png_handle_tIME\n");
  195018. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195019. png_error(png_ptr, "Out of place tIME chunk");
  195020. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195021. {
  195022. png_warning(png_ptr, "Duplicate tIME chunk");
  195023. png_crc_finish(png_ptr, length);
  195024. return;
  195025. }
  195026. if (png_ptr->mode & PNG_HAVE_IDAT)
  195027. png_ptr->mode |= PNG_AFTER_IDAT;
  195028. if (length != 7)
  195029. {
  195030. png_warning(png_ptr, "Incorrect tIME chunk length");
  195031. png_crc_finish(png_ptr, length);
  195032. return;
  195033. }
  195034. png_crc_read(png_ptr, buf, 7);
  195035. if (png_crc_finish(png_ptr, 0))
  195036. return;
  195037. mod_time.second = buf[6];
  195038. mod_time.minute = buf[5];
  195039. mod_time.hour = buf[4];
  195040. mod_time.day = buf[3];
  195041. mod_time.month = buf[2];
  195042. mod_time.year = png_get_uint_16(buf);
  195043. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195044. }
  195045. #endif
  195046. #if defined(PNG_READ_tEXt_SUPPORTED)
  195047. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195048. void /* PRIVATE */
  195049. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195050. {
  195051. png_textp text_ptr;
  195052. png_charp key;
  195053. png_charp text;
  195054. png_uint_32 skip = 0;
  195055. png_size_t slength;
  195056. int ret;
  195057. png_debug(1, "in png_handle_tEXt\n");
  195058. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195059. png_error(png_ptr, "Missing IHDR before tEXt");
  195060. if (png_ptr->mode & PNG_HAVE_IDAT)
  195061. png_ptr->mode |= PNG_AFTER_IDAT;
  195062. #ifdef PNG_MAX_MALLOC_64K
  195063. if (length > (png_uint_32)65535L)
  195064. {
  195065. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195066. skip = length - (png_uint_32)65535L;
  195067. length = (png_uint_32)65535L;
  195068. }
  195069. #endif
  195070. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195071. if (key == NULL)
  195072. {
  195073. png_warning(png_ptr, "No memory to process text chunk.");
  195074. return;
  195075. }
  195076. slength = (png_size_t)length;
  195077. png_crc_read(png_ptr, (png_bytep)key, slength);
  195078. if (png_crc_finish(png_ptr, skip))
  195079. {
  195080. png_free(png_ptr, key);
  195081. return;
  195082. }
  195083. key[slength] = 0x00;
  195084. for (text = key; *text; text++)
  195085. /* empty loop to find end of key */ ;
  195086. if (text != key + slength)
  195087. text++;
  195088. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195089. (png_uint_32)png_sizeof(png_text));
  195090. if (text_ptr == NULL)
  195091. {
  195092. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195093. png_free(png_ptr, key);
  195094. return;
  195095. }
  195096. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195097. text_ptr->key = key;
  195098. #ifdef PNG_iTXt_SUPPORTED
  195099. text_ptr->lang = NULL;
  195100. text_ptr->lang_key = NULL;
  195101. text_ptr->itxt_length = 0;
  195102. #endif
  195103. text_ptr->text = text;
  195104. text_ptr->text_length = png_strlen(text);
  195105. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195106. png_free(png_ptr, key);
  195107. png_free(png_ptr, text_ptr);
  195108. if (ret)
  195109. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195110. }
  195111. #endif
  195112. #if defined(PNG_READ_zTXt_SUPPORTED)
  195113. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195114. void /* PRIVATE */
  195115. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195116. {
  195117. png_textp text_ptr;
  195118. png_charp chunkdata;
  195119. png_charp text;
  195120. int comp_type;
  195121. int ret;
  195122. png_size_t slength, prefix_len, data_len;
  195123. png_debug(1, "in png_handle_zTXt\n");
  195124. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195125. png_error(png_ptr, "Missing IHDR before zTXt");
  195126. if (png_ptr->mode & PNG_HAVE_IDAT)
  195127. png_ptr->mode |= PNG_AFTER_IDAT;
  195128. #ifdef PNG_MAX_MALLOC_64K
  195129. /* We will no doubt have problems with chunks even half this size, but
  195130. there is no hard and fast rule to tell us where to stop. */
  195131. if (length > (png_uint_32)65535L)
  195132. {
  195133. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195134. png_crc_finish(png_ptr, length);
  195135. return;
  195136. }
  195137. #endif
  195138. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195139. if (chunkdata == NULL)
  195140. {
  195141. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195142. return;
  195143. }
  195144. slength = (png_size_t)length;
  195145. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195146. if (png_crc_finish(png_ptr, 0))
  195147. {
  195148. png_free(png_ptr, chunkdata);
  195149. return;
  195150. }
  195151. chunkdata[slength] = 0x00;
  195152. for (text = chunkdata; *text; text++)
  195153. /* empty loop */ ;
  195154. /* zTXt must have some text after the chunkdataword */
  195155. if (text >= chunkdata + slength - 2)
  195156. {
  195157. png_warning(png_ptr, "Truncated zTXt chunk");
  195158. png_free(png_ptr, chunkdata);
  195159. return;
  195160. }
  195161. else
  195162. {
  195163. comp_type = *(++text);
  195164. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195165. {
  195166. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195167. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195168. }
  195169. text++; /* skip the compression_method byte */
  195170. }
  195171. prefix_len = text - chunkdata;
  195172. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195173. (png_size_t)length, prefix_len, &data_len);
  195174. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195175. (png_uint_32)png_sizeof(png_text));
  195176. if (text_ptr == NULL)
  195177. {
  195178. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195179. png_free(png_ptr, chunkdata);
  195180. return;
  195181. }
  195182. text_ptr->compression = comp_type;
  195183. text_ptr->key = chunkdata;
  195184. #ifdef PNG_iTXt_SUPPORTED
  195185. text_ptr->lang = NULL;
  195186. text_ptr->lang_key = NULL;
  195187. text_ptr->itxt_length = 0;
  195188. #endif
  195189. text_ptr->text = chunkdata + prefix_len;
  195190. text_ptr->text_length = data_len;
  195191. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195192. png_free(png_ptr, text_ptr);
  195193. png_free(png_ptr, chunkdata);
  195194. if (ret)
  195195. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195196. }
  195197. #endif
  195198. #if defined(PNG_READ_iTXt_SUPPORTED)
  195199. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195200. void /* PRIVATE */
  195201. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195202. {
  195203. png_textp text_ptr;
  195204. png_charp chunkdata;
  195205. png_charp key, lang, text, lang_key;
  195206. int comp_flag;
  195207. int comp_type = 0;
  195208. int ret;
  195209. png_size_t slength, prefix_len, data_len;
  195210. png_debug(1, "in png_handle_iTXt\n");
  195211. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195212. png_error(png_ptr, "Missing IHDR before iTXt");
  195213. if (png_ptr->mode & PNG_HAVE_IDAT)
  195214. png_ptr->mode |= PNG_AFTER_IDAT;
  195215. #ifdef PNG_MAX_MALLOC_64K
  195216. /* We will no doubt have problems with chunks even half this size, but
  195217. there is no hard and fast rule to tell us where to stop. */
  195218. if (length > (png_uint_32)65535L)
  195219. {
  195220. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195221. png_crc_finish(png_ptr, length);
  195222. return;
  195223. }
  195224. #endif
  195225. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195226. if (chunkdata == NULL)
  195227. {
  195228. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195229. return;
  195230. }
  195231. slength = (png_size_t)length;
  195232. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195233. if (png_crc_finish(png_ptr, 0))
  195234. {
  195235. png_free(png_ptr, chunkdata);
  195236. return;
  195237. }
  195238. chunkdata[slength] = 0x00;
  195239. for (lang = chunkdata; *lang; lang++)
  195240. /* empty loop */ ;
  195241. lang++; /* skip NUL separator */
  195242. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195243. translated keyword (possibly empty), and possibly some text after the
  195244. keyword */
  195245. if (lang >= chunkdata + slength - 3)
  195246. {
  195247. png_warning(png_ptr, "Truncated iTXt chunk");
  195248. png_free(png_ptr, chunkdata);
  195249. return;
  195250. }
  195251. else
  195252. {
  195253. comp_flag = *lang++;
  195254. comp_type = *lang++;
  195255. }
  195256. for (lang_key = lang; *lang_key; lang_key++)
  195257. /* empty loop */ ;
  195258. lang_key++; /* skip NUL separator */
  195259. if (lang_key >= chunkdata + slength)
  195260. {
  195261. png_warning(png_ptr, "Truncated iTXt chunk");
  195262. png_free(png_ptr, chunkdata);
  195263. return;
  195264. }
  195265. for (text = lang_key; *text; text++)
  195266. /* empty loop */ ;
  195267. text++; /* skip NUL separator */
  195268. if (text >= chunkdata + slength)
  195269. {
  195270. png_warning(png_ptr, "Malformed iTXt chunk");
  195271. png_free(png_ptr, chunkdata);
  195272. return;
  195273. }
  195274. prefix_len = text - chunkdata;
  195275. key=chunkdata;
  195276. if (comp_flag)
  195277. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195278. (size_t)length, prefix_len, &data_len);
  195279. else
  195280. data_len=png_strlen(chunkdata + prefix_len);
  195281. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195282. (png_uint_32)png_sizeof(png_text));
  195283. if (text_ptr == NULL)
  195284. {
  195285. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195286. png_free(png_ptr, chunkdata);
  195287. return;
  195288. }
  195289. text_ptr->compression = (int)comp_flag + 1;
  195290. text_ptr->lang_key = chunkdata+(lang_key-key);
  195291. text_ptr->lang = chunkdata+(lang-key);
  195292. text_ptr->itxt_length = data_len;
  195293. text_ptr->text_length = 0;
  195294. text_ptr->key = chunkdata;
  195295. text_ptr->text = chunkdata + prefix_len;
  195296. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195297. png_free(png_ptr, text_ptr);
  195298. png_free(png_ptr, chunkdata);
  195299. if (ret)
  195300. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195301. }
  195302. #endif
  195303. /* This function is called when we haven't found a handler for a
  195304. chunk. If there isn't a problem with the chunk itself (ie bad
  195305. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195306. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195307. case it will be saved away to be written out later. */
  195308. void /* PRIVATE */
  195309. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195310. {
  195311. png_uint_32 skip = 0;
  195312. png_debug(1, "in png_handle_unknown\n");
  195313. if (png_ptr->mode & PNG_HAVE_IDAT)
  195314. {
  195315. #ifdef PNG_USE_LOCAL_ARRAYS
  195316. PNG_CONST PNG_IDAT;
  195317. #endif
  195318. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195319. png_ptr->mode |= PNG_AFTER_IDAT;
  195320. }
  195321. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195322. if (!(png_ptr->chunk_name[0] & 0x20))
  195323. {
  195324. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195325. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195326. PNG_HANDLE_CHUNK_ALWAYS
  195327. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195328. && png_ptr->read_user_chunk_fn == NULL
  195329. #endif
  195330. )
  195331. #endif
  195332. png_chunk_error(png_ptr, "unknown critical chunk");
  195333. }
  195334. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195335. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195336. (png_ptr->read_user_chunk_fn != NULL))
  195337. {
  195338. #ifdef PNG_MAX_MALLOC_64K
  195339. if (length > (png_uint_32)65535L)
  195340. {
  195341. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195342. skip = length - (png_uint_32)65535L;
  195343. length = (png_uint_32)65535L;
  195344. }
  195345. #endif
  195346. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195347. (png_charp)png_ptr->chunk_name, 5);
  195348. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195349. png_ptr->unknown_chunk.size = (png_size_t)length;
  195350. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195351. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195352. if(png_ptr->read_user_chunk_fn != NULL)
  195353. {
  195354. /* callback to user unknown chunk handler */
  195355. int ret;
  195356. ret = (*(png_ptr->read_user_chunk_fn))
  195357. (png_ptr, &png_ptr->unknown_chunk);
  195358. if (ret < 0)
  195359. png_chunk_error(png_ptr, "error in user chunk");
  195360. if (ret == 0)
  195361. {
  195362. if (!(png_ptr->chunk_name[0] & 0x20))
  195363. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195364. PNG_HANDLE_CHUNK_ALWAYS)
  195365. png_chunk_error(png_ptr, "unknown critical chunk");
  195366. png_set_unknown_chunks(png_ptr, info_ptr,
  195367. &png_ptr->unknown_chunk, 1);
  195368. }
  195369. }
  195370. #else
  195371. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195372. #endif
  195373. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195374. png_ptr->unknown_chunk.data = NULL;
  195375. }
  195376. else
  195377. #endif
  195378. skip = length;
  195379. png_crc_finish(png_ptr, skip);
  195380. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195381. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195382. #endif
  195383. }
  195384. /* This function is called to verify that a chunk name is valid.
  195385. This function can't have the "critical chunk check" incorporated
  195386. into it, since in the future we will need to be able to call user
  195387. functions to handle unknown critical chunks after we check that
  195388. the chunk name itself is valid. */
  195389. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195390. void /* PRIVATE */
  195391. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195392. {
  195393. png_debug(1, "in png_check_chunk_name\n");
  195394. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195395. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195396. {
  195397. png_chunk_error(png_ptr, "invalid chunk type");
  195398. }
  195399. }
  195400. /* Combines the row recently read in with the existing pixels in the
  195401. row. This routine takes care of alpha and transparency if requested.
  195402. This routine also handles the two methods of progressive display
  195403. of interlaced images, depending on the mask value.
  195404. The mask value describes which pixels are to be combined with
  195405. the row. The pattern always repeats every 8 pixels, so just 8
  195406. bits are needed. A one indicates the pixel is to be combined,
  195407. a zero indicates the pixel is to be skipped. This is in addition
  195408. to any alpha or transparency value associated with the pixel. If
  195409. you want all pixels to be combined, pass 0xff (255) in mask. */
  195410. void /* PRIVATE */
  195411. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195412. {
  195413. png_debug(1,"in png_combine_row\n");
  195414. if (mask == 0xff)
  195415. {
  195416. png_memcpy(row, png_ptr->row_buf + 1,
  195417. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195418. }
  195419. else
  195420. {
  195421. switch (png_ptr->row_info.pixel_depth)
  195422. {
  195423. case 1:
  195424. {
  195425. png_bytep sp = png_ptr->row_buf + 1;
  195426. png_bytep dp = row;
  195427. int s_inc, s_start, s_end;
  195428. int m = 0x80;
  195429. int shift;
  195430. png_uint_32 i;
  195431. png_uint_32 row_width = png_ptr->width;
  195432. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195433. if (png_ptr->transformations & PNG_PACKSWAP)
  195434. {
  195435. s_start = 0;
  195436. s_end = 7;
  195437. s_inc = 1;
  195438. }
  195439. else
  195440. #endif
  195441. {
  195442. s_start = 7;
  195443. s_end = 0;
  195444. s_inc = -1;
  195445. }
  195446. shift = s_start;
  195447. for (i = 0; i < row_width; i++)
  195448. {
  195449. if (m & mask)
  195450. {
  195451. int value;
  195452. value = (*sp >> shift) & 0x01;
  195453. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195454. *dp |= (png_byte)(value << shift);
  195455. }
  195456. if (shift == s_end)
  195457. {
  195458. shift = s_start;
  195459. sp++;
  195460. dp++;
  195461. }
  195462. else
  195463. shift += s_inc;
  195464. if (m == 1)
  195465. m = 0x80;
  195466. else
  195467. m >>= 1;
  195468. }
  195469. break;
  195470. }
  195471. case 2:
  195472. {
  195473. png_bytep sp = png_ptr->row_buf + 1;
  195474. png_bytep dp = row;
  195475. int s_start, s_end, s_inc;
  195476. int m = 0x80;
  195477. int shift;
  195478. png_uint_32 i;
  195479. png_uint_32 row_width = png_ptr->width;
  195480. int value;
  195481. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195482. if (png_ptr->transformations & PNG_PACKSWAP)
  195483. {
  195484. s_start = 0;
  195485. s_end = 6;
  195486. s_inc = 2;
  195487. }
  195488. else
  195489. #endif
  195490. {
  195491. s_start = 6;
  195492. s_end = 0;
  195493. s_inc = -2;
  195494. }
  195495. shift = s_start;
  195496. for (i = 0; i < row_width; i++)
  195497. {
  195498. if (m & mask)
  195499. {
  195500. value = (*sp >> shift) & 0x03;
  195501. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195502. *dp |= (png_byte)(value << shift);
  195503. }
  195504. if (shift == s_end)
  195505. {
  195506. shift = s_start;
  195507. sp++;
  195508. dp++;
  195509. }
  195510. else
  195511. shift += s_inc;
  195512. if (m == 1)
  195513. m = 0x80;
  195514. else
  195515. m >>= 1;
  195516. }
  195517. break;
  195518. }
  195519. case 4:
  195520. {
  195521. png_bytep sp = png_ptr->row_buf + 1;
  195522. png_bytep dp = row;
  195523. int s_start, s_end, s_inc;
  195524. int m = 0x80;
  195525. int shift;
  195526. png_uint_32 i;
  195527. png_uint_32 row_width = png_ptr->width;
  195528. int value;
  195529. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195530. if (png_ptr->transformations & PNG_PACKSWAP)
  195531. {
  195532. s_start = 0;
  195533. s_end = 4;
  195534. s_inc = 4;
  195535. }
  195536. else
  195537. #endif
  195538. {
  195539. s_start = 4;
  195540. s_end = 0;
  195541. s_inc = -4;
  195542. }
  195543. shift = s_start;
  195544. for (i = 0; i < row_width; i++)
  195545. {
  195546. if (m & mask)
  195547. {
  195548. value = (*sp >> shift) & 0xf;
  195549. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195550. *dp |= (png_byte)(value << shift);
  195551. }
  195552. if (shift == s_end)
  195553. {
  195554. shift = s_start;
  195555. sp++;
  195556. dp++;
  195557. }
  195558. else
  195559. shift += s_inc;
  195560. if (m == 1)
  195561. m = 0x80;
  195562. else
  195563. m >>= 1;
  195564. }
  195565. break;
  195566. }
  195567. default:
  195568. {
  195569. png_bytep sp = png_ptr->row_buf + 1;
  195570. png_bytep dp = row;
  195571. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195572. png_uint_32 i;
  195573. png_uint_32 row_width = png_ptr->width;
  195574. png_byte m = 0x80;
  195575. for (i = 0; i < row_width; i++)
  195576. {
  195577. if (m & mask)
  195578. {
  195579. png_memcpy(dp, sp, pixel_bytes);
  195580. }
  195581. sp += pixel_bytes;
  195582. dp += pixel_bytes;
  195583. if (m == 1)
  195584. m = 0x80;
  195585. else
  195586. m >>= 1;
  195587. }
  195588. break;
  195589. }
  195590. }
  195591. }
  195592. }
  195593. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195594. /* OLD pre-1.0.9 interface:
  195595. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195596. png_uint_32 transformations)
  195597. */
  195598. void /* PRIVATE */
  195599. png_do_read_interlace(png_structp png_ptr)
  195600. {
  195601. png_row_infop row_info = &(png_ptr->row_info);
  195602. png_bytep row = png_ptr->row_buf + 1;
  195603. int pass = png_ptr->pass;
  195604. png_uint_32 transformations = png_ptr->transformations;
  195605. #ifdef PNG_USE_LOCAL_ARRAYS
  195606. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195607. /* offset to next interlace block */
  195608. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195609. #endif
  195610. png_debug(1,"in png_do_read_interlace\n");
  195611. if (row != NULL && row_info != NULL)
  195612. {
  195613. png_uint_32 final_width;
  195614. final_width = row_info->width * png_pass_inc[pass];
  195615. switch (row_info->pixel_depth)
  195616. {
  195617. case 1:
  195618. {
  195619. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195620. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195621. int sshift, dshift;
  195622. int s_start, s_end, s_inc;
  195623. int jstop = png_pass_inc[pass];
  195624. png_byte v;
  195625. png_uint_32 i;
  195626. int j;
  195627. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195628. if (transformations & PNG_PACKSWAP)
  195629. {
  195630. sshift = (int)((row_info->width + 7) & 0x07);
  195631. dshift = (int)((final_width + 7) & 0x07);
  195632. s_start = 7;
  195633. s_end = 0;
  195634. s_inc = -1;
  195635. }
  195636. else
  195637. #endif
  195638. {
  195639. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195640. dshift = 7 - (int)((final_width + 7) & 0x07);
  195641. s_start = 0;
  195642. s_end = 7;
  195643. s_inc = 1;
  195644. }
  195645. for (i = 0; i < row_info->width; i++)
  195646. {
  195647. v = (png_byte)((*sp >> sshift) & 0x01);
  195648. for (j = 0; j < jstop; j++)
  195649. {
  195650. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195651. *dp |= (png_byte)(v << dshift);
  195652. if (dshift == s_end)
  195653. {
  195654. dshift = s_start;
  195655. dp--;
  195656. }
  195657. else
  195658. dshift += s_inc;
  195659. }
  195660. if (sshift == s_end)
  195661. {
  195662. sshift = s_start;
  195663. sp--;
  195664. }
  195665. else
  195666. sshift += s_inc;
  195667. }
  195668. break;
  195669. }
  195670. case 2:
  195671. {
  195672. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195673. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195674. int sshift, dshift;
  195675. int s_start, s_end, s_inc;
  195676. int jstop = png_pass_inc[pass];
  195677. png_uint_32 i;
  195678. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195679. if (transformations & PNG_PACKSWAP)
  195680. {
  195681. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195682. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195683. s_start = 6;
  195684. s_end = 0;
  195685. s_inc = -2;
  195686. }
  195687. else
  195688. #endif
  195689. {
  195690. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195691. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195692. s_start = 0;
  195693. s_end = 6;
  195694. s_inc = 2;
  195695. }
  195696. for (i = 0; i < row_info->width; i++)
  195697. {
  195698. png_byte v;
  195699. int j;
  195700. v = (png_byte)((*sp >> sshift) & 0x03);
  195701. for (j = 0; j < jstop; j++)
  195702. {
  195703. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195704. *dp |= (png_byte)(v << dshift);
  195705. if (dshift == s_end)
  195706. {
  195707. dshift = s_start;
  195708. dp--;
  195709. }
  195710. else
  195711. dshift += s_inc;
  195712. }
  195713. if (sshift == s_end)
  195714. {
  195715. sshift = s_start;
  195716. sp--;
  195717. }
  195718. else
  195719. sshift += s_inc;
  195720. }
  195721. break;
  195722. }
  195723. case 4:
  195724. {
  195725. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195726. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195727. int sshift, dshift;
  195728. int s_start, s_end, s_inc;
  195729. png_uint_32 i;
  195730. int jstop = png_pass_inc[pass];
  195731. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195732. if (transformations & PNG_PACKSWAP)
  195733. {
  195734. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195735. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195736. s_start = 4;
  195737. s_end = 0;
  195738. s_inc = -4;
  195739. }
  195740. else
  195741. #endif
  195742. {
  195743. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195744. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195745. s_start = 0;
  195746. s_end = 4;
  195747. s_inc = 4;
  195748. }
  195749. for (i = 0; i < row_info->width; i++)
  195750. {
  195751. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195752. int j;
  195753. for (j = 0; j < jstop; j++)
  195754. {
  195755. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195756. *dp |= (png_byte)(v << dshift);
  195757. if (dshift == s_end)
  195758. {
  195759. dshift = s_start;
  195760. dp--;
  195761. }
  195762. else
  195763. dshift += s_inc;
  195764. }
  195765. if (sshift == s_end)
  195766. {
  195767. sshift = s_start;
  195768. sp--;
  195769. }
  195770. else
  195771. sshift += s_inc;
  195772. }
  195773. break;
  195774. }
  195775. default:
  195776. {
  195777. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195778. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195779. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195780. int jstop = png_pass_inc[pass];
  195781. png_uint_32 i;
  195782. for (i = 0; i < row_info->width; i++)
  195783. {
  195784. png_byte v[8];
  195785. int j;
  195786. png_memcpy(v, sp, pixel_bytes);
  195787. for (j = 0; j < jstop; j++)
  195788. {
  195789. png_memcpy(dp, v, pixel_bytes);
  195790. dp -= pixel_bytes;
  195791. }
  195792. sp -= pixel_bytes;
  195793. }
  195794. break;
  195795. }
  195796. }
  195797. row_info->width = final_width;
  195798. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195799. }
  195800. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195801. transformations = transformations; /* silence compiler warning */
  195802. #endif
  195803. }
  195804. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195805. void /* PRIVATE */
  195806. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195807. png_bytep prev_row, int filter)
  195808. {
  195809. png_debug(1, "in png_read_filter_row\n");
  195810. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195811. switch (filter)
  195812. {
  195813. case PNG_FILTER_VALUE_NONE:
  195814. break;
  195815. case PNG_FILTER_VALUE_SUB:
  195816. {
  195817. png_uint_32 i;
  195818. png_uint_32 istop = row_info->rowbytes;
  195819. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195820. png_bytep rp = row + bpp;
  195821. png_bytep lp = row;
  195822. for (i = bpp; i < istop; i++)
  195823. {
  195824. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  195825. rp++;
  195826. }
  195827. break;
  195828. }
  195829. case PNG_FILTER_VALUE_UP:
  195830. {
  195831. png_uint_32 i;
  195832. png_uint_32 istop = row_info->rowbytes;
  195833. png_bytep rp = row;
  195834. png_bytep pp = prev_row;
  195835. for (i = 0; i < istop; i++)
  195836. {
  195837. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195838. rp++;
  195839. }
  195840. break;
  195841. }
  195842. case PNG_FILTER_VALUE_AVG:
  195843. {
  195844. png_uint_32 i;
  195845. png_bytep rp = row;
  195846. png_bytep pp = prev_row;
  195847. png_bytep lp = row;
  195848. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195849. png_uint_32 istop = row_info->rowbytes - bpp;
  195850. for (i = 0; i < bpp; i++)
  195851. {
  195852. *rp = (png_byte)(((int)(*rp) +
  195853. ((int)(*pp++) / 2 )) & 0xff);
  195854. rp++;
  195855. }
  195856. for (i = 0; i < istop; i++)
  195857. {
  195858. *rp = (png_byte)(((int)(*rp) +
  195859. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  195860. rp++;
  195861. }
  195862. break;
  195863. }
  195864. case PNG_FILTER_VALUE_PAETH:
  195865. {
  195866. png_uint_32 i;
  195867. png_bytep rp = row;
  195868. png_bytep pp = prev_row;
  195869. png_bytep lp = row;
  195870. png_bytep cp = prev_row;
  195871. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195872. png_uint_32 istop=row_info->rowbytes - bpp;
  195873. for (i = 0; i < bpp; i++)
  195874. {
  195875. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195876. rp++;
  195877. }
  195878. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  195879. {
  195880. int a, b, c, pa, pb, pc, p;
  195881. a = *lp++;
  195882. b = *pp++;
  195883. c = *cp++;
  195884. p = b - c;
  195885. pc = a - c;
  195886. #ifdef PNG_USE_ABS
  195887. pa = abs(p);
  195888. pb = abs(pc);
  195889. pc = abs(p + pc);
  195890. #else
  195891. pa = p < 0 ? -p : p;
  195892. pb = pc < 0 ? -pc : pc;
  195893. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  195894. #endif
  195895. /*
  195896. if (pa <= pb && pa <= pc)
  195897. p = a;
  195898. else if (pb <= pc)
  195899. p = b;
  195900. else
  195901. p = c;
  195902. */
  195903. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  195904. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  195905. rp++;
  195906. }
  195907. break;
  195908. }
  195909. default:
  195910. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  195911. *row=0;
  195912. break;
  195913. }
  195914. }
  195915. void /* PRIVATE */
  195916. png_read_finish_row(png_structp png_ptr)
  195917. {
  195918. #ifdef PNG_USE_LOCAL_ARRAYS
  195919. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195920. /* start of interlace block */
  195921. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195922. /* offset to next interlace block */
  195923. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195924. /* start of interlace block in the y direction */
  195925. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195926. /* offset to next interlace block in the y direction */
  195927. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195928. #endif
  195929. png_debug(1, "in png_read_finish_row\n");
  195930. png_ptr->row_number++;
  195931. if (png_ptr->row_number < png_ptr->num_rows)
  195932. return;
  195933. if (png_ptr->interlaced)
  195934. {
  195935. png_ptr->row_number = 0;
  195936. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  195937. png_ptr->rowbytes + 1);
  195938. do
  195939. {
  195940. png_ptr->pass++;
  195941. if (png_ptr->pass >= 7)
  195942. break;
  195943. png_ptr->iwidth = (png_ptr->width +
  195944. png_pass_inc[png_ptr->pass] - 1 -
  195945. png_pass_start[png_ptr->pass]) /
  195946. png_pass_inc[png_ptr->pass];
  195947. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  195948. png_ptr->iwidth) + 1;
  195949. if (!(png_ptr->transformations & PNG_INTERLACE))
  195950. {
  195951. png_ptr->num_rows = (png_ptr->height +
  195952. png_pass_yinc[png_ptr->pass] - 1 -
  195953. png_pass_ystart[png_ptr->pass]) /
  195954. png_pass_yinc[png_ptr->pass];
  195955. if (!(png_ptr->num_rows))
  195956. continue;
  195957. }
  195958. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  195959. break;
  195960. } while (png_ptr->iwidth == 0);
  195961. if (png_ptr->pass < 7)
  195962. return;
  195963. }
  195964. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  195965. {
  195966. #ifdef PNG_USE_LOCAL_ARRAYS
  195967. PNG_CONST PNG_IDAT;
  195968. #endif
  195969. char extra;
  195970. int ret;
  195971. png_ptr->zstream.next_out = (Bytef *)&extra;
  195972. png_ptr->zstream.avail_out = (uInt)1;
  195973. for(;;)
  195974. {
  195975. if (!(png_ptr->zstream.avail_in))
  195976. {
  195977. while (!png_ptr->idat_size)
  195978. {
  195979. png_byte chunk_length[4];
  195980. png_crc_finish(png_ptr, 0);
  195981. png_read_data(png_ptr, chunk_length, 4);
  195982. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  195983. png_reset_crc(png_ptr);
  195984. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  195985. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  195986. png_error(png_ptr, "Not enough image data");
  195987. }
  195988. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  195989. png_ptr->zstream.next_in = png_ptr->zbuf;
  195990. if (png_ptr->zbuf_size > png_ptr->idat_size)
  195991. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  195992. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  195993. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  195994. }
  195995. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  195996. if (ret == Z_STREAM_END)
  195997. {
  195998. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  195999. png_ptr->idat_size)
  196000. png_warning(png_ptr, "Extra compressed data");
  196001. png_ptr->mode |= PNG_AFTER_IDAT;
  196002. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196003. break;
  196004. }
  196005. if (ret != Z_OK)
  196006. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196007. "Decompression Error");
  196008. if (!(png_ptr->zstream.avail_out))
  196009. {
  196010. png_warning(png_ptr, "Extra compressed data.");
  196011. png_ptr->mode |= PNG_AFTER_IDAT;
  196012. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196013. break;
  196014. }
  196015. }
  196016. png_ptr->zstream.avail_out = 0;
  196017. }
  196018. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196019. png_warning(png_ptr, "Extra compression data");
  196020. inflateReset(&png_ptr->zstream);
  196021. png_ptr->mode |= PNG_AFTER_IDAT;
  196022. }
  196023. void /* PRIVATE */
  196024. png_read_start_row(png_structp png_ptr)
  196025. {
  196026. #ifdef PNG_USE_LOCAL_ARRAYS
  196027. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196028. /* start of interlace block */
  196029. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196030. /* offset to next interlace block */
  196031. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196032. /* start of interlace block in the y direction */
  196033. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196034. /* offset to next interlace block in the y direction */
  196035. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196036. #endif
  196037. int max_pixel_depth;
  196038. png_uint_32 row_bytes;
  196039. png_debug(1, "in png_read_start_row\n");
  196040. png_ptr->zstream.avail_in = 0;
  196041. png_init_read_transformations(png_ptr);
  196042. if (png_ptr->interlaced)
  196043. {
  196044. if (!(png_ptr->transformations & PNG_INTERLACE))
  196045. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196046. png_pass_ystart[0]) / png_pass_yinc[0];
  196047. else
  196048. png_ptr->num_rows = png_ptr->height;
  196049. png_ptr->iwidth = (png_ptr->width +
  196050. png_pass_inc[png_ptr->pass] - 1 -
  196051. png_pass_start[png_ptr->pass]) /
  196052. png_pass_inc[png_ptr->pass];
  196053. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196054. png_ptr->irowbytes = (png_size_t)row_bytes;
  196055. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196056. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196057. }
  196058. else
  196059. {
  196060. png_ptr->num_rows = png_ptr->height;
  196061. png_ptr->iwidth = png_ptr->width;
  196062. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196063. }
  196064. max_pixel_depth = png_ptr->pixel_depth;
  196065. #if defined(PNG_READ_PACK_SUPPORTED)
  196066. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196067. max_pixel_depth = 8;
  196068. #endif
  196069. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196070. if (png_ptr->transformations & PNG_EXPAND)
  196071. {
  196072. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196073. {
  196074. if (png_ptr->num_trans)
  196075. max_pixel_depth = 32;
  196076. else
  196077. max_pixel_depth = 24;
  196078. }
  196079. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196080. {
  196081. if (max_pixel_depth < 8)
  196082. max_pixel_depth = 8;
  196083. if (png_ptr->num_trans)
  196084. max_pixel_depth *= 2;
  196085. }
  196086. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196087. {
  196088. if (png_ptr->num_trans)
  196089. {
  196090. max_pixel_depth *= 4;
  196091. max_pixel_depth /= 3;
  196092. }
  196093. }
  196094. }
  196095. #endif
  196096. #if defined(PNG_READ_FILLER_SUPPORTED)
  196097. if (png_ptr->transformations & (PNG_FILLER))
  196098. {
  196099. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196100. max_pixel_depth = 32;
  196101. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196102. {
  196103. if (max_pixel_depth <= 8)
  196104. max_pixel_depth = 16;
  196105. else
  196106. max_pixel_depth = 32;
  196107. }
  196108. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196109. {
  196110. if (max_pixel_depth <= 32)
  196111. max_pixel_depth = 32;
  196112. else
  196113. max_pixel_depth = 64;
  196114. }
  196115. }
  196116. #endif
  196117. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196118. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196119. {
  196120. if (
  196121. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196122. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196123. #endif
  196124. #if defined(PNG_READ_FILLER_SUPPORTED)
  196125. (png_ptr->transformations & (PNG_FILLER)) ||
  196126. #endif
  196127. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196128. {
  196129. if (max_pixel_depth <= 16)
  196130. max_pixel_depth = 32;
  196131. else
  196132. max_pixel_depth = 64;
  196133. }
  196134. else
  196135. {
  196136. if (max_pixel_depth <= 8)
  196137. {
  196138. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196139. max_pixel_depth = 32;
  196140. else
  196141. max_pixel_depth = 24;
  196142. }
  196143. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196144. max_pixel_depth = 64;
  196145. else
  196146. max_pixel_depth = 48;
  196147. }
  196148. }
  196149. #endif
  196150. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196151. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196152. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196153. {
  196154. int user_pixel_depth=png_ptr->user_transform_depth*
  196155. png_ptr->user_transform_channels;
  196156. if(user_pixel_depth > max_pixel_depth)
  196157. max_pixel_depth=user_pixel_depth;
  196158. }
  196159. #endif
  196160. /* align the width on the next larger 8 pixels. Mainly used
  196161. for interlacing */
  196162. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196163. /* calculate the maximum bytes needed, adding a byte and a pixel
  196164. for safety's sake */
  196165. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196166. 1 + ((max_pixel_depth + 7) >> 3);
  196167. #ifdef PNG_MAX_MALLOC_64K
  196168. if (row_bytes > (png_uint_32)65536L)
  196169. png_error(png_ptr, "This image requires a row greater than 64KB");
  196170. #endif
  196171. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196172. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196173. #ifdef PNG_MAX_MALLOC_64K
  196174. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196175. png_error(png_ptr, "This image requires a row greater than 64KB");
  196176. #endif
  196177. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196178. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196179. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196180. png_ptr->rowbytes + 1));
  196181. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196182. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196183. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196184. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196185. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196186. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196187. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196188. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196189. }
  196190. #endif /* PNG_READ_SUPPORTED */
  196191. /*** End of inlined file: pngrutil.c ***/
  196192. /*** Start of inlined file: pngset.c ***/
  196193. /* pngset.c - storage of image information into info struct
  196194. *
  196195. * Last changed in libpng 1.2.21 [October 4, 2007]
  196196. * For conditions of distribution and use, see copyright notice in png.h
  196197. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196198. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196199. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196200. *
  196201. * The functions here are used during reads to store data from the file
  196202. * into the info struct, and during writes to store application data
  196203. * into the info struct for writing into the file. This abstracts the
  196204. * info struct and allows us to change the structure in the future.
  196205. */
  196206. #define PNG_INTERNAL
  196207. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196208. #if defined(PNG_bKGD_SUPPORTED)
  196209. void PNGAPI
  196210. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196211. {
  196212. png_debug1(1, "in %s storage function\n", "bKGD");
  196213. if (png_ptr == NULL || info_ptr == NULL)
  196214. return;
  196215. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196216. info_ptr->valid |= PNG_INFO_bKGD;
  196217. }
  196218. #endif
  196219. #if defined(PNG_cHRM_SUPPORTED)
  196220. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196221. void PNGAPI
  196222. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196223. double white_x, double white_y, double red_x, double red_y,
  196224. double green_x, double green_y, double blue_x, double blue_y)
  196225. {
  196226. png_debug1(1, "in %s storage function\n", "cHRM");
  196227. if (png_ptr == NULL || info_ptr == NULL)
  196228. return;
  196229. if (white_x < 0.0 || white_y < 0.0 ||
  196230. red_x < 0.0 || red_y < 0.0 ||
  196231. green_x < 0.0 || green_y < 0.0 ||
  196232. blue_x < 0.0 || blue_y < 0.0)
  196233. {
  196234. png_warning(png_ptr,
  196235. "Ignoring attempt to set negative chromaticity value");
  196236. return;
  196237. }
  196238. if (white_x > 21474.83 || white_y > 21474.83 ||
  196239. red_x > 21474.83 || red_y > 21474.83 ||
  196240. green_x > 21474.83 || green_y > 21474.83 ||
  196241. blue_x > 21474.83 || blue_y > 21474.83)
  196242. {
  196243. png_warning(png_ptr,
  196244. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196245. return;
  196246. }
  196247. info_ptr->x_white = (float)white_x;
  196248. info_ptr->y_white = (float)white_y;
  196249. info_ptr->x_red = (float)red_x;
  196250. info_ptr->y_red = (float)red_y;
  196251. info_ptr->x_green = (float)green_x;
  196252. info_ptr->y_green = (float)green_y;
  196253. info_ptr->x_blue = (float)blue_x;
  196254. info_ptr->y_blue = (float)blue_y;
  196255. #ifdef PNG_FIXED_POINT_SUPPORTED
  196256. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196257. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196258. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196259. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196260. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196261. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196262. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196263. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196264. #endif
  196265. info_ptr->valid |= PNG_INFO_cHRM;
  196266. }
  196267. #endif
  196268. #ifdef PNG_FIXED_POINT_SUPPORTED
  196269. void PNGAPI
  196270. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196271. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196272. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196273. png_fixed_point blue_x, png_fixed_point blue_y)
  196274. {
  196275. png_debug1(1, "in %s storage function\n", "cHRM");
  196276. if (png_ptr == NULL || info_ptr == NULL)
  196277. return;
  196278. if (white_x < 0 || white_y < 0 ||
  196279. red_x < 0 || red_y < 0 ||
  196280. green_x < 0 || green_y < 0 ||
  196281. blue_x < 0 || blue_y < 0)
  196282. {
  196283. png_warning(png_ptr,
  196284. "Ignoring attempt to set negative chromaticity value");
  196285. return;
  196286. }
  196287. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196288. if (white_x > (double) PNG_UINT_31_MAX ||
  196289. white_y > (double) PNG_UINT_31_MAX ||
  196290. red_x > (double) PNG_UINT_31_MAX ||
  196291. red_y > (double) PNG_UINT_31_MAX ||
  196292. green_x > (double) PNG_UINT_31_MAX ||
  196293. green_y > (double) PNG_UINT_31_MAX ||
  196294. blue_x > (double) PNG_UINT_31_MAX ||
  196295. blue_y > (double) PNG_UINT_31_MAX)
  196296. #else
  196297. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196298. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196299. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196300. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196301. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196302. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196303. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196304. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196305. #endif
  196306. {
  196307. png_warning(png_ptr,
  196308. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196309. return;
  196310. }
  196311. info_ptr->int_x_white = white_x;
  196312. info_ptr->int_y_white = white_y;
  196313. info_ptr->int_x_red = red_x;
  196314. info_ptr->int_y_red = red_y;
  196315. info_ptr->int_x_green = green_x;
  196316. info_ptr->int_y_green = green_y;
  196317. info_ptr->int_x_blue = blue_x;
  196318. info_ptr->int_y_blue = blue_y;
  196319. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196320. info_ptr->x_white = (float)(white_x/100000.);
  196321. info_ptr->y_white = (float)(white_y/100000.);
  196322. info_ptr->x_red = (float)( red_x/100000.);
  196323. info_ptr->y_red = (float)( red_y/100000.);
  196324. info_ptr->x_green = (float)(green_x/100000.);
  196325. info_ptr->y_green = (float)(green_y/100000.);
  196326. info_ptr->x_blue = (float)( blue_x/100000.);
  196327. info_ptr->y_blue = (float)( blue_y/100000.);
  196328. #endif
  196329. info_ptr->valid |= PNG_INFO_cHRM;
  196330. }
  196331. #endif
  196332. #endif
  196333. #if defined(PNG_gAMA_SUPPORTED)
  196334. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196335. void PNGAPI
  196336. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196337. {
  196338. double gamma;
  196339. png_debug1(1, "in %s storage function\n", "gAMA");
  196340. if (png_ptr == NULL || info_ptr == NULL)
  196341. return;
  196342. /* Check for overflow */
  196343. if (file_gamma > 21474.83)
  196344. {
  196345. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196346. gamma=21474.83;
  196347. }
  196348. else
  196349. gamma=file_gamma;
  196350. info_ptr->gamma = (float)gamma;
  196351. #ifdef PNG_FIXED_POINT_SUPPORTED
  196352. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196353. #endif
  196354. info_ptr->valid |= PNG_INFO_gAMA;
  196355. if(gamma == 0.0)
  196356. png_warning(png_ptr, "Setting gamma=0");
  196357. }
  196358. #endif
  196359. void PNGAPI
  196360. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196361. int_gamma)
  196362. {
  196363. png_fixed_point gamma;
  196364. png_debug1(1, "in %s storage function\n", "gAMA");
  196365. if (png_ptr == NULL || info_ptr == NULL)
  196366. return;
  196367. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196368. {
  196369. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196370. gamma=PNG_UINT_31_MAX;
  196371. }
  196372. else
  196373. {
  196374. if (int_gamma < 0)
  196375. {
  196376. png_warning(png_ptr, "Setting negative gamma to zero");
  196377. gamma=0;
  196378. }
  196379. else
  196380. gamma=int_gamma;
  196381. }
  196382. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196383. info_ptr->gamma = (float)(gamma/100000.);
  196384. #endif
  196385. #ifdef PNG_FIXED_POINT_SUPPORTED
  196386. info_ptr->int_gamma = gamma;
  196387. #endif
  196388. info_ptr->valid |= PNG_INFO_gAMA;
  196389. if(gamma == 0)
  196390. png_warning(png_ptr, "Setting gamma=0");
  196391. }
  196392. #endif
  196393. #if defined(PNG_hIST_SUPPORTED)
  196394. void PNGAPI
  196395. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196396. {
  196397. int i;
  196398. png_debug1(1, "in %s storage function\n", "hIST");
  196399. if (png_ptr == NULL || info_ptr == NULL)
  196400. return;
  196401. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196402. > PNG_MAX_PALETTE_LENGTH)
  196403. {
  196404. png_warning(png_ptr,
  196405. "Invalid palette size, hIST allocation skipped.");
  196406. return;
  196407. }
  196408. #ifdef PNG_FREE_ME_SUPPORTED
  196409. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196410. #endif
  196411. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196412. 1.2.1 */
  196413. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196414. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196415. if (png_ptr->hist == NULL)
  196416. {
  196417. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196418. return;
  196419. }
  196420. for (i = 0; i < info_ptr->num_palette; i++)
  196421. png_ptr->hist[i] = hist[i];
  196422. info_ptr->hist = png_ptr->hist;
  196423. info_ptr->valid |= PNG_INFO_hIST;
  196424. #ifdef PNG_FREE_ME_SUPPORTED
  196425. info_ptr->free_me |= PNG_FREE_HIST;
  196426. #else
  196427. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196428. #endif
  196429. }
  196430. #endif
  196431. void PNGAPI
  196432. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196433. png_uint_32 width, png_uint_32 height, int bit_depth,
  196434. int color_type, int interlace_type, int compression_type,
  196435. int filter_type)
  196436. {
  196437. png_debug1(1, "in %s storage function\n", "IHDR");
  196438. if (png_ptr == NULL || info_ptr == NULL)
  196439. return;
  196440. /* check for width and height valid values */
  196441. if (width == 0 || height == 0)
  196442. png_error(png_ptr, "Image width or height is zero in IHDR");
  196443. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196444. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196445. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196446. #else
  196447. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196448. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196449. #endif
  196450. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196451. png_error(png_ptr, "Invalid image size in IHDR");
  196452. if ( width > (PNG_UINT_32_MAX
  196453. >> 3) /* 8-byte RGBA pixels */
  196454. - 64 /* bigrowbuf hack */
  196455. - 1 /* filter byte */
  196456. - 7*8 /* rounding of width to multiple of 8 pixels */
  196457. - 8) /* extra max_pixel_depth pad */
  196458. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196459. /* check other values */
  196460. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196461. bit_depth != 8 && bit_depth != 16)
  196462. png_error(png_ptr, "Invalid bit depth in IHDR");
  196463. if (color_type < 0 || color_type == 1 ||
  196464. color_type == 5 || color_type > 6)
  196465. png_error(png_ptr, "Invalid color type in IHDR");
  196466. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196467. ((color_type == PNG_COLOR_TYPE_RGB ||
  196468. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196469. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196470. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196471. if (interlace_type >= PNG_INTERLACE_LAST)
  196472. png_error(png_ptr, "Unknown interlace method in IHDR");
  196473. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196474. png_error(png_ptr, "Unknown compression method in IHDR");
  196475. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196476. /* Accept filter_method 64 (intrapixel differencing) only if
  196477. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196478. * 2. Libpng did not read a PNG signature (this filter_method is only
  196479. * used in PNG datastreams that are embedded in MNG datastreams) and
  196480. * 3. The application called png_permit_mng_features with a mask that
  196481. * included PNG_FLAG_MNG_FILTER_64 and
  196482. * 4. The filter_method is 64 and
  196483. * 5. The color_type is RGB or RGBA
  196484. */
  196485. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196486. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196487. if(filter_type != PNG_FILTER_TYPE_BASE)
  196488. {
  196489. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196490. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196491. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196492. (color_type == PNG_COLOR_TYPE_RGB ||
  196493. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196494. png_error(png_ptr, "Unknown filter method in IHDR");
  196495. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196496. png_warning(png_ptr, "Invalid filter method in IHDR");
  196497. }
  196498. #else
  196499. if(filter_type != PNG_FILTER_TYPE_BASE)
  196500. png_error(png_ptr, "Unknown filter method in IHDR");
  196501. #endif
  196502. info_ptr->width = width;
  196503. info_ptr->height = height;
  196504. info_ptr->bit_depth = (png_byte)bit_depth;
  196505. info_ptr->color_type =(png_byte) color_type;
  196506. info_ptr->compression_type = (png_byte)compression_type;
  196507. info_ptr->filter_type = (png_byte)filter_type;
  196508. info_ptr->interlace_type = (png_byte)interlace_type;
  196509. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196510. info_ptr->channels = 1;
  196511. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196512. info_ptr->channels = 3;
  196513. else
  196514. info_ptr->channels = 1;
  196515. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196516. info_ptr->channels++;
  196517. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196518. /* check for potential overflow */
  196519. if (width > (PNG_UINT_32_MAX
  196520. >> 3) /* 8-byte RGBA pixels */
  196521. - 64 /* bigrowbuf hack */
  196522. - 1 /* filter byte */
  196523. - 7*8 /* rounding of width to multiple of 8 pixels */
  196524. - 8) /* extra max_pixel_depth pad */
  196525. info_ptr->rowbytes = (png_size_t)0;
  196526. else
  196527. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196528. }
  196529. #if defined(PNG_oFFs_SUPPORTED)
  196530. void PNGAPI
  196531. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196532. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196533. {
  196534. png_debug1(1, "in %s storage function\n", "oFFs");
  196535. if (png_ptr == NULL || info_ptr == NULL)
  196536. return;
  196537. info_ptr->x_offset = offset_x;
  196538. info_ptr->y_offset = offset_y;
  196539. info_ptr->offset_unit_type = (png_byte)unit_type;
  196540. info_ptr->valid |= PNG_INFO_oFFs;
  196541. }
  196542. #endif
  196543. #if defined(PNG_pCAL_SUPPORTED)
  196544. void PNGAPI
  196545. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196546. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196547. png_charp units, png_charpp params)
  196548. {
  196549. png_uint_32 length;
  196550. int i;
  196551. png_debug1(1, "in %s storage function\n", "pCAL");
  196552. if (png_ptr == NULL || info_ptr == NULL)
  196553. return;
  196554. length = png_strlen(purpose) + 1;
  196555. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196556. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196557. if (info_ptr->pcal_purpose == NULL)
  196558. {
  196559. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196560. return;
  196561. }
  196562. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196563. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196564. info_ptr->pcal_X0 = X0;
  196565. info_ptr->pcal_X1 = X1;
  196566. info_ptr->pcal_type = (png_byte)type;
  196567. info_ptr->pcal_nparams = (png_byte)nparams;
  196568. length = png_strlen(units) + 1;
  196569. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196570. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196571. if (info_ptr->pcal_units == NULL)
  196572. {
  196573. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196574. return;
  196575. }
  196576. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196577. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196578. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196579. if (info_ptr->pcal_params == NULL)
  196580. {
  196581. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196582. return;
  196583. }
  196584. info_ptr->pcal_params[nparams] = NULL;
  196585. for (i = 0; i < nparams; i++)
  196586. {
  196587. length = png_strlen(params[i]) + 1;
  196588. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196589. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196590. if (info_ptr->pcal_params[i] == NULL)
  196591. {
  196592. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196593. return;
  196594. }
  196595. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196596. }
  196597. info_ptr->valid |= PNG_INFO_pCAL;
  196598. #ifdef PNG_FREE_ME_SUPPORTED
  196599. info_ptr->free_me |= PNG_FREE_PCAL;
  196600. #endif
  196601. }
  196602. #endif
  196603. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196604. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196605. void PNGAPI
  196606. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196607. int unit, double width, double height)
  196608. {
  196609. png_debug1(1, "in %s storage function\n", "sCAL");
  196610. if (png_ptr == NULL || info_ptr == NULL)
  196611. return;
  196612. info_ptr->scal_unit = (png_byte)unit;
  196613. info_ptr->scal_pixel_width = width;
  196614. info_ptr->scal_pixel_height = height;
  196615. info_ptr->valid |= PNG_INFO_sCAL;
  196616. }
  196617. #else
  196618. #ifdef PNG_FIXED_POINT_SUPPORTED
  196619. void PNGAPI
  196620. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196621. int unit, png_charp swidth, png_charp sheight)
  196622. {
  196623. png_uint_32 length;
  196624. png_debug1(1, "in %s storage function\n", "sCAL");
  196625. if (png_ptr == NULL || info_ptr == NULL)
  196626. return;
  196627. info_ptr->scal_unit = (png_byte)unit;
  196628. length = png_strlen(swidth) + 1;
  196629. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196630. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196631. if (info_ptr->scal_s_width == NULL)
  196632. {
  196633. png_warning(png_ptr,
  196634. "Memory allocation failed while processing sCAL.");
  196635. }
  196636. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196637. length = png_strlen(sheight) + 1;
  196638. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196639. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196640. if (info_ptr->scal_s_height == NULL)
  196641. {
  196642. png_free (png_ptr, info_ptr->scal_s_width);
  196643. png_warning(png_ptr,
  196644. "Memory allocation failed while processing sCAL.");
  196645. }
  196646. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196647. info_ptr->valid |= PNG_INFO_sCAL;
  196648. #ifdef PNG_FREE_ME_SUPPORTED
  196649. info_ptr->free_me |= PNG_FREE_SCAL;
  196650. #endif
  196651. }
  196652. #endif
  196653. #endif
  196654. #endif
  196655. #if defined(PNG_pHYs_SUPPORTED)
  196656. void PNGAPI
  196657. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196658. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196659. {
  196660. png_debug1(1, "in %s storage function\n", "pHYs");
  196661. if (png_ptr == NULL || info_ptr == NULL)
  196662. return;
  196663. info_ptr->x_pixels_per_unit = res_x;
  196664. info_ptr->y_pixels_per_unit = res_y;
  196665. info_ptr->phys_unit_type = (png_byte)unit_type;
  196666. info_ptr->valid |= PNG_INFO_pHYs;
  196667. }
  196668. #endif
  196669. void PNGAPI
  196670. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196671. png_colorp palette, int num_palette)
  196672. {
  196673. png_debug1(1, "in %s storage function\n", "PLTE");
  196674. if (png_ptr == NULL || info_ptr == NULL)
  196675. return;
  196676. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196677. {
  196678. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196679. png_error(png_ptr, "Invalid palette length");
  196680. else
  196681. {
  196682. png_warning(png_ptr, "Invalid palette length");
  196683. return;
  196684. }
  196685. }
  196686. /*
  196687. * It may not actually be necessary to set png_ptr->palette here;
  196688. * we do it for backward compatibility with the way the png_handle_tRNS
  196689. * function used to do the allocation.
  196690. */
  196691. #ifdef PNG_FREE_ME_SUPPORTED
  196692. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196693. #endif
  196694. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196695. of num_palette entries,
  196696. in case of an invalid PNG file that has too-large sample values. */
  196697. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196698. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196699. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196700. png_sizeof(png_color));
  196701. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196702. info_ptr->palette = png_ptr->palette;
  196703. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196704. #ifdef PNG_FREE_ME_SUPPORTED
  196705. info_ptr->free_me |= PNG_FREE_PLTE;
  196706. #else
  196707. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196708. #endif
  196709. info_ptr->valid |= PNG_INFO_PLTE;
  196710. }
  196711. #if defined(PNG_sBIT_SUPPORTED)
  196712. void PNGAPI
  196713. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196714. png_color_8p sig_bit)
  196715. {
  196716. png_debug1(1, "in %s storage function\n", "sBIT");
  196717. if (png_ptr == NULL || info_ptr == NULL)
  196718. return;
  196719. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196720. info_ptr->valid |= PNG_INFO_sBIT;
  196721. }
  196722. #endif
  196723. #if defined(PNG_sRGB_SUPPORTED)
  196724. void PNGAPI
  196725. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196726. {
  196727. png_debug1(1, "in %s storage function\n", "sRGB");
  196728. if (png_ptr == NULL || info_ptr == NULL)
  196729. return;
  196730. info_ptr->srgb_intent = (png_byte)intent;
  196731. info_ptr->valid |= PNG_INFO_sRGB;
  196732. }
  196733. void PNGAPI
  196734. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196735. int intent)
  196736. {
  196737. #if defined(PNG_gAMA_SUPPORTED)
  196738. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196739. float file_gamma;
  196740. #endif
  196741. #ifdef PNG_FIXED_POINT_SUPPORTED
  196742. png_fixed_point int_file_gamma;
  196743. #endif
  196744. #endif
  196745. #if defined(PNG_cHRM_SUPPORTED)
  196746. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196747. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196748. #endif
  196749. #ifdef PNG_FIXED_POINT_SUPPORTED
  196750. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196751. int_green_y, int_blue_x, int_blue_y;
  196752. #endif
  196753. #endif
  196754. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196755. if (png_ptr == NULL || info_ptr == NULL)
  196756. return;
  196757. png_set_sRGB(png_ptr, info_ptr, intent);
  196758. #if defined(PNG_gAMA_SUPPORTED)
  196759. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196760. file_gamma = (float).45455;
  196761. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196762. #endif
  196763. #ifdef PNG_FIXED_POINT_SUPPORTED
  196764. int_file_gamma = 45455L;
  196765. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196766. #endif
  196767. #endif
  196768. #if defined(PNG_cHRM_SUPPORTED)
  196769. #ifdef PNG_FIXED_POINT_SUPPORTED
  196770. int_white_x = 31270L;
  196771. int_white_y = 32900L;
  196772. int_red_x = 64000L;
  196773. int_red_y = 33000L;
  196774. int_green_x = 30000L;
  196775. int_green_y = 60000L;
  196776. int_blue_x = 15000L;
  196777. int_blue_y = 6000L;
  196778. png_set_cHRM_fixed(png_ptr, info_ptr,
  196779. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196780. int_blue_x, int_blue_y);
  196781. #endif
  196782. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196783. white_x = (float).3127;
  196784. white_y = (float).3290;
  196785. red_x = (float).64;
  196786. red_y = (float).33;
  196787. green_x = (float).30;
  196788. green_y = (float).60;
  196789. blue_x = (float).15;
  196790. blue_y = (float).06;
  196791. png_set_cHRM(png_ptr, info_ptr,
  196792. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196793. #endif
  196794. #endif
  196795. }
  196796. #endif
  196797. #if defined(PNG_iCCP_SUPPORTED)
  196798. void PNGAPI
  196799. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196800. png_charp name, int compression_type,
  196801. png_charp profile, png_uint_32 proflen)
  196802. {
  196803. png_charp new_iccp_name;
  196804. png_charp new_iccp_profile;
  196805. png_debug1(1, "in %s storage function\n", "iCCP");
  196806. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196807. return;
  196808. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196809. if (new_iccp_name == NULL)
  196810. {
  196811. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196812. return;
  196813. }
  196814. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196815. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  196816. if (new_iccp_profile == NULL)
  196817. {
  196818. png_free (png_ptr, new_iccp_name);
  196819. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  196820. return;
  196821. }
  196822. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  196823. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  196824. info_ptr->iccp_proflen = proflen;
  196825. info_ptr->iccp_name = new_iccp_name;
  196826. info_ptr->iccp_profile = new_iccp_profile;
  196827. /* Compression is always zero but is here so the API and info structure
  196828. * does not have to change if we introduce multiple compression types */
  196829. info_ptr->iccp_compression = (png_byte)compression_type;
  196830. #ifdef PNG_FREE_ME_SUPPORTED
  196831. info_ptr->free_me |= PNG_FREE_ICCP;
  196832. #endif
  196833. info_ptr->valid |= PNG_INFO_iCCP;
  196834. }
  196835. #endif
  196836. #if defined(PNG_TEXT_SUPPORTED)
  196837. void PNGAPI
  196838. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196839. int num_text)
  196840. {
  196841. int ret;
  196842. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  196843. if (ret)
  196844. png_error(png_ptr, "Insufficient memory to store text");
  196845. }
  196846. int /* PRIVATE */
  196847. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196848. int num_text)
  196849. {
  196850. int i;
  196851. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  196852. "text" : (png_const_charp)png_ptr->chunk_name));
  196853. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  196854. return(0);
  196855. /* Make sure we have enough space in the "text" array in info_struct
  196856. * to hold all of the incoming text_ptr objects.
  196857. */
  196858. if (info_ptr->num_text + num_text > info_ptr->max_text)
  196859. {
  196860. if (info_ptr->text != NULL)
  196861. {
  196862. png_textp old_text;
  196863. int old_max;
  196864. old_max = info_ptr->max_text;
  196865. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  196866. old_text = info_ptr->text;
  196867. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196868. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196869. if (info_ptr->text == NULL)
  196870. {
  196871. png_free(png_ptr, old_text);
  196872. return(1);
  196873. }
  196874. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  196875. png_sizeof(png_text)));
  196876. png_free(png_ptr, old_text);
  196877. }
  196878. else
  196879. {
  196880. info_ptr->max_text = num_text + 8;
  196881. info_ptr->num_text = 0;
  196882. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196883. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196884. if (info_ptr->text == NULL)
  196885. return(1);
  196886. #ifdef PNG_FREE_ME_SUPPORTED
  196887. info_ptr->free_me |= PNG_FREE_TEXT;
  196888. #endif
  196889. }
  196890. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  196891. info_ptr->max_text);
  196892. }
  196893. for (i = 0; i < num_text; i++)
  196894. {
  196895. png_size_t text_length,key_len;
  196896. png_size_t lang_len,lang_key_len;
  196897. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  196898. if (text_ptr[i].key == NULL)
  196899. continue;
  196900. key_len = png_strlen(text_ptr[i].key);
  196901. if(text_ptr[i].compression <= 0)
  196902. {
  196903. lang_len = 0;
  196904. lang_key_len = 0;
  196905. }
  196906. else
  196907. #ifdef PNG_iTXt_SUPPORTED
  196908. {
  196909. /* set iTXt data */
  196910. if (text_ptr[i].lang != NULL)
  196911. lang_len = png_strlen(text_ptr[i].lang);
  196912. else
  196913. lang_len = 0;
  196914. if (text_ptr[i].lang_key != NULL)
  196915. lang_key_len = png_strlen(text_ptr[i].lang_key);
  196916. else
  196917. lang_key_len = 0;
  196918. }
  196919. #else
  196920. {
  196921. png_warning(png_ptr, "iTXt chunk not supported.");
  196922. continue;
  196923. }
  196924. #endif
  196925. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  196926. {
  196927. text_length = 0;
  196928. #ifdef PNG_iTXt_SUPPORTED
  196929. if(text_ptr[i].compression > 0)
  196930. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  196931. else
  196932. #endif
  196933. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  196934. }
  196935. else
  196936. {
  196937. text_length = png_strlen(text_ptr[i].text);
  196938. textp->compression = text_ptr[i].compression;
  196939. }
  196940. textp->key = (png_charp)png_malloc_warn(png_ptr,
  196941. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  196942. if (textp->key == NULL)
  196943. return(1);
  196944. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  196945. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  196946. (int)textp->key);
  196947. png_memcpy(textp->key, text_ptr[i].key,
  196948. (png_size_t)(key_len));
  196949. *(textp->key+key_len) = '\0';
  196950. #ifdef PNG_iTXt_SUPPORTED
  196951. if (text_ptr[i].compression > 0)
  196952. {
  196953. textp->lang=textp->key + key_len + 1;
  196954. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  196955. *(textp->lang+lang_len) = '\0';
  196956. textp->lang_key=textp->lang + lang_len + 1;
  196957. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  196958. *(textp->lang_key+lang_key_len) = '\0';
  196959. textp->text=textp->lang_key + lang_key_len + 1;
  196960. }
  196961. else
  196962. #endif
  196963. {
  196964. #ifdef PNG_iTXt_SUPPORTED
  196965. textp->lang=NULL;
  196966. textp->lang_key=NULL;
  196967. #endif
  196968. textp->text=textp->key + key_len + 1;
  196969. }
  196970. if(text_length)
  196971. png_memcpy(textp->text, text_ptr[i].text,
  196972. (png_size_t)(text_length));
  196973. *(textp->text+text_length) = '\0';
  196974. #ifdef PNG_iTXt_SUPPORTED
  196975. if(textp->compression > 0)
  196976. {
  196977. textp->text_length = 0;
  196978. textp->itxt_length = text_length;
  196979. }
  196980. else
  196981. #endif
  196982. {
  196983. textp->text_length = text_length;
  196984. #ifdef PNG_iTXt_SUPPORTED
  196985. textp->itxt_length = 0;
  196986. #endif
  196987. }
  196988. info_ptr->num_text++;
  196989. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  196990. }
  196991. return(0);
  196992. }
  196993. #endif
  196994. #if defined(PNG_tIME_SUPPORTED)
  196995. void PNGAPI
  196996. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  196997. {
  196998. png_debug1(1, "in %s storage function\n", "tIME");
  196999. if (png_ptr == NULL || info_ptr == NULL ||
  197000. (png_ptr->mode & PNG_WROTE_tIME))
  197001. return;
  197002. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197003. info_ptr->valid |= PNG_INFO_tIME;
  197004. }
  197005. #endif
  197006. #if defined(PNG_tRNS_SUPPORTED)
  197007. void PNGAPI
  197008. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197009. png_bytep trans, int num_trans, png_color_16p trans_values)
  197010. {
  197011. png_debug1(1, "in %s storage function\n", "tRNS");
  197012. if (png_ptr == NULL || info_ptr == NULL)
  197013. return;
  197014. if (trans != NULL)
  197015. {
  197016. /*
  197017. * It may not actually be necessary to set png_ptr->trans here;
  197018. * we do it for backward compatibility with the way the png_handle_tRNS
  197019. * function used to do the allocation.
  197020. */
  197021. #ifdef PNG_FREE_ME_SUPPORTED
  197022. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197023. #endif
  197024. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197025. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197026. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197027. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197028. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197029. #ifdef PNG_FREE_ME_SUPPORTED
  197030. info_ptr->free_me |= PNG_FREE_TRNS;
  197031. #else
  197032. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197033. #endif
  197034. }
  197035. if (trans_values != NULL)
  197036. {
  197037. png_memcpy(&(info_ptr->trans_values), trans_values,
  197038. png_sizeof(png_color_16));
  197039. if (num_trans == 0)
  197040. num_trans = 1;
  197041. }
  197042. info_ptr->num_trans = (png_uint_16)num_trans;
  197043. info_ptr->valid |= PNG_INFO_tRNS;
  197044. }
  197045. #endif
  197046. #if defined(PNG_sPLT_SUPPORTED)
  197047. void PNGAPI
  197048. png_set_sPLT(png_structp png_ptr,
  197049. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197050. {
  197051. png_sPLT_tp np;
  197052. int i;
  197053. if (png_ptr == NULL || info_ptr == NULL)
  197054. return;
  197055. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197056. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197057. if (np == NULL)
  197058. {
  197059. png_warning(png_ptr, "No memory for sPLT palettes.");
  197060. return;
  197061. }
  197062. png_memcpy(np, info_ptr->splt_palettes,
  197063. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197064. png_free(png_ptr, info_ptr->splt_palettes);
  197065. info_ptr->splt_palettes=NULL;
  197066. for (i = 0; i < nentries; i++)
  197067. {
  197068. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197069. png_sPLT_tp from = entries + i;
  197070. to->name = (png_charp)png_malloc_warn(png_ptr,
  197071. png_strlen(from->name) + 1);
  197072. if (to->name == NULL)
  197073. {
  197074. png_warning(png_ptr,
  197075. "Out of memory while processing sPLT chunk");
  197076. }
  197077. /* TODO: use png_malloc_warn */
  197078. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197079. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197080. from->nentries * png_sizeof(png_sPLT_entry));
  197081. /* TODO: use png_malloc_warn */
  197082. png_memcpy(to->entries, from->entries,
  197083. from->nentries * png_sizeof(png_sPLT_entry));
  197084. if (to->entries == NULL)
  197085. {
  197086. png_warning(png_ptr,
  197087. "Out of memory while processing sPLT chunk");
  197088. png_free(png_ptr,to->name);
  197089. to->name = NULL;
  197090. }
  197091. to->nentries = from->nentries;
  197092. to->depth = from->depth;
  197093. }
  197094. info_ptr->splt_palettes = np;
  197095. info_ptr->splt_palettes_num += nentries;
  197096. info_ptr->valid |= PNG_INFO_sPLT;
  197097. #ifdef PNG_FREE_ME_SUPPORTED
  197098. info_ptr->free_me |= PNG_FREE_SPLT;
  197099. #endif
  197100. }
  197101. #endif /* PNG_sPLT_SUPPORTED */
  197102. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197103. void PNGAPI
  197104. png_set_unknown_chunks(png_structp png_ptr,
  197105. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197106. {
  197107. png_unknown_chunkp np;
  197108. int i;
  197109. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197110. return;
  197111. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197112. (info_ptr->unknown_chunks_num + num_unknowns) *
  197113. png_sizeof(png_unknown_chunk));
  197114. if (np == NULL)
  197115. {
  197116. png_warning(png_ptr,
  197117. "Out of memory while processing unknown chunk.");
  197118. return;
  197119. }
  197120. png_memcpy(np, info_ptr->unknown_chunks,
  197121. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197122. png_free(png_ptr, info_ptr->unknown_chunks);
  197123. info_ptr->unknown_chunks=NULL;
  197124. for (i = 0; i < num_unknowns; i++)
  197125. {
  197126. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197127. png_unknown_chunkp from = unknowns + i;
  197128. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197129. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197130. if (to->data == NULL)
  197131. {
  197132. png_warning(png_ptr,
  197133. "Out of memory while processing unknown chunk.");
  197134. }
  197135. else
  197136. {
  197137. png_memcpy(to->data, from->data, from->size);
  197138. to->size = from->size;
  197139. /* note our location in the read or write sequence */
  197140. to->location = (png_byte)(png_ptr->mode & 0xff);
  197141. }
  197142. }
  197143. info_ptr->unknown_chunks = np;
  197144. info_ptr->unknown_chunks_num += num_unknowns;
  197145. #ifdef PNG_FREE_ME_SUPPORTED
  197146. info_ptr->free_me |= PNG_FREE_UNKN;
  197147. #endif
  197148. }
  197149. void PNGAPI
  197150. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197151. int chunk, int location)
  197152. {
  197153. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197154. (int)info_ptr->unknown_chunks_num)
  197155. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197156. }
  197157. #endif
  197158. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197159. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197160. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197161. void PNGAPI
  197162. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197163. {
  197164. /* This function is deprecated in favor of png_permit_mng_features()
  197165. and will be removed from libpng-1.3.0 */
  197166. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197167. if (png_ptr == NULL)
  197168. return;
  197169. png_ptr->mng_features_permitted = (png_byte)
  197170. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197171. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197172. }
  197173. #endif
  197174. #endif
  197175. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197176. png_uint_32 PNGAPI
  197177. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197178. {
  197179. png_debug(1, "in png_permit_mng_features\n");
  197180. if (png_ptr == NULL)
  197181. return (png_uint_32)0;
  197182. png_ptr->mng_features_permitted =
  197183. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197184. return (png_uint_32)png_ptr->mng_features_permitted;
  197185. }
  197186. #endif
  197187. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197188. void PNGAPI
  197189. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197190. chunk_list, int num_chunks)
  197191. {
  197192. png_bytep new_list, p;
  197193. int i, old_num_chunks;
  197194. if (png_ptr == NULL)
  197195. return;
  197196. if (num_chunks == 0)
  197197. {
  197198. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197199. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197200. else
  197201. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197202. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197203. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197204. else
  197205. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197206. return;
  197207. }
  197208. if (chunk_list == NULL)
  197209. return;
  197210. old_num_chunks=png_ptr->num_chunk_list;
  197211. new_list=(png_bytep)png_malloc(png_ptr,
  197212. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197213. if(png_ptr->chunk_list != NULL)
  197214. {
  197215. png_memcpy(new_list, png_ptr->chunk_list,
  197216. (png_size_t)(5*old_num_chunks));
  197217. png_free(png_ptr, png_ptr->chunk_list);
  197218. png_ptr->chunk_list=NULL;
  197219. }
  197220. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197221. (png_size_t)(5*num_chunks));
  197222. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197223. *p=(png_byte)keep;
  197224. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197225. png_ptr->chunk_list=new_list;
  197226. #ifdef PNG_FREE_ME_SUPPORTED
  197227. png_ptr->free_me |= PNG_FREE_LIST;
  197228. #endif
  197229. }
  197230. #endif
  197231. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197232. void PNGAPI
  197233. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197234. png_user_chunk_ptr read_user_chunk_fn)
  197235. {
  197236. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197237. if (png_ptr == NULL)
  197238. return;
  197239. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197240. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197241. }
  197242. #endif
  197243. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197244. void PNGAPI
  197245. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197246. {
  197247. png_debug1(1, "in %s storage function\n", "rows");
  197248. if (png_ptr == NULL || info_ptr == NULL)
  197249. return;
  197250. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197251. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197252. info_ptr->row_pointers = row_pointers;
  197253. if(row_pointers)
  197254. info_ptr->valid |= PNG_INFO_IDAT;
  197255. }
  197256. #endif
  197257. #ifdef PNG_WRITE_SUPPORTED
  197258. void PNGAPI
  197259. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197260. {
  197261. if (png_ptr == NULL)
  197262. return;
  197263. if(png_ptr->zbuf)
  197264. png_free(png_ptr, png_ptr->zbuf);
  197265. png_ptr->zbuf_size = (png_size_t)size;
  197266. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197267. png_ptr->zstream.next_out = png_ptr->zbuf;
  197268. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197269. }
  197270. #endif
  197271. void PNGAPI
  197272. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197273. {
  197274. if (png_ptr && info_ptr)
  197275. info_ptr->valid &= ~(mask);
  197276. }
  197277. #ifndef PNG_1_0_X
  197278. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197279. /* function was added to libpng 1.2.0 and should always exist by default */
  197280. void PNGAPI
  197281. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197282. {
  197283. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197284. if (png_ptr != NULL)
  197285. png_ptr->asm_flags = 0;
  197286. }
  197287. /* this function was added to libpng 1.2.0 */
  197288. void PNGAPI
  197289. png_set_mmx_thresholds (png_structp png_ptr,
  197290. png_byte,
  197291. png_uint_32)
  197292. {
  197293. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197294. if (png_ptr == NULL)
  197295. return;
  197296. }
  197297. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197298. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197299. /* this function was added to libpng 1.2.6 */
  197300. void PNGAPI
  197301. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197302. png_uint_32 user_height_max)
  197303. {
  197304. /* Images with dimensions larger than these limits will be
  197305. * rejected by png_set_IHDR(). To accept any PNG datastream
  197306. * regardless of dimensions, set both limits to 0x7ffffffL.
  197307. */
  197308. if(png_ptr == NULL) return;
  197309. png_ptr->user_width_max = user_width_max;
  197310. png_ptr->user_height_max = user_height_max;
  197311. }
  197312. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197313. #endif /* ?PNG_1_0_X */
  197314. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197315. /*** End of inlined file: pngset.c ***/
  197316. /*** Start of inlined file: pngtrans.c ***/
  197317. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197318. *
  197319. * Last changed in libpng 1.2.17 May 15, 2007
  197320. * For conditions of distribution and use, see copyright notice in png.h
  197321. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197322. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197323. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197324. */
  197325. #define PNG_INTERNAL
  197326. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197327. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197328. /* turn on BGR-to-RGB mapping */
  197329. void PNGAPI
  197330. png_set_bgr(png_structp png_ptr)
  197331. {
  197332. png_debug(1, "in png_set_bgr\n");
  197333. if(png_ptr == NULL) return;
  197334. png_ptr->transformations |= PNG_BGR;
  197335. }
  197336. #endif
  197337. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197338. /* turn on 16 bit byte swapping */
  197339. void PNGAPI
  197340. png_set_swap(png_structp png_ptr)
  197341. {
  197342. png_debug(1, "in png_set_swap\n");
  197343. if(png_ptr == NULL) return;
  197344. if (png_ptr->bit_depth == 16)
  197345. png_ptr->transformations |= PNG_SWAP_BYTES;
  197346. }
  197347. #endif
  197348. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197349. /* turn on pixel packing */
  197350. void PNGAPI
  197351. png_set_packing(png_structp png_ptr)
  197352. {
  197353. png_debug(1, "in png_set_packing\n");
  197354. if(png_ptr == NULL) return;
  197355. if (png_ptr->bit_depth < 8)
  197356. {
  197357. png_ptr->transformations |= PNG_PACK;
  197358. png_ptr->usr_bit_depth = 8;
  197359. }
  197360. }
  197361. #endif
  197362. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197363. /* turn on packed pixel swapping */
  197364. void PNGAPI
  197365. png_set_packswap(png_structp png_ptr)
  197366. {
  197367. png_debug(1, "in png_set_packswap\n");
  197368. if(png_ptr == NULL) return;
  197369. if (png_ptr->bit_depth < 8)
  197370. png_ptr->transformations |= PNG_PACKSWAP;
  197371. }
  197372. #endif
  197373. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197374. void PNGAPI
  197375. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197376. {
  197377. png_debug(1, "in png_set_shift\n");
  197378. if(png_ptr == NULL) return;
  197379. png_ptr->transformations |= PNG_SHIFT;
  197380. png_ptr->shift = *true_bits;
  197381. }
  197382. #endif
  197383. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197384. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197385. int PNGAPI
  197386. png_set_interlace_handling(png_structp png_ptr)
  197387. {
  197388. png_debug(1, "in png_set_interlace handling\n");
  197389. if (png_ptr && png_ptr->interlaced)
  197390. {
  197391. png_ptr->transformations |= PNG_INTERLACE;
  197392. return (7);
  197393. }
  197394. return (1);
  197395. }
  197396. #endif
  197397. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197398. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197399. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197400. * for 48-bit input data, as well as to avoid problems with some compilers
  197401. * that don't like bytes as parameters.
  197402. */
  197403. void PNGAPI
  197404. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197405. {
  197406. png_debug(1, "in png_set_filler\n");
  197407. if(png_ptr == NULL) return;
  197408. png_ptr->transformations |= PNG_FILLER;
  197409. png_ptr->filler = (png_byte)filler;
  197410. if (filler_loc == PNG_FILLER_AFTER)
  197411. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197412. else
  197413. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197414. /* This should probably go in the "do_read_filler" routine.
  197415. * I attempted to do that in libpng-1.0.1a but that caused problems
  197416. * so I restored it in libpng-1.0.2a
  197417. */
  197418. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197419. {
  197420. png_ptr->usr_channels = 4;
  197421. }
  197422. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197423. * a less-than-8-bit grayscale to GA? */
  197424. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197425. {
  197426. png_ptr->usr_channels = 2;
  197427. }
  197428. }
  197429. #if !defined(PNG_1_0_X)
  197430. /* Added to libpng-1.2.7 */
  197431. void PNGAPI
  197432. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197433. {
  197434. png_debug(1, "in png_set_add_alpha\n");
  197435. if(png_ptr == NULL) return;
  197436. png_set_filler(png_ptr, filler, filler_loc);
  197437. png_ptr->transformations |= PNG_ADD_ALPHA;
  197438. }
  197439. #endif
  197440. #endif
  197441. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197442. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197443. void PNGAPI
  197444. png_set_swap_alpha(png_structp png_ptr)
  197445. {
  197446. png_debug(1, "in png_set_swap_alpha\n");
  197447. if(png_ptr == NULL) return;
  197448. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197449. }
  197450. #endif
  197451. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197452. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197453. void PNGAPI
  197454. png_set_invert_alpha(png_structp png_ptr)
  197455. {
  197456. png_debug(1, "in png_set_invert_alpha\n");
  197457. if(png_ptr == NULL) return;
  197458. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197459. }
  197460. #endif
  197461. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197462. void PNGAPI
  197463. png_set_invert_mono(png_structp png_ptr)
  197464. {
  197465. png_debug(1, "in png_set_invert_mono\n");
  197466. if(png_ptr == NULL) return;
  197467. png_ptr->transformations |= PNG_INVERT_MONO;
  197468. }
  197469. /* invert monochrome grayscale data */
  197470. void /* PRIVATE */
  197471. png_do_invert(png_row_infop row_info, png_bytep row)
  197472. {
  197473. png_debug(1, "in png_do_invert\n");
  197474. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197475. * if (row_info->bit_depth == 1 &&
  197476. */
  197477. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197478. if (row == NULL || row_info == NULL)
  197479. return;
  197480. #endif
  197481. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197482. {
  197483. png_bytep rp = row;
  197484. png_uint_32 i;
  197485. png_uint_32 istop = row_info->rowbytes;
  197486. for (i = 0; i < istop; i++)
  197487. {
  197488. *rp = (png_byte)(~(*rp));
  197489. rp++;
  197490. }
  197491. }
  197492. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197493. row_info->bit_depth == 8)
  197494. {
  197495. png_bytep rp = row;
  197496. png_uint_32 i;
  197497. png_uint_32 istop = row_info->rowbytes;
  197498. for (i = 0; i < istop; i+=2)
  197499. {
  197500. *rp = (png_byte)(~(*rp));
  197501. rp+=2;
  197502. }
  197503. }
  197504. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197505. row_info->bit_depth == 16)
  197506. {
  197507. png_bytep rp = row;
  197508. png_uint_32 i;
  197509. png_uint_32 istop = row_info->rowbytes;
  197510. for (i = 0; i < istop; i+=4)
  197511. {
  197512. *rp = (png_byte)(~(*rp));
  197513. *(rp+1) = (png_byte)(~(*(rp+1)));
  197514. rp+=4;
  197515. }
  197516. }
  197517. }
  197518. #endif
  197519. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197520. /* swaps byte order on 16 bit depth images */
  197521. void /* PRIVATE */
  197522. png_do_swap(png_row_infop row_info, png_bytep row)
  197523. {
  197524. png_debug(1, "in png_do_swap\n");
  197525. if (
  197526. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197527. row != NULL && row_info != NULL &&
  197528. #endif
  197529. row_info->bit_depth == 16)
  197530. {
  197531. png_bytep rp = row;
  197532. png_uint_32 i;
  197533. png_uint_32 istop= row_info->width * row_info->channels;
  197534. for (i = 0; i < istop; i++, rp += 2)
  197535. {
  197536. png_byte t = *rp;
  197537. *rp = *(rp + 1);
  197538. *(rp + 1) = t;
  197539. }
  197540. }
  197541. }
  197542. #endif
  197543. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197544. static PNG_CONST png_byte onebppswaptable[256] = {
  197545. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197546. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197547. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197548. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197549. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197550. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197551. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197552. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197553. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197554. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197555. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197556. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197557. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197558. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197559. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197560. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197561. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197562. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197563. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197564. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197565. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197566. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197567. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197568. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197569. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197570. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197571. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197572. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197573. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197574. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197575. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197576. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197577. };
  197578. static PNG_CONST png_byte twobppswaptable[256] = {
  197579. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197580. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197581. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197582. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197583. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197584. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197585. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197586. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197587. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197588. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197589. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197590. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197591. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197592. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197593. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197594. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197595. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197596. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197597. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197598. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197599. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197600. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197601. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197602. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197603. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197604. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197605. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197606. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197607. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197608. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197609. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197610. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197611. };
  197612. static PNG_CONST png_byte fourbppswaptable[256] = {
  197613. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197614. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197615. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197616. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197617. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197618. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197619. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197620. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197621. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197622. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197623. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197624. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197625. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197626. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197627. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197628. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197629. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197630. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197631. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197632. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197633. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197634. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197635. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197636. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197637. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197638. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197639. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197640. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197641. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197642. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197643. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197644. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197645. };
  197646. /* swaps pixel packing order within bytes */
  197647. void /* PRIVATE */
  197648. png_do_packswap(png_row_infop row_info, png_bytep row)
  197649. {
  197650. png_debug(1, "in png_do_packswap\n");
  197651. if (
  197652. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197653. row != NULL && row_info != NULL &&
  197654. #endif
  197655. row_info->bit_depth < 8)
  197656. {
  197657. png_bytep rp, end, table;
  197658. end = row + row_info->rowbytes;
  197659. if (row_info->bit_depth == 1)
  197660. table = (png_bytep)onebppswaptable;
  197661. else if (row_info->bit_depth == 2)
  197662. table = (png_bytep)twobppswaptable;
  197663. else if (row_info->bit_depth == 4)
  197664. table = (png_bytep)fourbppswaptable;
  197665. else
  197666. return;
  197667. for (rp = row; rp < end; rp++)
  197668. *rp = table[*rp];
  197669. }
  197670. }
  197671. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197672. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197673. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197674. /* remove filler or alpha byte(s) */
  197675. void /* PRIVATE */
  197676. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197677. {
  197678. png_debug(1, "in png_do_strip_filler\n");
  197679. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197680. if (row != NULL && row_info != NULL)
  197681. #endif
  197682. {
  197683. png_bytep sp=row;
  197684. png_bytep dp=row;
  197685. png_uint_32 row_width=row_info->width;
  197686. png_uint_32 i;
  197687. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197688. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197689. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197690. row_info->channels == 4)
  197691. {
  197692. if (row_info->bit_depth == 8)
  197693. {
  197694. /* This converts from RGBX or RGBA to RGB */
  197695. if (flags & PNG_FLAG_FILLER_AFTER)
  197696. {
  197697. dp+=3; sp+=4;
  197698. for (i = 1; i < row_width; i++)
  197699. {
  197700. *dp++ = *sp++;
  197701. *dp++ = *sp++;
  197702. *dp++ = *sp++;
  197703. sp++;
  197704. }
  197705. }
  197706. /* This converts from XRGB or ARGB to RGB */
  197707. else
  197708. {
  197709. for (i = 0; i < row_width; i++)
  197710. {
  197711. sp++;
  197712. *dp++ = *sp++;
  197713. *dp++ = *sp++;
  197714. *dp++ = *sp++;
  197715. }
  197716. }
  197717. row_info->pixel_depth = 24;
  197718. row_info->rowbytes = row_width * 3;
  197719. }
  197720. else /* if (row_info->bit_depth == 16) */
  197721. {
  197722. if (flags & PNG_FLAG_FILLER_AFTER)
  197723. {
  197724. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197725. sp += 8; dp += 6;
  197726. for (i = 1; i < row_width; i++)
  197727. {
  197728. /* This could be (although png_memcpy is probably slower):
  197729. png_memcpy(dp, sp, 6);
  197730. sp += 8;
  197731. dp += 6;
  197732. */
  197733. *dp++ = *sp++;
  197734. *dp++ = *sp++;
  197735. *dp++ = *sp++;
  197736. *dp++ = *sp++;
  197737. *dp++ = *sp++;
  197738. *dp++ = *sp++;
  197739. sp += 2;
  197740. }
  197741. }
  197742. else
  197743. {
  197744. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197745. for (i = 0; i < row_width; i++)
  197746. {
  197747. /* This could be (although png_memcpy is probably slower):
  197748. png_memcpy(dp, sp, 6);
  197749. sp += 8;
  197750. dp += 6;
  197751. */
  197752. sp+=2;
  197753. *dp++ = *sp++;
  197754. *dp++ = *sp++;
  197755. *dp++ = *sp++;
  197756. *dp++ = *sp++;
  197757. *dp++ = *sp++;
  197758. *dp++ = *sp++;
  197759. }
  197760. }
  197761. row_info->pixel_depth = 48;
  197762. row_info->rowbytes = row_width * 6;
  197763. }
  197764. row_info->channels = 3;
  197765. }
  197766. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197767. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197768. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197769. row_info->channels == 2)
  197770. {
  197771. if (row_info->bit_depth == 8)
  197772. {
  197773. /* This converts from GX or GA to G */
  197774. if (flags & PNG_FLAG_FILLER_AFTER)
  197775. {
  197776. for (i = 0; i < row_width; i++)
  197777. {
  197778. *dp++ = *sp++;
  197779. sp++;
  197780. }
  197781. }
  197782. /* This converts from XG or AG to G */
  197783. else
  197784. {
  197785. for (i = 0; i < row_width; i++)
  197786. {
  197787. sp++;
  197788. *dp++ = *sp++;
  197789. }
  197790. }
  197791. row_info->pixel_depth = 8;
  197792. row_info->rowbytes = row_width;
  197793. }
  197794. else /* if (row_info->bit_depth == 16) */
  197795. {
  197796. if (flags & PNG_FLAG_FILLER_AFTER)
  197797. {
  197798. /* This converts from GGXX or GGAA to GG */
  197799. sp += 4; dp += 2;
  197800. for (i = 1; i < row_width; i++)
  197801. {
  197802. *dp++ = *sp++;
  197803. *dp++ = *sp++;
  197804. sp += 2;
  197805. }
  197806. }
  197807. else
  197808. {
  197809. /* This converts from XXGG or AAGG to GG */
  197810. for (i = 0; i < row_width; i++)
  197811. {
  197812. sp += 2;
  197813. *dp++ = *sp++;
  197814. *dp++ = *sp++;
  197815. }
  197816. }
  197817. row_info->pixel_depth = 16;
  197818. row_info->rowbytes = row_width * 2;
  197819. }
  197820. row_info->channels = 1;
  197821. }
  197822. if (flags & PNG_FLAG_STRIP_ALPHA)
  197823. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  197824. }
  197825. }
  197826. #endif
  197827. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197828. /* swaps red and blue bytes within a pixel */
  197829. void /* PRIVATE */
  197830. png_do_bgr(png_row_infop row_info, png_bytep row)
  197831. {
  197832. png_debug(1, "in png_do_bgr\n");
  197833. if (
  197834. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197835. row != NULL && row_info != NULL &&
  197836. #endif
  197837. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197838. {
  197839. png_uint_32 row_width = row_info->width;
  197840. if (row_info->bit_depth == 8)
  197841. {
  197842. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197843. {
  197844. png_bytep rp;
  197845. png_uint_32 i;
  197846. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  197847. {
  197848. png_byte save = *rp;
  197849. *rp = *(rp + 2);
  197850. *(rp + 2) = save;
  197851. }
  197852. }
  197853. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197854. {
  197855. png_bytep rp;
  197856. png_uint_32 i;
  197857. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  197858. {
  197859. png_byte save = *rp;
  197860. *rp = *(rp + 2);
  197861. *(rp + 2) = save;
  197862. }
  197863. }
  197864. }
  197865. else if (row_info->bit_depth == 16)
  197866. {
  197867. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197868. {
  197869. png_bytep rp;
  197870. png_uint_32 i;
  197871. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  197872. {
  197873. png_byte save = *rp;
  197874. *rp = *(rp + 4);
  197875. *(rp + 4) = save;
  197876. save = *(rp + 1);
  197877. *(rp + 1) = *(rp + 5);
  197878. *(rp + 5) = save;
  197879. }
  197880. }
  197881. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197882. {
  197883. png_bytep rp;
  197884. png_uint_32 i;
  197885. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  197886. {
  197887. png_byte save = *rp;
  197888. *rp = *(rp + 4);
  197889. *(rp + 4) = save;
  197890. save = *(rp + 1);
  197891. *(rp + 1) = *(rp + 5);
  197892. *(rp + 5) = save;
  197893. }
  197894. }
  197895. }
  197896. }
  197897. }
  197898. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  197899. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  197900. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  197901. defined(PNG_LEGACY_SUPPORTED)
  197902. void PNGAPI
  197903. png_set_user_transform_info(png_structp png_ptr, png_voidp
  197904. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  197905. {
  197906. png_debug(1, "in png_set_user_transform_info\n");
  197907. if(png_ptr == NULL) return;
  197908. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197909. png_ptr->user_transform_ptr = user_transform_ptr;
  197910. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  197911. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  197912. #else
  197913. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  197914. png_warning(png_ptr,
  197915. "This version of libpng does not support user transform info");
  197916. #endif
  197917. }
  197918. #endif
  197919. /* This function returns a pointer to the user_transform_ptr associated with
  197920. * the user transform functions. The application should free any memory
  197921. * associated with this pointer before png_write_destroy and png_read_destroy
  197922. * are called.
  197923. */
  197924. png_voidp PNGAPI
  197925. png_get_user_transform_ptr(png_structp png_ptr)
  197926. {
  197927. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197928. if (png_ptr == NULL) return (NULL);
  197929. return ((png_voidp)png_ptr->user_transform_ptr);
  197930. #else
  197931. return (NULL);
  197932. #endif
  197933. }
  197934. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197935. /*** End of inlined file: pngtrans.c ***/
  197936. /*** Start of inlined file: pngwio.c ***/
  197937. /* pngwio.c - functions for data output
  197938. *
  197939. * Last changed in libpng 1.2.13 November 13, 2006
  197940. * For conditions of distribution and use, see copyright notice in png.h
  197941. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197942. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197943. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197944. *
  197945. * This file provides a location for all output. Users who need
  197946. * special handling are expected to write functions that have the same
  197947. * arguments as these and perform similar functions, but that possibly
  197948. * use different output methods. Note that you shouldn't change these
  197949. * functions, but rather write replacement functions and then change
  197950. * them at run time with png_set_write_fn(...).
  197951. */
  197952. #define PNG_INTERNAL
  197953. #ifdef PNG_WRITE_SUPPORTED
  197954. /* Write the data to whatever output you are using. The default routine
  197955. writes to a file pointer. Note that this routine sometimes gets called
  197956. with very small lengths, so you should implement some kind of simple
  197957. buffering if you are using unbuffered writes. This should never be asked
  197958. to write more than 64K on a 16 bit machine. */
  197959. void /* PRIVATE */
  197960. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197961. {
  197962. if (png_ptr->write_data_fn != NULL )
  197963. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  197964. else
  197965. png_error(png_ptr, "Call to NULL write function");
  197966. }
  197967. #if !defined(PNG_NO_STDIO)
  197968. /* This is the function that does the actual writing of data. If you are
  197969. not writing to a standard C stream, you should create a replacement
  197970. write_data function and use it at run time with png_set_write_fn(), rather
  197971. than changing the library. */
  197972. #ifndef USE_FAR_KEYWORD
  197973. void PNGAPI
  197974. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197975. {
  197976. png_uint_32 check;
  197977. if(png_ptr == NULL) return;
  197978. #if defined(_WIN32_WCE)
  197979. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  197980. check = 0;
  197981. #else
  197982. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  197983. #endif
  197984. if (check != length)
  197985. png_error(png_ptr, "Write Error");
  197986. }
  197987. #else
  197988. /* this is the model-independent version. Since the standard I/O library
  197989. can't handle far buffers in the medium and small models, we have to copy
  197990. the data.
  197991. */
  197992. #define NEAR_BUF_SIZE 1024
  197993. #define MIN(a,b) (a <= b ? a : b)
  197994. void PNGAPI
  197995. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197996. {
  197997. png_uint_32 check;
  197998. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  197999. png_FILE_p io_ptr;
  198000. if(png_ptr == NULL) return;
  198001. /* Check if data really is near. If so, use usual code. */
  198002. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198003. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198004. if ((png_bytep)near_data == data)
  198005. {
  198006. #if defined(_WIN32_WCE)
  198007. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198008. check = 0;
  198009. #else
  198010. check = fwrite(near_data, 1, length, io_ptr);
  198011. #endif
  198012. }
  198013. else
  198014. {
  198015. png_byte buf[NEAR_BUF_SIZE];
  198016. png_size_t written, remaining, err;
  198017. check = 0;
  198018. remaining = length;
  198019. do
  198020. {
  198021. written = MIN(NEAR_BUF_SIZE, remaining);
  198022. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198023. #if defined(_WIN32_WCE)
  198024. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198025. err = 0;
  198026. #else
  198027. err = fwrite(buf, 1, written, io_ptr);
  198028. #endif
  198029. if (err != written)
  198030. break;
  198031. else
  198032. check += err;
  198033. data += written;
  198034. remaining -= written;
  198035. }
  198036. while (remaining != 0);
  198037. }
  198038. if (check != length)
  198039. png_error(png_ptr, "Write Error");
  198040. }
  198041. #endif
  198042. #endif
  198043. /* This function is called to output any data pending writing (normally
  198044. to disk). After png_flush is called, there should be no data pending
  198045. writing in any buffers. */
  198046. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198047. void /* PRIVATE */
  198048. png_flush(png_structp png_ptr)
  198049. {
  198050. if (png_ptr->output_flush_fn != NULL)
  198051. (*(png_ptr->output_flush_fn))(png_ptr);
  198052. }
  198053. #if !defined(PNG_NO_STDIO)
  198054. void PNGAPI
  198055. png_default_flush(png_structp png_ptr)
  198056. {
  198057. #if !defined(_WIN32_WCE)
  198058. png_FILE_p io_ptr;
  198059. #endif
  198060. if(png_ptr == NULL) return;
  198061. #if !defined(_WIN32_WCE)
  198062. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198063. if (io_ptr != NULL)
  198064. fflush(io_ptr);
  198065. #endif
  198066. }
  198067. #endif
  198068. #endif
  198069. /* This function allows the application to supply new output functions for
  198070. libpng if standard C streams aren't being used.
  198071. This function takes as its arguments:
  198072. png_ptr - pointer to a png output data structure
  198073. io_ptr - pointer to user supplied structure containing info about
  198074. the output functions. May be NULL.
  198075. write_data_fn - pointer to a new output function that takes as its
  198076. arguments a pointer to a png_struct, a pointer to
  198077. data to be written, and a 32-bit unsigned int that is
  198078. the number of bytes to be written. The new write
  198079. function should call png_error(png_ptr, "Error msg")
  198080. to exit and output any fatal error messages.
  198081. flush_data_fn - pointer to a new flush function that takes as its
  198082. arguments a pointer to a png_struct. After a call to
  198083. the flush function, there should be no data in any buffers
  198084. or pending transmission. If the output method doesn't do
  198085. any buffering of ouput, a function prototype must still be
  198086. supplied although it doesn't have to do anything. If
  198087. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198088. time, output_flush_fn will be ignored, although it must be
  198089. supplied for compatibility. */
  198090. void PNGAPI
  198091. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198092. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198093. {
  198094. if(png_ptr == NULL) return;
  198095. png_ptr->io_ptr = io_ptr;
  198096. #if !defined(PNG_NO_STDIO)
  198097. if (write_data_fn != NULL)
  198098. png_ptr->write_data_fn = write_data_fn;
  198099. else
  198100. png_ptr->write_data_fn = png_default_write_data;
  198101. #else
  198102. png_ptr->write_data_fn = write_data_fn;
  198103. #endif
  198104. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198105. #if !defined(PNG_NO_STDIO)
  198106. if (output_flush_fn != NULL)
  198107. png_ptr->output_flush_fn = output_flush_fn;
  198108. else
  198109. png_ptr->output_flush_fn = png_default_flush;
  198110. #else
  198111. png_ptr->output_flush_fn = output_flush_fn;
  198112. #endif
  198113. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198114. /* It is an error to read while writing a png file */
  198115. if (png_ptr->read_data_fn != NULL)
  198116. {
  198117. png_ptr->read_data_fn = NULL;
  198118. png_warning(png_ptr,
  198119. "Attempted to set both read_data_fn and write_data_fn in");
  198120. png_warning(png_ptr,
  198121. "the same structure. Resetting read_data_fn to NULL.");
  198122. }
  198123. }
  198124. #if defined(USE_FAR_KEYWORD)
  198125. #if defined(_MSC_VER)
  198126. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198127. {
  198128. void *near_ptr;
  198129. void FAR *far_ptr;
  198130. FP_OFF(near_ptr) = FP_OFF(ptr);
  198131. far_ptr = (void FAR *)near_ptr;
  198132. if(check != 0)
  198133. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198134. png_error(png_ptr,"segment lost in conversion");
  198135. return(near_ptr);
  198136. }
  198137. # else
  198138. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198139. {
  198140. void *near_ptr;
  198141. void FAR *far_ptr;
  198142. near_ptr = (void FAR *)ptr;
  198143. far_ptr = (void FAR *)near_ptr;
  198144. if(check != 0)
  198145. if(far_ptr != ptr)
  198146. png_error(png_ptr,"segment lost in conversion");
  198147. return(near_ptr);
  198148. }
  198149. # endif
  198150. # endif
  198151. #endif /* PNG_WRITE_SUPPORTED */
  198152. /*** End of inlined file: pngwio.c ***/
  198153. /*** Start of inlined file: pngwrite.c ***/
  198154. /* pngwrite.c - general routines to write a PNG file
  198155. *
  198156. * Last changed in libpng 1.2.15 January 5, 2007
  198157. * For conditions of distribution and use, see copyright notice in png.h
  198158. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198159. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198160. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198161. */
  198162. /* get internal access to png.h */
  198163. #define PNG_INTERNAL
  198164. #ifdef PNG_WRITE_SUPPORTED
  198165. /* Writes all the PNG information. This is the suggested way to use the
  198166. * library. If you have a new chunk to add, make a function to write it,
  198167. * and put it in the correct location here. If you want the chunk written
  198168. * after the image data, put it in png_write_end(). I strongly encourage
  198169. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198170. * the chunk, as that will keep the code from breaking if you want to just
  198171. * write a plain PNG file. If you have long comments, I suggest writing
  198172. * them in png_write_end(), and compressing them.
  198173. */
  198174. void PNGAPI
  198175. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198176. {
  198177. png_debug(1, "in png_write_info_before_PLTE\n");
  198178. if (png_ptr == NULL || info_ptr == NULL)
  198179. return;
  198180. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198181. {
  198182. png_write_sig(png_ptr); /* write PNG signature */
  198183. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198184. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198185. {
  198186. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198187. png_ptr->mng_features_permitted=0;
  198188. }
  198189. #endif
  198190. /* write IHDR information. */
  198191. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198192. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198193. info_ptr->filter_type,
  198194. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198195. info_ptr->interlace_type);
  198196. #else
  198197. 0);
  198198. #endif
  198199. /* the rest of these check to see if the valid field has the appropriate
  198200. flag set, and if it does, writes the chunk. */
  198201. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198202. if (info_ptr->valid & PNG_INFO_gAMA)
  198203. {
  198204. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198205. png_write_gAMA(png_ptr, info_ptr->gamma);
  198206. #else
  198207. #ifdef PNG_FIXED_POINT_SUPPORTED
  198208. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198209. # endif
  198210. #endif
  198211. }
  198212. #endif
  198213. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198214. if (info_ptr->valid & PNG_INFO_sRGB)
  198215. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198216. #endif
  198217. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198218. if (info_ptr->valid & PNG_INFO_iCCP)
  198219. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198220. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198221. #endif
  198222. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198223. if (info_ptr->valid & PNG_INFO_sBIT)
  198224. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198225. #endif
  198226. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198227. if (info_ptr->valid & PNG_INFO_cHRM)
  198228. {
  198229. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198230. png_write_cHRM(png_ptr,
  198231. info_ptr->x_white, info_ptr->y_white,
  198232. info_ptr->x_red, info_ptr->y_red,
  198233. info_ptr->x_green, info_ptr->y_green,
  198234. info_ptr->x_blue, info_ptr->y_blue);
  198235. #else
  198236. # ifdef PNG_FIXED_POINT_SUPPORTED
  198237. png_write_cHRM_fixed(png_ptr,
  198238. info_ptr->int_x_white, info_ptr->int_y_white,
  198239. info_ptr->int_x_red, info_ptr->int_y_red,
  198240. info_ptr->int_x_green, info_ptr->int_y_green,
  198241. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198242. # endif
  198243. #endif
  198244. }
  198245. #endif
  198246. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198247. if (info_ptr->unknown_chunks_num)
  198248. {
  198249. png_unknown_chunk *up;
  198250. png_debug(5, "writing extra chunks\n");
  198251. for (up = info_ptr->unknown_chunks;
  198252. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198253. up++)
  198254. {
  198255. int keep=png_handle_as_unknown(png_ptr, up->name);
  198256. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198257. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198258. !(up->location & PNG_HAVE_IDAT) &&
  198259. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198260. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198261. {
  198262. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198263. }
  198264. }
  198265. }
  198266. #endif
  198267. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198268. }
  198269. }
  198270. void PNGAPI
  198271. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198272. {
  198273. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198274. int i;
  198275. #endif
  198276. png_debug(1, "in png_write_info\n");
  198277. if (png_ptr == NULL || info_ptr == NULL)
  198278. return;
  198279. png_write_info_before_PLTE(png_ptr, info_ptr);
  198280. if (info_ptr->valid & PNG_INFO_PLTE)
  198281. png_write_PLTE(png_ptr, info_ptr->palette,
  198282. (png_uint_32)info_ptr->num_palette);
  198283. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198284. png_error(png_ptr, "Valid palette required for paletted images");
  198285. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198286. if (info_ptr->valid & PNG_INFO_tRNS)
  198287. {
  198288. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198289. /* invert the alpha channel (in tRNS) */
  198290. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198291. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198292. {
  198293. int j;
  198294. for (j=0; j<(int)info_ptr->num_trans; j++)
  198295. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198296. }
  198297. #endif
  198298. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198299. info_ptr->num_trans, info_ptr->color_type);
  198300. }
  198301. #endif
  198302. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198303. if (info_ptr->valid & PNG_INFO_bKGD)
  198304. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198305. #endif
  198306. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198307. if (info_ptr->valid & PNG_INFO_hIST)
  198308. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198309. #endif
  198310. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198311. if (info_ptr->valid & PNG_INFO_oFFs)
  198312. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198313. info_ptr->offset_unit_type);
  198314. #endif
  198315. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198316. if (info_ptr->valid & PNG_INFO_pCAL)
  198317. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198318. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198319. info_ptr->pcal_units, info_ptr->pcal_params);
  198320. #endif
  198321. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198322. if (info_ptr->valid & PNG_INFO_sCAL)
  198323. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198324. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198325. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198326. #else
  198327. #ifdef PNG_FIXED_POINT_SUPPORTED
  198328. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198329. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198330. #else
  198331. png_warning(png_ptr,
  198332. "png_write_sCAL not supported; sCAL chunk not written.");
  198333. #endif
  198334. #endif
  198335. #endif
  198336. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198337. if (info_ptr->valid & PNG_INFO_pHYs)
  198338. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198339. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198340. #endif
  198341. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198342. if (info_ptr->valid & PNG_INFO_tIME)
  198343. {
  198344. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198345. png_ptr->mode |= PNG_WROTE_tIME;
  198346. }
  198347. #endif
  198348. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198349. if (info_ptr->valid & PNG_INFO_sPLT)
  198350. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198351. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198352. #endif
  198353. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198354. /* Check to see if we need to write text chunks */
  198355. for (i = 0; i < info_ptr->num_text; i++)
  198356. {
  198357. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198358. info_ptr->text[i].compression);
  198359. /* an internationalized chunk? */
  198360. if (info_ptr->text[i].compression > 0)
  198361. {
  198362. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198363. /* write international chunk */
  198364. png_write_iTXt(png_ptr,
  198365. info_ptr->text[i].compression,
  198366. info_ptr->text[i].key,
  198367. info_ptr->text[i].lang,
  198368. info_ptr->text[i].lang_key,
  198369. info_ptr->text[i].text);
  198370. #else
  198371. png_warning(png_ptr, "Unable to write international text");
  198372. #endif
  198373. /* Mark this chunk as written */
  198374. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198375. }
  198376. /* If we want a compressed text chunk */
  198377. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198378. {
  198379. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198380. /* write compressed chunk */
  198381. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198382. info_ptr->text[i].text, 0,
  198383. info_ptr->text[i].compression);
  198384. #else
  198385. png_warning(png_ptr, "Unable to write compressed text");
  198386. #endif
  198387. /* Mark this chunk as written */
  198388. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198389. }
  198390. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198391. {
  198392. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198393. /* write uncompressed chunk */
  198394. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198395. info_ptr->text[i].text,
  198396. 0);
  198397. #else
  198398. png_warning(png_ptr, "Unable to write uncompressed text");
  198399. #endif
  198400. /* Mark this chunk as written */
  198401. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198402. }
  198403. }
  198404. #endif
  198405. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198406. if (info_ptr->unknown_chunks_num)
  198407. {
  198408. png_unknown_chunk *up;
  198409. png_debug(5, "writing extra chunks\n");
  198410. for (up = info_ptr->unknown_chunks;
  198411. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198412. up++)
  198413. {
  198414. int keep=png_handle_as_unknown(png_ptr, up->name);
  198415. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198416. up->location && (up->location & PNG_HAVE_PLTE) &&
  198417. !(up->location & PNG_HAVE_IDAT) &&
  198418. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198419. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198420. {
  198421. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198422. }
  198423. }
  198424. }
  198425. #endif
  198426. }
  198427. /* Writes the end of the PNG file. If you don't want to write comments or
  198428. * time information, you can pass NULL for info. If you already wrote these
  198429. * in png_write_info(), do not write them again here. If you have long
  198430. * comments, I suggest writing them here, and compressing them.
  198431. */
  198432. void PNGAPI
  198433. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198434. {
  198435. png_debug(1, "in png_write_end\n");
  198436. if (png_ptr == NULL)
  198437. return;
  198438. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198439. png_error(png_ptr, "No IDATs written into file");
  198440. /* see if user wants us to write information chunks */
  198441. if (info_ptr != NULL)
  198442. {
  198443. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198444. int i; /* local index variable */
  198445. #endif
  198446. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198447. /* check to see if user has supplied a time chunk */
  198448. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198449. !(png_ptr->mode & PNG_WROTE_tIME))
  198450. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198451. #endif
  198452. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198453. /* loop through comment chunks */
  198454. for (i = 0; i < info_ptr->num_text; i++)
  198455. {
  198456. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198457. info_ptr->text[i].compression);
  198458. /* an internationalized chunk? */
  198459. if (info_ptr->text[i].compression > 0)
  198460. {
  198461. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198462. /* write international chunk */
  198463. png_write_iTXt(png_ptr,
  198464. info_ptr->text[i].compression,
  198465. info_ptr->text[i].key,
  198466. info_ptr->text[i].lang,
  198467. info_ptr->text[i].lang_key,
  198468. info_ptr->text[i].text);
  198469. #else
  198470. png_warning(png_ptr, "Unable to write international text");
  198471. #endif
  198472. /* Mark this chunk as written */
  198473. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198474. }
  198475. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198476. {
  198477. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198478. /* write compressed chunk */
  198479. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198480. info_ptr->text[i].text, 0,
  198481. info_ptr->text[i].compression);
  198482. #else
  198483. png_warning(png_ptr, "Unable to write compressed text");
  198484. #endif
  198485. /* Mark this chunk as written */
  198486. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198487. }
  198488. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198489. {
  198490. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198491. /* write uncompressed chunk */
  198492. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198493. info_ptr->text[i].text, 0);
  198494. #else
  198495. png_warning(png_ptr, "Unable to write uncompressed text");
  198496. #endif
  198497. /* Mark this chunk as written */
  198498. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198499. }
  198500. }
  198501. #endif
  198502. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198503. if (info_ptr->unknown_chunks_num)
  198504. {
  198505. png_unknown_chunk *up;
  198506. png_debug(5, "writing extra chunks\n");
  198507. for (up = info_ptr->unknown_chunks;
  198508. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198509. up++)
  198510. {
  198511. int keep=png_handle_as_unknown(png_ptr, up->name);
  198512. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198513. up->location && (up->location & PNG_AFTER_IDAT) &&
  198514. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198515. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198516. {
  198517. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198518. }
  198519. }
  198520. }
  198521. #endif
  198522. }
  198523. png_ptr->mode |= PNG_AFTER_IDAT;
  198524. /* write end of PNG file */
  198525. png_write_IEND(png_ptr);
  198526. }
  198527. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198528. #if !defined(_WIN32_WCE)
  198529. /* "time.h" functions are not supported on WindowsCE */
  198530. void PNGAPI
  198531. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198532. {
  198533. png_debug(1, "in png_convert_from_struct_tm\n");
  198534. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198535. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198536. ptime->day = (png_byte)ttime->tm_mday;
  198537. ptime->hour = (png_byte)ttime->tm_hour;
  198538. ptime->minute = (png_byte)ttime->tm_min;
  198539. ptime->second = (png_byte)ttime->tm_sec;
  198540. }
  198541. void PNGAPI
  198542. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198543. {
  198544. struct tm *tbuf;
  198545. png_debug(1, "in png_convert_from_time_t\n");
  198546. tbuf = gmtime(&ttime);
  198547. png_convert_from_struct_tm(ptime, tbuf);
  198548. }
  198549. #endif
  198550. #endif
  198551. /* Initialize png_ptr structure, and allocate any memory needed */
  198552. png_structp PNGAPI
  198553. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198554. png_error_ptr error_fn, png_error_ptr warn_fn)
  198555. {
  198556. #ifdef PNG_USER_MEM_SUPPORTED
  198557. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198558. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198559. }
  198560. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198561. png_structp PNGAPI
  198562. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198563. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198564. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198565. {
  198566. #endif /* PNG_USER_MEM_SUPPORTED */
  198567. png_structp png_ptr;
  198568. #ifdef PNG_SETJMP_SUPPORTED
  198569. #ifdef USE_FAR_KEYWORD
  198570. jmp_buf jmpbuf;
  198571. #endif
  198572. #endif
  198573. int i;
  198574. png_debug(1, "in png_create_write_struct\n");
  198575. #ifdef PNG_USER_MEM_SUPPORTED
  198576. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198577. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198578. #else
  198579. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198580. #endif /* PNG_USER_MEM_SUPPORTED */
  198581. if (png_ptr == NULL)
  198582. return (NULL);
  198583. /* added at libpng-1.2.6 */
  198584. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198585. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198586. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198587. #endif
  198588. #ifdef PNG_SETJMP_SUPPORTED
  198589. #ifdef USE_FAR_KEYWORD
  198590. if (setjmp(jmpbuf))
  198591. #else
  198592. if (setjmp(png_ptr->jmpbuf))
  198593. #endif
  198594. {
  198595. png_free(png_ptr, png_ptr->zbuf);
  198596. png_ptr->zbuf=NULL;
  198597. png_destroy_struct(png_ptr);
  198598. return (NULL);
  198599. }
  198600. #ifdef USE_FAR_KEYWORD
  198601. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198602. #endif
  198603. #endif
  198604. #ifdef PNG_USER_MEM_SUPPORTED
  198605. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198606. #endif /* PNG_USER_MEM_SUPPORTED */
  198607. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198608. i=0;
  198609. do
  198610. {
  198611. if(user_png_ver[i] != png_libpng_ver[i])
  198612. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198613. } while (png_libpng_ver[i++]);
  198614. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198615. {
  198616. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198617. * we must recompile any applications that use any older library version.
  198618. * For versions after libpng 1.0, we will be compatible, so we need
  198619. * only check the first digit.
  198620. */
  198621. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198622. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198623. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198624. {
  198625. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198626. char msg[80];
  198627. if (user_png_ver)
  198628. {
  198629. png_snprintf(msg, 80,
  198630. "Application was compiled with png.h from libpng-%.20s",
  198631. user_png_ver);
  198632. png_warning(png_ptr, msg);
  198633. }
  198634. png_snprintf(msg, 80,
  198635. "Application is running with png.c from libpng-%.20s",
  198636. png_libpng_ver);
  198637. png_warning(png_ptr, msg);
  198638. #endif
  198639. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198640. png_ptr->flags=0;
  198641. #endif
  198642. png_error(png_ptr,
  198643. "Incompatible libpng version in application and library");
  198644. }
  198645. }
  198646. /* initialize zbuf - compression buffer */
  198647. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198648. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198649. (png_uint_32)png_ptr->zbuf_size);
  198650. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198651. png_flush_ptr_NULL);
  198652. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198653. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198654. 1, png_doublep_NULL, png_doublep_NULL);
  198655. #endif
  198656. #ifdef PNG_SETJMP_SUPPORTED
  198657. /* Applications that neglect to set up their own setjmp() and then encounter
  198658. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198659. abort instead of returning. */
  198660. #ifdef USE_FAR_KEYWORD
  198661. if (setjmp(jmpbuf))
  198662. PNG_ABORT();
  198663. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198664. #else
  198665. if (setjmp(png_ptr->jmpbuf))
  198666. PNG_ABORT();
  198667. #endif
  198668. #endif
  198669. return (png_ptr);
  198670. }
  198671. /* Initialize png_ptr structure, and allocate any memory needed */
  198672. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198673. /* Deprecated. */
  198674. #undef png_write_init
  198675. void PNGAPI
  198676. png_write_init(png_structp png_ptr)
  198677. {
  198678. /* We only come here via pre-1.0.7-compiled applications */
  198679. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198680. }
  198681. void PNGAPI
  198682. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198683. png_size_t png_struct_size, png_size_t png_info_size)
  198684. {
  198685. /* We only come here via pre-1.0.12-compiled applications */
  198686. if(png_ptr == NULL) return;
  198687. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198688. if(png_sizeof(png_struct) > png_struct_size ||
  198689. png_sizeof(png_info) > png_info_size)
  198690. {
  198691. char msg[80];
  198692. png_ptr->warning_fn=NULL;
  198693. if (user_png_ver)
  198694. {
  198695. png_snprintf(msg, 80,
  198696. "Application was compiled with png.h from libpng-%.20s",
  198697. user_png_ver);
  198698. png_warning(png_ptr, msg);
  198699. }
  198700. png_snprintf(msg, 80,
  198701. "Application is running with png.c from libpng-%.20s",
  198702. png_libpng_ver);
  198703. png_warning(png_ptr, msg);
  198704. }
  198705. #endif
  198706. if(png_sizeof(png_struct) > png_struct_size)
  198707. {
  198708. png_ptr->error_fn=NULL;
  198709. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198710. png_ptr->flags=0;
  198711. #endif
  198712. png_error(png_ptr,
  198713. "The png struct allocated by the application for writing is too small.");
  198714. }
  198715. if(png_sizeof(png_info) > png_info_size)
  198716. {
  198717. png_ptr->error_fn=NULL;
  198718. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198719. png_ptr->flags=0;
  198720. #endif
  198721. png_error(png_ptr,
  198722. "The info struct allocated by the application for writing is too small.");
  198723. }
  198724. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198725. }
  198726. #endif /* PNG_1_0_X || PNG_1_2_X */
  198727. void PNGAPI
  198728. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198729. png_size_t png_struct_size)
  198730. {
  198731. png_structp png_ptr=*ptr_ptr;
  198732. #ifdef PNG_SETJMP_SUPPORTED
  198733. jmp_buf tmp_jmp; /* to save current jump buffer */
  198734. #endif
  198735. int i = 0;
  198736. if (png_ptr == NULL)
  198737. return;
  198738. do
  198739. {
  198740. if (user_png_ver[i] != png_libpng_ver[i])
  198741. {
  198742. #ifdef PNG_LEGACY_SUPPORTED
  198743. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198744. #else
  198745. png_ptr->warning_fn=NULL;
  198746. png_warning(png_ptr,
  198747. "Application uses deprecated png_write_init() and should be recompiled.");
  198748. break;
  198749. #endif
  198750. }
  198751. } while (png_libpng_ver[i++]);
  198752. png_debug(1, "in png_write_init_3\n");
  198753. #ifdef PNG_SETJMP_SUPPORTED
  198754. /* save jump buffer and error functions */
  198755. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198756. #endif
  198757. if (png_sizeof(png_struct) > png_struct_size)
  198758. {
  198759. png_destroy_struct(png_ptr);
  198760. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198761. *ptr_ptr = png_ptr;
  198762. }
  198763. /* reset all variables to 0 */
  198764. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198765. /* added at libpng-1.2.6 */
  198766. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198767. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198768. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198769. #endif
  198770. #ifdef PNG_SETJMP_SUPPORTED
  198771. /* restore jump buffer */
  198772. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198773. #endif
  198774. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198775. png_flush_ptr_NULL);
  198776. /* initialize zbuf - compression buffer */
  198777. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198778. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198779. (png_uint_32)png_ptr->zbuf_size);
  198780. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198781. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198782. 1, png_doublep_NULL, png_doublep_NULL);
  198783. #endif
  198784. }
  198785. /* Write a few rows of image data. If the image is interlaced,
  198786. * either you will have to write the 7 sub images, or, if you
  198787. * have called png_set_interlace_handling(), you will have to
  198788. * "write" the image seven times.
  198789. */
  198790. void PNGAPI
  198791. png_write_rows(png_structp png_ptr, png_bytepp row,
  198792. png_uint_32 num_rows)
  198793. {
  198794. png_uint_32 i; /* row counter */
  198795. png_bytepp rp; /* row pointer */
  198796. png_debug(1, "in png_write_rows\n");
  198797. if (png_ptr == NULL)
  198798. return;
  198799. /* loop through the rows */
  198800. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198801. {
  198802. png_write_row(png_ptr, *rp);
  198803. }
  198804. }
  198805. /* Write the image. You only need to call this function once, even
  198806. * if you are writing an interlaced image.
  198807. */
  198808. void PNGAPI
  198809. png_write_image(png_structp png_ptr, png_bytepp image)
  198810. {
  198811. png_uint_32 i; /* row index */
  198812. int pass, num_pass; /* pass variables */
  198813. png_bytepp rp; /* points to current row */
  198814. if (png_ptr == NULL)
  198815. return;
  198816. png_debug(1, "in png_write_image\n");
  198817. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198818. /* intialize interlace handling. If image is not interlaced,
  198819. this will set pass to 1 */
  198820. num_pass = png_set_interlace_handling(png_ptr);
  198821. #else
  198822. num_pass = 1;
  198823. #endif
  198824. /* loop through passes */
  198825. for (pass = 0; pass < num_pass; pass++)
  198826. {
  198827. /* loop through image */
  198828. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  198829. {
  198830. png_write_row(png_ptr, *rp);
  198831. }
  198832. }
  198833. }
  198834. /* called by user to write a row of image data */
  198835. void PNGAPI
  198836. png_write_row(png_structp png_ptr, png_bytep row)
  198837. {
  198838. if (png_ptr == NULL)
  198839. return;
  198840. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  198841. png_ptr->row_number, png_ptr->pass);
  198842. /* initialize transformations and other stuff if first time */
  198843. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  198844. {
  198845. /* make sure we wrote the header info */
  198846. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198847. png_error(png_ptr,
  198848. "png_write_info was never called before png_write_row.");
  198849. /* check for transforms that have been set but were defined out */
  198850. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  198851. if (png_ptr->transformations & PNG_INVERT_MONO)
  198852. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  198853. #endif
  198854. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  198855. if (png_ptr->transformations & PNG_FILLER)
  198856. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  198857. #endif
  198858. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  198859. if (png_ptr->transformations & PNG_PACKSWAP)
  198860. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  198861. #endif
  198862. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  198863. if (png_ptr->transformations & PNG_PACK)
  198864. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  198865. #endif
  198866. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  198867. if (png_ptr->transformations & PNG_SHIFT)
  198868. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  198869. #endif
  198870. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  198871. if (png_ptr->transformations & PNG_BGR)
  198872. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  198873. #endif
  198874. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  198875. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198876. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  198877. #endif
  198878. png_write_start_row(png_ptr);
  198879. }
  198880. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198881. /* if interlaced and not interested in row, return */
  198882. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  198883. {
  198884. switch (png_ptr->pass)
  198885. {
  198886. case 0:
  198887. if (png_ptr->row_number & 0x07)
  198888. {
  198889. png_write_finish_row(png_ptr);
  198890. return;
  198891. }
  198892. break;
  198893. case 1:
  198894. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  198895. {
  198896. png_write_finish_row(png_ptr);
  198897. return;
  198898. }
  198899. break;
  198900. case 2:
  198901. if ((png_ptr->row_number & 0x07) != 4)
  198902. {
  198903. png_write_finish_row(png_ptr);
  198904. return;
  198905. }
  198906. break;
  198907. case 3:
  198908. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  198909. {
  198910. png_write_finish_row(png_ptr);
  198911. return;
  198912. }
  198913. break;
  198914. case 4:
  198915. if ((png_ptr->row_number & 0x03) != 2)
  198916. {
  198917. png_write_finish_row(png_ptr);
  198918. return;
  198919. }
  198920. break;
  198921. case 5:
  198922. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  198923. {
  198924. png_write_finish_row(png_ptr);
  198925. return;
  198926. }
  198927. break;
  198928. case 6:
  198929. if (!(png_ptr->row_number & 0x01))
  198930. {
  198931. png_write_finish_row(png_ptr);
  198932. return;
  198933. }
  198934. break;
  198935. }
  198936. }
  198937. #endif
  198938. /* set up row info for transformations */
  198939. png_ptr->row_info.color_type = png_ptr->color_type;
  198940. png_ptr->row_info.width = png_ptr->usr_width;
  198941. png_ptr->row_info.channels = png_ptr->usr_channels;
  198942. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  198943. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  198944. png_ptr->row_info.channels);
  198945. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  198946. png_ptr->row_info.width);
  198947. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  198948. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  198949. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  198950. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  198951. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  198952. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  198953. /* Copy user's row into buffer, leaving room for filter byte. */
  198954. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  198955. png_ptr->row_info.rowbytes);
  198956. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198957. /* handle interlacing */
  198958. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  198959. (png_ptr->transformations & PNG_INTERLACE))
  198960. {
  198961. png_do_write_interlace(&(png_ptr->row_info),
  198962. png_ptr->row_buf + 1, png_ptr->pass);
  198963. /* this should always get caught above, but still ... */
  198964. if (!(png_ptr->row_info.width))
  198965. {
  198966. png_write_finish_row(png_ptr);
  198967. return;
  198968. }
  198969. }
  198970. #endif
  198971. /* handle other transformations */
  198972. if (png_ptr->transformations)
  198973. png_do_write_transformations(png_ptr);
  198974. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198975. /* Write filter_method 64 (intrapixel differencing) only if
  198976. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198977. * 2. Libpng did not write a PNG signature (this filter_method is only
  198978. * used in PNG datastreams that are embedded in MNG datastreams) and
  198979. * 3. The application called png_permit_mng_features with a mask that
  198980. * included PNG_FLAG_MNG_FILTER_64 and
  198981. * 4. The filter_method is 64 and
  198982. * 5. The color_type is RGB or RGBA
  198983. */
  198984. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198985. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  198986. {
  198987. /* Intrapixel differencing */
  198988. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198989. }
  198990. #endif
  198991. /* Find a filter if necessary, filter the row and write it out. */
  198992. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  198993. if (png_ptr->write_row_fn != NULL)
  198994. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  198995. }
  198996. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198997. /* Set the automatic flush interval or 0 to turn flushing off */
  198998. void PNGAPI
  198999. png_set_flush(png_structp png_ptr, int nrows)
  199000. {
  199001. png_debug(1, "in png_set_flush\n");
  199002. if (png_ptr == NULL)
  199003. return;
  199004. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199005. }
  199006. /* flush the current output buffers now */
  199007. void PNGAPI
  199008. png_write_flush(png_structp png_ptr)
  199009. {
  199010. int wrote_IDAT;
  199011. png_debug(1, "in png_write_flush\n");
  199012. if (png_ptr == NULL)
  199013. return;
  199014. /* We have already written out all of the data */
  199015. if (png_ptr->row_number >= png_ptr->num_rows)
  199016. return;
  199017. do
  199018. {
  199019. int ret;
  199020. /* compress the data */
  199021. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199022. wrote_IDAT = 0;
  199023. /* check for compression errors */
  199024. if (ret != Z_OK)
  199025. {
  199026. if (png_ptr->zstream.msg != NULL)
  199027. png_error(png_ptr, png_ptr->zstream.msg);
  199028. else
  199029. png_error(png_ptr, "zlib error");
  199030. }
  199031. if (!(png_ptr->zstream.avail_out))
  199032. {
  199033. /* write the IDAT and reset the zlib output buffer */
  199034. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199035. png_ptr->zbuf_size);
  199036. png_ptr->zstream.next_out = png_ptr->zbuf;
  199037. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199038. wrote_IDAT = 1;
  199039. }
  199040. } while(wrote_IDAT == 1);
  199041. /* If there is any data left to be output, write it into a new IDAT */
  199042. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199043. {
  199044. /* write the IDAT and reset the zlib output buffer */
  199045. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199046. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199047. png_ptr->zstream.next_out = png_ptr->zbuf;
  199048. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199049. }
  199050. png_ptr->flush_rows = 0;
  199051. png_flush(png_ptr);
  199052. }
  199053. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199054. /* free all memory used by the write */
  199055. void PNGAPI
  199056. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199057. {
  199058. png_structp png_ptr = NULL;
  199059. png_infop info_ptr = NULL;
  199060. #ifdef PNG_USER_MEM_SUPPORTED
  199061. png_free_ptr free_fn = NULL;
  199062. png_voidp mem_ptr = NULL;
  199063. #endif
  199064. png_debug(1, "in png_destroy_write_struct\n");
  199065. if (png_ptr_ptr != NULL)
  199066. {
  199067. png_ptr = *png_ptr_ptr;
  199068. #ifdef PNG_USER_MEM_SUPPORTED
  199069. free_fn = png_ptr->free_fn;
  199070. mem_ptr = png_ptr->mem_ptr;
  199071. #endif
  199072. }
  199073. if (info_ptr_ptr != NULL)
  199074. info_ptr = *info_ptr_ptr;
  199075. if (info_ptr != NULL)
  199076. {
  199077. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199078. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199079. if (png_ptr->num_chunk_list)
  199080. {
  199081. png_free(png_ptr, png_ptr->chunk_list);
  199082. png_ptr->chunk_list=NULL;
  199083. png_ptr->num_chunk_list=0;
  199084. }
  199085. #endif
  199086. #ifdef PNG_USER_MEM_SUPPORTED
  199087. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199088. (png_voidp)mem_ptr);
  199089. #else
  199090. png_destroy_struct((png_voidp)info_ptr);
  199091. #endif
  199092. *info_ptr_ptr = NULL;
  199093. }
  199094. if (png_ptr != NULL)
  199095. {
  199096. png_write_destroy(png_ptr);
  199097. #ifdef PNG_USER_MEM_SUPPORTED
  199098. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199099. (png_voidp)mem_ptr);
  199100. #else
  199101. png_destroy_struct((png_voidp)png_ptr);
  199102. #endif
  199103. *png_ptr_ptr = NULL;
  199104. }
  199105. }
  199106. /* Free any memory used in png_ptr struct (old method) */
  199107. void /* PRIVATE */
  199108. png_write_destroy(png_structp png_ptr)
  199109. {
  199110. #ifdef PNG_SETJMP_SUPPORTED
  199111. jmp_buf tmp_jmp; /* save jump buffer */
  199112. #endif
  199113. png_error_ptr error_fn;
  199114. png_error_ptr warning_fn;
  199115. png_voidp error_ptr;
  199116. #ifdef PNG_USER_MEM_SUPPORTED
  199117. png_free_ptr free_fn;
  199118. #endif
  199119. png_debug(1, "in png_write_destroy\n");
  199120. /* free any memory zlib uses */
  199121. deflateEnd(&png_ptr->zstream);
  199122. /* free our memory. png_free checks NULL for us. */
  199123. png_free(png_ptr, png_ptr->zbuf);
  199124. png_free(png_ptr, png_ptr->row_buf);
  199125. png_free(png_ptr, png_ptr->prev_row);
  199126. png_free(png_ptr, png_ptr->sub_row);
  199127. png_free(png_ptr, png_ptr->up_row);
  199128. png_free(png_ptr, png_ptr->avg_row);
  199129. png_free(png_ptr, png_ptr->paeth_row);
  199130. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199131. png_free(png_ptr, png_ptr->time_buffer);
  199132. #endif
  199133. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199134. png_free(png_ptr, png_ptr->prev_filters);
  199135. png_free(png_ptr, png_ptr->filter_weights);
  199136. png_free(png_ptr, png_ptr->inv_filter_weights);
  199137. png_free(png_ptr, png_ptr->filter_costs);
  199138. png_free(png_ptr, png_ptr->inv_filter_costs);
  199139. #endif
  199140. #ifdef PNG_SETJMP_SUPPORTED
  199141. /* reset structure */
  199142. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199143. #endif
  199144. error_fn = png_ptr->error_fn;
  199145. warning_fn = png_ptr->warning_fn;
  199146. error_ptr = png_ptr->error_ptr;
  199147. #ifdef PNG_USER_MEM_SUPPORTED
  199148. free_fn = png_ptr->free_fn;
  199149. #endif
  199150. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199151. png_ptr->error_fn = error_fn;
  199152. png_ptr->warning_fn = warning_fn;
  199153. png_ptr->error_ptr = error_ptr;
  199154. #ifdef PNG_USER_MEM_SUPPORTED
  199155. png_ptr->free_fn = free_fn;
  199156. #endif
  199157. #ifdef PNG_SETJMP_SUPPORTED
  199158. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199159. #endif
  199160. }
  199161. /* Allow the application to select one or more row filters to use. */
  199162. void PNGAPI
  199163. png_set_filter(png_structp png_ptr, int method, int filters)
  199164. {
  199165. png_debug(1, "in png_set_filter\n");
  199166. if (png_ptr == NULL)
  199167. return;
  199168. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199169. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199170. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199171. method = PNG_FILTER_TYPE_BASE;
  199172. #endif
  199173. if (method == PNG_FILTER_TYPE_BASE)
  199174. {
  199175. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199176. {
  199177. #ifndef PNG_NO_WRITE_FILTER
  199178. case 5:
  199179. case 6:
  199180. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199181. #endif /* PNG_NO_WRITE_FILTER */
  199182. case PNG_FILTER_VALUE_NONE:
  199183. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199184. #ifndef PNG_NO_WRITE_FILTER
  199185. case PNG_FILTER_VALUE_SUB:
  199186. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199187. case PNG_FILTER_VALUE_UP:
  199188. png_ptr->do_filter=PNG_FILTER_UP; break;
  199189. case PNG_FILTER_VALUE_AVG:
  199190. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199191. case PNG_FILTER_VALUE_PAETH:
  199192. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199193. default: png_ptr->do_filter = (png_byte)filters; break;
  199194. #else
  199195. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199196. #endif /* PNG_NO_WRITE_FILTER */
  199197. }
  199198. /* If we have allocated the row_buf, this means we have already started
  199199. * with the image and we should have allocated all of the filter buffers
  199200. * that have been selected. If prev_row isn't already allocated, then
  199201. * it is too late to start using the filters that need it, since we
  199202. * will be missing the data in the previous row. If an application
  199203. * wants to start and stop using particular filters during compression,
  199204. * it should start out with all of the filters, and then add and
  199205. * remove them after the start of compression.
  199206. */
  199207. if (png_ptr->row_buf != NULL)
  199208. {
  199209. #ifndef PNG_NO_WRITE_FILTER
  199210. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199211. {
  199212. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199213. (png_ptr->rowbytes + 1));
  199214. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199215. }
  199216. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199217. {
  199218. if (png_ptr->prev_row == NULL)
  199219. {
  199220. png_warning(png_ptr, "Can't add Up filter after starting");
  199221. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199222. }
  199223. else
  199224. {
  199225. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199226. (png_ptr->rowbytes + 1));
  199227. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199228. }
  199229. }
  199230. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199231. {
  199232. if (png_ptr->prev_row == NULL)
  199233. {
  199234. png_warning(png_ptr, "Can't add Average filter after starting");
  199235. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199236. }
  199237. else
  199238. {
  199239. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199240. (png_ptr->rowbytes + 1));
  199241. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199242. }
  199243. }
  199244. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199245. png_ptr->paeth_row == NULL)
  199246. {
  199247. if (png_ptr->prev_row == NULL)
  199248. {
  199249. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199250. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199251. }
  199252. else
  199253. {
  199254. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199255. (png_ptr->rowbytes + 1));
  199256. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199257. }
  199258. }
  199259. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199260. #endif /* PNG_NO_WRITE_FILTER */
  199261. png_ptr->do_filter = PNG_FILTER_NONE;
  199262. }
  199263. }
  199264. else
  199265. png_error(png_ptr, "Unknown custom filter method");
  199266. }
  199267. /* This allows us to influence the way in which libpng chooses the "best"
  199268. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199269. * differences metric is relatively fast and effective, there is some
  199270. * question as to whether it can be improved upon by trying to keep the
  199271. * filtered data going to zlib more consistent, hopefully resulting in
  199272. * better compression.
  199273. */
  199274. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199275. void PNGAPI
  199276. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199277. int num_weights, png_doublep filter_weights,
  199278. png_doublep filter_costs)
  199279. {
  199280. int i;
  199281. png_debug(1, "in png_set_filter_heuristics\n");
  199282. if (png_ptr == NULL)
  199283. return;
  199284. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199285. {
  199286. png_warning(png_ptr, "Unknown filter heuristic method");
  199287. return;
  199288. }
  199289. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199290. {
  199291. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199292. }
  199293. if (num_weights < 0 || filter_weights == NULL ||
  199294. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199295. {
  199296. num_weights = 0;
  199297. }
  199298. png_ptr->num_prev_filters = (png_byte)num_weights;
  199299. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199300. if (num_weights > 0)
  199301. {
  199302. if (png_ptr->prev_filters == NULL)
  199303. {
  199304. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199305. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199306. /* To make sure that the weighting starts out fairly */
  199307. for (i = 0; i < num_weights; i++)
  199308. {
  199309. png_ptr->prev_filters[i] = 255;
  199310. }
  199311. }
  199312. if (png_ptr->filter_weights == NULL)
  199313. {
  199314. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199315. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199316. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199317. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199318. for (i = 0; i < num_weights; i++)
  199319. {
  199320. png_ptr->inv_filter_weights[i] =
  199321. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199322. }
  199323. }
  199324. for (i = 0; i < num_weights; i++)
  199325. {
  199326. if (filter_weights[i] < 0.0)
  199327. {
  199328. png_ptr->inv_filter_weights[i] =
  199329. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199330. }
  199331. else
  199332. {
  199333. png_ptr->inv_filter_weights[i] =
  199334. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199335. png_ptr->filter_weights[i] =
  199336. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199337. }
  199338. }
  199339. }
  199340. /* If, in the future, there are other filter methods, this would
  199341. * need to be based on png_ptr->filter.
  199342. */
  199343. if (png_ptr->filter_costs == NULL)
  199344. {
  199345. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199346. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199347. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199348. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199349. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199350. {
  199351. png_ptr->inv_filter_costs[i] =
  199352. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199353. }
  199354. }
  199355. /* Here is where we set the relative costs of the different filters. We
  199356. * should take the desired compression level into account when setting
  199357. * the costs, so that Paeth, for instance, has a high relative cost at low
  199358. * compression levels, while it has a lower relative cost at higher
  199359. * compression settings. The filter types are in order of increasing
  199360. * relative cost, so it would be possible to do this with an algorithm.
  199361. */
  199362. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199363. {
  199364. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199365. {
  199366. png_ptr->inv_filter_costs[i] =
  199367. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199368. }
  199369. else if (filter_costs[i] >= 1.0)
  199370. {
  199371. png_ptr->inv_filter_costs[i] =
  199372. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199373. png_ptr->filter_costs[i] =
  199374. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199375. }
  199376. }
  199377. }
  199378. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199379. void PNGAPI
  199380. png_set_compression_level(png_structp png_ptr, int level)
  199381. {
  199382. png_debug(1, "in png_set_compression_level\n");
  199383. if (png_ptr == NULL)
  199384. return;
  199385. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199386. png_ptr->zlib_level = level;
  199387. }
  199388. void PNGAPI
  199389. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199390. {
  199391. png_debug(1, "in png_set_compression_mem_level\n");
  199392. if (png_ptr == NULL)
  199393. return;
  199394. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199395. png_ptr->zlib_mem_level = mem_level;
  199396. }
  199397. void PNGAPI
  199398. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199399. {
  199400. png_debug(1, "in png_set_compression_strategy\n");
  199401. if (png_ptr == NULL)
  199402. return;
  199403. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199404. png_ptr->zlib_strategy = strategy;
  199405. }
  199406. void PNGAPI
  199407. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199408. {
  199409. if (png_ptr == NULL)
  199410. return;
  199411. if (window_bits > 15)
  199412. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199413. else if (window_bits < 8)
  199414. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199415. #ifndef WBITS_8_OK
  199416. /* avoid libpng bug with 256-byte windows */
  199417. if (window_bits == 8)
  199418. {
  199419. png_warning(png_ptr, "Compression window is being reset to 512");
  199420. window_bits=9;
  199421. }
  199422. #endif
  199423. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199424. png_ptr->zlib_window_bits = window_bits;
  199425. }
  199426. void PNGAPI
  199427. png_set_compression_method(png_structp png_ptr, int method)
  199428. {
  199429. png_debug(1, "in png_set_compression_method\n");
  199430. if (png_ptr == NULL)
  199431. return;
  199432. if (method != 8)
  199433. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199434. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199435. png_ptr->zlib_method = method;
  199436. }
  199437. void PNGAPI
  199438. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199439. {
  199440. if (png_ptr == NULL)
  199441. return;
  199442. png_ptr->write_row_fn = write_row_fn;
  199443. }
  199444. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199445. void PNGAPI
  199446. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199447. write_user_transform_fn)
  199448. {
  199449. png_debug(1, "in png_set_write_user_transform_fn\n");
  199450. if (png_ptr == NULL)
  199451. return;
  199452. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199453. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199454. }
  199455. #endif
  199456. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199457. void PNGAPI
  199458. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199459. int transforms, voidp params)
  199460. {
  199461. if (png_ptr == NULL || info_ptr == NULL)
  199462. return;
  199463. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199464. /* invert the alpha channel from opacity to transparency */
  199465. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199466. png_set_invert_alpha(png_ptr);
  199467. #endif
  199468. /* Write the file header information. */
  199469. png_write_info(png_ptr, info_ptr);
  199470. /* ------ these transformations don't touch the info structure ------- */
  199471. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199472. /* invert monochrome pixels */
  199473. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199474. png_set_invert_mono(png_ptr);
  199475. #endif
  199476. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199477. /* Shift the pixels up to a legal bit depth and fill in
  199478. * as appropriate to correctly scale the image.
  199479. */
  199480. if ((transforms & PNG_TRANSFORM_SHIFT)
  199481. && (info_ptr->valid & PNG_INFO_sBIT))
  199482. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199483. #endif
  199484. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199485. /* pack pixels into bytes */
  199486. if (transforms & PNG_TRANSFORM_PACKING)
  199487. png_set_packing(png_ptr);
  199488. #endif
  199489. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199490. /* swap location of alpha bytes from ARGB to RGBA */
  199491. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199492. png_set_swap_alpha(png_ptr);
  199493. #endif
  199494. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199495. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199496. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199497. */
  199498. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199499. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199500. #endif
  199501. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199502. /* flip BGR pixels to RGB */
  199503. if (transforms & PNG_TRANSFORM_BGR)
  199504. png_set_bgr(png_ptr);
  199505. #endif
  199506. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199507. /* swap bytes of 16-bit files to most significant byte first */
  199508. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199509. png_set_swap(png_ptr);
  199510. #endif
  199511. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199512. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199513. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199514. png_set_packswap(png_ptr);
  199515. #endif
  199516. /* ----------------------- end of transformations ------------------- */
  199517. /* write the bits */
  199518. if (info_ptr->valid & PNG_INFO_IDAT)
  199519. png_write_image(png_ptr, info_ptr->row_pointers);
  199520. /* It is REQUIRED to call this to finish writing the rest of the file */
  199521. png_write_end(png_ptr, info_ptr);
  199522. transforms = transforms; /* quiet compiler warnings */
  199523. params = params;
  199524. }
  199525. #endif
  199526. #endif /* PNG_WRITE_SUPPORTED */
  199527. /*** End of inlined file: pngwrite.c ***/
  199528. /*** Start of inlined file: pngwtran.c ***/
  199529. /* pngwtran.c - transforms the data in a row for PNG writers
  199530. *
  199531. * Last changed in libpng 1.2.9 April 14, 2006
  199532. * For conditions of distribution and use, see copyright notice in png.h
  199533. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199534. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199535. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199536. */
  199537. #define PNG_INTERNAL
  199538. #ifdef PNG_WRITE_SUPPORTED
  199539. /* Transform the data according to the user's wishes. The order of
  199540. * transformations is significant.
  199541. */
  199542. void /* PRIVATE */
  199543. png_do_write_transformations(png_structp png_ptr)
  199544. {
  199545. png_debug(1, "in png_do_write_transformations\n");
  199546. if (png_ptr == NULL)
  199547. return;
  199548. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199549. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199550. if(png_ptr->write_user_transform_fn != NULL)
  199551. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199552. (png_ptr, /* png_ptr */
  199553. &(png_ptr->row_info), /* row_info: */
  199554. /* png_uint_32 width; width of row */
  199555. /* png_uint_32 rowbytes; number of bytes in row */
  199556. /* png_byte color_type; color type of pixels */
  199557. /* png_byte bit_depth; bit depth of samples */
  199558. /* png_byte channels; number of channels (1-4) */
  199559. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199560. png_ptr->row_buf + 1); /* start of pixel data for row */
  199561. #endif
  199562. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199563. if (png_ptr->transformations & PNG_FILLER)
  199564. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199565. png_ptr->flags);
  199566. #endif
  199567. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199568. if (png_ptr->transformations & PNG_PACKSWAP)
  199569. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199570. #endif
  199571. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199572. if (png_ptr->transformations & PNG_PACK)
  199573. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199574. (png_uint_32)png_ptr->bit_depth);
  199575. #endif
  199576. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199577. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199578. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199579. #endif
  199580. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199581. if (png_ptr->transformations & PNG_SHIFT)
  199582. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199583. &(png_ptr->shift));
  199584. #endif
  199585. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199586. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199587. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199588. #endif
  199589. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199590. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199591. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199592. #endif
  199593. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199594. if (png_ptr->transformations & PNG_BGR)
  199595. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199596. #endif
  199597. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199598. if (png_ptr->transformations & PNG_INVERT_MONO)
  199599. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199600. #endif
  199601. }
  199602. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199603. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199604. * row_info bit depth should be 8 (one pixel per byte). The channels
  199605. * should be 1 (this only happens on grayscale and paletted images).
  199606. */
  199607. void /* PRIVATE */
  199608. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199609. {
  199610. png_debug(1, "in png_do_pack\n");
  199611. if (row_info->bit_depth == 8 &&
  199612. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199613. row != NULL && row_info != NULL &&
  199614. #endif
  199615. row_info->channels == 1)
  199616. {
  199617. switch ((int)bit_depth)
  199618. {
  199619. case 1:
  199620. {
  199621. png_bytep sp, dp;
  199622. int mask, v;
  199623. png_uint_32 i;
  199624. png_uint_32 row_width = row_info->width;
  199625. sp = row;
  199626. dp = row;
  199627. mask = 0x80;
  199628. v = 0;
  199629. for (i = 0; i < row_width; i++)
  199630. {
  199631. if (*sp != 0)
  199632. v |= mask;
  199633. sp++;
  199634. if (mask > 1)
  199635. mask >>= 1;
  199636. else
  199637. {
  199638. mask = 0x80;
  199639. *dp = (png_byte)v;
  199640. dp++;
  199641. v = 0;
  199642. }
  199643. }
  199644. if (mask != 0x80)
  199645. *dp = (png_byte)v;
  199646. break;
  199647. }
  199648. case 2:
  199649. {
  199650. png_bytep sp, dp;
  199651. int shift, v;
  199652. png_uint_32 i;
  199653. png_uint_32 row_width = row_info->width;
  199654. sp = row;
  199655. dp = row;
  199656. shift = 6;
  199657. v = 0;
  199658. for (i = 0; i < row_width; i++)
  199659. {
  199660. png_byte value;
  199661. value = (png_byte)(*sp & 0x03);
  199662. v |= (value << shift);
  199663. if (shift == 0)
  199664. {
  199665. shift = 6;
  199666. *dp = (png_byte)v;
  199667. dp++;
  199668. v = 0;
  199669. }
  199670. else
  199671. shift -= 2;
  199672. sp++;
  199673. }
  199674. if (shift != 6)
  199675. *dp = (png_byte)v;
  199676. break;
  199677. }
  199678. case 4:
  199679. {
  199680. png_bytep sp, dp;
  199681. int shift, v;
  199682. png_uint_32 i;
  199683. png_uint_32 row_width = row_info->width;
  199684. sp = row;
  199685. dp = row;
  199686. shift = 4;
  199687. v = 0;
  199688. for (i = 0; i < row_width; i++)
  199689. {
  199690. png_byte value;
  199691. value = (png_byte)(*sp & 0x0f);
  199692. v |= (value << shift);
  199693. if (shift == 0)
  199694. {
  199695. shift = 4;
  199696. *dp = (png_byte)v;
  199697. dp++;
  199698. v = 0;
  199699. }
  199700. else
  199701. shift -= 4;
  199702. sp++;
  199703. }
  199704. if (shift != 4)
  199705. *dp = (png_byte)v;
  199706. break;
  199707. }
  199708. }
  199709. row_info->bit_depth = (png_byte)bit_depth;
  199710. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199711. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199712. row_info->width);
  199713. }
  199714. }
  199715. #endif
  199716. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199717. /* Shift pixel values to take advantage of whole range. Pass the
  199718. * true number of bits in bit_depth. The row should be packed
  199719. * according to row_info->bit_depth. Thus, if you had a row of
  199720. * bit depth 4, but the pixels only had values from 0 to 7, you
  199721. * would pass 3 as bit_depth, and this routine would translate the
  199722. * data to 0 to 15.
  199723. */
  199724. void /* PRIVATE */
  199725. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199726. {
  199727. png_debug(1, "in png_do_shift\n");
  199728. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199729. if (row != NULL && row_info != NULL &&
  199730. #else
  199731. if (
  199732. #endif
  199733. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199734. {
  199735. int shift_start[4], shift_dec[4];
  199736. int channels = 0;
  199737. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199738. {
  199739. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199740. shift_dec[channels] = bit_depth->red;
  199741. channels++;
  199742. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199743. shift_dec[channels] = bit_depth->green;
  199744. channels++;
  199745. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199746. shift_dec[channels] = bit_depth->blue;
  199747. channels++;
  199748. }
  199749. else
  199750. {
  199751. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199752. shift_dec[channels] = bit_depth->gray;
  199753. channels++;
  199754. }
  199755. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199756. {
  199757. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199758. shift_dec[channels] = bit_depth->alpha;
  199759. channels++;
  199760. }
  199761. /* with low row depths, could only be grayscale, so one channel */
  199762. if (row_info->bit_depth < 8)
  199763. {
  199764. png_bytep bp = row;
  199765. png_uint_32 i;
  199766. png_byte mask;
  199767. png_uint_32 row_bytes = row_info->rowbytes;
  199768. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199769. mask = 0x55;
  199770. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199771. mask = 0x11;
  199772. else
  199773. mask = 0xff;
  199774. for (i = 0; i < row_bytes; i++, bp++)
  199775. {
  199776. png_uint_16 v;
  199777. int j;
  199778. v = *bp;
  199779. *bp = 0;
  199780. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199781. {
  199782. if (j > 0)
  199783. *bp |= (png_byte)((v << j) & 0xff);
  199784. else
  199785. *bp |= (png_byte)((v >> (-j)) & mask);
  199786. }
  199787. }
  199788. }
  199789. else if (row_info->bit_depth == 8)
  199790. {
  199791. png_bytep bp = row;
  199792. png_uint_32 i;
  199793. png_uint_32 istop = channels * row_info->width;
  199794. for (i = 0; i < istop; i++, bp++)
  199795. {
  199796. png_uint_16 v;
  199797. int j;
  199798. int c = (int)(i%channels);
  199799. v = *bp;
  199800. *bp = 0;
  199801. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199802. {
  199803. if (j > 0)
  199804. *bp |= (png_byte)((v << j) & 0xff);
  199805. else
  199806. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199807. }
  199808. }
  199809. }
  199810. else
  199811. {
  199812. png_bytep bp;
  199813. png_uint_32 i;
  199814. png_uint_32 istop = channels * row_info->width;
  199815. for (bp = row, i = 0; i < istop; i++)
  199816. {
  199817. int c = (int)(i%channels);
  199818. png_uint_16 value, v;
  199819. int j;
  199820. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  199821. value = 0;
  199822. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199823. {
  199824. if (j > 0)
  199825. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  199826. else
  199827. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  199828. }
  199829. *bp++ = (png_byte)(value >> 8);
  199830. *bp++ = (png_byte)(value & 0xff);
  199831. }
  199832. }
  199833. }
  199834. }
  199835. #endif
  199836. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199837. void /* PRIVATE */
  199838. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  199839. {
  199840. png_debug(1, "in png_do_write_swap_alpha\n");
  199841. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199842. if (row != NULL && row_info != NULL)
  199843. #endif
  199844. {
  199845. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199846. {
  199847. /* This converts from ARGB to RGBA */
  199848. if (row_info->bit_depth == 8)
  199849. {
  199850. png_bytep sp, dp;
  199851. png_uint_32 i;
  199852. png_uint_32 row_width = row_info->width;
  199853. for (i = 0, sp = dp = row; i < row_width; i++)
  199854. {
  199855. png_byte save = *(sp++);
  199856. *(dp++) = *(sp++);
  199857. *(dp++) = *(sp++);
  199858. *(dp++) = *(sp++);
  199859. *(dp++) = save;
  199860. }
  199861. }
  199862. /* This converts from AARRGGBB to RRGGBBAA */
  199863. else
  199864. {
  199865. png_bytep sp, dp;
  199866. png_uint_32 i;
  199867. png_uint_32 row_width = row_info->width;
  199868. for (i = 0, sp = dp = row; i < row_width; i++)
  199869. {
  199870. png_byte save[2];
  199871. save[0] = *(sp++);
  199872. save[1] = *(sp++);
  199873. *(dp++) = *(sp++);
  199874. *(dp++) = *(sp++);
  199875. *(dp++) = *(sp++);
  199876. *(dp++) = *(sp++);
  199877. *(dp++) = *(sp++);
  199878. *(dp++) = *(sp++);
  199879. *(dp++) = save[0];
  199880. *(dp++) = save[1];
  199881. }
  199882. }
  199883. }
  199884. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199885. {
  199886. /* This converts from AG to GA */
  199887. if (row_info->bit_depth == 8)
  199888. {
  199889. png_bytep sp, dp;
  199890. png_uint_32 i;
  199891. png_uint_32 row_width = row_info->width;
  199892. for (i = 0, sp = dp = row; i < row_width; i++)
  199893. {
  199894. png_byte save = *(sp++);
  199895. *(dp++) = *(sp++);
  199896. *(dp++) = save;
  199897. }
  199898. }
  199899. /* This converts from AAGG to GGAA */
  199900. else
  199901. {
  199902. png_bytep sp, dp;
  199903. png_uint_32 i;
  199904. png_uint_32 row_width = row_info->width;
  199905. for (i = 0, sp = dp = row; i < row_width; i++)
  199906. {
  199907. png_byte save[2];
  199908. save[0] = *(sp++);
  199909. save[1] = *(sp++);
  199910. *(dp++) = *(sp++);
  199911. *(dp++) = *(sp++);
  199912. *(dp++) = save[0];
  199913. *(dp++) = save[1];
  199914. }
  199915. }
  199916. }
  199917. }
  199918. }
  199919. #endif
  199920. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199921. void /* PRIVATE */
  199922. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  199923. {
  199924. png_debug(1, "in png_do_write_invert_alpha\n");
  199925. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199926. if (row != NULL && row_info != NULL)
  199927. #endif
  199928. {
  199929. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199930. {
  199931. /* This inverts the alpha channel in RGBA */
  199932. if (row_info->bit_depth == 8)
  199933. {
  199934. png_bytep sp, dp;
  199935. png_uint_32 i;
  199936. png_uint_32 row_width = row_info->width;
  199937. for (i = 0, sp = dp = row; i < row_width; i++)
  199938. {
  199939. /* does nothing
  199940. *(dp++) = *(sp++);
  199941. *(dp++) = *(sp++);
  199942. *(dp++) = *(sp++);
  199943. */
  199944. sp+=3; dp = sp;
  199945. *(dp++) = (png_byte)(255 - *(sp++));
  199946. }
  199947. }
  199948. /* This inverts the alpha channel in RRGGBBAA */
  199949. else
  199950. {
  199951. png_bytep sp, dp;
  199952. png_uint_32 i;
  199953. png_uint_32 row_width = row_info->width;
  199954. for (i = 0, sp = dp = row; i < row_width; i++)
  199955. {
  199956. /* does nothing
  199957. *(dp++) = *(sp++);
  199958. *(dp++) = *(sp++);
  199959. *(dp++) = *(sp++);
  199960. *(dp++) = *(sp++);
  199961. *(dp++) = *(sp++);
  199962. *(dp++) = *(sp++);
  199963. */
  199964. sp+=6; dp = sp;
  199965. *(dp++) = (png_byte)(255 - *(sp++));
  199966. *(dp++) = (png_byte)(255 - *(sp++));
  199967. }
  199968. }
  199969. }
  199970. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199971. {
  199972. /* This inverts the alpha channel in GA */
  199973. if (row_info->bit_depth == 8)
  199974. {
  199975. png_bytep sp, dp;
  199976. png_uint_32 i;
  199977. png_uint_32 row_width = row_info->width;
  199978. for (i = 0, sp = dp = row; i < row_width; i++)
  199979. {
  199980. *(dp++) = *(sp++);
  199981. *(dp++) = (png_byte)(255 - *(sp++));
  199982. }
  199983. }
  199984. /* This inverts the alpha channel in GGAA */
  199985. else
  199986. {
  199987. png_bytep sp, dp;
  199988. png_uint_32 i;
  199989. png_uint_32 row_width = row_info->width;
  199990. for (i = 0, sp = dp = row; i < row_width; i++)
  199991. {
  199992. /* does nothing
  199993. *(dp++) = *(sp++);
  199994. *(dp++) = *(sp++);
  199995. */
  199996. sp+=2; dp = sp;
  199997. *(dp++) = (png_byte)(255 - *(sp++));
  199998. *(dp++) = (png_byte)(255 - *(sp++));
  199999. }
  200000. }
  200001. }
  200002. }
  200003. }
  200004. #endif
  200005. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200006. /* undoes intrapixel differencing */
  200007. void /* PRIVATE */
  200008. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200009. {
  200010. png_debug(1, "in png_do_write_intrapixel\n");
  200011. if (
  200012. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200013. row != NULL && row_info != NULL &&
  200014. #endif
  200015. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200016. {
  200017. int bytes_per_pixel;
  200018. png_uint_32 row_width = row_info->width;
  200019. if (row_info->bit_depth == 8)
  200020. {
  200021. png_bytep rp;
  200022. png_uint_32 i;
  200023. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200024. bytes_per_pixel = 3;
  200025. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200026. bytes_per_pixel = 4;
  200027. else
  200028. return;
  200029. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200030. {
  200031. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200032. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200033. }
  200034. }
  200035. else if (row_info->bit_depth == 16)
  200036. {
  200037. png_bytep rp;
  200038. png_uint_32 i;
  200039. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200040. bytes_per_pixel = 6;
  200041. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200042. bytes_per_pixel = 8;
  200043. else
  200044. return;
  200045. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200046. {
  200047. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200048. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200049. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200050. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200051. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200052. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200053. *(rp+1) = (png_byte)(red & 0xff);
  200054. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200055. *(rp+5) = (png_byte)(blue & 0xff);
  200056. }
  200057. }
  200058. }
  200059. }
  200060. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200061. #endif /* PNG_WRITE_SUPPORTED */
  200062. /*** End of inlined file: pngwtran.c ***/
  200063. /*** Start of inlined file: pngwutil.c ***/
  200064. /* pngwutil.c - utilities to write a PNG file
  200065. *
  200066. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200067. * For conditions of distribution and use, see copyright notice in png.h
  200068. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200069. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200070. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200071. */
  200072. #define PNG_INTERNAL
  200073. #ifdef PNG_WRITE_SUPPORTED
  200074. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200075. * with unsigned numbers for convenience, although one supported
  200076. * ancillary chunk uses signed (two's complement) numbers.
  200077. */
  200078. void PNGAPI
  200079. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200080. {
  200081. buf[0] = (png_byte)((i >> 24) & 0xff);
  200082. buf[1] = (png_byte)((i >> 16) & 0xff);
  200083. buf[2] = (png_byte)((i >> 8) & 0xff);
  200084. buf[3] = (png_byte)(i & 0xff);
  200085. }
  200086. /* The png_save_int_32 function assumes integers are stored in two's
  200087. * complement format. If this isn't the case, then this routine needs to
  200088. * be modified to write data in two's complement format.
  200089. */
  200090. void PNGAPI
  200091. png_save_int_32(png_bytep buf, png_int_32 i)
  200092. {
  200093. buf[0] = (png_byte)((i >> 24) & 0xff);
  200094. buf[1] = (png_byte)((i >> 16) & 0xff);
  200095. buf[2] = (png_byte)((i >> 8) & 0xff);
  200096. buf[3] = (png_byte)(i & 0xff);
  200097. }
  200098. /* Place a 16-bit number into a buffer in PNG byte order.
  200099. * The parameter is declared unsigned int, not png_uint_16,
  200100. * just to avoid potential problems on pre-ANSI C compilers.
  200101. */
  200102. void PNGAPI
  200103. png_save_uint_16(png_bytep buf, unsigned int i)
  200104. {
  200105. buf[0] = (png_byte)((i >> 8) & 0xff);
  200106. buf[1] = (png_byte)(i & 0xff);
  200107. }
  200108. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200109. * representing the chunk name. The array must be at least 4 bytes in
  200110. * length, and does not need to be null terminated. To be safe, pass the
  200111. * pre-defined chunk names here, and if you need a new one, define it
  200112. * where the others are defined. The length is the length of the data.
  200113. * All the data must be present. If that is not possible, use the
  200114. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200115. * functions instead.
  200116. */
  200117. void PNGAPI
  200118. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200119. png_bytep data, png_size_t length)
  200120. {
  200121. if(png_ptr == NULL) return;
  200122. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200123. png_write_chunk_data(png_ptr, data, length);
  200124. png_write_chunk_end(png_ptr);
  200125. }
  200126. /* Write the start of a PNG chunk. The type is the chunk type.
  200127. * The total_length is the sum of the lengths of all the data you will be
  200128. * passing in png_write_chunk_data().
  200129. */
  200130. void PNGAPI
  200131. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200132. png_uint_32 length)
  200133. {
  200134. png_byte buf[4];
  200135. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200136. if(png_ptr == NULL) return;
  200137. /* write the length */
  200138. png_save_uint_32(buf, length);
  200139. png_write_data(png_ptr, buf, (png_size_t)4);
  200140. /* write the chunk name */
  200141. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200142. /* reset the crc and run it over the chunk name */
  200143. png_reset_crc(png_ptr);
  200144. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200145. }
  200146. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200147. * Note that multiple calls to this function are allowed, and that the
  200148. * sum of the lengths from these calls *must* add up to the total_length
  200149. * given to png_write_chunk_start().
  200150. */
  200151. void PNGAPI
  200152. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200153. {
  200154. /* write the data, and run the CRC over it */
  200155. if(png_ptr == NULL) return;
  200156. if (data != NULL && length > 0)
  200157. {
  200158. png_calculate_crc(png_ptr, data, length);
  200159. png_write_data(png_ptr, data, length);
  200160. }
  200161. }
  200162. /* Finish a chunk started with png_write_chunk_start(). */
  200163. void PNGAPI
  200164. png_write_chunk_end(png_structp png_ptr)
  200165. {
  200166. png_byte buf[4];
  200167. if(png_ptr == NULL) return;
  200168. /* write the crc */
  200169. png_save_uint_32(buf, png_ptr->crc);
  200170. png_write_data(png_ptr, buf, (png_size_t)4);
  200171. }
  200172. /* Simple function to write the signature. If we have already written
  200173. * the magic bytes of the signature, or more likely, the PNG stream is
  200174. * being embedded into another stream and doesn't need its own signature,
  200175. * we should call png_set_sig_bytes() to tell libpng how many of the
  200176. * bytes have already been written.
  200177. */
  200178. void /* PRIVATE */
  200179. png_write_sig(png_structp png_ptr)
  200180. {
  200181. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200182. /* write the rest of the 8 byte signature */
  200183. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200184. (png_size_t)8 - png_ptr->sig_bytes);
  200185. if(png_ptr->sig_bytes < 3)
  200186. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200187. }
  200188. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200189. /*
  200190. * This pair of functions encapsulates the operation of (a) compressing a
  200191. * text string, and (b) issuing it later as a series of chunk data writes.
  200192. * The compression_state structure is shared context for these functions
  200193. * set up by the caller in order to make the whole mess thread-safe.
  200194. */
  200195. typedef struct
  200196. {
  200197. char *input; /* the uncompressed input data */
  200198. int input_len; /* its length */
  200199. int num_output_ptr; /* number of output pointers used */
  200200. int max_output_ptr; /* size of output_ptr */
  200201. png_charpp output_ptr; /* array of pointers to output */
  200202. } compression_state;
  200203. /* compress given text into storage in the png_ptr structure */
  200204. static int /* PRIVATE */
  200205. png_text_compress(png_structp png_ptr,
  200206. png_charp text, png_size_t text_len, int compression,
  200207. compression_state *comp)
  200208. {
  200209. int ret;
  200210. comp->num_output_ptr = 0;
  200211. comp->max_output_ptr = 0;
  200212. comp->output_ptr = NULL;
  200213. comp->input = NULL;
  200214. comp->input_len = 0;
  200215. /* we may just want to pass the text right through */
  200216. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200217. {
  200218. comp->input = text;
  200219. comp->input_len = text_len;
  200220. return((int)text_len);
  200221. }
  200222. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200223. {
  200224. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200225. char msg[50];
  200226. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200227. png_warning(png_ptr, msg);
  200228. #else
  200229. png_warning(png_ptr, "Unknown compression type");
  200230. #endif
  200231. }
  200232. /* We can't write the chunk until we find out how much data we have,
  200233. * which means we need to run the compressor first and save the
  200234. * output. This shouldn't be a problem, as the vast majority of
  200235. * comments should be reasonable, but we will set up an array of
  200236. * malloc'd pointers to be sure.
  200237. *
  200238. * If we knew the application was well behaved, we could simplify this
  200239. * greatly by assuming we can always malloc an output buffer large
  200240. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200241. * and malloc this directly. The only time this would be a bad idea is
  200242. * if we can't malloc more than 64K and we have 64K of random input
  200243. * data, or if the input string is incredibly large (although this
  200244. * wouldn't cause a failure, just a slowdown due to swapping).
  200245. */
  200246. /* set up the compression buffers */
  200247. png_ptr->zstream.avail_in = (uInt)text_len;
  200248. png_ptr->zstream.next_in = (Bytef *)text;
  200249. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200250. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200251. /* this is the same compression loop as in png_write_row() */
  200252. do
  200253. {
  200254. /* compress the data */
  200255. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200256. if (ret != Z_OK)
  200257. {
  200258. /* error */
  200259. if (png_ptr->zstream.msg != NULL)
  200260. png_error(png_ptr, png_ptr->zstream.msg);
  200261. else
  200262. png_error(png_ptr, "zlib error");
  200263. }
  200264. /* check to see if we need more room */
  200265. if (!(png_ptr->zstream.avail_out))
  200266. {
  200267. /* make sure the output array has room */
  200268. if (comp->num_output_ptr >= comp->max_output_ptr)
  200269. {
  200270. int old_max;
  200271. old_max = comp->max_output_ptr;
  200272. comp->max_output_ptr = comp->num_output_ptr + 4;
  200273. if (comp->output_ptr != NULL)
  200274. {
  200275. png_charpp old_ptr;
  200276. old_ptr = comp->output_ptr;
  200277. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200278. (png_uint_32)(comp->max_output_ptr *
  200279. png_sizeof (png_charpp)));
  200280. png_memcpy(comp->output_ptr, old_ptr, old_max
  200281. * png_sizeof (png_charp));
  200282. png_free(png_ptr, old_ptr);
  200283. }
  200284. else
  200285. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200286. (png_uint_32)(comp->max_output_ptr *
  200287. png_sizeof (png_charp)));
  200288. }
  200289. /* save the data */
  200290. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200291. (png_uint_32)png_ptr->zbuf_size);
  200292. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200293. png_ptr->zbuf_size);
  200294. comp->num_output_ptr++;
  200295. /* and reset the buffer */
  200296. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200297. png_ptr->zstream.next_out = png_ptr->zbuf;
  200298. }
  200299. /* continue until we don't have any more to compress */
  200300. } while (png_ptr->zstream.avail_in);
  200301. /* finish the compression */
  200302. do
  200303. {
  200304. /* tell zlib we are finished */
  200305. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200306. if (ret == Z_OK)
  200307. {
  200308. /* check to see if we need more room */
  200309. if (!(png_ptr->zstream.avail_out))
  200310. {
  200311. /* check to make sure our output array has room */
  200312. if (comp->num_output_ptr >= comp->max_output_ptr)
  200313. {
  200314. int old_max;
  200315. old_max = comp->max_output_ptr;
  200316. comp->max_output_ptr = comp->num_output_ptr + 4;
  200317. if (comp->output_ptr != NULL)
  200318. {
  200319. png_charpp old_ptr;
  200320. old_ptr = comp->output_ptr;
  200321. /* This could be optimized to realloc() */
  200322. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200323. (png_uint_32)(comp->max_output_ptr *
  200324. png_sizeof (png_charpp)));
  200325. png_memcpy(comp->output_ptr, old_ptr,
  200326. old_max * png_sizeof (png_charp));
  200327. png_free(png_ptr, old_ptr);
  200328. }
  200329. else
  200330. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200331. (png_uint_32)(comp->max_output_ptr *
  200332. png_sizeof (png_charp)));
  200333. }
  200334. /* save off the data */
  200335. comp->output_ptr[comp->num_output_ptr] =
  200336. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200337. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200338. png_ptr->zbuf_size);
  200339. comp->num_output_ptr++;
  200340. /* and reset the buffer pointers */
  200341. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200342. png_ptr->zstream.next_out = png_ptr->zbuf;
  200343. }
  200344. }
  200345. else if (ret != Z_STREAM_END)
  200346. {
  200347. /* we got an error */
  200348. if (png_ptr->zstream.msg != NULL)
  200349. png_error(png_ptr, png_ptr->zstream.msg);
  200350. else
  200351. png_error(png_ptr, "zlib error");
  200352. }
  200353. } while (ret != Z_STREAM_END);
  200354. /* text length is number of buffers plus last buffer */
  200355. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200356. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200357. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200358. return((int)text_len);
  200359. }
  200360. /* ship the compressed text out via chunk writes */
  200361. static void /* PRIVATE */
  200362. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200363. {
  200364. int i;
  200365. /* handle the no-compression case */
  200366. if (comp->input)
  200367. {
  200368. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200369. (png_size_t)comp->input_len);
  200370. return;
  200371. }
  200372. /* write saved output buffers, if any */
  200373. for (i = 0; i < comp->num_output_ptr; i++)
  200374. {
  200375. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200376. png_ptr->zbuf_size);
  200377. png_free(png_ptr, comp->output_ptr[i]);
  200378. comp->output_ptr[i]=NULL;
  200379. }
  200380. if (comp->max_output_ptr != 0)
  200381. png_free(png_ptr, comp->output_ptr);
  200382. comp->output_ptr=NULL;
  200383. /* write anything left in zbuf */
  200384. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200385. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200386. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200387. /* reset zlib for another zTXt/iTXt or image data */
  200388. deflateReset(&png_ptr->zstream);
  200389. png_ptr->zstream.data_type = Z_BINARY;
  200390. }
  200391. #endif
  200392. /* Write the IHDR chunk, and update the png_struct with the necessary
  200393. * information. Note that the rest of this code depends upon this
  200394. * information being correct.
  200395. */
  200396. void /* PRIVATE */
  200397. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200398. int bit_depth, int color_type, int compression_type, int filter_type,
  200399. int interlace_type)
  200400. {
  200401. #ifdef PNG_USE_LOCAL_ARRAYS
  200402. PNG_IHDR;
  200403. #endif
  200404. png_byte buf[13]; /* buffer to store the IHDR info */
  200405. png_debug(1, "in png_write_IHDR\n");
  200406. /* Check that we have valid input data from the application info */
  200407. switch (color_type)
  200408. {
  200409. case PNG_COLOR_TYPE_GRAY:
  200410. switch (bit_depth)
  200411. {
  200412. case 1:
  200413. case 2:
  200414. case 4:
  200415. case 8:
  200416. case 16: png_ptr->channels = 1; break;
  200417. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200418. }
  200419. break;
  200420. case PNG_COLOR_TYPE_RGB:
  200421. if (bit_depth != 8 && bit_depth != 16)
  200422. png_error(png_ptr, "Invalid bit depth for RGB image");
  200423. png_ptr->channels = 3;
  200424. break;
  200425. case PNG_COLOR_TYPE_PALETTE:
  200426. switch (bit_depth)
  200427. {
  200428. case 1:
  200429. case 2:
  200430. case 4:
  200431. case 8: png_ptr->channels = 1; break;
  200432. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200433. }
  200434. break;
  200435. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200436. if (bit_depth != 8 && bit_depth != 16)
  200437. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200438. png_ptr->channels = 2;
  200439. break;
  200440. case PNG_COLOR_TYPE_RGB_ALPHA:
  200441. if (bit_depth != 8 && bit_depth != 16)
  200442. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200443. png_ptr->channels = 4;
  200444. break;
  200445. default:
  200446. png_error(png_ptr, "Invalid image color type specified");
  200447. }
  200448. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200449. {
  200450. png_warning(png_ptr, "Invalid compression type specified");
  200451. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200452. }
  200453. /* Write filter_method 64 (intrapixel differencing) only if
  200454. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200455. * 2. Libpng did not write a PNG signature (this filter_method is only
  200456. * used in PNG datastreams that are embedded in MNG datastreams) and
  200457. * 3. The application called png_permit_mng_features with a mask that
  200458. * included PNG_FLAG_MNG_FILTER_64 and
  200459. * 4. The filter_method is 64 and
  200460. * 5. The color_type is RGB or RGBA
  200461. */
  200462. if (
  200463. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200464. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200465. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200466. (color_type == PNG_COLOR_TYPE_RGB ||
  200467. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200468. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200469. #endif
  200470. filter_type != PNG_FILTER_TYPE_BASE)
  200471. {
  200472. png_warning(png_ptr, "Invalid filter type specified");
  200473. filter_type = PNG_FILTER_TYPE_BASE;
  200474. }
  200475. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200476. if (interlace_type != PNG_INTERLACE_NONE &&
  200477. interlace_type != PNG_INTERLACE_ADAM7)
  200478. {
  200479. png_warning(png_ptr, "Invalid interlace type specified");
  200480. interlace_type = PNG_INTERLACE_ADAM7;
  200481. }
  200482. #else
  200483. interlace_type=PNG_INTERLACE_NONE;
  200484. #endif
  200485. /* save off the relevent information */
  200486. png_ptr->bit_depth = (png_byte)bit_depth;
  200487. png_ptr->color_type = (png_byte)color_type;
  200488. png_ptr->interlaced = (png_byte)interlace_type;
  200489. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200490. png_ptr->filter_type = (png_byte)filter_type;
  200491. #endif
  200492. png_ptr->compression_type = (png_byte)compression_type;
  200493. png_ptr->width = width;
  200494. png_ptr->height = height;
  200495. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200496. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200497. /* set the usr info, so any transformations can modify it */
  200498. png_ptr->usr_width = png_ptr->width;
  200499. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200500. png_ptr->usr_channels = png_ptr->channels;
  200501. /* pack the header information into the buffer */
  200502. png_save_uint_32(buf, width);
  200503. png_save_uint_32(buf + 4, height);
  200504. buf[8] = (png_byte)bit_depth;
  200505. buf[9] = (png_byte)color_type;
  200506. buf[10] = (png_byte)compression_type;
  200507. buf[11] = (png_byte)filter_type;
  200508. buf[12] = (png_byte)interlace_type;
  200509. /* write the chunk */
  200510. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200511. /* initialize zlib with PNG info */
  200512. png_ptr->zstream.zalloc = png_zalloc;
  200513. png_ptr->zstream.zfree = png_zfree;
  200514. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200515. if (!(png_ptr->do_filter))
  200516. {
  200517. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200518. png_ptr->bit_depth < 8)
  200519. png_ptr->do_filter = PNG_FILTER_NONE;
  200520. else
  200521. png_ptr->do_filter = PNG_ALL_FILTERS;
  200522. }
  200523. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200524. {
  200525. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200526. png_ptr->zlib_strategy = Z_FILTERED;
  200527. else
  200528. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200529. }
  200530. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200531. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200532. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200533. png_ptr->zlib_mem_level = 8;
  200534. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200535. png_ptr->zlib_window_bits = 15;
  200536. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200537. png_ptr->zlib_method = 8;
  200538. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200539. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200540. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200541. png_error(png_ptr, "zlib failed to initialize compressor");
  200542. png_ptr->zstream.next_out = png_ptr->zbuf;
  200543. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200544. /* libpng is not interested in zstream.data_type */
  200545. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200546. png_ptr->zstream.data_type = Z_BINARY;
  200547. png_ptr->mode = PNG_HAVE_IHDR;
  200548. }
  200549. /* write the palette. We are careful not to trust png_color to be in the
  200550. * correct order for PNG, so people can redefine it to any convenient
  200551. * structure.
  200552. */
  200553. void /* PRIVATE */
  200554. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200555. {
  200556. #ifdef PNG_USE_LOCAL_ARRAYS
  200557. PNG_PLTE;
  200558. #endif
  200559. png_uint_32 i;
  200560. png_colorp pal_ptr;
  200561. png_byte buf[3];
  200562. png_debug(1, "in png_write_PLTE\n");
  200563. if ((
  200564. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200565. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200566. #endif
  200567. num_pal == 0) || num_pal > 256)
  200568. {
  200569. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200570. {
  200571. png_error(png_ptr, "Invalid number of colors in palette");
  200572. }
  200573. else
  200574. {
  200575. png_warning(png_ptr, "Invalid number of colors in palette");
  200576. return;
  200577. }
  200578. }
  200579. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200580. {
  200581. png_warning(png_ptr,
  200582. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200583. return;
  200584. }
  200585. png_ptr->num_palette = (png_uint_16)num_pal;
  200586. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200587. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200588. #ifndef PNG_NO_POINTER_INDEXING
  200589. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200590. {
  200591. buf[0] = pal_ptr->red;
  200592. buf[1] = pal_ptr->green;
  200593. buf[2] = pal_ptr->blue;
  200594. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200595. }
  200596. #else
  200597. /* This is a little slower but some buggy compilers need to do this instead */
  200598. pal_ptr=palette;
  200599. for (i = 0; i < num_pal; i++)
  200600. {
  200601. buf[0] = pal_ptr[i].red;
  200602. buf[1] = pal_ptr[i].green;
  200603. buf[2] = pal_ptr[i].blue;
  200604. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200605. }
  200606. #endif
  200607. png_write_chunk_end(png_ptr);
  200608. png_ptr->mode |= PNG_HAVE_PLTE;
  200609. }
  200610. /* write an IDAT chunk */
  200611. void /* PRIVATE */
  200612. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200613. {
  200614. #ifdef PNG_USE_LOCAL_ARRAYS
  200615. PNG_IDAT;
  200616. #endif
  200617. png_debug(1, "in png_write_IDAT\n");
  200618. /* Optimize the CMF field in the zlib stream. */
  200619. /* This hack of the zlib stream is compliant to the stream specification. */
  200620. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200621. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200622. {
  200623. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200624. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200625. {
  200626. /* Avoid memory underflows and multiplication overflows. */
  200627. /* The conditions below are practically always satisfied;
  200628. however, they still must be checked. */
  200629. if (length >= 2 &&
  200630. png_ptr->height < 16384 && png_ptr->width < 16384)
  200631. {
  200632. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200633. ((png_ptr->width *
  200634. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200635. unsigned int z_cinfo = z_cmf >> 4;
  200636. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200637. while (uncompressed_idat_size <= half_z_window_size &&
  200638. half_z_window_size >= 256)
  200639. {
  200640. z_cinfo--;
  200641. half_z_window_size >>= 1;
  200642. }
  200643. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200644. if (data[0] != (png_byte)z_cmf)
  200645. {
  200646. data[0] = (png_byte)z_cmf;
  200647. data[1] &= 0xe0;
  200648. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200649. }
  200650. }
  200651. }
  200652. else
  200653. png_error(png_ptr,
  200654. "Invalid zlib compression method or flags in IDAT");
  200655. }
  200656. png_write_chunk(png_ptr, png_IDAT, data, length);
  200657. png_ptr->mode |= PNG_HAVE_IDAT;
  200658. }
  200659. /* write an IEND chunk */
  200660. void /* PRIVATE */
  200661. png_write_IEND(png_structp png_ptr)
  200662. {
  200663. #ifdef PNG_USE_LOCAL_ARRAYS
  200664. PNG_IEND;
  200665. #endif
  200666. png_debug(1, "in png_write_IEND\n");
  200667. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200668. (png_size_t)0);
  200669. png_ptr->mode |= PNG_HAVE_IEND;
  200670. }
  200671. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200672. /* write a gAMA chunk */
  200673. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200674. void /* PRIVATE */
  200675. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200676. {
  200677. #ifdef PNG_USE_LOCAL_ARRAYS
  200678. PNG_gAMA;
  200679. #endif
  200680. png_uint_32 igamma;
  200681. png_byte buf[4];
  200682. png_debug(1, "in png_write_gAMA\n");
  200683. /* file_gamma is saved in 1/100,000ths */
  200684. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200685. png_save_uint_32(buf, igamma);
  200686. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200687. }
  200688. #endif
  200689. #ifdef PNG_FIXED_POINT_SUPPORTED
  200690. void /* PRIVATE */
  200691. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200692. {
  200693. #ifdef PNG_USE_LOCAL_ARRAYS
  200694. PNG_gAMA;
  200695. #endif
  200696. png_byte buf[4];
  200697. png_debug(1, "in png_write_gAMA\n");
  200698. /* file_gamma is saved in 1/100,000ths */
  200699. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200700. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200701. }
  200702. #endif
  200703. #endif
  200704. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200705. /* write a sRGB chunk */
  200706. void /* PRIVATE */
  200707. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200708. {
  200709. #ifdef PNG_USE_LOCAL_ARRAYS
  200710. PNG_sRGB;
  200711. #endif
  200712. png_byte buf[1];
  200713. png_debug(1, "in png_write_sRGB\n");
  200714. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200715. png_warning(png_ptr,
  200716. "Invalid sRGB rendering intent specified");
  200717. buf[0]=(png_byte)srgb_intent;
  200718. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200719. }
  200720. #endif
  200721. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200722. /* write an iCCP chunk */
  200723. void /* PRIVATE */
  200724. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200725. png_charp profile, int profile_len)
  200726. {
  200727. #ifdef PNG_USE_LOCAL_ARRAYS
  200728. PNG_iCCP;
  200729. #endif
  200730. png_size_t name_len;
  200731. png_charp new_name;
  200732. compression_state comp;
  200733. int embedded_profile_len = 0;
  200734. png_debug(1, "in png_write_iCCP\n");
  200735. comp.num_output_ptr = 0;
  200736. comp.max_output_ptr = 0;
  200737. comp.output_ptr = NULL;
  200738. comp.input = NULL;
  200739. comp.input_len = 0;
  200740. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200741. &new_name)) == 0)
  200742. {
  200743. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200744. return;
  200745. }
  200746. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200747. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200748. if (profile == NULL)
  200749. profile_len = 0;
  200750. if (profile_len > 3)
  200751. embedded_profile_len =
  200752. ((*( (png_bytep)profile ))<<24) |
  200753. ((*( (png_bytep)profile+1))<<16) |
  200754. ((*( (png_bytep)profile+2))<< 8) |
  200755. ((*( (png_bytep)profile+3)) );
  200756. if (profile_len < embedded_profile_len)
  200757. {
  200758. png_warning(png_ptr,
  200759. "Embedded profile length too large in iCCP chunk");
  200760. return;
  200761. }
  200762. if (profile_len > embedded_profile_len)
  200763. {
  200764. png_warning(png_ptr,
  200765. "Truncating profile to actual length in iCCP chunk");
  200766. profile_len = embedded_profile_len;
  200767. }
  200768. if (profile_len)
  200769. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200770. PNG_COMPRESSION_TYPE_BASE, &comp);
  200771. /* make sure we include the NULL after the name and the compression type */
  200772. png_write_chunk_start(png_ptr, png_iCCP,
  200773. (png_uint_32)name_len+profile_len+2);
  200774. new_name[name_len+1]=0x00;
  200775. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200776. if (profile_len)
  200777. png_write_compressed_data_out(png_ptr, &comp);
  200778. png_write_chunk_end(png_ptr);
  200779. png_free(png_ptr, new_name);
  200780. }
  200781. #endif
  200782. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200783. /* write a sPLT chunk */
  200784. void /* PRIVATE */
  200785. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200786. {
  200787. #ifdef PNG_USE_LOCAL_ARRAYS
  200788. PNG_sPLT;
  200789. #endif
  200790. png_size_t name_len;
  200791. png_charp new_name;
  200792. png_byte entrybuf[10];
  200793. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200794. int palette_size = entry_size * spalette->nentries;
  200795. png_sPLT_entryp ep;
  200796. #ifdef PNG_NO_POINTER_INDEXING
  200797. int i;
  200798. #endif
  200799. png_debug(1, "in png_write_sPLT\n");
  200800. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200801. spalette->name, &new_name))==0)
  200802. {
  200803. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200804. return;
  200805. }
  200806. /* make sure we include the NULL after the name */
  200807. png_write_chunk_start(png_ptr, png_sPLT,
  200808. (png_uint_32)(name_len + 2 + palette_size));
  200809. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200810. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200811. /* loop through each palette entry, writing appropriately */
  200812. #ifndef PNG_NO_POINTER_INDEXING
  200813. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200814. {
  200815. if (spalette->depth == 8)
  200816. {
  200817. entrybuf[0] = (png_byte)ep->red;
  200818. entrybuf[1] = (png_byte)ep->green;
  200819. entrybuf[2] = (png_byte)ep->blue;
  200820. entrybuf[3] = (png_byte)ep->alpha;
  200821. png_save_uint_16(entrybuf + 4, ep->frequency);
  200822. }
  200823. else
  200824. {
  200825. png_save_uint_16(entrybuf + 0, ep->red);
  200826. png_save_uint_16(entrybuf + 2, ep->green);
  200827. png_save_uint_16(entrybuf + 4, ep->blue);
  200828. png_save_uint_16(entrybuf + 6, ep->alpha);
  200829. png_save_uint_16(entrybuf + 8, ep->frequency);
  200830. }
  200831. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  200832. }
  200833. #else
  200834. ep=spalette->entries;
  200835. for (i=0; i>spalette->nentries; i++)
  200836. {
  200837. if (spalette->depth == 8)
  200838. {
  200839. entrybuf[0] = (png_byte)ep[i].red;
  200840. entrybuf[1] = (png_byte)ep[i].green;
  200841. entrybuf[2] = (png_byte)ep[i].blue;
  200842. entrybuf[3] = (png_byte)ep[i].alpha;
  200843. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  200844. }
  200845. else
  200846. {
  200847. png_save_uint_16(entrybuf + 0, ep[i].red);
  200848. png_save_uint_16(entrybuf + 2, ep[i].green);
  200849. png_save_uint_16(entrybuf + 4, ep[i].blue);
  200850. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  200851. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  200852. }
  200853. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  200854. }
  200855. #endif
  200856. png_write_chunk_end(png_ptr);
  200857. png_free(png_ptr, new_name);
  200858. }
  200859. #endif
  200860. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  200861. /* write the sBIT chunk */
  200862. void /* PRIVATE */
  200863. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  200864. {
  200865. #ifdef PNG_USE_LOCAL_ARRAYS
  200866. PNG_sBIT;
  200867. #endif
  200868. png_byte buf[4];
  200869. png_size_t size;
  200870. png_debug(1, "in png_write_sBIT\n");
  200871. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  200872. if (color_type & PNG_COLOR_MASK_COLOR)
  200873. {
  200874. png_byte maxbits;
  200875. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  200876. png_ptr->usr_bit_depth);
  200877. if (sbit->red == 0 || sbit->red > maxbits ||
  200878. sbit->green == 0 || sbit->green > maxbits ||
  200879. sbit->blue == 0 || sbit->blue > maxbits)
  200880. {
  200881. png_warning(png_ptr, "Invalid sBIT depth specified");
  200882. return;
  200883. }
  200884. buf[0] = sbit->red;
  200885. buf[1] = sbit->green;
  200886. buf[2] = sbit->blue;
  200887. size = 3;
  200888. }
  200889. else
  200890. {
  200891. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  200892. {
  200893. png_warning(png_ptr, "Invalid sBIT depth specified");
  200894. return;
  200895. }
  200896. buf[0] = sbit->gray;
  200897. size = 1;
  200898. }
  200899. if (color_type & PNG_COLOR_MASK_ALPHA)
  200900. {
  200901. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  200902. {
  200903. png_warning(png_ptr, "Invalid sBIT depth specified");
  200904. return;
  200905. }
  200906. buf[size++] = sbit->alpha;
  200907. }
  200908. png_write_chunk(png_ptr, png_sBIT, buf, size);
  200909. }
  200910. #endif
  200911. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  200912. /* write the cHRM chunk */
  200913. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200914. void /* PRIVATE */
  200915. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  200916. double red_x, double red_y, double green_x, double green_y,
  200917. double blue_x, double blue_y)
  200918. {
  200919. #ifdef PNG_USE_LOCAL_ARRAYS
  200920. PNG_cHRM;
  200921. #endif
  200922. png_byte buf[32];
  200923. png_uint_32 itemp;
  200924. png_debug(1, "in png_write_cHRM\n");
  200925. /* each value is saved in 1/100,000ths */
  200926. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  200927. white_x + white_y > 1.0)
  200928. {
  200929. png_warning(png_ptr, "Invalid cHRM white point specified");
  200930. #if !defined(PNG_NO_CONSOLE_IO)
  200931. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  200932. #endif
  200933. return;
  200934. }
  200935. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  200936. png_save_uint_32(buf, itemp);
  200937. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  200938. png_save_uint_32(buf + 4, itemp);
  200939. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  200940. {
  200941. png_warning(png_ptr, "Invalid cHRM red point specified");
  200942. return;
  200943. }
  200944. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  200945. png_save_uint_32(buf + 8, itemp);
  200946. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  200947. png_save_uint_32(buf + 12, itemp);
  200948. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  200949. {
  200950. png_warning(png_ptr, "Invalid cHRM green point specified");
  200951. return;
  200952. }
  200953. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  200954. png_save_uint_32(buf + 16, itemp);
  200955. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  200956. png_save_uint_32(buf + 20, itemp);
  200957. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  200958. {
  200959. png_warning(png_ptr, "Invalid cHRM blue point specified");
  200960. return;
  200961. }
  200962. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  200963. png_save_uint_32(buf + 24, itemp);
  200964. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  200965. png_save_uint_32(buf + 28, itemp);
  200966. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200967. }
  200968. #endif
  200969. #ifdef PNG_FIXED_POINT_SUPPORTED
  200970. void /* PRIVATE */
  200971. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  200972. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  200973. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  200974. png_fixed_point blue_y)
  200975. {
  200976. #ifdef PNG_USE_LOCAL_ARRAYS
  200977. PNG_cHRM;
  200978. #endif
  200979. png_byte buf[32];
  200980. png_debug(1, "in png_write_cHRM\n");
  200981. /* each value is saved in 1/100,000ths */
  200982. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  200983. {
  200984. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  200985. #if !defined(PNG_NO_CONSOLE_IO)
  200986. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  200987. #endif
  200988. return;
  200989. }
  200990. png_save_uint_32(buf, (png_uint_32)white_x);
  200991. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  200992. if (red_x + red_y > 100000L)
  200993. {
  200994. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  200995. return;
  200996. }
  200997. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  200998. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  200999. if (green_x + green_y > 100000L)
  201000. {
  201001. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201002. return;
  201003. }
  201004. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201005. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201006. if (blue_x + blue_y > 100000L)
  201007. {
  201008. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201009. return;
  201010. }
  201011. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201012. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201013. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201014. }
  201015. #endif
  201016. #endif
  201017. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201018. /* write the tRNS chunk */
  201019. void /* PRIVATE */
  201020. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201021. int num_trans, int color_type)
  201022. {
  201023. #ifdef PNG_USE_LOCAL_ARRAYS
  201024. PNG_tRNS;
  201025. #endif
  201026. png_byte buf[6];
  201027. png_debug(1, "in png_write_tRNS\n");
  201028. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201029. {
  201030. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201031. {
  201032. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201033. return;
  201034. }
  201035. /* write the chunk out as it is */
  201036. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201037. }
  201038. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201039. {
  201040. /* one 16 bit value */
  201041. if(tran->gray >= (1 << png_ptr->bit_depth))
  201042. {
  201043. png_warning(png_ptr,
  201044. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201045. return;
  201046. }
  201047. png_save_uint_16(buf, tran->gray);
  201048. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201049. }
  201050. else if (color_type == PNG_COLOR_TYPE_RGB)
  201051. {
  201052. /* three 16 bit values */
  201053. png_save_uint_16(buf, tran->red);
  201054. png_save_uint_16(buf + 2, tran->green);
  201055. png_save_uint_16(buf + 4, tran->blue);
  201056. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201057. {
  201058. png_warning(png_ptr,
  201059. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201060. return;
  201061. }
  201062. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201063. }
  201064. else
  201065. {
  201066. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201067. }
  201068. }
  201069. #endif
  201070. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201071. /* write the background chunk */
  201072. void /* PRIVATE */
  201073. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201074. {
  201075. #ifdef PNG_USE_LOCAL_ARRAYS
  201076. PNG_bKGD;
  201077. #endif
  201078. png_byte buf[6];
  201079. png_debug(1, "in png_write_bKGD\n");
  201080. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201081. {
  201082. if (
  201083. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201084. (png_ptr->num_palette ||
  201085. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201086. #endif
  201087. back->index > png_ptr->num_palette)
  201088. {
  201089. png_warning(png_ptr, "Invalid background palette index");
  201090. return;
  201091. }
  201092. buf[0] = back->index;
  201093. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201094. }
  201095. else if (color_type & PNG_COLOR_MASK_COLOR)
  201096. {
  201097. png_save_uint_16(buf, back->red);
  201098. png_save_uint_16(buf + 2, back->green);
  201099. png_save_uint_16(buf + 4, back->blue);
  201100. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201101. {
  201102. png_warning(png_ptr,
  201103. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201104. return;
  201105. }
  201106. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201107. }
  201108. else
  201109. {
  201110. if(back->gray >= (1 << png_ptr->bit_depth))
  201111. {
  201112. png_warning(png_ptr,
  201113. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201114. return;
  201115. }
  201116. png_save_uint_16(buf, back->gray);
  201117. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201118. }
  201119. }
  201120. #endif
  201121. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201122. /* write the histogram */
  201123. void /* PRIVATE */
  201124. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201125. {
  201126. #ifdef PNG_USE_LOCAL_ARRAYS
  201127. PNG_hIST;
  201128. #endif
  201129. int i;
  201130. png_byte buf[3];
  201131. png_debug(1, "in png_write_hIST\n");
  201132. if (num_hist > (int)png_ptr->num_palette)
  201133. {
  201134. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201135. png_ptr->num_palette);
  201136. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201137. return;
  201138. }
  201139. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201140. for (i = 0; i < num_hist; i++)
  201141. {
  201142. png_save_uint_16(buf, hist[i]);
  201143. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201144. }
  201145. png_write_chunk_end(png_ptr);
  201146. }
  201147. #endif
  201148. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201149. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201150. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201151. * and if invalid, correct the keyword rather than discarding the entire
  201152. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201153. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201154. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201155. *
  201156. * The new_key is allocated to hold the corrected keyword and must be freed
  201157. * by the calling routine. This avoids problems with trying to write to
  201158. * static keywords without having to have duplicate copies of the strings.
  201159. */
  201160. png_size_t /* PRIVATE */
  201161. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201162. {
  201163. png_size_t key_len;
  201164. png_charp kp, dp;
  201165. int kflag;
  201166. int kwarn=0;
  201167. png_debug(1, "in png_check_keyword\n");
  201168. *new_key = NULL;
  201169. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201170. {
  201171. png_warning(png_ptr, "zero length keyword");
  201172. return ((png_size_t)0);
  201173. }
  201174. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201175. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201176. if (*new_key == NULL)
  201177. {
  201178. png_warning(png_ptr, "Out of memory while procesing keyword");
  201179. return ((png_size_t)0);
  201180. }
  201181. /* Replace non-printing characters with a blank and print a warning */
  201182. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201183. {
  201184. if ((png_byte)*kp < 0x20 ||
  201185. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201186. {
  201187. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201188. char msg[40];
  201189. png_snprintf(msg, 40,
  201190. "invalid keyword character 0x%02X", (png_byte)*kp);
  201191. png_warning(png_ptr, msg);
  201192. #else
  201193. png_warning(png_ptr, "invalid character in keyword");
  201194. #endif
  201195. *dp = ' ';
  201196. }
  201197. else
  201198. {
  201199. *dp = *kp;
  201200. }
  201201. }
  201202. *dp = '\0';
  201203. /* Remove any trailing white space. */
  201204. kp = *new_key + key_len - 1;
  201205. if (*kp == ' ')
  201206. {
  201207. png_warning(png_ptr, "trailing spaces removed from keyword");
  201208. while (*kp == ' ')
  201209. {
  201210. *(kp--) = '\0';
  201211. key_len--;
  201212. }
  201213. }
  201214. /* Remove any leading white space. */
  201215. kp = *new_key;
  201216. if (*kp == ' ')
  201217. {
  201218. png_warning(png_ptr, "leading spaces removed from keyword");
  201219. while (*kp == ' ')
  201220. {
  201221. kp++;
  201222. key_len--;
  201223. }
  201224. }
  201225. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201226. /* Remove multiple internal spaces. */
  201227. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201228. {
  201229. if (*kp == ' ' && kflag == 0)
  201230. {
  201231. *(dp++) = *kp;
  201232. kflag = 1;
  201233. }
  201234. else if (*kp == ' ')
  201235. {
  201236. key_len--;
  201237. kwarn=1;
  201238. }
  201239. else
  201240. {
  201241. *(dp++) = *kp;
  201242. kflag = 0;
  201243. }
  201244. }
  201245. *dp = '\0';
  201246. if(kwarn)
  201247. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201248. if (key_len == 0)
  201249. {
  201250. png_free(png_ptr, *new_key);
  201251. *new_key=NULL;
  201252. png_warning(png_ptr, "Zero length keyword");
  201253. }
  201254. if (key_len > 79)
  201255. {
  201256. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201257. new_key[79] = '\0';
  201258. key_len = 79;
  201259. }
  201260. return (key_len);
  201261. }
  201262. #endif
  201263. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201264. /* write a tEXt chunk */
  201265. void /* PRIVATE */
  201266. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201267. png_size_t text_len)
  201268. {
  201269. #ifdef PNG_USE_LOCAL_ARRAYS
  201270. PNG_tEXt;
  201271. #endif
  201272. png_size_t key_len;
  201273. png_charp new_key;
  201274. png_debug(1, "in png_write_tEXt\n");
  201275. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201276. {
  201277. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201278. return;
  201279. }
  201280. if (text == NULL || *text == '\0')
  201281. text_len = 0;
  201282. else
  201283. text_len = png_strlen(text);
  201284. /* make sure we include the 0 after the key */
  201285. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201286. /*
  201287. * We leave it to the application to meet PNG-1.0 requirements on the
  201288. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201289. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201290. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201291. */
  201292. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201293. if (text_len)
  201294. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201295. png_write_chunk_end(png_ptr);
  201296. png_free(png_ptr, new_key);
  201297. }
  201298. #endif
  201299. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201300. /* write a compressed text chunk */
  201301. void /* PRIVATE */
  201302. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201303. png_size_t text_len, int compression)
  201304. {
  201305. #ifdef PNG_USE_LOCAL_ARRAYS
  201306. PNG_zTXt;
  201307. #endif
  201308. png_size_t key_len;
  201309. char buf[1];
  201310. png_charp new_key;
  201311. compression_state comp;
  201312. png_debug(1, "in png_write_zTXt\n");
  201313. comp.num_output_ptr = 0;
  201314. comp.max_output_ptr = 0;
  201315. comp.output_ptr = NULL;
  201316. comp.input = NULL;
  201317. comp.input_len = 0;
  201318. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201319. {
  201320. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201321. return;
  201322. }
  201323. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201324. {
  201325. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201326. png_free(png_ptr, new_key);
  201327. return;
  201328. }
  201329. text_len = png_strlen(text);
  201330. /* compute the compressed data; do it now for the length */
  201331. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201332. &comp);
  201333. /* write start of chunk */
  201334. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201335. (key_len+text_len+2));
  201336. /* write key */
  201337. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201338. png_free(png_ptr, new_key);
  201339. buf[0] = (png_byte)compression;
  201340. /* write compression */
  201341. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201342. /* write the compressed data */
  201343. png_write_compressed_data_out(png_ptr, &comp);
  201344. /* close the chunk */
  201345. png_write_chunk_end(png_ptr);
  201346. }
  201347. #endif
  201348. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201349. /* write an iTXt chunk */
  201350. void /* PRIVATE */
  201351. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201352. png_charp lang, png_charp lang_key, png_charp text)
  201353. {
  201354. #ifdef PNG_USE_LOCAL_ARRAYS
  201355. PNG_iTXt;
  201356. #endif
  201357. png_size_t lang_len, key_len, lang_key_len, text_len;
  201358. png_charp new_lang, new_key;
  201359. png_byte cbuf[2];
  201360. compression_state comp;
  201361. png_debug(1, "in png_write_iTXt\n");
  201362. comp.num_output_ptr = 0;
  201363. comp.max_output_ptr = 0;
  201364. comp.output_ptr = NULL;
  201365. comp.input = NULL;
  201366. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201367. {
  201368. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201369. return;
  201370. }
  201371. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201372. {
  201373. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201374. new_lang = NULL;
  201375. lang_len = 0;
  201376. }
  201377. if (lang_key == NULL)
  201378. lang_key_len = 0;
  201379. else
  201380. lang_key_len = png_strlen(lang_key);
  201381. if (text == NULL)
  201382. text_len = 0;
  201383. else
  201384. text_len = png_strlen(text);
  201385. /* compute the compressed data; do it now for the length */
  201386. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201387. &comp);
  201388. /* make sure we include the compression flag, the compression byte,
  201389. * and the NULs after the key, lang, and lang_key parts */
  201390. png_write_chunk_start(png_ptr, png_iTXt,
  201391. (png_uint_32)(
  201392. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201393. + key_len
  201394. + lang_len
  201395. + lang_key_len
  201396. + text_len));
  201397. /*
  201398. * We leave it to the application to meet PNG-1.0 requirements on the
  201399. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201400. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201401. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201402. */
  201403. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201404. /* set the compression flag */
  201405. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201406. compression == PNG_TEXT_COMPRESSION_NONE)
  201407. cbuf[0] = 0;
  201408. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201409. cbuf[0] = 1;
  201410. /* set the compression method */
  201411. cbuf[1] = 0;
  201412. png_write_chunk_data(png_ptr, cbuf, 2);
  201413. cbuf[0] = 0;
  201414. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201415. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201416. png_write_compressed_data_out(png_ptr, &comp);
  201417. png_write_chunk_end(png_ptr);
  201418. png_free(png_ptr, new_key);
  201419. if (new_lang)
  201420. png_free(png_ptr, new_lang);
  201421. }
  201422. #endif
  201423. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201424. /* write the oFFs chunk */
  201425. void /* PRIVATE */
  201426. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201427. int unit_type)
  201428. {
  201429. #ifdef PNG_USE_LOCAL_ARRAYS
  201430. PNG_oFFs;
  201431. #endif
  201432. png_byte buf[9];
  201433. png_debug(1, "in png_write_oFFs\n");
  201434. if (unit_type >= PNG_OFFSET_LAST)
  201435. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201436. png_save_int_32(buf, x_offset);
  201437. png_save_int_32(buf + 4, y_offset);
  201438. buf[8] = (png_byte)unit_type;
  201439. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201440. }
  201441. #endif
  201442. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201443. /* write the pCAL chunk (described in the PNG extensions document) */
  201444. void /* PRIVATE */
  201445. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201446. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201447. {
  201448. #ifdef PNG_USE_LOCAL_ARRAYS
  201449. PNG_pCAL;
  201450. #endif
  201451. png_size_t purpose_len, units_len, total_len;
  201452. png_uint_32p params_len;
  201453. png_byte buf[10];
  201454. png_charp new_purpose;
  201455. int i;
  201456. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201457. if (type >= PNG_EQUATION_LAST)
  201458. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201459. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201460. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201461. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201462. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201463. total_len = purpose_len + units_len + 10;
  201464. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201465. *png_sizeof(png_uint_32)));
  201466. /* Find the length of each parameter, making sure we don't count the
  201467. null terminator for the last parameter. */
  201468. for (i = 0; i < nparams; i++)
  201469. {
  201470. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201471. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201472. total_len += (png_size_t)params_len[i];
  201473. }
  201474. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201475. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201476. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201477. png_save_int_32(buf, X0);
  201478. png_save_int_32(buf + 4, X1);
  201479. buf[8] = (png_byte)type;
  201480. buf[9] = (png_byte)nparams;
  201481. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201482. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201483. png_free(png_ptr, new_purpose);
  201484. for (i = 0; i < nparams; i++)
  201485. {
  201486. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201487. (png_size_t)params_len[i]);
  201488. }
  201489. png_free(png_ptr, params_len);
  201490. png_write_chunk_end(png_ptr);
  201491. }
  201492. #endif
  201493. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201494. /* write the sCAL chunk */
  201495. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201496. void /* PRIVATE */
  201497. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201498. {
  201499. #ifdef PNG_USE_LOCAL_ARRAYS
  201500. PNG_sCAL;
  201501. #endif
  201502. char buf[64];
  201503. png_size_t total_len;
  201504. png_debug(1, "in png_write_sCAL\n");
  201505. buf[0] = (char)unit;
  201506. #if defined(_WIN32_WCE)
  201507. /* sprintf() function is not supported on WindowsCE */
  201508. {
  201509. wchar_t wc_buf[32];
  201510. size_t wc_len;
  201511. swprintf(wc_buf, TEXT("%12.12e"), width);
  201512. wc_len = wcslen(wc_buf);
  201513. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201514. total_len = wc_len + 2;
  201515. swprintf(wc_buf, TEXT("%12.12e"), height);
  201516. wc_len = wcslen(wc_buf);
  201517. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201518. NULL, NULL);
  201519. total_len += wc_len;
  201520. }
  201521. #else
  201522. png_snprintf(buf + 1, 63, "%12.12e", width);
  201523. total_len = 1 + png_strlen(buf + 1) + 1;
  201524. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201525. total_len += png_strlen(buf + total_len);
  201526. #endif
  201527. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201528. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201529. }
  201530. #else
  201531. #ifdef PNG_FIXED_POINT_SUPPORTED
  201532. void /* PRIVATE */
  201533. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201534. png_charp height)
  201535. {
  201536. #ifdef PNG_USE_LOCAL_ARRAYS
  201537. PNG_sCAL;
  201538. #endif
  201539. png_byte buf[64];
  201540. png_size_t wlen, hlen, total_len;
  201541. png_debug(1, "in png_write_sCAL_s\n");
  201542. wlen = png_strlen(width);
  201543. hlen = png_strlen(height);
  201544. total_len = wlen + hlen + 2;
  201545. if (total_len > 64)
  201546. {
  201547. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201548. return;
  201549. }
  201550. buf[0] = (png_byte)unit;
  201551. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201552. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201553. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201554. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201555. }
  201556. #endif
  201557. #endif
  201558. #endif
  201559. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201560. /* write the pHYs chunk */
  201561. void /* PRIVATE */
  201562. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201563. png_uint_32 y_pixels_per_unit,
  201564. int unit_type)
  201565. {
  201566. #ifdef PNG_USE_LOCAL_ARRAYS
  201567. PNG_pHYs;
  201568. #endif
  201569. png_byte buf[9];
  201570. png_debug(1, "in png_write_pHYs\n");
  201571. if (unit_type >= PNG_RESOLUTION_LAST)
  201572. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201573. png_save_uint_32(buf, x_pixels_per_unit);
  201574. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201575. buf[8] = (png_byte)unit_type;
  201576. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201577. }
  201578. #endif
  201579. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201580. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201581. * or png_convert_from_time_t(), or fill in the structure yourself.
  201582. */
  201583. void /* PRIVATE */
  201584. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201585. {
  201586. #ifdef PNG_USE_LOCAL_ARRAYS
  201587. PNG_tIME;
  201588. #endif
  201589. png_byte buf[7];
  201590. png_debug(1, "in png_write_tIME\n");
  201591. if (mod_time->month > 12 || mod_time->month < 1 ||
  201592. mod_time->day > 31 || mod_time->day < 1 ||
  201593. mod_time->hour > 23 || mod_time->second > 60)
  201594. {
  201595. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201596. return;
  201597. }
  201598. png_save_uint_16(buf, mod_time->year);
  201599. buf[2] = mod_time->month;
  201600. buf[3] = mod_time->day;
  201601. buf[4] = mod_time->hour;
  201602. buf[5] = mod_time->minute;
  201603. buf[6] = mod_time->second;
  201604. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201605. }
  201606. #endif
  201607. /* initializes the row writing capability of libpng */
  201608. void /* PRIVATE */
  201609. png_write_start_row(png_structp png_ptr)
  201610. {
  201611. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201612. #ifdef PNG_USE_LOCAL_ARRAYS
  201613. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201614. /* start of interlace block */
  201615. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201616. /* offset to next interlace block */
  201617. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201618. /* start of interlace block in the y direction */
  201619. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201620. /* offset to next interlace block in the y direction */
  201621. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201622. #endif
  201623. #endif
  201624. png_size_t buf_size;
  201625. png_debug(1, "in png_write_start_row\n");
  201626. buf_size = (png_size_t)(PNG_ROWBYTES(
  201627. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201628. /* set up row buffer */
  201629. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201630. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201631. #ifndef PNG_NO_WRITE_FILTERING
  201632. /* set up filtering buffer, if using this filter */
  201633. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201634. {
  201635. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201636. (png_ptr->rowbytes + 1));
  201637. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201638. }
  201639. /* We only need to keep the previous row if we are using one of these. */
  201640. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201641. {
  201642. /* set up previous row buffer */
  201643. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201644. png_memset(png_ptr->prev_row, 0, buf_size);
  201645. if (png_ptr->do_filter & PNG_FILTER_UP)
  201646. {
  201647. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201648. (png_ptr->rowbytes + 1));
  201649. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201650. }
  201651. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201652. {
  201653. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201654. (png_ptr->rowbytes + 1));
  201655. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201656. }
  201657. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201658. {
  201659. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201660. (png_ptr->rowbytes + 1));
  201661. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201662. }
  201663. #endif /* PNG_NO_WRITE_FILTERING */
  201664. }
  201665. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201666. /* if interlaced, we need to set up width and height of pass */
  201667. if (png_ptr->interlaced)
  201668. {
  201669. if (!(png_ptr->transformations & PNG_INTERLACE))
  201670. {
  201671. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201672. png_pass_ystart[0]) / png_pass_yinc[0];
  201673. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201674. png_pass_start[0]) / png_pass_inc[0];
  201675. }
  201676. else
  201677. {
  201678. png_ptr->num_rows = png_ptr->height;
  201679. png_ptr->usr_width = png_ptr->width;
  201680. }
  201681. }
  201682. else
  201683. #endif
  201684. {
  201685. png_ptr->num_rows = png_ptr->height;
  201686. png_ptr->usr_width = png_ptr->width;
  201687. }
  201688. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201689. png_ptr->zstream.next_out = png_ptr->zbuf;
  201690. }
  201691. /* Internal use only. Called when finished processing a row of data. */
  201692. void /* PRIVATE */
  201693. png_write_finish_row(png_structp png_ptr)
  201694. {
  201695. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201696. #ifdef PNG_USE_LOCAL_ARRAYS
  201697. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201698. /* start of interlace block */
  201699. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201700. /* offset to next interlace block */
  201701. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201702. /* start of interlace block in the y direction */
  201703. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201704. /* offset to next interlace block in the y direction */
  201705. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201706. #endif
  201707. #endif
  201708. int ret;
  201709. png_debug(1, "in png_write_finish_row\n");
  201710. /* next row */
  201711. png_ptr->row_number++;
  201712. /* see if we are done */
  201713. if (png_ptr->row_number < png_ptr->num_rows)
  201714. return;
  201715. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201716. /* if interlaced, go to next pass */
  201717. if (png_ptr->interlaced)
  201718. {
  201719. png_ptr->row_number = 0;
  201720. if (png_ptr->transformations & PNG_INTERLACE)
  201721. {
  201722. png_ptr->pass++;
  201723. }
  201724. else
  201725. {
  201726. /* loop until we find a non-zero width or height pass */
  201727. do
  201728. {
  201729. png_ptr->pass++;
  201730. if (png_ptr->pass >= 7)
  201731. break;
  201732. png_ptr->usr_width = (png_ptr->width +
  201733. png_pass_inc[png_ptr->pass] - 1 -
  201734. png_pass_start[png_ptr->pass]) /
  201735. png_pass_inc[png_ptr->pass];
  201736. png_ptr->num_rows = (png_ptr->height +
  201737. png_pass_yinc[png_ptr->pass] - 1 -
  201738. png_pass_ystart[png_ptr->pass]) /
  201739. png_pass_yinc[png_ptr->pass];
  201740. if (png_ptr->transformations & PNG_INTERLACE)
  201741. break;
  201742. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201743. }
  201744. /* reset the row above the image for the next pass */
  201745. if (png_ptr->pass < 7)
  201746. {
  201747. if (png_ptr->prev_row != NULL)
  201748. png_memset(png_ptr->prev_row, 0,
  201749. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201750. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201751. return;
  201752. }
  201753. }
  201754. #endif
  201755. /* if we get here, we've just written the last row, so we need
  201756. to flush the compressor */
  201757. do
  201758. {
  201759. /* tell the compressor we are done */
  201760. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201761. /* check for an error */
  201762. if (ret == Z_OK)
  201763. {
  201764. /* check to see if we need more room */
  201765. if (!(png_ptr->zstream.avail_out))
  201766. {
  201767. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201768. png_ptr->zstream.next_out = png_ptr->zbuf;
  201769. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201770. }
  201771. }
  201772. else if (ret != Z_STREAM_END)
  201773. {
  201774. if (png_ptr->zstream.msg != NULL)
  201775. png_error(png_ptr, png_ptr->zstream.msg);
  201776. else
  201777. png_error(png_ptr, "zlib error");
  201778. }
  201779. } while (ret != Z_STREAM_END);
  201780. /* write any extra space */
  201781. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201782. {
  201783. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201784. png_ptr->zstream.avail_out);
  201785. }
  201786. deflateReset(&png_ptr->zstream);
  201787. png_ptr->zstream.data_type = Z_BINARY;
  201788. }
  201789. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201790. /* Pick out the correct pixels for the interlace pass.
  201791. * The basic idea here is to go through the row with a source
  201792. * pointer and a destination pointer (sp and dp), and copy the
  201793. * correct pixels for the pass. As the row gets compacted,
  201794. * sp will always be >= dp, so we should never overwrite anything.
  201795. * See the default: case for the easiest code to understand.
  201796. */
  201797. void /* PRIVATE */
  201798. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201799. {
  201800. #ifdef PNG_USE_LOCAL_ARRAYS
  201801. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201802. /* start of interlace block */
  201803. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201804. /* offset to next interlace block */
  201805. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201806. #endif
  201807. png_debug(1, "in png_do_write_interlace\n");
  201808. /* we don't have to do anything on the last pass (6) */
  201809. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201810. if (row != NULL && row_info != NULL && pass < 6)
  201811. #else
  201812. if (pass < 6)
  201813. #endif
  201814. {
  201815. /* each pixel depth is handled separately */
  201816. switch (row_info->pixel_depth)
  201817. {
  201818. case 1:
  201819. {
  201820. png_bytep sp;
  201821. png_bytep dp;
  201822. int shift;
  201823. int d;
  201824. int value;
  201825. png_uint_32 i;
  201826. png_uint_32 row_width = row_info->width;
  201827. dp = row;
  201828. d = 0;
  201829. shift = 7;
  201830. for (i = png_pass_start[pass]; i < row_width;
  201831. i += png_pass_inc[pass])
  201832. {
  201833. sp = row + (png_size_t)(i >> 3);
  201834. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  201835. d |= (value << shift);
  201836. if (shift == 0)
  201837. {
  201838. shift = 7;
  201839. *dp++ = (png_byte)d;
  201840. d = 0;
  201841. }
  201842. else
  201843. shift--;
  201844. }
  201845. if (shift != 7)
  201846. *dp = (png_byte)d;
  201847. break;
  201848. }
  201849. case 2:
  201850. {
  201851. png_bytep sp;
  201852. png_bytep dp;
  201853. int shift;
  201854. int d;
  201855. int value;
  201856. png_uint_32 i;
  201857. png_uint_32 row_width = row_info->width;
  201858. dp = row;
  201859. shift = 6;
  201860. d = 0;
  201861. for (i = png_pass_start[pass]; i < row_width;
  201862. i += png_pass_inc[pass])
  201863. {
  201864. sp = row + (png_size_t)(i >> 2);
  201865. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  201866. d |= (value << shift);
  201867. if (shift == 0)
  201868. {
  201869. shift = 6;
  201870. *dp++ = (png_byte)d;
  201871. d = 0;
  201872. }
  201873. else
  201874. shift -= 2;
  201875. }
  201876. if (shift != 6)
  201877. *dp = (png_byte)d;
  201878. break;
  201879. }
  201880. case 4:
  201881. {
  201882. png_bytep sp;
  201883. png_bytep dp;
  201884. int shift;
  201885. int d;
  201886. int value;
  201887. png_uint_32 i;
  201888. png_uint_32 row_width = row_info->width;
  201889. dp = row;
  201890. shift = 4;
  201891. d = 0;
  201892. for (i = png_pass_start[pass]; i < row_width;
  201893. i += png_pass_inc[pass])
  201894. {
  201895. sp = row + (png_size_t)(i >> 1);
  201896. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  201897. d |= (value << shift);
  201898. if (shift == 0)
  201899. {
  201900. shift = 4;
  201901. *dp++ = (png_byte)d;
  201902. d = 0;
  201903. }
  201904. else
  201905. shift -= 4;
  201906. }
  201907. if (shift != 4)
  201908. *dp = (png_byte)d;
  201909. break;
  201910. }
  201911. default:
  201912. {
  201913. png_bytep sp;
  201914. png_bytep dp;
  201915. png_uint_32 i;
  201916. png_uint_32 row_width = row_info->width;
  201917. png_size_t pixel_bytes;
  201918. /* start at the beginning */
  201919. dp = row;
  201920. /* find out how many bytes each pixel takes up */
  201921. pixel_bytes = (row_info->pixel_depth >> 3);
  201922. /* loop through the row, only looking at the pixels that
  201923. matter */
  201924. for (i = png_pass_start[pass]; i < row_width;
  201925. i += png_pass_inc[pass])
  201926. {
  201927. /* find out where the original pixel is */
  201928. sp = row + (png_size_t)i * pixel_bytes;
  201929. /* move the pixel */
  201930. if (dp != sp)
  201931. png_memcpy(dp, sp, pixel_bytes);
  201932. /* next pixel */
  201933. dp += pixel_bytes;
  201934. }
  201935. break;
  201936. }
  201937. }
  201938. /* set new row width */
  201939. row_info->width = (row_info->width +
  201940. png_pass_inc[pass] - 1 -
  201941. png_pass_start[pass]) /
  201942. png_pass_inc[pass];
  201943. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201944. row_info->width);
  201945. }
  201946. }
  201947. #endif
  201948. /* This filters the row, chooses which filter to use, if it has not already
  201949. * been specified by the application, and then writes the row out with the
  201950. * chosen filter.
  201951. */
  201952. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  201953. #define PNG_HISHIFT 10
  201954. #define PNG_LOMASK ((png_uint_32)0xffffL)
  201955. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  201956. void /* PRIVATE */
  201957. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  201958. {
  201959. png_bytep best_row;
  201960. #ifndef PNG_NO_WRITE_FILTER
  201961. png_bytep prev_row, row_buf;
  201962. png_uint_32 mins, bpp;
  201963. png_byte filter_to_do = png_ptr->do_filter;
  201964. png_uint_32 row_bytes = row_info->rowbytes;
  201965. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201966. int num_p_filters = (int)png_ptr->num_prev_filters;
  201967. #endif
  201968. png_debug(1, "in png_write_find_filter\n");
  201969. /* find out how many bytes offset each pixel is */
  201970. bpp = (row_info->pixel_depth + 7) >> 3;
  201971. prev_row = png_ptr->prev_row;
  201972. #endif
  201973. best_row = png_ptr->row_buf;
  201974. #ifndef PNG_NO_WRITE_FILTER
  201975. row_buf = best_row;
  201976. mins = PNG_MAXSUM;
  201977. /* The prediction method we use is to find which method provides the
  201978. * smallest value when summing the absolute values of the distances
  201979. * from zero, using anything >= 128 as negative numbers. This is known
  201980. * as the "minimum sum of absolute differences" heuristic. Other
  201981. * heuristics are the "weighted minimum sum of absolute differences"
  201982. * (experimental and can in theory improve compression), and the "zlib
  201983. * predictive" method (not implemented yet), which does test compressions
  201984. * of lines using different filter methods, and then chooses the
  201985. * (series of) filter(s) that give minimum compressed data size (VERY
  201986. * computationally expensive).
  201987. *
  201988. * GRR 980525: consider also
  201989. * (1) minimum sum of absolute differences from running average (i.e.,
  201990. * keep running sum of non-absolute differences & count of bytes)
  201991. * [track dispersion, too? restart average if dispersion too large?]
  201992. * (1b) minimum sum of absolute differences from sliding average, probably
  201993. * with window size <= deflate window (usually 32K)
  201994. * (2) minimum sum of squared differences from zero or running average
  201995. * (i.e., ~ root-mean-square approach)
  201996. */
  201997. /* We don't need to test the 'no filter' case if this is the only filter
  201998. * that has been chosen, as it doesn't actually do anything to the data.
  201999. */
  202000. if ((filter_to_do & PNG_FILTER_NONE) &&
  202001. filter_to_do != PNG_FILTER_NONE)
  202002. {
  202003. png_bytep rp;
  202004. png_uint_32 sum = 0;
  202005. png_uint_32 i;
  202006. int v;
  202007. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202008. {
  202009. v = *rp;
  202010. sum += (v < 128) ? v : 256 - v;
  202011. }
  202012. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202013. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202014. {
  202015. png_uint_32 sumhi, sumlo;
  202016. int j;
  202017. sumlo = sum & PNG_LOMASK;
  202018. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202019. /* Reduce the sum if we match any of the previous rows */
  202020. for (j = 0; j < num_p_filters; j++)
  202021. {
  202022. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202023. {
  202024. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202025. PNG_WEIGHT_SHIFT;
  202026. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202027. PNG_WEIGHT_SHIFT;
  202028. }
  202029. }
  202030. /* Factor in the cost of this filter (this is here for completeness,
  202031. * but it makes no sense to have a "cost" for the NONE filter, as
  202032. * it has the minimum possible computational cost - none).
  202033. */
  202034. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202035. PNG_COST_SHIFT;
  202036. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202037. PNG_COST_SHIFT;
  202038. if (sumhi > PNG_HIMASK)
  202039. sum = PNG_MAXSUM;
  202040. else
  202041. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202042. }
  202043. #endif
  202044. mins = sum;
  202045. }
  202046. /* sub filter */
  202047. if (filter_to_do == PNG_FILTER_SUB)
  202048. /* it's the only filter so no testing is needed */
  202049. {
  202050. png_bytep rp, lp, dp;
  202051. png_uint_32 i;
  202052. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202053. i++, rp++, dp++)
  202054. {
  202055. *dp = *rp;
  202056. }
  202057. for (lp = row_buf + 1; i < row_bytes;
  202058. i++, rp++, lp++, dp++)
  202059. {
  202060. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202061. }
  202062. best_row = png_ptr->sub_row;
  202063. }
  202064. else if (filter_to_do & PNG_FILTER_SUB)
  202065. {
  202066. png_bytep rp, dp, lp;
  202067. png_uint_32 sum = 0, lmins = mins;
  202068. png_uint_32 i;
  202069. int v;
  202070. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202071. /* We temporarily increase the "minimum sum" by the factor we
  202072. * would reduce the sum of this filter, so that we can do the
  202073. * early exit comparison without scaling the sum each time.
  202074. */
  202075. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202076. {
  202077. int j;
  202078. png_uint_32 lmhi, lmlo;
  202079. lmlo = lmins & PNG_LOMASK;
  202080. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202081. for (j = 0; j < num_p_filters; j++)
  202082. {
  202083. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202084. {
  202085. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202086. PNG_WEIGHT_SHIFT;
  202087. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202088. PNG_WEIGHT_SHIFT;
  202089. }
  202090. }
  202091. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202092. PNG_COST_SHIFT;
  202093. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202094. PNG_COST_SHIFT;
  202095. if (lmhi > PNG_HIMASK)
  202096. lmins = PNG_MAXSUM;
  202097. else
  202098. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202099. }
  202100. #endif
  202101. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202102. i++, rp++, dp++)
  202103. {
  202104. v = *dp = *rp;
  202105. sum += (v < 128) ? v : 256 - v;
  202106. }
  202107. for (lp = row_buf + 1; i < row_bytes;
  202108. i++, rp++, lp++, dp++)
  202109. {
  202110. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202111. sum += (v < 128) ? v : 256 - v;
  202112. if (sum > lmins) /* We are already worse, don't continue. */
  202113. break;
  202114. }
  202115. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202116. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202117. {
  202118. int j;
  202119. png_uint_32 sumhi, sumlo;
  202120. sumlo = sum & PNG_LOMASK;
  202121. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202122. for (j = 0; j < num_p_filters; j++)
  202123. {
  202124. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202125. {
  202126. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202127. PNG_WEIGHT_SHIFT;
  202128. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202129. PNG_WEIGHT_SHIFT;
  202130. }
  202131. }
  202132. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202133. PNG_COST_SHIFT;
  202134. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202135. PNG_COST_SHIFT;
  202136. if (sumhi > PNG_HIMASK)
  202137. sum = PNG_MAXSUM;
  202138. else
  202139. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202140. }
  202141. #endif
  202142. if (sum < mins)
  202143. {
  202144. mins = sum;
  202145. best_row = png_ptr->sub_row;
  202146. }
  202147. }
  202148. /* up filter */
  202149. if (filter_to_do == PNG_FILTER_UP)
  202150. {
  202151. png_bytep rp, dp, pp;
  202152. png_uint_32 i;
  202153. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202154. pp = prev_row + 1; i < row_bytes;
  202155. i++, rp++, pp++, dp++)
  202156. {
  202157. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202158. }
  202159. best_row = png_ptr->up_row;
  202160. }
  202161. else if (filter_to_do & PNG_FILTER_UP)
  202162. {
  202163. png_bytep rp, dp, pp;
  202164. png_uint_32 sum = 0, lmins = mins;
  202165. png_uint_32 i;
  202166. int v;
  202167. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202168. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202169. {
  202170. int j;
  202171. png_uint_32 lmhi, lmlo;
  202172. lmlo = lmins & PNG_LOMASK;
  202173. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202174. for (j = 0; j < num_p_filters; j++)
  202175. {
  202176. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202177. {
  202178. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202179. PNG_WEIGHT_SHIFT;
  202180. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202181. PNG_WEIGHT_SHIFT;
  202182. }
  202183. }
  202184. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202185. PNG_COST_SHIFT;
  202186. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202187. PNG_COST_SHIFT;
  202188. if (lmhi > PNG_HIMASK)
  202189. lmins = PNG_MAXSUM;
  202190. else
  202191. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202192. }
  202193. #endif
  202194. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202195. pp = prev_row + 1; i < row_bytes; i++)
  202196. {
  202197. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202198. sum += (v < 128) ? v : 256 - v;
  202199. if (sum > lmins) /* We are already worse, don't continue. */
  202200. break;
  202201. }
  202202. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202203. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202204. {
  202205. int j;
  202206. png_uint_32 sumhi, sumlo;
  202207. sumlo = sum & PNG_LOMASK;
  202208. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202209. for (j = 0; j < num_p_filters; j++)
  202210. {
  202211. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202212. {
  202213. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202214. PNG_WEIGHT_SHIFT;
  202215. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202216. PNG_WEIGHT_SHIFT;
  202217. }
  202218. }
  202219. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202220. PNG_COST_SHIFT;
  202221. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202222. PNG_COST_SHIFT;
  202223. if (sumhi > PNG_HIMASK)
  202224. sum = PNG_MAXSUM;
  202225. else
  202226. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202227. }
  202228. #endif
  202229. if (sum < mins)
  202230. {
  202231. mins = sum;
  202232. best_row = png_ptr->up_row;
  202233. }
  202234. }
  202235. /* avg filter */
  202236. if (filter_to_do == PNG_FILTER_AVG)
  202237. {
  202238. png_bytep rp, dp, pp, lp;
  202239. png_uint_32 i;
  202240. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202241. pp = prev_row + 1; i < bpp; i++)
  202242. {
  202243. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202244. }
  202245. for (lp = row_buf + 1; i < row_bytes; i++)
  202246. {
  202247. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202248. & 0xff);
  202249. }
  202250. best_row = png_ptr->avg_row;
  202251. }
  202252. else if (filter_to_do & PNG_FILTER_AVG)
  202253. {
  202254. png_bytep rp, dp, pp, lp;
  202255. png_uint_32 sum = 0, lmins = mins;
  202256. png_uint_32 i;
  202257. int v;
  202258. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202259. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202260. {
  202261. int j;
  202262. png_uint_32 lmhi, lmlo;
  202263. lmlo = lmins & PNG_LOMASK;
  202264. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202265. for (j = 0; j < num_p_filters; j++)
  202266. {
  202267. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202268. {
  202269. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202270. PNG_WEIGHT_SHIFT;
  202271. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202272. PNG_WEIGHT_SHIFT;
  202273. }
  202274. }
  202275. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202276. PNG_COST_SHIFT;
  202277. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202278. PNG_COST_SHIFT;
  202279. if (lmhi > PNG_HIMASK)
  202280. lmins = PNG_MAXSUM;
  202281. else
  202282. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202283. }
  202284. #endif
  202285. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202286. pp = prev_row + 1; i < bpp; i++)
  202287. {
  202288. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202289. sum += (v < 128) ? v : 256 - v;
  202290. }
  202291. for (lp = row_buf + 1; i < row_bytes; i++)
  202292. {
  202293. v = *dp++ =
  202294. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202295. sum += (v < 128) ? v : 256 - v;
  202296. if (sum > lmins) /* We are already worse, don't continue. */
  202297. break;
  202298. }
  202299. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202300. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202301. {
  202302. int j;
  202303. png_uint_32 sumhi, sumlo;
  202304. sumlo = sum & PNG_LOMASK;
  202305. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202306. for (j = 0; j < num_p_filters; j++)
  202307. {
  202308. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202309. {
  202310. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202311. PNG_WEIGHT_SHIFT;
  202312. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202313. PNG_WEIGHT_SHIFT;
  202314. }
  202315. }
  202316. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202317. PNG_COST_SHIFT;
  202318. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202319. PNG_COST_SHIFT;
  202320. if (sumhi > PNG_HIMASK)
  202321. sum = PNG_MAXSUM;
  202322. else
  202323. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202324. }
  202325. #endif
  202326. if (sum < mins)
  202327. {
  202328. mins = sum;
  202329. best_row = png_ptr->avg_row;
  202330. }
  202331. }
  202332. /* Paeth filter */
  202333. if (filter_to_do == PNG_FILTER_PAETH)
  202334. {
  202335. png_bytep rp, dp, pp, cp, lp;
  202336. png_uint_32 i;
  202337. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202338. pp = prev_row + 1; i < bpp; i++)
  202339. {
  202340. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202341. }
  202342. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202343. {
  202344. int a, b, c, pa, pb, pc, p;
  202345. b = *pp++;
  202346. c = *cp++;
  202347. a = *lp++;
  202348. p = b - c;
  202349. pc = a - c;
  202350. #ifdef PNG_USE_ABS
  202351. pa = abs(p);
  202352. pb = abs(pc);
  202353. pc = abs(p + pc);
  202354. #else
  202355. pa = p < 0 ? -p : p;
  202356. pb = pc < 0 ? -pc : pc;
  202357. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202358. #endif
  202359. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202360. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202361. }
  202362. best_row = png_ptr->paeth_row;
  202363. }
  202364. else if (filter_to_do & PNG_FILTER_PAETH)
  202365. {
  202366. png_bytep rp, dp, pp, cp, lp;
  202367. png_uint_32 sum = 0, lmins = mins;
  202368. png_uint_32 i;
  202369. int v;
  202370. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202371. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202372. {
  202373. int j;
  202374. png_uint_32 lmhi, lmlo;
  202375. lmlo = lmins & PNG_LOMASK;
  202376. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202377. for (j = 0; j < num_p_filters; j++)
  202378. {
  202379. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202380. {
  202381. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202382. PNG_WEIGHT_SHIFT;
  202383. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202384. PNG_WEIGHT_SHIFT;
  202385. }
  202386. }
  202387. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202388. PNG_COST_SHIFT;
  202389. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202390. PNG_COST_SHIFT;
  202391. if (lmhi > PNG_HIMASK)
  202392. lmins = PNG_MAXSUM;
  202393. else
  202394. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202395. }
  202396. #endif
  202397. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202398. pp = prev_row + 1; i < bpp; i++)
  202399. {
  202400. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202401. sum += (v < 128) ? v : 256 - v;
  202402. }
  202403. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202404. {
  202405. int a, b, c, pa, pb, pc, p;
  202406. b = *pp++;
  202407. c = *cp++;
  202408. a = *lp++;
  202409. #ifndef PNG_SLOW_PAETH
  202410. p = b - c;
  202411. pc = a - c;
  202412. #ifdef PNG_USE_ABS
  202413. pa = abs(p);
  202414. pb = abs(pc);
  202415. pc = abs(p + pc);
  202416. #else
  202417. pa = p < 0 ? -p : p;
  202418. pb = pc < 0 ? -pc : pc;
  202419. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202420. #endif
  202421. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202422. #else /* PNG_SLOW_PAETH */
  202423. p = a + b - c;
  202424. pa = abs(p - a);
  202425. pb = abs(p - b);
  202426. pc = abs(p - c);
  202427. if (pa <= pb && pa <= pc)
  202428. p = a;
  202429. else if (pb <= pc)
  202430. p = b;
  202431. else
  202432. p = c;
  202433. #endif /* PNG_SLOW_PAETH */
  202434. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202435. sum += (v < 128) ? v : 256 - v;
  202436. if (sum > lmins) /* We are already worse, don't continue. */
  202437. break;
  202438. }
  202439. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202440. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202441. {
  202442. int j;
  202443. png_uint_32 sumhi, sumlo;
  202444. sumlo = sum & PNG_LOMASK;
  202445. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202446. for (j = 0; j < num_p_filters; j++)
  202447. {
  202448. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202449. {
  202450. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202451. PNG_WEIGHT_SHIFT;
  202452. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202453. PNG_WEIGHT_SHIFT;
  202454. }
  202455. }
  202456. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202457. PNG_COST_SHIFT;
  202458. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202459. PNG_COST_SHIFT;
  202460. if (sumhi > PNG_HIMASK)
  202461. sum = PNG_MAXSUM;
  202462. else
  202463. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202464. }
  202465. #endif
  202466. if (sum < mins)
  202467. {
  202468. best_row = png_ptr->paeth_row;
  202469. }
  202470. }
  202471. #endif /* PNG_NO_WRITE_FILTER */
  202472. /* Do the actual writing of the filtered row data from the chosen filter. */
  202473. png_write_filtered_row(png_ptr, best_row);
  202474. #ifndef PNG_NO_WRITE_FILTER
  202475. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202476. /* Save the type of filter we picked this time for future calculations */
  202477. if (png_ptr->num_prev_filters > 0)
  202478. {
  202479. int j;
  202480. for (j = 1; j < num_p_filters; j++)
  202481. {
  202482. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202483. }
  202484. png_ptr->prev_filters[j] = best_row[0];
  202485. }
  202486. #endif
  202487. #endif /* PNG_NO_WRITE_FILTER */
  202488. }
  202489. /* Do the actual writing of a previously filtered row. */
  202490. void /* PRIVATE */
  202491. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202492. {
  202493. png_debug(1, "in png_write_filtered_row\n");
  202494. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202495. /* set up the zlib input buffer */
  202496. png_ptr->zstream.next_in = filtered_row;
  202497. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202498. /* repeat until we have compressed all the data */
  202499. do
  202500. {
  202501. int ret; /* return of zlib */
  202502. /* compress the data */
  202503. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202504. /* check for compression errors */
  202505. if (ret != Z_OK)
  202506. {
  202507. if (png_ptr->zstream.msg != NULL)
  202508. png_error(png_ptr, png_ptr->zstream.msg);
  202509. else
  202510. png_error(png_ptr, "zlib error");
  202511. }
  202512. /* see if it is time to write another IDAT */
  202513. if (!(png_ptr->zstream.avail_out))
  202514. {
  202515. /* write the IDAT and reset the zlib output buffer */
  202516. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202517. png_ptr->zstream.next_out = png_ptr->zbuf;
  202518. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202519. }
  202520. /* repeat until all data has been compressed */
  202521. } while (png_ptr->zstream.avail_in);
  202522. /* swap the current and previous rows */
  202523. if (png_ptr->prev_row != NULL)
  202524. {
  202525. png_bytep tptr;
  202526. tptr = png_ptr->prev_row;
  202527. png_ptr->prev_row = png_ptr->row_buf;
  202528. png_ptr->row_buf = tptr;
  202529. }
  202530. /* finish row - updates counters and flushes zlib if last row */
  202531. png_write_finish_row(png_ptr);
  202532. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202533. png_ptr->flush_rows++;
  202534. if (png_ptr->flush_dist > 0 &&
  202535. png_ptr->flush_rows >= png_ptr->flush_dist)
  202536. {
  202537. png_write_flush(png_ptr);
  202538. }
  202539. #endif
  202540. }
  202541. #endif /* PNG_WRITE_SUPPORTED */
  202542. /*** End of inlined file: pngwutil.c ***/
  202543. }
  202544. #else
  202545. extern "C"
  202546. {
  202547. #include <png.h>
  202548. #include <pngconf.h>
  202549. }
  202550. #endif
  202551. }
  202552. #undef max
  202553. #undef min
  202554. #if JUCE_MSVC
  202555. #pragma warning (pop)
  202556. #endif
  202557. BEGIN_JUCE_NAMESPACE
  202558. using ::calloc;
  202559. using ::malloc;
  202560. using ::free;
  202561. namespace PNGHelpers
  202562. {
  202563. using namespace pnglibNamespace;
  202564. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  202565. {
  202566. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202567. }
  202568. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202569. {
  202570. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202571. }
  202572. struct PNGErrorStruct {};
  202573. static void errorCallback (png_structp, png_const_charp)
  202574. {
  202575. throw PNGErrorStruct();
  202576. }
  202577. }
  202578. PNGImageFormat::PNGImageFormat() {}
  202579. PNGImageFormat::~PNGImageFormat() {}
  202580. const String PNGImageFormat::getFormatName()
  202581. {
  202582. return "PNG";
  202583. }
  202584. bool PNGImageFormat::canUnderstand (InputStream& in)
  202585. {
  202586. const int bytesNeeded = 4;
  202587. char header [bytesNeeded];
  202588. return in.read (header, bytesNeeded) == bytesNeeded
  202589. && header[1] == 'P'
  202590. && header[2] == 'N'
  202591. && header[3] == 'G';
  202592. }
  202593. const Image PNGImageFormat::decodeImage (InputStream& in)
  202594. {
  202595. using namespace pnglibNamespace;
  202596. Image image;
  202597. png_structp pngReadStruct;
  202598. png_infop pngInfoStruct;
  202599. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202600. if (pngReadStruct != 0)
  202601. {
  202602. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202603. if (pngInfoStruct == 0)
  202604. {
  202605. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202606. return Image::null;
  202607. }
  202608. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202609. // read the header..
  202610. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202611. png_uint_32 width, height;
  202612. int bitDepth, colorType, interlaceType;
  202613. png_read_info (pngReadStruct, pngInfoStruct);
  202614. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202615. &width, &height,
  202616. &bitDepth, &colorType,
  202617. &interlaceType, 0, 0);
  202618. if (bitDepth == 16)
  202619. png_set_strip_16 (pngReadStruct);
  202620. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202621. png_set_expand (pngReadStruct);
  202622. if (bitDepth < 8)
  202623. png_set_expand (pngReadStruct);
  202624. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202625. png_set_expand (pngReadStruct);
  202626. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202627. png_set_gray_to_rgb (pngReadStruct);
  202628. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202629. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202630. || pngInfoStruct->num_trans > 0;
  202631. // Load the image into a temp buffer in the pnglib format..
  202632. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202633. {
  202634. HeapBlock <png_bytep> rows (height);
  202635. for (int y = (int) height; --y >= 0;)
  202636. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202637. png_read_image (pngReadStruct, rows);
  202638. png_read_end (pngReadStruct, pngInfoStruct);
  202639. }
  202640. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202641. // now convert the data to a juce image format..
  202642. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202643. (int) width, (int) height, hasAlphaChan);
  202644. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202645. const Image::BitmapData destData (image, true);
  202646. uint8* srcRow = tempBuffer;
  202647. uint8* destRow = destData.data;
  202648. for (int y = 0; y < (int) height; ++y)
  202649. {
  202650. const uint8* src = srcRow;
  202651. srcRow += (width << 2);
  202652. uint8* dest = destRow;
  202653. destRow += destData.lineStride;
  202654. if (hasAlphaChan)
  202655. {
  202656. for (int i = (int) width; --i >= 0;)
  202657. {
  202658. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202659. ((PixelARGB*) dest)->premultiply();
  202660. dest += destData.pixelStride;
  202661. src += 4;
  202662. }
  202663. }
  202664. else
  202665. {
  202666. for (int i = (int) width; --i >= 0;)
  202667. {
  202668. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202669. dest += destData.pixelStride;
  202670. src += 4;
  202671. }
  202672. }
  202673. }
  202674. }
  202675. return image;
  202676. }
  202677. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202678. {
  202679. using namespace pnglibNamespace;
  202680. const int width = image.getWidth();
  202681. const int height = image.getHeight();
  202682. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202683. if (pngWriteStruct == 0)
  202684. return false;
  202685. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202686. if (pngInfoStruct == 0)
  202687. {
  202688. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202689. return false;
  202690. }
  202691. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202692. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202693. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202694. : PNG_COLOR_TYPE_RGB,
  202695. PNG_INTERLACE_NONE,
  202696. PNG_COMPRESSION_TYPE_BASE,
  202697. PNG_FILTER_TYPE_BASE);
  202698. HeapBlock <uint8> rowData (width * 4);
  202699. png_color_8 sig_bit;
  202700. sig_bit.red = 8;
  202701. sig_bit.green = 8;
  202702. sig_bit.blue = 8;
  202703. sig_bit.alpha = 8;
  202704. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202705. png_write_info (pngWriteStruct, pngInfoStruct);
  202706. png_set_shift (pngWriteStruct, &sig_bit);
  202707. png_set_packing (pngWriteStruct);
  202708. const Image::BitmapData srcData (image, false);
  202709. for (int y = 0; y < height; ++y)
  202710. {
  202711. uint8* dst = rowData;
  202712. const uint8* src = srcData.getLinePointer (y);
  202713. if (image.hasAlphaChannel())
  202714. {
  202715. for (int i = width; --i >= 0;)
  202716. {
  202717. PixelARGB p (*(const PixelARGB*) src);
  202718. p.unpremultiply();
  202719. *dst++ = p.getRed();
  202720. *dst++ = p.getGreen();
  202721. *dst++ = p.getBlue();
  202722. *dst++ = p.getAlpha();
  202723. src += srcData.pixelStride;
  202724. }
  202725. }
  202726. else
  202727. {
  202728. for (int i = width; --i >= 0;)
  202729. {
  202730. *dst++ = ((const PixelRGB*) src)->getRed();
  202731. *dst++ = ((const PixelRGB*) src)->getGreen();
  202732. *dst++ = ((const PixelRGB*) src)->getBlue();
  202733. src += srcData.pixelStride;
  202734. }
  202735. }
  202736. png_write_rows (pngWriteStruct, &rowData, 1);
  202737. }
  202738. png_write_end (pngWriteStruct, pngInfoStruct);
  202739. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202740. out.flush();
  202741. return true;
  202742. }
  202743. END_JUCE_NAMESPACE
  202744. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202745. #endif
  202746. //==============================================================================
  202747. #if JUCE_BUILD_NATIVE
  202748. #if JUCE_WINDOWS
  202749. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  202750. /*
  202751. This file wraps together all the win32-specific code, so that
  202752. we can include all the native headers just once, and compile all our
  202753. platform-specific stuff in one big lump, keeping it out of the way of
  202754. the rest of the codebase.
  202755. */
  202756. #if JUCE_WINDOWS
  202757. BEGIN_JUCE_NAMESPACE
  202758. #define JUCE_INCLUDED_FILE 1
  202759. // Now include the actual code files..
  202760. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202761. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202762. // compiled on its own).
  202763. #if JUCE_INCLUDED_FILE
  202764. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202765. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202766. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202767. #ifndef DOXYGEN
  202768. // use with DynamicLibraryLoader to simplify importing functions
  202769. //
  202770. // functionName: function to import
  202771. // localFunctionName: name you want to use to actually call it (must be different)
  202772. // returnType: the return type
  202773. // object: the DynamicLibraryLoader to use
  202774. // params: list of params (bracketed)
  202775. //
  202776. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  202777. typedef returnType (WINAPI *type##localFunctionName) params; \
  202778. type##localFunctionName localFunctionName \
  202779. = (type##localFunctionName)object.findProcAddress (#functionName);
  202780. // loads and unloads a DLL automatically
  202781. class JUCE_API DynamicLibraryLoader
  202782. {
  202783. public:
  202784. DynamicLibraryLoader (const String& name);
  202785. ~DynamicLibraryLoader();
  202786. void* findProcAddress (const String& functionName);
  202787. private:
  202788. void* libHandle;
  202789. };
  202790. #endif
  202791. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202792. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202793. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  202794. {
  202795. libHandle = LoadLibrary (name);
  202796. }
  202797. DynamicLibraryLoader::~DynamicLibraryLoader()
  202798. {
  202799. FreeLibrary ((HMODULE) libHandle);
  202800. }
  202801. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  202802. {
  202803. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  202804. }
  202805. #endif
  202806. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202807. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  202808. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202809. // compiled on its own).
  202810. #if JUCE_INCLUDED_FILE
  202811. extern void juce_initialiseThreadEvents();
  202812. void Logger::outputDebugString (const String& text)
  202813. {
  202814. OutputDebugString (text + "\n");
  202815. }
  202816. static int64 hiResTicksPerSecond;
  202817. static double hiResTicksScaleFactor;
  202818. #if JUCE_USE_INTRINSICS
  202819. // CPU info functions using intrinsics...
  202820. #pragma intrinsic (__cpuid)
  202821. #pragma intrinsic (__rdtsc)
  202822. const String SystemStats::getCpuVendor()
  202823. {
  202824. int info [4];
  202825. __cpuid (info, 0);
  202826. char v [12];
  202827. memcpy (v, info + 1, 4);
  202828. memcpy (v + 4, info + 3, 4);
  202829. memcpy (v + 8, info + 2, 4);
  202830. return String (v, 12);
  202831. }
  202832. #else
  202833. // CPU info functions using old fashioned inline asm...
  202834. static void juce_getCpuVendor (char* const v)
  202835. {
  202836. int vendor[4];
  202837. zeromem (vendor, 16);
  202838. #ifdef JUCE_64BIT
  202839. #else
  202840. #ifndef __MINGW32__
  202841. __try
  202842. #endif
  202843. {
  202844. #if JUCE_GCC
  202845. unsigned int dummy = 0;
  202846. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  202847. #else
  202848. __asm
  202849. {
  202850. mov eax, 0
  202851. cpuid
  202852. mov [vendor], ebx
  202853. mov [vendor + 4], edx
  202854. mov [vendor + 8], ecx
  202855. }
  202856. #endif
  202857. }
  202858. #ifndef __MINGW32__
  202859. __except (EXCEPTION_EXECUTE_HANDLER)
  202860. {
  202861. *v = 0;
  202862. }
  202863. #endif
  202864. #endif
  202865. memcpy (v, vendor, 16);
  202866. }
  202867. const String SystemStats::getCpuVendor()
  202868. {
  202869. char v [16];
  202870. juce_getCpuVendor (v);
  202871. return String (v, 16);
  202872. }
  202873. #endif
  202874. void SystemStats::initialiseStats()
  202875. {
  202876. juce_initialiseThreadEvents();
  202877. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  202878. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  202879. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  202880. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  202881. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  202882. #else
  202883. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  202884. #endif
  202885. {
  202886. SYSTEM_INFO systemInfo;
  202887. GetSystemInfo (&systemInfo);
  202888. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  202889. }
  202890. LARGE_INTEGER f;
  202891. QueryPerformanceFrequency (&f);
  202892. hiResTicksPerSecond = f.QuadPart;
  202893. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  202894. String s (SystemStats::getJUCEVersion());
  202895. const MMRESULT res = timeBeginPeriod (1);
  202896. (void) res;
  202897. jassert (res == TIMERR_NOERROR);
  202898. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202899. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  202900. #endif
  202901. }
  202902. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  202903. {
  202904. OSVERSIONINFO info;
  202905. info.dwOSVersionInfoSize = sizeof (info);
  202906. GetVersionEx (&info);
  202907. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  202908. {
  202909. switch (info.dwMajorVersion)
  202910. {
  202911. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  202912. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  202913. default: jassertfalse; break; // !! not a supported OS!
  202914. }
  202915. }
  202916. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  202917. {
  202918. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  202919. return Win98;
  202920. }
  202921. return UnknownOS;
  202922. }
  202923. const String SystemStats::getOperatingSystemName()
  202924. {
  202925. const char* name = "Unknown OS";
  202926. switch (getOperatingSystemType())
  202927. {
  202928. case Windows7: name = "Windows 7"; break;
  202929. case WinVista: name = "Windows Vista"; break;
  202930. case WinXP: name = "Windows XP"; break;
  202931. case Win2000: name = "Windows 2000"; break;
  202932. case Win98: name = "Windows 98"; break;
  202933. default: jassertfalse; break; // !! new type of OS?
  202934. }
  202935. return name;
  202936. }
  202937. bool SystemStats::isOperatingSystem64Bit()
  202938. {
  202939. #ifdef _WIN64
  202940. return true;
  202941. #else
  202942. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  202943. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  202944. BOOL isWow64 = FALSE;
  202945. return (fnIsWow64Process != 0)
  202946. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  202947. && (isWow64 != FALSE);
  202948. #endif
  202949. }
  202950. int SystemStats::getMemorySizeInMegabytes()
  202951. {
  202952. MEMORYSTATUSEX mem;
  202953. mem.dwLength = sizeof (mem);
  202954. GlobalMemoryStatusEx (&mem);
  202955. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  202956. }
  202957. uint32 juce_millisecondsSinceStartup() throw()
  202958. {
  202959. return (uint32) GetTickCount();
  202960. }
  202961. int64 Time::getHighResolutionTicks() throw()
  202962. {
  202963. LARGE_INTEGER ticks;
  202964. QueryPerformanceCounter (&ticks);
  202965. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  202966. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  202967. // fix for a very obscure PCI hardware bug that can make the counter
  202968. // sometimes jump forwards by a few seconds..
  202969. static int64 hiResTicksOffset = 0;
  202970. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  202971. if (offsetDrift > (hiResTicksPerSecond >> 1))
  202972. hiResTicksOffset = newOffset;
  202973. return ticks.QuadPart + hiResTicksOffset;
  202974. }
  202975. double Time::getMillisecondCounterHiRes() throw()
  202976. {
  202977. return getHighResolutionTicks() * hiResTicksScaleFactor;
  202978. }
  202979. int64 Time::getHighResolutionTicksPerSecond() throw()
  202980. {
  202981. return hiResTicksPerSecond;
  202982. }
  202983. static int64 juce_getClockCycleCounter() throw()
  202984. {
  202985. #if JUCE_USE_INTRINSICS
  202986. // MS intrinsics version...
  202987. return __rdtsc();
  202988. #elif JUCE_GCC
  202989. // GNU inline asm version...
  202990. unsigned int hi = 0, lo = 0;
  202991. __asm__ __volatile__ (
  202992. "xor %%eax, %%eax \n\
  202993. xor %%edx, %%edx \n\
  202994. rdtsc \n\
  202995. movl %%eax, %[lo] \n\
  202996. movl %%edx, %[hi]"
  202997. :
  202998. : [hi] "m" (hi),
  202999. [lo] "m" (lo)
  203000. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203001. return (int64) ((((uint64) hi) << 32) | lo);
  203002. #else
  203003. // MSVC inline asm version...
  203004. unsigned int hi = 0, lo = 0;
  203005. __asm
  203006. {
  203007. xor eax, eax
  203008. xor edx, edx
  203009. rdtsc
  203010. mov lo, eax
  203011. mov hi, edx
  203012. }
  203013. return (int64) ((((uint64) hi) << 32) | lo);
  203014. #endif
  203015. }
  203016. int SystemStats::getCpuSpeedInMegaherz()
  203017. {
  203018. const int64 cycles = juce_getClockCycleCounter();
  203019. const uint32 millis = Time::getMillisecondCounter();
  203020. int lastResult = 0;
  203021. for (;;)
  203022. {
  203023. int n = 1000000;
  203024. while (--n > 0) {}
  203025. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203026. const int64 cyclesNow = juce_getClockCycleCounter();
  203027. if (millisElapsed > 80)
  203028. {
  203029. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203030. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203031. return newResult;
  203032. lastResult = newResult;
  203033. }
  203034. }
  203035. }
  203036. bool Time::setSystemTimeToThisTime() const
  203037. {
  203038. SYSTEMTIME st;
  203039. st.wDayOfWeek = 0;
  203040. st.wYear = (WORD) getYear();
  203041. st.wMonth = (WORD) (getMonth() + 1);
  203042. st.wDay = (WORD) getDayOfMonth();
  203043. st.wHour = (WORD) getHours();
  203044. st.wMinute = (WORD) getMinutes();
  203045. st.wSecond = (WORD) getSeconds();
  203046. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203047. // do this twice because of daylight saving conversion problems - the
  203048. // first one sets it up, the second one kicks it in.
  203049. return SetLocalTime (&st) != 0
  203050. && SetLocalTime (&st) != 0;
  203051. }
  203052. int SystemStats::getPageSize()
  203053. {
  203054. SYSTEM_INFO systemInfo;
  203055. GetSystemInfo (&systemInfo);
  203056. return systemInfo.dwPageSize;
  203057. }
  203058. const String SystemStats::getLogonName()
  203059. {
  203060. TCHAR text [256];
  203061. DWORD len = numElementsInArray (text) - 2;
  203062. zerostruct (text);
  203063. GetUserName (text, &len);
  203064. return String (text, len);
  203065. }
  203066. const String SystemStats::getFullUserName()
  203067. {
  203068. return getLogonName();
  203069. }
  203070. #endif
  203071. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203072. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203073. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203074. // compiled on its own).
  203075. #if JUCE_INCLUDED_FILE
  203076. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203077. extern HWND juce_messageWindowHandle;
  203078. #endif
  203079. #if ! JUCE_USE_INTRINSICS
  203080. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203081. // older ones we have to actually call the ops as win32 functions..
  203082. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203083. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203084. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203085. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203086. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203087. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203088. {
  203089. jassertfalse; // This operation isn't available in old MS compiler versions!
  203090. __int64 oldValue = *value;
  203091. if (oldValue == valueToCompare)
  203092. *value = newValue;
  203093. return oldValue;
  203094. }
  203095. #endif
  203096. CriticalSection::CriticalSection() throw()
  203097. {
  203098. // (just to check the MS haven't changed this structure and broken things...)
  203099. #if _MSC_VER >= 1400
  203100. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203101. #else
  203102. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203103. #endif
  203104. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203105. }
  203106. CriticalSection::~CriticalSection() throw()
  203107. {
  203108. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203109. }
  203110. void CriticalSection::enter() const throw()
  203111. {
  203112. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203113. }
  203114. bool CriticalSection::tryEnter() const throw()
  203115. {
  203116. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203117. }
  203118. void CriticalSection::exit() const throw()
  203119. {
  203120. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203121. }
  203122. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203123. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203124. {
  203125. }
  203126. WaitableEvent::~WaitableEvent() throw()
  203127. {
  203128. CloseHandle (internal);
  203129. }
  203130. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203131. {
  203132. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203133. }
  203134. void WaitableEvent::signal() const throw()
  203135. {
  203136. SetEvent (internal);
  203137. }
  203138. void WaitableEvent::reset() const throw()
  203139. {
  203140. ResetEvent (internal);
  203141. }
  203142. void JUCE_API juce_threadEntryPoint (void*);
  203143. static unsigned int __stdcall threadEntryProc (void* userData)
  203144. {
  203145. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203146. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203147. GetCurrentThreadId(), TRUE);
  203148. #endif
  203149. juce_threadEntryPoint (userData);
  203150. _endthreadex (0);
  203151. return 0;
  203152. }
  203153. void juce_CloseThreadHandle (void* handle)
  203154. {
  203155. CloseHandle ((HANDLE) handle);
  203156. }
  203157. void* juce_createThread (void* userData)
  203158. {
  203159. unsigned int threadId;
  203160. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203161. }
  203162. void juce_killThread (void* handle)
  203163. {
  203164. if (handle != 0)
  203165. {
  203166. #if JUCE_DEBUG
  203167. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203168. #endif
  203169. TerminateThread (handle, 0);
  203170. }
  203171. }
  203172. void juce_setCurrentThreadName (const String& name)
  203173. {
  203174. #if JUCE_DEBUG && JUCE_MSVC
  203175. struct
  203176. {
  203177. DWORD dwType;
  203178. LPCSTR szName;
  203179. DWORD dwThreadID;
  203180. DWORD dwFlags;
  203181. } info;
  203182. info.dwType = 0x1000;
  203183. info.szName = name.toCString();
  203184. info.dwThreadID = GetCurrentThreadId();
  203185. info.dwFlags = 0;
  203186. __try
  203187. {
  203188. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203189. }
  203190. __except (EXCEPTION_CONTINUE_EXECUTION)
  203191. {}
  203192. #else
  203193. (void) name;
  203194. #endif
  203195. }
  203196. Thread::ThreadID Thread::getCurrentThreadId()
  203197. {
  203198. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203199. }
  203200. // priority 1 to 10 where 5=normal, 1=low
  203201. bool juce_setThreadPriority (void* threadHandle, int priority)
  203202. {
  203203. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203204. if (priority < 1)
  203205. pri = THREAD_PRIORITY_IDLE;
  203206. else if (priority < 2)
  203207. pri = THREAD_PRIORITY_LOWEST;
  203208. else if (priority < 5)
  203209. pri = THREAD_PRIORITY_BELOW_NORMAL;
  203210. else if (priority < 7)
  203211. pri = THREAD_PRIORITY_NORMAL;
  203212. else if (priority < 9)
  203213. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203214. else if (priority < 10)
  203215. pri = THREAD_PRIORITY_HIGHEST;
  203216. if (threadHandle == 0)
  203217. threadHandle = GetCurrentThread();
  203218. return SetThreadPriority (threadHandle, pri) != FALSE;
  203219. }
  203220. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203221. {
  203222. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203223. }
  203224. static HANDLE sleepEvent = 0;
  203225. void juce_initialiseThreadEvents()
  203226. {
  203227. if (sleepEvent == 0)
  203228. #if JUCE_DEBUG
  203229. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203230. #else
  203231. sleepEvent = CreateEvent (0, 0, 0, 0);
  203232. #endif
  203233. }
  203234. void Thread::yield()
  203235. {
  203236. Sleep (0);
  203237. }
  203238. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203239. {
  203240. if (millisecs >= 10)
  203241. {
  203242. Sleep (millisecs);
  203243. }
  203244. else
  203245. {
  203246. jassert (sleepEvent != 0);
  203247. // unlike Sleep() this is guaranteed to return to the current thread after
  203248. // the time expires, so we'll use this for short waits, which are more likely
  203249. // to need to be accurate
  203250. WaitForSingleObject (sleepEvent, millisecs);
  203251. }
  203252. }
  203253. static int lastProcessPriority = -1;
  203254. // called by WindowDriver because Windows does wierd things to process priority
  203255. // when you swap apps, and this forces an update when the app is brought to the front.
  203256. void juce_repeatLastProcessPriority()
  203257. {
  203258. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203259. {
  203260. DWORD p;
  203261. switch (lastProcessPriority)
  203262. {
  203263. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203264. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203265. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203266. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203267. default: jassertfalse; return; // bad priority value
  203268. }
  203269. SetPriorityClass (GetCurrentProcess(), p);
  203270. }
  203271. }
  203272. void Process::setPriority (ProcessPriority prior)
  203273. {
  203274. if (lastProcessPriority != (int) prior)
  203275. {
  203276. lastProcessPriority = (int) prior;
  203277. juce_repeatLastProcessPriority();
  203278. }
  203279. }
  203280. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203281. {
  203282. return IsDebuggerPresent() != FALSE;
  203283. }
  203284. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203285. {
  203286. return juce_isRunningUnderDebugger();
  203287. }
  203288. void Process::raisePrivilege()
  203289. {
  203290. jassertfalse; // xxx not implemented
  203291. }
  203292. void Process::lowerPrivilege()
  203293. {
  203294. jassertfalse; // xxx not implemented
  203295. }
  203296. void Process::terminate()
  203297. {
  203298. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203299. _CrtDumpMemoryLeaks();
  203300. #endif
  203301. // bullet in the head in case there's a problem shutting down..
  203302. ExitProcess (0);
  203303. }
  203304. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203305. {
  203306. void* result = 0;
  203307. JUCE_TRY
  203308. {
  203309. result = LoadLibrary (name);
  203310. }
  203311. JUCE_CATCH_ALL
  203312. return result;
  203313. }
  203314. void PlatformUtilities::freeDynamicLibrary (void* h)
  203315. {
  203316. JUCE_TRY
  203317. {
  203318. if (h != 0)
  203319. FreeLibrary ((HMODULE) h);
  203320. }
  203321. JUCE_CATCH_ALL
  203322. }
  203323. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203324. {
  203325. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  203326. }
  203327. class InterProcessLock::Pimpl
  203328. {
  203329. public:
  203330. Pimpl (const String& name, const int timeOutMillisecs)
  203331. : handle (0), refCount (1)
  203332. {
  203333. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203334. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203335. {
  203336. if (timeOutMillisecs == 0)
  203337. {
  203338. close();
  203339. return;
  203340. }
  203341. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203342. {
  203343. case WAIT_OBJECT_0:
  203344. case WAIT_ABANDONED:
  203345. break;
  203346. case WAIT_TIMEOUT:
  203347. default:
  203348. close();
  203349. break;
  203350. }
  203351. }
  203352. }
  203353. ~Pimpl()
  203354. {
  203355. close();
  203356. }
  203357. void close()
  203358. {
  203359. if (handle != 0)
  203360. {
  203361. ReleaseMutex (handle);
  203362. CloseHandle (handle);
  203363. handle = 0;
  203364. }
  203365. }
  203366. HANDLE handle;
  203367. int refCount;
  203368. };
  203369. InterProcessLock::InterProcessLock (const String& name_)
  203370. : name (name_)
  203371. {
  203372. }
  203373. InterProcessLock::~InterProcessLock()
  203374. {
  203375. }
  203376. bool InterProcessLock::enter (const int timeOutMillisecs)
  203377. {
  203378. const ScopedLock sl (lock);
  203379. if (pimpl == 0)
  203380. {
  203381. pimpl = new Pimpl (name, timeOutMillisecs);
  203382. if (pimpl->handle == 0)
  203383. pimpl = 0;
  203384. }
  203385. else
  203386. {
  203387. pimpl->refCount++;
  203388. }
  203389. return pimpl != 0;
  203390. }
  203391. void InterProcessLock::exit()
  203392. {
  203393. const ScopedLock sl (lock);
  203394. // Trying to release the lock too many times!
  203395. jassert (pimpl != 0);
  203396. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203397. pimpl = 0;
  203398. }
  203399. #endif
  203400. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203401. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203402. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203403. // compiled on its own).
  203404. #if JUCE_INCLUDED_FILE
  203405. #ifndef CSIDL_MYMUSIC
  203406. #define CSIDL_MYMUSIC 0x000d
  203407. #endif
  203408. #ifndef CSIDL_MYVIDEO
  203409. #define CSIDL_MYVIDEO 0x000e
  203410. #endif
  203411. #ifndef INVALID_FILE_ATTRIBUTES
  203412. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203413. #endif
  203414. const juce_wchar File::separator = '\\';
  203415. const String File::separatorString ("\\");
  203416. bool File::exists() const
  203417. {
  203418. return fullPath.isNotEmpty()
  203419. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203420. }
  203421. bool File::existsAsFile() const
  203422. {
  203423. return fullPath.isNotEmpty()
  203424. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203425. }
  203426. bool File::isDirectory() const
  203427. {
  203428. const DWORD attr = GetFileAttributes (fullPath);
  203429. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203430. }
  203431. bool File::hasWriteAccess() const
  203432. {
  203433. if (exists())
  203434. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203435. // on windows, it seems that even read-only directories can still be written into,
  203436. // so checking the parent directory's permissions would return the wrong result..
  203437. return true;
  203438. }
  203439. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203440. {
  203441. DWORD attr = GetFileAttributes (fullPath);
  203442. if (attr == INVALID_FILE_ATTRIBUTES)
  203443. return false;
  203444. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203445. return true;
  203446. if (shouldBeReadOnly)
  203447. attr |= FILE_ATTRIBUTE_READONLY;
  203448. else
  203449. attr &= ~FILE_ATTRIBUTE_READONLY;
  203450. return SetFileAttributes (fullPath, attr) != FALSE;
  203451. }
  203452. bool File::isHidden() const
  203453. {
  203454. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203455. }
  203456. bool File::deleteFile() const
  203457. {
  203458. if (! exists())
  203459. return true;
  203460. else if (isDirectory())
  203461. return RemoveDirectory (fullPath) != 0;
  203462. else
  203463. return DeleteFile (fullPath) != 0;
  203464. }
  203465. bool File::moveToTrash() const
  203466. {
  203467. if (! exists())
  203468. return true;
  203469. SHFILEOPSTRUCT fos;
  203470. zerostruct (fos);
  203471. // The string we pass in must be double null terminated..
  203472. String doubleNullTermPath (getFullPathName() + " ");
  203473. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203474. p [getFullPathName().length()] = 0;
  203475. fos.wFunc = FO_DELETE;
  203476. fos.pFrom = p;
  203477. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203478. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203479. return SHFileOperation (&fos) == 0;
  203480. }
  203481. bool File::copyInternal (const File& dest) const
  203482. {
  203483. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203484. }
  203485. bool File::moveInternal (const File& dest) const
  203486. {
  203487. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203488. }
  203489. void File::createDirectoryInternal (const String& fileName) const
  203490. {
  203491. CreateDirectory (fileName, 0);
  203492. }
  203493. // return 0 if not possible
  203494. void* juce_fileOpen (const File& file, bool forWriting)
  203495. {
  203496. HANDLE h;
  203497. if (forWriting)
  203498. {
  203499. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203500. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203501. if (h != INVALID_HANDLE_VALUE)
  203502. SetFilePointer (h, 0, 0, FILE_END);
  203503. else
  203504. h = 0;
  203505. }
  203506. else
  203507. {
  203508. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203509. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203510. if (h == INVALID_HANDLE_VALUE)
  203511. h = 0;
  203512. }
  203513. return h;
  203514. }
  203515. void juce_fileClose (void* handle)
  203516. {
  203517. CloseHandle (handle);
  203518. }
  203519. int juce_fileRead (void* handle, void* buffer, int size)
  203520. {
  203521. DWORD num = 0;
  203522. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  203523. return (int) num;
  203524. }
  203525. int juce_fileWrite (void* handle, const void* buffer, int size)
  203526. {
  203527. DWORD num;
  203528. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  203529. return (int) num;
  203530. }
  203531. int64 juce_fileSetPosition (void* handle, int64 pos)
  203532. {
  203533. LARGE_INTEGER li;
  203534. li.QuadPart = pos;
  203535. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203536. return li.QuadPart;
  203537. }
  203538. int64 FileOutputStream::getPositionInternal() const
  203539. {
  203540. if (fileHandle == 0)
  203541. return -1;
  203542. LARGE_INTEGER li;
  203543. li.QuadPart = 0;
  203544. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  203545. return jmax ((int64) 0, li.QuadPart);
  203546. }
  203547. void FileOutputStream::flushInternal()
  203548. {
  203549. if (fileHandle != 0)
  203550. FlushFileBuffers ((HANDLE) fileHandle);
  203551. }
  203552. int64 File::getSize() const
  203553. {
  203554. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203555. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203556. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203557. return 0;
  203558. }
  203559. static int64 fileTimeToTime (const FILETIME* const ft)
  203560. {
  203561. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203562. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203563. }
  203564. static void timeToFileTime (const int64 time, FILETIME* const ft)
  203565. {
  203566. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203567. }
  203568. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203569. {
  203570. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203571. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203572. {
  203573. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203574. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203575. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203576. }
  203577. else
  203578. {
  203579. creationTime = accessTime = modificationTime = 0;
  203580. }
  203581. }
  203582. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203583. {
  203584. void* const h = juce_fileOpen (fullPath, true);
  203585. bool ok = false;
  203586. if (h != 0)
  203587. {
  203588. FILETIME m, a, c;
  203589. timeToFileTime (modificationTime, &m);
  203590. timeToFileTime (accessTime, &a);
  203591. timeToFileTime (creationTime, &c);
  203592. ok = SetFileTime ((HANDLE) h,
  203593. creationTime > 0 ? &c : 0,
  203594. accessTime > 0 ? &a : 0,
  203595. modificationTime > 0 ? &m : 0) != 0;
  203596. juce_fileClose (h);
  203597. }
  203598. return ok;
  203599. }
  203600. void File::findFileSystemRoots (Array<File>& destArray)
  203601. {
  203602. TCHAR buffer [2048];
  203603. buffer[0] = 0;
  203604. buffer[1] = 0;
  203605. GetLogicalDriveStrings (2048, buffer);
  203606. const TCHAR* n = buffer;
  203607. StringArray roots;
  203608. while (*n != 0)
  203609. {
  203610. roots.add (String (n));
  203611. while (*n++ != 0)
  203612. {}
  203613. }
  203614. roots.sort (true);
  203615. for (int i = 0; i < roots.size(); ++i)
  203616. destArray.add (roots [i]);
  203617. }
  203618. static const String getDriveFromPath (const String& path)
  203619. {
  203620. if (path.isNotEmpty() && path[1] == ':')
  203621. return path.substring (0, 2) + '\\';
  203622. return path;
  203623. }
  203624. const String File::getVolumeLabel() const
  203625. {
  203626. TCHAR dest[64];
  203627. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203628. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203629. dest[0] = 0;
  203630. return dest;
  203631. }
  203632. int File::getVolumeSerialNumber() const
  203633. {
  203634. TCHAR dest[64];
  203635. DWORD serialNum;
  203636. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203637. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203638. return 0;
  203639. return (int) serialNum;
  203640. }
  203641. static int64 getDiskSpaceInfo (const String& path, const bool total)
  203642. {
  203643. ULARGE_INTEGER spc, tot, totFree;
  203644. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203645. return total ? (int64) tot.QuadPart
  203646. : (int64) spc.QuadPart;
  203647. return 0;
  203648. }
  203649. int64 File::getBytesFreeOnVolume() const
  203650. {
  203651. return getDiskSpaceInfo (getFullPathName(), false);
  203652. }
  203653. int64 File::getVolumeTotalSize() const
  203654. {
  203655. return getDiskSpaceInfo (getFullPathName(), true);
  203656. }
  203657. static unsigned int getWindowsDriveType (const String& path)
  203658. {
  203659. return GetDriveType (getDriveFromPath (path));
  203660. }
  203661. bool File::isOnCDRomDrive() const
  203662. {
  203663. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203664. }
  203665. bool File::isOnHardDisk() const
  203666. {
  203667. if (fullPath.isEmpty())
  203668. return false;
  203669. const unsigned int n = getWindowsDriveType (getFullPathName());
  203670. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203671. return n != DRIVE_REMOVABLE;
  203672. else
  203673. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  203674. }
  203675. bool File::isOnRemovableDrive() const
  203676. {
  203677. if (fullPath.isEmpty())
  203678. return false;
  203679. const unsigned int n = getWindowsDriveType (getFullPathName());
  203680. return n == DRIVE_CDROM
  203681. || n == DRIVE_REMOTE
  203682. || n == DRIVE_REMOVABLE
  203683. || n == DRIVE_RAMDISK;
  203684. }
  203685. static const File juce_getSpecialFolderPath (int type)
  203686. {
  203687. WCHAR path [MAX_PATH + 256];
  203688. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203689. return File (String (path));
  203690. return File::nonexistent;
  203691. }
  203692. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  203693. {
  203694. int csidlType = 0;
  203695. switch (type)
  203696. {
  203697. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  203698. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  203699. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  203700. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  203701. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  203702. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  203703. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  203704. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  203705. case tempDirectory:
  203706. {
  203707. WCHAR dest [2048];
  203708. dest[0] = 0;
  203709. GetTempPath (numElementsInArray (dest), dest);
  203710. return File (String (dest));
  203711. }
  203712. case invokedExecutableFile:
  203713. case currentExecutableFile:
  203714. case currentApplicationFile:
  203715. {
  203716. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203717. WCHAR dest [MAX_PATH + 256];
  203718. dest[0] = 0;
  203719. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  203720. return File (String (dest));
  203721. }
  203722. break;
  203723. default:
  203724. jassertfalse; // unknown type?
  203725. return File::nonexistent;
  203726. }
  203727. return juce_getSpecialFolderPath (csidlType);
  203728. }
  203729. const File File::getCurrentWorkingDirectory()
  203730. {
  203731. WCHAR dest [MAX_PATH + 256];
  203732. dest[0] = 0;
  203733. GetCurrentDirectory (numElementsInArray (dest), dest);
  203734. return File (String (dest));
  203735. }
  203736. bool File::setAsCurrentWorkingDirectory() const
  203737. {
  203738. return SetCurrentDirectory (getFullPathName()) != FALSE;
  203739. }
  203740. const String File::getVersion() const
  203741. {
  203742. String result;
  203743. DWORD handle = 0;
  203744. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  203745. HeapBlock<char> buffer;
  203746. buffer.calloc (bufferSize);
  203747. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  203748. {
  203749. VS_FIXEDFILEINFO* vffi;
  203750. UINT len = 0;
  203751. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  203752. {
  203753. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  203754. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  203755. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  203756. << (int) LOWORD (vffi->dwFileVersionLS);
  203757. }
  203758. }
  203759. return result;
  203760. }
  203761. const File File::getLinkedTarget() const
  203762. {
  203763. File result (*this);
  203764. String p (getFullPathName());
  203765. if (! exists())
  203766. p += ".lnk";
  203767. else if (getFileExtension() != ".lnk")
  203768. return result;
  203769. ComSmartPtr <IShellLink> shellLink;
  203770. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  203771. {
  203772. ComSmartPtr <IPersistFile> persistFile;
  203773. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  203774. {
  203775. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  203776. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  203777. {
  203778. WIN32_FIND_DATA winFindData;
  203779. WCHAR resolvedPath [MAX_PATH];
  203780. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  203781. result = File (resolvedPath);
  203782. }
  203783. }
  203784. }
  203785. return result;
  203786. }
  203787. class DirectoryIterator::NativeIterator::Pimpl
  203788. {
  203789. public:
  203790. Pimpl (const File& directory, const String& wildCard)
  203791. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  203792. handle (INVALID_HANDLE_VALUE)
  203793. {
  203794. }
  203795. ~Pimpl()
  203796. {
  203797. if (handle != INVALID_HANDLE_VALUE)
  203798. FindClose (handle);
  203799. }
  203800. bool next (String& filenameFound,
  203801. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203802. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203803. {
  203804. WIN32_FIND_DATA findData;
  203805. if (handle == INVALID_HANDLE_VALUE)
  203806. {
  203807. handle = FindFirstFile (directoryWithWildCard, &findData);
  203808. if (handle == INVALID_HANDLE_VALUE)
  203809. return false;
  203810. }
  203811. else
  203812. {
  203813. if (FindNextFile (handle, &findData) == 0)
  203814. return false;
  203815. }
  203816. filenameFound = findData.cFileName;
  203817. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  203818. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  203819. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  203820. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  203821. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  203822. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  203823. return true;
  203824. }
  203825. juce_UseDebuggingNewOperator
  203826. private:
  203827. const String directoryWithWildCard;
  203828. HANDLE handle;
  203829. Pimpl (const Pimpl&);
  203830. Pimpl& operator= (const Pimpl&);
  203831. };
  203832. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  203833. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  203834. {
  203835. }
  203836. DirectoryIterator::NativeIterator::~NativeIterator()
  203837. {
  203838. }
  203839. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  203840. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203841. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203842. {
  203843. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  203844. }
  203845. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  203846. {
  203847. HINSTANCE hInstance = 0;
  203848. JUCE_TRY
  203849. {
  203850. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  203851. }
  203852. JUCE_CATCH_ALL
  203853. return hInstance > (HINSTANCE) 32;
  203854. }
  203855. void File::revealToUser() const
  203856. {
  203857. if (isDirectory())
  203858. startAsProcess();
  203859. else if (getParentDirectory().exists())
  203860. getParentDirectory().startAsProcess();
  203861. }
  203862. class NamedPipeInternal
  203863. {
  203864. public:
  203865. NamedPipeInternal (const String& file, const bool isPipe_)
  203866. : pipeH (0),
  203867. cancelEvent (0),
  203868. connected (false),
  203869. isPipe (isPipe_)
  203870. {
  203871. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  203872. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  203873. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  203874. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  203875. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  203876. }
  203877. ~NamedPipeInternal()
  203878. {
  203879. disconnectPipe();
  203880. if (pipeH != 0)
  203881. CloseHandle (pipeH);
  203882. CloseHandle (cancelEvent);
  203883. }
  203884. bool connect (const int timeOutMs)
  203885. {
  203886. if (! isPipe)
  203887. return true;
  203888. if (! connected)
  203889. {
  203890. OVERLAPPED over;
  203891. zerostruct (over);
  203892. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203893. if (ConnectNamedPipe (pipeH, &over))
  203894. {
  203895. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  203896. }
  203897. else
  203898. {
  203899. const int err = GetLastError();
  203900. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  203901. {
  203902. HANDLE handles[] = { over.hEvent, cancelEvent };
  203903. if (WaitForMultipleObjects (2, handles, FALSE,
  203904. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  203905. connected = true;
  203906. }
  203907. else if (err == ERROR_PIPE_CONNECTED)
  203908. {
  203909. connected = true;
  203910. }
  203911. }
  203912. CloseHandle (over.hEvent);
  203913. }
  203914. return connected;
  203915. }
  203916. void disconnectPipe()
  203917. {
  203918. if (connected)
  203919. {
  203920. DisconnectNamedPipe (pipeH);
  203921. connected = false;
  203922. }
  203923. }
  203924. HANDLE pipeH;
  203925. HANDLE cancelEvent;
  203926. bool connected, isPipe;
  203927. };
  203928. void NamedPipe::close()
  203929. {
  203930. cancelPendingReads();
  203931. const ScopedLock sl (lock);
  203932. delete static_cast<NamedPipeInternal*> (internal);
  203933. internal = 0;
  203934. }
  203935. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  203936. {
  203937. close();
  203938. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  203939. if (intern->pipeH != INVALID_HANDLE_VALUE)
  203940. {
  203941. internal = intern.release();
  203942. return true;
  203943. }
  203944. return false;
  203945. }
  203946. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  203947. {
  203948. const ScopedLock sl (lock);
  203949. int bytesRead = -1;
  203950. bool waitAgain = true;
  203951. while (waitAgain && internal != 0)
  203952. {
  203953. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203954. waitAgain = false;
  203955. if (! intern->connect (timeOutMilliseconds))
  203956. break;
  203957. if (maxBytesToRead <= 0)
  203958. return 0;
  203959. OVERLAPPED over;
  203960. zerostruct (over);
  203961. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203962. unsigned long numRead;
  203963. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  203964. {
  203965. bytesRead = (int) numRead;
  203966. }
  203967. else if (GetLastError() == ERROR_IO_PENDING)
  203968. {
  203969. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203970. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203971. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203972. : INFINITE);
  203973. if (waitResult != WAIT_OBJECT_0)
  203974. {
  203975. // if the operation timed out, let's cancel it...
  203976. CancelIo (intern->pipeH);
  203977. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  203978. }
  203979. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  203980. {
  203981. bytesRead = (int) numRead;
  203982. }
  203983. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203984. {
  203985. intern->disconnectPipe();
  203986. waitAgain = true;
  203987. }
  203988. }
  203989. else
  203990. {
  203991. waitAgain = internal != 0;
  203992. Sleep (5);
  203993. }
  203994. CloseHandle (over.hEvent);
  203995. }
  203996. return bytesRead;
  203997. }
  203998. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  203999. {
  204000. int bytesWritten = -1;
  204001. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204002. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204003. {
  204004. if (numBytesToWrite <= 0)
  204005. return 0;
  204006. OVERLAPPED over;
  204007. zerostruct (over);
  204008. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204009. unsigned long numWritten;
  204010. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204011. {
  204012. bytesWritten = (int) numWritten;
  204013. }
  204014. else if (GetLastError() == ERROR_IO_PENDING)
  204015. {
  204016. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204017. DWORD waitResult;
  204018. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204019. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204020. : INFINITE);
  204021. if (waitResult != WAIT_OBJECT_0)
  204022. {
  204023. CancelIo (intern->pipeH);
  204024. WaitForSingleObject (over.hEvent, INFINITE);
  204025. }
  204026. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204027. {
  204028. bytesWritten = (int) numWritten;
  204029. }
  204030. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204031. {
  204032. intern->disconnectPipe();
  204033. }
  204034. }
  204035. CloseHandle (over.hEvent);
  204036. }
  204037. return bytesWritten;
  204038. }
  204039. void NamedPipe::cancelPendingReads()
  204040. {
  204041. if (internal != 0)
  204042. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204043. }
  204044. #endif
  204045. /*** End of inlined file: juce_win32_Files.cpp ***/
  204046. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204047. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204048. // compiled on its own).
  204049. #if JUCE_INCLUDED_FILE
  204050. #ifndef INTERNET_FLAG_NEED_FILE
  204051. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204052. #endif
  204053. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204054. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204055. #endif
  204056. struct ConnectionAndRequestStruct
  204057. {
  204058. HINTERNET connection, request;
  204059. };
  204060. static HINTERNET sessionHandle = 0;
  204061. #ifndef WORKAROUND_TIMEOUT_BUG
  204062. //#define WORKAROUND_TIMEOUT_BUG 1
  204063. #endif
  204064. #if WORKAROUND_TIMEOUT_BUG
  204065. // Required because of a Microsoft bug in setting a timeout
  204066. class InternetConnectThread : public Thread
  204067. {
  204068. public:
  204069. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204070. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204071. {
  204072. startThread();
  204073. }
  204074. ~InternetConnectThread()
  204075. {
  204076. stopThread (60000);
  204077. }
  204078. void run()
  204079. {
  204080. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204081. uc.nPort, _T(""), _T(""),
  204082. isFtp ? INTERNET_SERVICE_FTP
  204083. : INTERNET_SERVICE_HTTP,
  204084. 0, 0);
  204085. notify();
  204086. }
  204087. juce_UseDebuggingNewOperator
  204088. private:
  204089. URL_COMPONENTS& uc;
  204090. HINTERNET& connection;
  204091. const bool isFtp;
  204092. InternetConnectThread (const InternetConnectThread&);
  204093. InternetConnectThread& operator= (const InternetConnectThread&);
  204094. };
  204095. #endif
  204096. void* juce_openInternetFile (const String& url,
  204097. const String& headers,
  204098. const MemoryBlock& postData,
  204099. const bool isPost,
  204100. URL::OpenStreamProgressCallback* callback,
  204101. void* callbackContext,
  204102. int timeOutMs)
  204103. {
  204104. if (sessionHandle == 0)
  204105. sessionHandle = InternetOpen (_T("juce"),
  204106. INTERNET_OPEN_TYPE_PRECONFIG,
  204107. 0, 0, 0);
  204108. if (sessionHandle != 0)
  204109. {
  204110. // break up the url..
  204111. TCHAR file[1024], server[1024];
  204112. URL_COMPONENTS uc;
  204113. zerostruct (uc);
  204114. uc.dwStructSize = sizeof (uc);
  204115. uc.dwUrlPathLength = sizeof (file);
  204116. uc.dwHostNameLength = sizeof (server);
  204117. uc.lpszUrlPath = file;
  204118. uc.lpszHostName = server;
  204119. if (InternetCrackUrl (url, 0, 0, &uc))
  204120. {
  204121. int disable = 1;
  204122. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204123. if (timeOutMs == 0)
  204124. timeOutMs = 30000;
  204125. else if (timeOutMs < 0)
  204126. timeOutMs = -1;
  204127. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204128. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204129. #if WORKAROUND_TIMEOUT_BUG
  204130. HINTERNET connection = 0;
  204131. {
  204132. InternetConnectThread connectThread (uc, connection, isFtp);
  204133. connectThread.wait (timeOutMs);
  204134. if (connection == 0)
  204135. {
  204136. InternetCloseHandle (sessionHandle);
  204137. sessionHandle = 0;
  204138. }
  204139. }
  204140. #else
  204141. HINTERNET connection = InternetConnect (sessionHandle,
  204142. uc.lpszHostName,
  204143. uc.nPort,
  204144. _T(""), _T(""),
  204145. isFtp ? INTERNET_SERVICE_FTP
  204146. : INTERNET_SERVICE_HTTP,
  204147. 0, 0);
  204148. #endif
  204149. if (connection != 0)
  204150. {
  204151. if (isFtp)
  204152. {
  204153. HINTERNET request = FtpOpenFile (connection,
  204154. uc.lpszUrlPath,
  204155. GENERIC_READ,
  204156. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204157. 0);
  204158. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204159. result->connection = connection;
  204160. result->request = request;
  204161. return result;
  204162. }
  204163. else
  204164. {
  204165. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204166. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204167. if (url.startsWithIgnoreCase ("https:"))
  204168. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204169. // IE7 seems to automatically work out when it's https)
  204170. HINTERNET request = HttpOpenRequest (connection,
  204171. isPost ? _T("POST")
  204172. : _T("GET"),
  204173. uc.lpszUrlPath,
  204174. 0, 0, mimeTypes, flags, 0);
  204175. if (request != 0)
  204176. {
  204177. INTERNET_BUFFERS buffers;
  204178. zerostruct (buffers);
  204179. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204180. buffers.lpcszHeader = (LPCTSTR) headers;
  204181. buffers.dwHeadersLength = headers.length();
  204182. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204183. ConnectionAndRequestStruct* result = 0;
  204184. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204185. {
  204186. int bytesSent = 0;
  204187. for (;;)
  204188. {
  204189. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204190. DWORD bytesDone = 0;
  204191. if (bytesToDo > 0
  204192. && ! InternetWriteFile (request,
  204193. static_cast <const char*> (postData.getData()) + bytesSent,
  204194. bytesToDo, &bytesDone))
  204195. {
  204196. break;
  204197. }
  204198. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204199. {
  204200. result = new ConnectionAndRequestStruct();
  204201. result->connection = connection;
  204202. result->request = request;
  204203. if (! HttpEndRequest (request, 0, 0, 0))
  204204. break;
  204205. return result;
  204206. }
  204207. bytesSent += bytesDone;
  204208. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204209. break;
  204210. }
  204211. }
  204212. InternetCloseHandle (request);
  204213. }
  204214. InternetCloseHandle (connection);
  204215. }
  204216. }
  204217. }
  204218. }
  204219. return 0;
  204220. }
  204221. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204222. {
  204223. DWORD bytesRead = 0;
  204224. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204225. if (crs != 0)
  204226. InternetReadFile (crs->request,
  204227. buffer, bytesToRead,
  204228. &bytesRead);
  204229. return bytesRead;
  204230. }
  204231. int juce_seekInInternetFile (void* handle, int newPosition)
  204232. {
  204233. if (handle != 0)
  204234. {
  204235. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204236. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204237. }
  204238. return -1;
  204239. }
  204240. int64 juce_getInternetFileContentLength (void* handle)
  204241. {
  204242. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204243. if (crs != 0)
  204244. {
  204245. DWORD index = 0, result = 0, size = sizeof (result);
  204246. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204247. return (int64) result;
  204248. }
  204249. return -1;
  204250. }
  204251. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204252. {
  204253. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204254. if (crs != 0)
  204255. {
  204256. DWORD bufferSizeBytes = 4096;
  204257. for (;;)
  204258. {
  204259. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204260. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204261. {
  204262. StringArray headersArray;
  204263. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204264. for (int i = 0; i < headersArray.size(); ++i)
  204265. {
  204266. const String& header = headersArray[i];
  204267. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204268. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204269. const String previousValue (headers [key]);
  204270. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204271. }
  204272. break;
  204273. }
  204274. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204275. break;
  204276. }
  204277. }
  204278. }
  204279. void juce_closeInternetFile (void* handle)
  204280. {
  204281. if (handle != 0)
  204282. {
  204283. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204284. InternetCloseHandle (crs->request);
  204285. InternetCloseHandle (crs->connection);
  204286. }
  204287. }
  204288. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204289. {
  204290. int numFound = 0;
  204291. DynamicLibraryLoader dll ("iphlpapi.dll");
  204292. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204293. if (getAdaptersInfo != 0)
  204294. {
  204295. ULONG len = sizeof (IP_ADAPTER_INFO);
  204296. MemoryBlock mb;
  204297. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204298. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204299. {
  204300. mb.setSize (len);
  204301. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204302. }
  204303. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204304. {
  204305. PIP_ADAPTER_INFO adapter = adapterInfo;
  204306. while (adapter != 0)
  204307. {
  204308. int64 mac = 0;
  204309. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204310. mac = (mac << 8) | adapter->Address[i];
  204311. if (littleEndian)
  204312. mac = (int64) ByteOrder::swap ((uint64) mac);
  204313. if (numFound < maxNum && mac != 0)
  204314. addresses [numFound++] = mac;
  204315. adapter = adapter->Next;
  204316. }
  204317. }
  204318. }
  204319. return numFound;
  204320. }
  204321. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204322. {
  204323. int numFound = 0;
  204324. DynamicLibraryLoader dll ("netapi32.dll");
  204325. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204326. if (NetbiosCall != 0)
  204327. {
  204328. NCB ncb;
  204329. zerostruct (ncb);
  204330. struct ASTAT
  204331. {
  204332. ADAPTER_STATUS adapt;
  204333. NAME_BUFFER NameBuff [30];
  204334. };
  204335. ASTAT astat;
  204336. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204337. LANA_ENUM enums;
  204338. zerostruct (enums);
  204339. ncb.ncb_command = NCBENUM;
  204340. ncb.ncb_buffer = (unsigned char*) &enums;
  204341. ncb.ncb_length = sizeof (LANA_ENUM);
  204342. NetbiosCall (&ncb);
  204343. for (int i = 0; i < enums.length; ++i)
  204344. {
  204345. zerostruct (ncb);
  204346. ncb.ncb_command = NCBRESET;
  204347. ncb.ncb_lana_num = enums.lana[i];
  204348. if (NetbiosCall (&ncb) == 0)
  204349. {
  204350. zerostruct (ncb);
  204351. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204352. ncb.ncb_command = NCBASTAT;
  204353. ncb.ncb_lana_num = enums.lana[i];
  204354. ncb.ncb_buffer = (unsigned char*) &astat;
  204355. ncb.ncb_length = sizeof (ASTAT);
  204356. if (NetbiosCall (&ncb) == 0)
  204357. {
  204358. if (astat.adapt.adapter_type == 0xfe)
  204359. {
  204360. uint64 mac = 0;
  204361. for (int i = 6; --i >= 0;)
  204362. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  204363. if (numFound < maxNum && mac != 0)
  204364. addresses [numFound++] = mac;
  204365. }
  204366. }
  204367. }
  204368. }
  204369. }
  204370. return numFound;
  204371. }
  204372. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  204373. {
  204374. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  204375. if (numFound == 0)
  204376. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  204377. return numFound;
  204378. }
  204379. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204380. const String& emailSubject,
  204381. const String& bodyText,
  204382. const StringArray& filesToAttach)
  204383. {
  204384. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204385. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204386. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204387. bool ok = false;
  204388. if (mapiSendMail != 0)
  204389. {
  204390. MapiMessage message;
  204391. zerostruct (message);
  204392. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204393. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204394. MapiRecipDesc recip;
  204395. zerostruct (recip);
  204396. recip.ulRecipClass = MAPI_TO;
  204397. String targetEmailAddress_ (targetEmailAddress);
  204398. if (targetEmailAddress_.isEmpty())
  204399. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204400. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204401. message.nRecipCount = 1;
  204402. message.lpRecips = &recip;
  204403. HeapBlock <MapiFileDesc> files;
  204404. files.calloc (filesToAttach.size());
  204405. message.nFileCount = filesToAttach.size();
  204406. message.lpFiles = files;
  204407. for (int i = 0; i < filesToAttach.size(); ++i)
  204408. {
  204409. files[i].nPosition = (ULONG) -1;
  204410. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204411. }
  204412. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204413. }
  204414. FreeLibrary (h);
  204415. return ok;
  204416. }
  204417. #endif
  204418. /*** End of inlined file: juce_win32_Network.cpp ***/
  204419. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204420. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204421. // compiled on its own).
  204422. #if JUCE_INCLUDED_FILE
  204423. static HKEY findKeyForPath (String name,
  204424. const bool createForWriting,
  204425. String& valueName)
  204426. {
  204427. HKEY rootKey = 0;
  204428. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204429. rootKey = HKEY_CURRENT_USER;
  204430. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204431. rootKey = HKEY_LOCAL_MACHINE;
  204432. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204433. rootKey = HKEY_CLASSES_ROOT;
  204434. if (rootKey != 0)
  204435. {
  204436. name = name.substring (name.indexOfChar ('\\') + 1);
  204437. const int lastSlash = name.lastIndexOfChar ('\\');
  204438. valueName = name.substring (lastSlash + 1);
  204439. name = name.substring (0, lastSlash);
  204440. HKEY key;
  204441. DWORD result;
  204442. if (createForWriting)
  204443. {
  204444. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204445. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204446. return key;
  204447. }
  204448. else
  204449. {
  204450. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204451. return key;
  204452. }
  204453. }
  204454. return 0;
  204455. }
  204456. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204457. const String& defaultValue)
  204458. {
  204459. String valueName, result (defaultValue);
  204460. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204461. if (k != 0)
  204462. {
  204463. WCHAR buffer [2048];
  204464. unsigned long bufferSize = sizeof (buffer);
  204465. DWORD type = REG_SZ;
  204466. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204467. {
  204468. if (type == REG_SZ)
  204469. result = buffer;
  204470. else if (type == REG_DWORD)
  204471. result = String ((int) *(DWORD*) buffer);
  204472. }
  204473. RegCloseKey (k);
  204474. }
  204475. return result;
  204476. }
  204477. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204478. const String& value)
  204479. {
  204480. String valueName;
  204481. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204482. if (k != 0)
  204483. {
  204484. RegSetValueEx (k, valueName, 0, REG_SZ,
  204485. (const BYTE*) (const WCHAR*) value,
  204486. sizeof (WCHAR) * (value.length() + 1));
  204487. RegCloseKey (k);
  204488. }
  204489. }
  204490. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204491. {
  204492. bool exists = false;
  204493. String valueName;
  204494. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204495. if (k != 0)
  204496. {
  204497. unsigned char buffer [2048];
  204498. unsigned long bufferSize = sizeof (buffer);
  204499. DWORD type = 0;
  204500. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204501. exists = true;
  204502. RegCloseKey (k);
  204503. }
  204504. return exists;
  204505. }
  204506. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204507. {
  204508. String valueName;
  204509. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204510. if (k != 0)
  204511. {
  204512. RegDeleteValue (k, valueName);
  204513. RegCloseKey (k);
  204514. }
  204515. }
  204516. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204517. {
  204518. String valueName;
  204519. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204520. if (k != 0)
  204521. {
  204522. RegDeleteKey (k, valueName);
  204523. RegCloseKey (k);
  204524. }
  204525. }
  204526. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204527. const String& symbolicDescription,
  204528. const String& fullDescription,
  204529. const File& targetExecutable,
  204530. int iconResourceNumber)
  204531. {
  204532. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204533. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204534. if (iconResourceNumber != 0)
  204535. setRegistryValue (key + "\\DefaultIcon\\",
  204536. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204537. setRegistryValue (key + "\\", fullDescription);
  204538. setRegistryValue (key + "\\shell\\open\\command\\",
  204539. targetExecutable.getFullPathName() + " %1");
  204540. }
  204541. bool juce_IsRunningInWine()
  204542. {
  204543. HKEY key;
  204544. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204545. {
  204546. RegCloseKey (key);
  204547. return true;
  204548. }
  204549. return false;
  204550. }
  204551. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204552. {
  204553. String s (::GetCommandLineW());
  204554. StringArray tokens;
  204555. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204556. return tokens.joinIntoString (" ", 1);
  204557. }
  204558. static void* currentModuleHandle = 0;
  204559. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204560. {
  204561. if (currentModuleHandle == 0)
  204562. currentModuleHandle = GetModuleHandle (0);
  204563. return currentModuleHandle;
  204564. }
  204565. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204566. {
  204567. currentModuleHandle = newHandle;
  204568. }
  204569. void PlatformUtilities::fpuReset()
  204570. {
  204571. #if JUCE_MSVC
  204572. _clearfp();
  204573. #endif
  204574. }
  204575. void PlatformUtilities::beep()
  204576. {
  204577. MessageBeep (MB_OK);
  204578. }
  204579. #endif
  204580. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204581. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204582. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204583. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204584. // compiled on its own).
  204585. #if JUCE_INCLUDED_FILE
  204586. static const unsigned int specialId = WM_APP + 0x4400;
  204587. static const unsigned int broadcastId = WM_APP + 0x4403;
  204588. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204589. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204590. HWND juce_messageWindowHandle = 0;
  204591. extern long improbableWindowNumber; // defined in windowing.cpp
  204592. #ifndef WM_APPCOMMAND
  204593. #define WM_APPCOMMAND 0x0319
  204594. #endif
  204595. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204596. const UINT message,
  204597. const WPARAM wParam,
  204598. const LPARAM lParam) throw()
  204599. {
  204600. JUCE_TRY
  204601. {
  204602. if (h == juce_messageWindowHandle)
  204603. {
  204604. if (message == specialCallbackId)
  204605. {
  204606. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204607. return (LRESULT) (*func) ((void*) lParam);
  204608. }
  204609. else if (message == specialId)
  204610. {
  204611. // these are trapped early in the dispatch call, but must also be checked
  204612. // here in case there are windows modal dialog boxes doing their own
  204613. // dispatch loop and not calling our version
  204614. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  204615. return 0;
  204616. }
  204617. else if (message == broadcastId)
  204618. {
  204619. const ScopedPointer <String> messageString ((String*) lParam);
  204620. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204621. return 0;
  204622. }
  204623. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204624. {
  204625. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204626. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204627. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204628. return 0;
  204629. }
  204630. }
  204631. }
  204632. JUCE_CATCH_EXCEPTION
  204633. return DefWindowProc (h, message, wParam, lParam);
  204634. }
  204635. static bool isEventBlockedByModalComps (MSG& m)
  204636. {
  204637. if (Component::getNumCurrentlyModalComponents() == 0
  204638. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204639. return false;
  204640. switch (m.message)
  204641. {
  204642. case WM_MOUSEMOVE:
  204643. case WM_NCMOUSEMOVE:
  204644. case 0x020A: /* WM_MOUSEWHEEL */
  204645. case 0x020E: /* WM_MOUSEHWHEEL */
  204646. case WM_KEYUP:
  204647. case WM_SYSKEYUP:
  204648. case WM_CHAR:
  204649. case WM_APPCOMMAND:
  204650. case WM_LBUTTONUP:
  204651. case WM_MBUTTONUP:
  204652. case WM_RBUTTONUP:
  204653. case WM_MOUSEACTIVATE:
  204654. case WM_NCMOUSEHOVER:
  204655. case WM_MOUSEHOVER:
  204656. return true;
  204657. case WM_NCLBUTTONDOWN:
  204658. case WM_NCLBUTTONDBLCLK:
  204659. case WM_NCRBUTTONDOWN:
  204660. case WM_NCRBUTTONDBLCLK:
  204661. case WM_NCMBUTTONDOWN:
  204662. case WM_NCMBUTTONDBLCLK:
  204663. case WM_LBUTTONDOWN:
  204664. case WM_LBUTTONDBLCLK:
  204665. case WM_MBUTTONDOWN:
  204666. case WM_MBUTTONDBLCLK:
  204667. case WM_RBUTTONDOWN:
  204668. case WM_RBUTTONDBLCLK:
  204669. case WM_KEYDOWN:
  204670. case WM_SYSKEYDOWN:
  204671. {
  204672. Component* const modal = Component::getCurrentlyModalComponent (0);
  204673. if (modal != 0)
  204674. modal->inputAttemptWhenModal();
  204675. return true;
  204676. }
  204677. default:
  204678. break;
  204679. }
  204680. return false;
  204681. }
  204682. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204683. {
  204684. MSG m;
  204685. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204686. return false;
  204687. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  204688. {
  204689. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  204690. {
  204691. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  204692. }
  204693. else if (m.message == WM_QUIT)
  204694. {
  204695. if (JUCEApplication::getInstance() != 0)
  204696. JUCEApplication::getInstance()->systemRequestedQuit();
  204697. }
  204698. else if (! isEventBlockedByModalComps (m))
  204699. {
  204700. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  204701. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  204702. {
  204703. // if it's someone else's window being clicked on, and the focus is
  204704. // currently on a juce window, pass the kb focus over..
  204705. HWND currentFocus = GetFocus();
  204706. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204707. SetFocus (m.hwnd);
  204708. }
  204709. TranslateMessage (&m);
  204710. DispatchMessage (&m);
  204711. }
  204712. }
  204713. return true;
  204714. }
  204715. bool juce_postMessageToSystemQueue (Message* message)
  204716. {
  204717. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204718. }
  204719. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204720. void* userData)
  204721. {
  204722. if (MessageManager::getInstance()->isThisTheMessageThread())
  204723. {
  204724. return (*callback) (userData);
  204725. }
  204726. else
  204727. {
  204728. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204729. // deadlock because the message manager is blocked from running, and can't
  204730. // call your function..
  204731. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204732. return (void*) SendMessage (juce_messageWindowHandle,
  204733. specialCallbackId,
  204734. (WPARAM) callback,
  204735. (LPARAM) userData);
  204736. }
  204737. }
  204738. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204739. {
  204740. if (hwnd != juce_messageWindowHandle)
  204741. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  204742. return TRUE;
  204743. }
  204744. void MessageManager::broadcastMessage (const String& value) throw()
  204745. {
  204746. Array<void*> windows;
  204747. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204748. const String localCopy (value);
  204749. COPYDATASTRUCT data;
  204750. data.dwData = broadcastId;
  204751. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204752. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  204753. for (int i = windows.size(); --i >= 0;)
  204754. {
  204755. HWND hwnd = (HWND) windows.getUnchecked(i);
  204756. TCHAR windowName [64]; // no need to read longer strings than this
  204757. GetWindowText (hwnd, windowName, 64);
  204758. windowName [63] = 0;
  204759. if (String (windowName) == messageWindowName)
  204760. {
  204761. DWORD_PTR result;
  204762. SendMessageTimeout (hwnd, WM_COPYDATA,
  204763. (WPARAM) juce_messageWindowHandle,
  204764. (LPARAM) &data,
  204765. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204766. 8000,
  204767. &result);
  204768. }
  204769. }
  204770. }
  204771. static const String getMessageWindowClassName()
  204772. {
  204773. // this name has to be different for each app/dll instance because otherwise
  204774. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204775. // window class).
  204776. static int number = 0;
  204777. if (number == 0)
  204778. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204779. return "JUCEcs_" + String (number);
  204780. }
  204781. void MessageManager::doPlatformSpecificInitialisation()
  204782. {
  204783. OleInitialize (0);
  204784. const String className (getMessageWindowClassName());
  204785. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204786. WNDCLASSEX wc;
  204787. zerostruct (wc);
  204788. wc.cbSize = sizeof (wc);
  204789. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204790. wc.cbWndExtra = 4;
  204791. wc.hInstance = hmod;
  204792. wc.lpszClassName = className;
  204793. RegisterClassEx (&wc);
  204794. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204795. messageWindowName,
  204796. 0, 0, 0, 0, 0, 0, 0,
  204797. hmod, 0);
  204798. }
  204799. void MessageManager::doPlatformSpecificShutdown()
  204800. {
  204801. DestroyWindow (juce_messageWindowHandle);
  204802. UnregisterClass (getMessageWindowClassName(), 0);
  204803. OleUninitialize();
  204804. }
  204805. #endif
  204806. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  204807. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  204808. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204809. // compiled on its own).
  204810. #if JUCE_INCLUDED_FILE
  204811. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204812. // these are in the windows SDK, but need to be repeated here for GCC..
  204813. #ifndef GET_APPCOMMAND_LPARAM
  204814. #define FAPPCOMMAND_MASK 0xF000
  204815. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204816. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204817. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204818. #define APPCOMMAND_MEDIA_STOP 13
  204819. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204820. #define WM_APPCOMMAND 0x0319
  204821. #endif
  204822. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  204823. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  204824. extern bool juce_IsRunningInWine();
  204825. #ifndef ULW_ALPHA
  204826. #define ULW_ALPHA 0x00000002
  204827. #endif
  204828. #ifndef AC_SRC_ALPHA
  204829. #define AC_SRC_ALPHA 0x01
  204830. #endif
  204831. static HPALETTE palette = 0;
  204832. static bool createPaletteIfNeeded = true;
  204833. static bool shouldDeactivateTitleBar = true;
  204834. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  204835. #define WM_TRAYNOTIFY WM_USER + 100
  204836. using ::abs;
  204837. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204838. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204839. bool Desktop::canUseSemiTransparentWindows() throw()
  204840. {
  204841. if (updateLayeredWindow == 0)
  204842. {
  204843. if (! juce_IsRunningInWine())
  204844. {
  204845. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204846. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204847. }
  204848. }
  204849. return updateLayeredWindow != 0;
  204850. }
  204851. const int extendedKeyModifier = 0x10000;
  204852. const int KeyPress::spaceKey = VK_SPACE;
  204853. const int KeyPress::returnKey = VK_RETURN;
  204854. const int KeyPress::escapeKey = VK_ESCAPE;
  204855. const int KeyPress::backspaceKey = VK_BACK;
  204856. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204857. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204858. const int KeyPress::tabKey = VK_TAB;
  204859. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204860. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204861. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204862. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204863. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204864. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204865. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204866. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204867. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204868. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204869. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204870. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204871. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204872. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204873. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204874. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204875. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204876. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204877. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204878. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204879. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204880. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204881. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204882. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204883. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204884. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204885. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204886. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204887. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204888. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204889. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204890. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204891. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204892. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204893. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204894. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204895. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204896. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204897. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204898. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204899. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204900. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204901. const int KeyPress::playKey = 0x30000;
  204902. const int KeyPress::stopKey = 0x30001;
  204903. const int KeyPress::fastForwardKey = 0x30002;
  204904. const int KeyPress::rewindKey = 0x30003;
  204905. class WindowsBitmapImage : public Image::SharedImage
  204906. {
  204907. public:
  204908. HBITMAP hBitmap;
  204909. BITMAPV4HEADER bitmapInfo;
  204910. HDC hdc;
  204911. unsigned char* bitmapData;
  204912. WindowsBitmapImage (const Image::PixelFormat format_,
  204913. const int w, const int h, const bool clearImage)
  204914. : Image::SharedImage (format_, w, h)
  204915. {
  204916. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  204917. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  204918. zerostruct (bitmapInfo);
  204919. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204920. bitmapInfo.bV4Width = w;
  204921. bitmapInfo.bV4Height = h;
  204922. bitmapInfo.bV4Planes = 1;
  204923. bitmapInfo.bV4CSType = 1;
  204924. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204925. if (format_ == Image::ARGB)
  204926. {
  204927. bitmapInfo.bV4AlphaMask = 0xff000000;
  204928. bitmapInfo.bV4RedMask = 0xff0000;
  204929. bitmapInfo.bV4GreenMask = 0xff00;
  204930. bitmapInfo.bV4BlueMask = 0xff;
  204931. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204932. }
  204933. else
  204934. {
  204935. bitmapInfo.bV4V4Compression = BI_RGB;
  204936. }
  204937. lineStride = -((w * pixelStride + 3) & ~3);
  204938. HDC dc = GetDC (0);
  204939. hdc = CreateCompatibleDC (dc);
  204940. ReleaseDC (0, dc);
  204941. SetMapMode (hdc, MM_TEXT);
  204942. hBitmap = CreateDIBSection (hdc,
  204943. (BITMAPINFO*) &(bitmapInfo),
  204944. DIB_RGB_COLORS,
  204945. (void**) &bitmapData,
  204946. 0, 0);
  204947. SelectObject (hdc, hBitmap);
  204948. if (format_ == Image::ARGB && clearImage)
  204949. zeromem (bitmapData, abs (h * lineStride));
  204950. imageData = bitmapData - (lineStride * (h - 1));
  204951. }
  204952. ~WindowsBitmapImage()
  204953. {
  204954. DeleteDC (hdc);
  204955. DeleteObject (hBitmap);
  204956. }
  204957. Image::ImageType getType() const { return Image::NativeImage; }
  204958. LowLevelGraphicsContext* createLowLevelContext()
  204959. {
  204960. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  204961. }
  204962. SharedImage* clone()
  204963. {
  204964. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  204965. for (int i = 0; i < height; ++i)
  204966. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  204967. return im;
  204968. }
  204969. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  204970. const int x, const int y,
  204971. const RectangleList& maskedRegion) throw()
  204972. {
  204973. static HDRAWDIB hdd = 0;
  204974. static bool needToCreateDrawDib = true;
  204975. if (needToCreateDrawDib)
  204976. {
  204977. needToCreateDrawDib = false;
  204978. HDC dc = GetDC (0);
  204979. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204980. ReleaseDC (0, dc);
  204981. // only open if we're not palettised
  204982. if (n > 8)
  204983. hdd = DrawDibOpen();
  204984. }
  204985. if (createPaletteIfNeeded)
  204986. {
  204987. HDC dc = GetDC (0);
  204988. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204989. ReleaseDC (0, dc);
  204990. if (n <= 8)
  204991. palette = CreateHalftonePalette (dc);
  204992. createPaletteIfNeeded = false;
  204993. }
  204994. if (palette != 0)
  204995. {
  204996. SelectPalette (dc, palette, FALSE);
  204997. RealizePalette (dc);
  204998. SetStretchBltMode (dc, HALFTONE);
  204999. }
  205000. SetMapMode (dc, MM_TEXT);
  205001. if (transparent)
  205002. {
  205003. POINT p, pos;
  205004. SIZE size;
  205005. RECT windowBounds;
  205006. GetWindowRect (hwnd, &windowBounds);
  205007. p.x = -x;
  205008. p.y = -y;
  205009. pos.x = windowBounds.left;
  205010. pos.y = windowBounds.top;
  205011. size.cx = windowBounds.right - windowBounds.left;
  205012. size.cy = windowBounds.bottom - windowBounds.top;
  205013. BLENDFUNCTION bf;
  205014. bf.AlphaFormat = AC_SRC_ALPHA;
  205015. bf.BlendFlags = 0;
  205016. bf.BlendOp = AC_SRC_OVER;
  205017. bf.SourceConstantAlpha = 0xff;
  205018. if (! maskedRegion.isEmpty())
  205019. {
  205020. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205021. {
  205022. const Rectangle<int>& r = *i.getRectangle();
  205023. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205024. }
  205025. }
  205026. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  205027. }
  205028. else
  205029. {
  205030. int savedDC = 0;
  205031. if (! maskedRegion.isEmpty())
  205032. {
  205033. savedDC = SaveDC (dc);
  205034. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205035. {
  205036. const Rectangle<int>& r = *i.getRectangle();
  205037. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205038. }
  205039. }
  205040. if (hdd == 0)
  205041. {
  205042. StretchDIBits (dc,
  205043. x, y, width, height,
  205044. 0, 0, width, height,
  205045. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  205046. DIB_RGB_COLORS, SRCCOPY);
  205047. }
  205048. else
  205049. {
  205050. DrawDibDraw (hdd, dc, x, y, -1, -1,
  205051. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  205052. 0, 0, width, height, 0);
  205053. }
  205054. if (! maskedRegion.isEmpty())
  205055. RestoreDC (dc, savedDC);
  205056. }
  205057. }
  205058. juce_UseDebuggingNewOperator
  205059. private:
  205060. WindowsBitmapImage (const WindowsBitmapImage&);
  205061. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  205062. };
  205063. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  205064. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  205065. {
  205066. SHORT k = (SHORT) keyCode;
  205067. if ((keyCode & extendedKeyModifier) == 0
  205068. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  205069. k += (SHORT) 'A' - (SHORT) 'a';
  205070. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  205071. (SHORT) '+', VK_OEM_PLUS,
  205072. (SHORT) '-', VK_OEM_MINUS,
  205073. (SHORT) '.', VK_OEM_PERIOD,
  205074. (SHORT) ';', VK_OEM_1,
  205075. (SHORT) ':', VK_OEM_1,
  205076. (SHORT) '/', VK_OEM_2,
  205077. (SHORT) '?', VK_OEM_2,
  205078. (SHORT) '[', VK_OEM_4,
  205079. (SHORT) ']', VK_OEM_6 };
  205080. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  205081. if (k == translatedValues [i])
  205082. k = translatedValues [i + 1];
  205083. return (GetKeyState (k) & 0x8000) != 0;
  205084. }
  205085. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  205086. {
  205087. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  205088. return callback (userData);
  205089. else
  205090. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  205091. }
  205092. class Win32ComponentPeer : public ComponentPeer
  205093. {
  205094. public:
  205095. Win32ComponentPeer (Component* const component,
  205096. const int windowStyleFlags)
  205097. : ComponentPeer (component, windowStyleFlags),
  205098. dontRepaint (false),
  205099. fullScreen (false),
  205100. isDragging (false),
  205101. isMouseOver (false),
  205102. hasCreatedCaret (false),
  205103. currentWindowIcon (0),
  205104. taskBarIcon (0),
  205105. dropTarget (0)
  205106. {
  205107. callFunctionIfNotLocked (&createWindowCallback, this);
  205108. setTitle (component->getName());
  205109. if ((windowStyleFlags & windowHasDropShadow) != 0
  205110. && Desktop::canUseSemiTransparentWindows())
  205111. {
  205112. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  205113. if (shadower != 0)
  205114. shadower->setOwner (component);
  205115. }
  205116. else
  205117. {
  205118. shadower = 0;
  205119. }
  205120. }
  205121. ~Win32ComponentPeer()
  205122. {
  205123. setTaskBarIcon (Image());
  205124. deleteAndZero (shadower);
  205125. // do this before the next bit to avoid messages arriving for this window
  205126. // before it's destroyed
  205127. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  205128. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  205129. if (currentWindowIcon != 0)
  205130. DestroyIcon (currentWindowIcon);
  205131. if (dropTarget != 0)
  205132. {
  205133. dropTarget->Release();
  205134. dropTarget = 0;
  205135. }
  205136. }
  205137. void* getNativeHandle() const
  205138. {
  205139. return hwnd;
  205140. }
  205141. void setVisible (bool shouldBeVisible)
  205142. {
  205143. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205144. if (shouldBeVisible)
  205145. InvalidateRect (hwnd, 0, 0);
  205146. else
  205147. lastPaintTime = 0;
  205148. }
  205149. void setTitle (const String& title)
  205150. {
  205151. SetWindowText (hwnd, title);
  205152. }
  205153. void setPosition (int x, int y)
  205154. {
  205155. offsetWithinParent (x, y);
  205156. SetWindowPos (hwnd, 0,
  205157. x - windowBorder.getLeft(),
  205158. y - windowBorder.getTop(),
  205159. 0, 0,
  205160. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205161. }
  205162. void repaintNowIfTransparent()
  205163. {
  205164. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  205165. handlePaintMessage();
  205166. }
  205167. void updateBorderSize()
  205168. {
  205169. WINDOWINFO info;
  205170. info.cbSize = sizeof (info);
  205171. if (GetWindowInfo (hwnd, &info))
  205172. {
  205173. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  205174. info.rcClient.left - info.rcWindow.left,
  205175. info.rcWindow.bottom - info.rcClient.bottom,
  205176. info.rcWindow.right - info.rcClient.right);
  205177. }
  205178. }
  205179. void setSize (int w, int h)
  205180. {
  205181. SetWindowPos (hwnd, 0, 0, 0,
  205182. w + windowBorder.getLeftAndRight(),
  205183. h + windowBorder.getTopAndBottom(),
  205184. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205185. updateBorderSize();
  205186. repaintNowIfTransparent();
  205187. }
  205188. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  205189. {
  205190. fullScreen = isNowFullScreen;
  205191. offsetWithinParent (x, y);
  205192. SetWindowPos (hwnd, 0,
  205193. x - windowBorder.getLeft(),
  205194. y - windowBorder.getTop(),
  205195. w + windowBorder.getLeftAndRight(),
  205196. h + windowBorder.getTopAndBottom(),
  205197. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205198. updateBorderSize();
  205199. repaintNowIfTransparent();
  205200. }
  205201. const Rectangle<int> getBounds() const
  205202. {
  205203. RECT r;
  205204. GetWindowRect (hwnd, &r);
  205205. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  205206. HWND parentH = GetParent (hwnd);
  205207. if (parentH != 0)
  205208. {
  205209. GetWindowRect (parentH, &r);
  205210. bounds.translate (-r.left, -r.top);
  205211. }
  205212. return windowBorder.subtractedFrom (bounds);
  205213. }
  205214. const Point<int> getScreenPosition() const
  205215. {
  205216. RECT r;
  205217. GetWindowRect (hwnd, &r);
  205218. return Point<int> (r.left + windowBorder.getLeft(),
  205219. r.top + windowBorder.getTop());
  205220. }
  205221. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  205222. {
  205223. return relativePosition + getScreenPosition();
  205224. }
  205225. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  205226. {
  205227. return screenPosition - getScreenPosition();
  205228. }
  205229. void setMinimised (bool shouldBeMinimised)
  205230. {
  205231. if (shouldBeMinimised != isMinimised())
  205232. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  205233. }
  205234. bool isMinimised() const
  205235. {
  205236. WINDOWPLACEMENT wp;
  205237. wp.length = sizeof (WINDOWPLACEMENT);
  205238. GetWindowPlacement (hwnd, &wp);
  205239. return wp.showCmd == SW_SHOWMINIMIZED;
  205240. }
  205241. void setFullScreen (bool shouldBeFullScreen)
  205242. {
  205243. setMinimised (false);
  205244. if (fullScreen != shouldBeFullScreen)
  205245. {
  205246. fullScreen = shouldBeFullScreen;
  205247. const Component::SafePointer<Component> deletionChecker (component);
  205248. if (! fullScreen)
  205249. {
  205250. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  205251. if (hasTitleBar())
  205252. ShowWindow (hwnd, SW_SHOWNORMAL);
  205253. if (! boundsCopy.isEmpty())
  205254. {
  205255. setBounds (boundsCopy.getX(),
  205256. boundsCopy.getY(),
  205257. boundsCopy.getWidth(),
  205258. boundsCopy.getHeight(),
  205259. false);
  205260. }
  205261. }
  205262. else
  205263. {
  205264. if (hasTitleBar())
  205265. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  205266. else
  205267. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  205268. }
  205269. if (deletionChecker != 0)
  205270. handleMovedOrResized();
  205271. }
  205272. }
  205273. bool isFullScreen() const
  205274. {
  205275. if (! hasTitleBar())
  205276. return fullScreen;
  205277. WINDOWPLACEMENT wp;
  205278. wp.length = sizeof (wp);
  205279. GetWindowPlacement (hwnd, &wp);
  205280. return wp.showCmd == SW_SHOWMAXIMIZED;
  205281. }
  205282. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  205283. {
  205284. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  205285. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  205286. return false;
  205287. RECT r;
  205288. GetWindowRect (hwnd, &r);
  205289. POINT p;
  205290. p.x = position.getX() + r.left + windowBorder.getLeft();
  205291. p.y = position.getY() + r.top + windowBorder.getTop();
  205292. HWND w = WindowFromPoint (p);
  205293. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  205294. }
  205295. const BorderSize getFrameSize() const
  205296. {
  205297. return windowBorder;
  205298. }
  205299. bool setAlwaysOnTop (bool alwaysOnTop)
  205300. {
  205301. const bool oldDeactivate = shouldDeactivateTitleBar;
  205302. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205303. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  205304. 0, 0, 0, 0,
  205305. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205306. shouldDeactivateTitleBar = oldDeactivate;
  205307. if (shadower != 0)
  205308. shadower->componentBroughtToFront (*component);
  205309. return true;
  205310. }
  205311. void toFront (bool makeActive)
  205312. {
  205313. setMinimised (false);
  205314. const bool oldDeactivate = shouldDeactivateTitleBar;
  205315. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205316. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  205317. shouldDeactivateTitleBar = oldDeactivate;
  205318. if (! makeActive)
  205319. {
  205320. // in this case a broughttofront call won't have occured, so do it now..
  205321. handleBroughtToFront();
  205322. }
  205323. }
  205324. void toBehind (ComponentPeer* other)
  205325. {
  205326. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  205327. jassert (otherPeer != 0); // wrong type of window?
  205328. if (otherPeer != 0)
  205329. {
  205330. setMinimised (false);
  205331. // must be careful not to try to put a topmost window behind a normal one, or win32
  205332. // promotes the normal one to be topmost!
  205333. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  205334. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  205335. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205336. else if (otherPeer->getComponent()->isAlwaysOnTop())
  205337. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  205338. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205339. }
  205340. }
  205341. bool isFocused() const
  205342. {
  205343. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  205344. }
  205345. void grabFocus()
  205346. {
  205347. const bool oldDeactivate = shouldDeactivateTitleBar;
  205348. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205349. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  205350. shouldDeactivateTitleBar = oldDeactivate;
  205351. }
  205352. void textInputRequired (const Point<int>&)
  205353. {
  205354. if (! hasCreatedCaret)
  205355. {
  205356. hasCreatedCaret = true;
  205357. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  205358. }
  205359. ShowCaret (hwnd);
  205360. SetCaretPos (0, 0);
  205361. }
  205362. void repaint (const Rectangle<int>& area)
  205363. {
  205364. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  205365. InvalidateRect (hwnd, &r, FALSE);
  205366. }
  205367. void performAnyPendingRepaintsNow()
  205368. {
  205369. MSG m;
  205370. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  205371. DispatchMessage (&m);
  205372. }
  205373. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  205374. {
  205375. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  205376. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  205377. return 0;
  205378. }
  205379. void setTaskBarIcon (const Image& image)
  205380. {
  205381. if (image.isValid())
  205382. {
  205383. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  205384. if (taskBarIcon == 0)
  205385. {
  205386. taskBarIcon = new NOTIFYICONDATA();
  205387. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  205388. taskBarIcon->hWnd = (HWND) hwnd;
  205389. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  205390. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  205391. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  205392. taskBarIcon->hIcon = hicon;
  205393. taskBarIcon->szTip[0] = 0;
  205394. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  205395. }
  205396. else
  205397. {
  205398. HICON oldIcon = taskBarIcon->hIcon;
  205399. taskBarIcon->hIcon = hicon;
  205400. taskBarIcon->uFlags = NIF_ICON;
  205401. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205402. DestroyIcon (oldIcon);
  205403. }
  205404. DestroyIcon (hicon);
  205405. }
  205406. else if (taskBarIcon != 0)
  205407. {
  205408. taskBarIcon->uFlags = 0;
  205409. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  205410. DestroyIcon (taskBarIcon->hIcon);
  205411. deleteAndZero (taskBarIcon);
  205412. }
  205413. }
  205414. void setTaskBarIconToolTip (const String& toolTip) const
  205415. {
  205416. if (taskBarIcon != 0)
  205417. {
  205418. taskBarIcon->uFlags = NIF_TIP;
  205419. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  205420. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205421. }
  205422. }
  205423. bool isInside (HWND h) const
  205424. {
  205425. return GetAncestor (hwnd, GA_ROOT) == h;
  205426. }
  205427. static void updateKeyModifiers() throw()
  205428. {
  205429. int keyMods = 0;
  205430. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  205431. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  205432. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  205433. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205434. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  205435. }
  205436. static void updateModifiersFromWParam (const WPARAM wParam)
  205437. {
  205438. int mouseMods = 0;
  205439. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  205440. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  205441. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  205442. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  205443. updateKeyModifiers();
  205444. }
  205445. static int64 getMouseEventTime()
  205446. {
  205447. static int64 eventTimeOffset = 0;
  205448. static DWORD lastMessageTime = 0;
  205449. const DWORD thisMessageTime = GetMessageTime();
  205450. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205451. {
  205452. lastMessageTime = thisMessageTime;
  205453. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205454. }
  205455. return eventTimeOffset + thisMessageTime;
  205456. }
  205457. juce_UseDebuggingNewOperator
  205458. bool dontRepaint;
  205459. static ModifierKeys currentModifiers;
  205460. static ModifierKeys modifiersAtLastCallback;
  205461. private:
  205462. HWND hwnd;
  205463. DropShadower* shadower;
  205464. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  205465. BorderSize windowBorder;
  205466. HICON currentWindowIcon;
  205467. NOTIFYICONDATA* taskBarIcon;
  205468. IDropTarget* dropTarget;
  205469. class TemporaryImage : public Timer
  205470. {
  205471. public:
  205472. TemporaryImage() {}
  205473. ~TemporaryImage() {}
  205474. const Image& getImage (const bool transparent, const int w, const int h)
  205475. {
  205476. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205477. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  205478. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  205479. startTimer (3000);
  205480. return image;
  205481. }
  205482. void timerCallback()
  205483. {
  205484. stopTimer();
  205485. image = Image::null;
  205486. }
  205487. private:
  205488. Image image;
  205489. TemporaryImage (const TemporaryImage&);
  205490. TemporaryImage& operator= (const TemporaryImage&);
  205491. };
  205492. TemporaryImage offscreenImageGenerator;
  205493. class WindowClassHolder : public DeletedAtShutdown
  205494. {
  205495. public:
  205496. WindowClassHolder()
  205497. : windowClassName ("JUCE_")
  205498. {
  205499. // this name has to be different for each app/dll instance because otherwise
  205500. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205501. // window class).
  205502. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205503. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205504. TCHAR moduleFile [1024];
  205505. moduleFile[0] = 0;
  205506. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205507. WORD iconNum = 0;
  205508. WNDCLASSEX wcex;
  205509. wcex.cbSize = sizeof (wcex);
  205510. wcex.style = CS_OWNDC;
  205511. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205512. wcex.lpszClassName = windowClassName;
  205513. wcex.cbClsExtra = 0;
  205514. wcex.cbWndExtra = 32;
  205515. wcex.hInstance = moduleHandle;
  205516. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205517. iconNum = 1;
  205518. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205519. wcex.hCursor = 0;
  205520. wcex.hbrBackground = 0;
  205521. wcex.lpszMenuName = 0;
  205522. RegisterClassEx (&wcex);
  205523. }
  205524. ~WindowClassHolder()
  205525. {
  205526. if (ComponentPeer::getNumPeers() == 0)
  205527. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205528. clearSingletonInstance();
  205529. }
  205530. String windowClassName;
  205531. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205532. };
  205533. static void* createWindowCallback (void* userData)
  205534. {
  205535. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  205536. return 0;
  205537. }
  205538. void createWindow()
  205539. {
  205540. DWORD exstyle = WS_EX_ACCEPTFILES;
  205541. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205542. if (hasTitleBar())
  205543. {
  205544. type |= WS_OVERLAPPED;
  205545. if ((styleFlags & windowHasCloseButton) != 0)
  205546. {
  205547. type |= WS_SYSMENU;
  205548. }
  205549. else
  205550. {
  205551. // annoyingly, windows won't let you have a min/max button without a close button
  205552. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205553. }
  205554. if ((styleFlags & windowIsResizable) != 0)
  205555. type |= WS_THICKFRAME;
  205556. }
  205557. else
  205558. {
  205559. type |= WS_POPUP | WS_SYSMENU;
  205560. }
  205561. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205562. exstyle |= WS_EX_TOOLWINDOW;
  205563. else
  205564. exstyle |= WS_EX_APPWINDOW;
  205565. if ((styleFlags & windowHasMinimiseButton) != 0)
  205566. type |= WS_MINIMIZEBOX;
  205567. if ((styleFlags & windowHasMaximiseButton) != 0)
  205568. type |= WS_MAXIMIZEBOX;
  205569. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205570. exstyle |= WS_EX_TRANSPARENT;
  205571. if ((styleFlags & windowIsSemiTransparent) != 0
  205572. && Desktop::canUseSemiTransparentWindows())
  205573. exstyle |= WS_EX_LAYERED;
  205574. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205575. if (hwnd != 0)
  205576. {
  205577. SetWindowLongPtr (hwnd, 0, 0);
  205578. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205579. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205580. if (dropTarget == 0)
  205581. dropTarget = new JuceDropTarget (this);
  205582. RegisterDragDrop (hwnd, dropTarget);
  205583. updateBorderSize();
  205584. // Calling this function here is (for some reason) necessary to make Windows
  205585. // correctly enable the menu items that we specify in the wm_initmenu message.
  205586. GetSystemMenu (hwnd, false);
  205587. }
  205588. else
  205589. {
  205590. jassertfalse;
  205591. }
  205592. }
  205593. static void* destroyWindowCallback (void* handle)
  205594. {
  205595. RevokeDragDrop ((HWND) handle);
  205596. DestroyWindow ((HWND) handle);
  205597. return 0;
  205598. }
  205599. static void* toFrontCallback1 (void* h)
  205600. {
  205601. SetForegroundWindow ((HWND) h);
  205602. return 0;
  205603. }
  205604. static void* toFrontCallback2 (void* h)
  205605. {
  205606. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205607. return 0;
  205608. }
  205609. static void* setFocusCallback (void* h)
  205610. {
  205611. SetFocus ((HWND) h);
  205612. return 0;
  205613. }
  205614. static void* getFocusCallback (void*)
  205615. {
  205616. return GetFocus();
  205617. }
  205618. void offsetWithinParent (int& x, int& y) const
  205619. {
  205620. if (isTransparent())
  205621. {
  205622. HWND parentHwnd = GetParent (hwnd);
  205623. if (parentHwnd != 0)
  205624. {
  205625. RECT parentRect;
  205626. GetWindowRect (parentHwnd, &parentRect);
  205627. x += parentRect.left;
  205628. y += parentRect.top;
  205629. }
  205630. }
  205631. }
  205632. bool isTransparent() const
  205633. {
  205634. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205635. }
  205636. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205637. void setIcon (const Image& newIcon)
  205638. {
  205639. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205640. if (hicon != 0)
  205641. {
  205642. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205643. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205644. if (currentWindowIcon != 0)
  205645. DestroyIcon (currentWindowIcon);
  205646. currentWindowIcon = hicon;
  205647. }
  205648. }
  205649. void handlePaintMessage()
  205650. {
  205651. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205652. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205653. PAINTSTRUCT paintStruct;
  205654. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205655. // message and become re-entrant, but that's OK
  205656. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205657. // corrupt the image it's using to paint into, so do a check here.
  205658. static bool reentrant = false;
  205659. if (reentrant)
  205660. {
  205661. DeleteObject (rgn);
  205662. EndPaint (hwnd, &paintStruct);
  205663. return;
  205664. }
  205665. reentrant = true;
  205666. // this is the rectangle to update..
  205667. int x = paintStruct.rcPaint.left;
  205668. int y = paintStruct.rcPaint.top;
  205669. int w = paintStruct.rcPaint.right - x;
  205670. int h = paintStruct.rcPaint.bottom - y;
  205671. const bool transparent = isTransparent();
  205672. if (transparent)
  205673. {
  205674. // it's not possible to have a transparent window with a title bar at the moment!
  205675. jassert (! hasTitleBar());
  205676. RECT r;
  205677. GetWindowRect (hwnd, &r);
  205678. x = y = 0;
  205679. w = r.right - r.left;
  205680. h = r.bottom - r.top;
  205681. }
  205682. if (w > 0 && h > 0)
  205683. {
  205684. clearMaskedRegion();
  205685. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  205686. RectangleList contextClip;
  205687. const Rectangle<int> clipBounds (0, 0, w, h);
  205688. bool needToPaintAll = true;
  205689. if (regionType == COMPLEXREGION && ! transparent)
  205690. {
  205691. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205692. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205693. DeleteObject (clipRgn);
  205694. char rgnData [8192];
  205695. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205696. if (res > 0 && res <= sizeof (rgnData))
  205697. {
  205698. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205699. if (hdr->iType == RDH_RECTANGLES
  205700. && hdr->rcBound.right - hdr->rcBound.left >= w
  205701. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205702. {
  205703. needToPaintAll = false;
  205704. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205705. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205706. while (--num >= 0)
  205707. {
  205708. if (rects->right <= x + w && rects->bottom <= y + h)
  205709. {
  205710. // (need to move this one pixel to the left because of a win32 bug)
  205711. const int cx = jmax (x, (int) rects->left - 1);
  205712. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  205713. .getIntersection (clipBounds));
  205714. }
  205715. else
  205716. {
  205717. needToPaintAll = true;
  205718. break;
  205719. }
  205720. ++rects;
  205721. }
  205722. }
  205723. }
  205724. }
  205725. if (needToPaintAll)
  205726. {
  205727. contextClip.clear();
  205728. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  205729. }
  205730. if (transparent)
  205731. {
  205732. RectangleList::Iterator i (contextClip);
  205733. while (i.next())
  205734. offscreenImage.clear (*i.getRectangle());
  205735. }
  205736. // if the component's not opaque, this won't draw properly unless the platform can support this
  205737. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205738. updateCurrentModifiers();
  205739. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  205740. handlePaint (context);
  205741. if (! dontRepaint)
  205742. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  205743. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205744. }
  205745. DeleteObject (rgn);
  205746. EndPaint (hwnd, &paintStruct);
  205747. reentrant = false;
  205748. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205749. _fpreset(); // because some graphics cards can unmask FP exceptions
  205750. #endif
  205751. lastPaintTime = Time::getMillisecondCounter();
  205752. }
  205753. void doMouseEvent (const Point<int>& position)
  205754. {
  205755. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  205756. }
  205757. void doMouseMove (const Point<int>& position)
  205758. {
  205759. if (! isMouseOver)
  205760. {
  205761. isMouseOver = true;
  205762. updateKeyModifiers();
  205763. TRACKMOUSEEVENT tme;
  205764. tme.cbSize = sizeof (tme);
  205765. tme.dwFlags = TME_LEAVE;
  205766. tme.hwndTrack = hwnd;
  205767. tme.dwHoverTime = 0;
  205768. if (! TrackMouseEvent (&tme))
  205769. jassertfalse;
  205770. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  205771. }
  205772. else if (! isDragging)
  205773. {
  205774. if (! contains (position, false))
  205775. return;
  205776. }
  205777. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  205778. static uint32 lastMouseTime = 0;
  205779. const uint32 now = Time::getMillisecondCounter();
  205780. const int maxMouseMovesPerSecond = 60;
  205781. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205782. {
  205783. lastMouseTime = now;
  205784. doMouseEvent (position);
  205785. }
  205786. }
  205787. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  205788. {
  205789. if (GetCapture() != hwnd)
  205790. SetCapture (hwnd);
  205791. doMouseMove (position);
  205792. updateModifiersFromWParam (wParam);
  205793. isDragging = true;
  205794. doMouseEvent (position);
  205795. }
  205796. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  205797. {
  205798. updateModifiersFromWParam (wParam);
  205799. isDragging = false;
  205800. // release the mouse capture if the user has released all buttons
  205801. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  205802. ReleaseCapture();
  205803. doMouseEvent (position);
  205804. }
  205805. void doCaptureChanged()
  205806. {
  205807. if (isDragging)
  205808. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  205809. }
  205810. void doMouseExit()
  205811. {
  205812. isMouseOver = false;
  205813. doMouseEvent (getCurrentMousePos());
  205814. }
  205815. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  205816. {
  205817. updateKeyModifiers();
  205818. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  205819. handleMouseWheel (0, position, getMouseEventTime(),
  205820. isVertical ? 0.0f : amount,
  205821. isVertical ? amount : 0.0f);
  205822. }
  205823. void sendModifierKeyChangeIfNeeded()
  205824. {
  205825. if (modifiersAtLastCallback != currentModifiers)
  205826. {
  205827. modifiersAtLastCallback = currentModifiers;
  205828. handleModifierKeysChange();
  205829. }
  205830. }
  205831. bool doKeyUp (const WPARAM key)
  205832. {
  205833. updateKeyModifiers();
  205834. switch (key)
  205835. {
  205836. case VK_SHIFT:
  205837. case VK_CONTROL:
  205838. case VK_MENU:
  205839. case VK_CAPITAL:
  205840. case VK_LWIN:
  205841. case VK_RWIN:
  205842. case VK_APPS:
  205843. case VK_NUMLOCK:
  205844. case VK_SCROLL:
  205845. case VK_LSHIFT:
  205846. case VK_RSHIFT:
  205847. case VK_LCONTROL:
  205848. case VK_LMENU:
  205849. case VK_RCONTROL:
  205850. case VK_RMENU:
  205851. sendModifierKeyChangeIfNeeded();
  205852. }
  205853. return handleKeyUpOrDown (false)
  205854. || Component::getCurrentlyModalComponent() != 0;
  205855. }
  205856. bool doKeyDown (const WPARAM key)
  205857. {
  205858. updateKeyModifiers();
  205859. bool used = false;
  205860. switch (key)
  205861. {
  205862. case VK_SHIFT:
  205863. case VK_LSHIFT:
  205864. case VK_RSHIFT:
  205865. case VK_CONTROL:
  205866. case VK_LCONTROL:
  205867. case VK_RCONTROL:
  205868. case VK_MENU:
  205869. case VK_LMENU:
  205870. case VK_RMENU:
  205871. case VK_LWIN:
  205872. case VK_RWIN:
  205873. case VK_CAPITAL:
  205874. case VK_NUMLOCK:
  205875. case VK_SCROLL:
  205876. case VK_APPS:
  205877. sendModifierKeyChangeIfNeeded();
  205878. break;
  205879. case VK_LEFT:
  205880. case VK_RIGHT:
  205881. case VK_UP:
  205882. case VK_DOWN:
  205883. case VK_PRIOR:
  205884. case VK_NEXT:
  205885. case VK_HOME:
  205886. case VK_END:
  205887. case VK_DELETE:
  205888. case VK_INSERT:
  205889. case VK_F1:
  205890. case VK_F2:
  205891. case VK_F3:
  205892. case VK_F4:
  205893. case VK_F5:
  205894. case VK_F6:
  205895. case VK_F7:
  205896. case VK_F8:
  205897. case VK_F9:
  205898. case VK_F10:
  205899. case VK_F11:
  205900. case VK_F12:
  205901. case VK_F13:
  205902. case VK_F14:
  205903. case VK_F15:
  205904. case VK_F16:
  205905. used = handleKeyUpOrDown (true);
  205906. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  205907. break;
  205908. case VK_ADD:
  205909. case VK_SUBTRACT:
  205910. case VK_MULTIPLY:
  205911. case VK_DIVIDE:
  205912. case VK_SEPARATOR:
  205913. case VK_DECIMAL:
  205914. used = handleKeyUpOrDown (true);
  205915. break;
  205916. default:
  205917. used = handleKeyUpOrDown (true);
  205918. {
  205919. MSG msg;
  205920. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  205921. {
  205922. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  205923. // manually generate the key-press event that matches this key-down.
  205924. const UINT keyChar = MapVirtualKey (key, 2);
  205925. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  205926. }
  205927. }
  205928. break;
  205929. }
  205930. if (Component::getCurrentlyModalComponent() != 0)
  205931. used = true;
  205932. return used;
  205933. }
  205934. bool doKeyChar (int key, const LPARAM flags)
  205935. {
  205936. updateKeyModifiers();
  205937. juce_wchar textChar = (juce_wchar) key;
  205938. const int virtualScanCode = (flags >> 16) & 0xff;
  205939. if (key >= '0' && key <= '9')
  205940. {
  205941. switch (virtualScanCode) // check for a numeric keypad scan-code
  205942. {
  205943. case 0x52:
  205944. case 0x4f:
  205945. case 0x50:
  205946. case 0x51:
  205947. case 0x4b:
  205948. case 0x4c:
  205949. case 0x4d:
  205950. case 0x47:
  205951. case 0x48:
  205952. case 0x49:
  205953. key = (key - '0') + KeyPress::numberPad0;
  205954. break;
  205955. default:
  205956. break;
  205957. }
  205958. }
  205959. else
  205960. {
  205961. // convert the scan code to an unmodified character code..
  205962. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  205963. UINT keyChar = MapVirtualKey (virtualKey, 2);
  205964. keyChar = LOWORD (keyChar);
  205965. if (keyChar != 0)
  205966. key = (int) keyChar;
  205967. // avoid sending junk text characters for some control-key combinations
  205968. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  205969. textChar = 0;
  205970. }
  205971. return handleKeyPress (key, textChar);
  205972. }
  205973. bool doAppCommand (const LPARAM lParam)
  205974. {
  205975. int key = 0;
  205976. switch (GET_APPCOMMAND_LPARAM (lParam))
  205977. {
  205978. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  205979. key = KeyPress::playKey;
  205980. break;
  205981. case APPCOMMAND_MEDIA_STOP:
  205982. key = KeyPress::stopKey;
  205983. break;
  205984. case APPCOMMAND_MEDIA_NEXTTRACK:
  205985. key = KeyPress::fastForwardKey;
  205986. break;
  205987. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  205988. key = KeyPress::rewindKey;
  205989. break;
  205990. }
  205991. if (key != 0)
  205992. {
  205993. updateKeyModifiers();
  205994. if (hwnd == GetActiveWindow())
  205995. {
  205996. handleKeyPress (key, 0);
  205997. return true;
  205998. }
  205999. }
  206000. return false;
  206001. }
  206002. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  206003. {
  206004. public:
  206005. JuceDropTarget (Win32ComponentPeer* const owner_)
  206006. : owner (owner_)
  206007. {
  206008. }
  206009. ~JuceDropTarget() {}
  206010. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206011. {
  206012. updateFileList (pDataObject);
  206013. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206014. *pdwEffect = DROPEFFECT_COPY;
  206015. return S_OK;
  206016. }
  206017. HRESULT __stdcall DragLeave()
  206018. {
  206019. owner->handleFileDragExit (files);
  206020. return S_OK;
  206021. }
  206022. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206023. {
  206024. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206025. *pdwEffect = DROPEFFECT_COPY;
  206026. return S_OK;
  206027. }
  206028. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206029. {
  206030. updateFileList (pDataObject);
  206031. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  206032. *pdwEffect = DROPEFFECT_COPY;
  206033. return S_OK;
  206034. }
  206035. private:
  206036. Win32ComponentPeer* const owner;
  206037. StringArray files;
  206038. void updateFileList (IDataObject* const pDataObject)
  206039. {
  206040. files.clear();
  206041. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206042. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206043. if (pDataObject->GetData (&format, &medium) == S_OK)
  206044. {
  206045. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  206046. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  206047. unsigned int i = 0;
  206048. if (pDropFiles->fWide)
  206049. {
  206050. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  206051. for (;;)
  206052. {
  206053. unsigned int len = 0;
  206054. while (i + len < totalLen && fname [i + len] != 0)
  206055. ++len;
  206056. if (len == 0)
  206057. break;
  206058. files.add (String (fname + i, len));
  206059. i += len + 1;
  206060. }
  206061. }
  206062. else
  206063. {
  206064. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  206065. for (;;)
  206066. {
  206067. unsigned int len = 0;
  206068. while (i + len < totalLen && fname [i + len] != 0)
  206069. ++len;
  206070. if (len == 0)
  206071. break;
  206072. files.add (String (fname + i, len));
  206073. i += len + 1;
  206074. }
  206075. }
  206076. GlobalUnlock (medium.hGlobal);
  206077. }
  206078. }
  206079. JuceDropTarget (const JuceDropTarget&);
  206080. JuceDropTarget& operator= (const JuceDropTarget&);
  206081. };
  206082. void doSettingChange()
  206083. {
  206084. Desktop::getInstance().refreshMonitorSizes();
  206085. if (fullScreen && ! isMinimised())
  206086. {
  206087. const Rectangle<int> r (component->getParentMonitorArea());
  206088. SetWindowPos (hwnd, 0,
  206089. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  206090. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  206091. }
  206092. }
  206093. public:
  206094. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206095. {
  206096. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  206097. if (peer != 0)
  206098. return peer->peerWindowProc (h, message, wParam, lParam);
  206099. return DefWindowProcW (h, message, wParam, lParam);
  206100. }
  206101. private:
  206102. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  206103. {
  206104. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  206105. }
  206106. const Point<int> getCurrentMousePos() throw()
  206107. {
  206108. RECT wr;
  206109. GetWindowRect (hwnd, &wr);
  206110. const DWORD mp = GetMessagePos();
  206111. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206112. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  206113. }
  206114. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206115. {
  206116. if (isValidPeer (this))
  206117. {
  206118. switch (message)
  206119. {
  206120. case WM_NCHITTEST:
  206121. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  206122. return HTTRANSPARENT;
  206123. if (hasTitleBar())
  206124. break;
  206125. return HTCLIENT;
  206126. case WM_PAINT:
  206127. handlePaintMessage();
  206128. return 0;
  206129. case WM_NCPAINT:
  206130. if (wParam != 1)
  206131. handlePaintMessage();
  206132. if (hasTitleBar())
  206133. break;
  206134. return 0;
  206135. case WM_ERASEBKGND:
  206136. case WM_NCCALCSIZE:
  206137. if (hasTitleBar())
  206138. break;
  206139. return 1;
  206140. case WM_MOUSEMOVE:
  206141. doMouseMove (getPointFromLParam (lParam));
  206142. return 0;
  206143. case WM_MOUSELEAVE:
  206144. doMouseExit();
  206145. return 0;
  206146. case WM_LBUTTONDOWN:
  206147. case WM_MBUTTONDOWN:
  206148. case WM_RBUTTONDOWN:
  206149. doMouseDown (getPointFromLParam (lParam), wParam);
  206150. return 0;
  206151. case WM_LBUTTONUP:
  206152. case WM_MBUTTONUP:
  206153. case WM_RBUTTONUP:
  206154. doMouseUp (getPointFromLParam (lParam), wParam);
  206155. return 0;
  206156. case WM_CAPTURECHANGED:
  206157. doCaptureChanged();
  206158. return 0;
  206159. case WM_NCMOUSEMOVE:
  206160. if (hasTitleBar())
  206161. break;
  206162. return 0;
  206163. case 0x020A: /* WM_MOUSEWHEEL */
  206164. doMouseWheel (getCurrentMousePos(), wParam, true);
  206165. return 0;
  206166. case 0x020E: /* WM_MOUSEHWHEEL */
  206167. doMouseWheel (getCurrentMousePos(), wParam, false);
  206168. return 0;
  206169. case WM_WINDOWPOSCHANGING:
  206170. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  206171. {
  206172. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  206173. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  206174. {
  206175. if (constrainer != 0)
  206176. {
  206177. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  206178. component->getY() - windowBorder.getTop(),
  206179. component->getWidth() + windowBorder.getLeftAndRight(),
  206180. component->getHeight() + windowBorder.getTopAndBottom());
  206181. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  206182. constrainer->checkBounds (pos, current,
  206183. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  206184. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  206185. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  206186. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  206187. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  206188. wp->x = pos.getX();
  206189. wp->y = pos.getY();
  206190. wp->cx = pos.getWidth();
  206191. wp->cy = pos.getHeight();
  206192. }
  206193. }
  206194. }
  206195. return 0;
  206196. case WM_WINDOWPOSCHANGED:
  206197. handleMovedOrResized();
  206198. if (dontRepaint)
  206199. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  206200. return 0;
  206201. case WM_KEYDOWN:
  206202. case WM_SYSKEYDOWN:
  206203. if (doKeyDown (wParam))
  206204. return 0;
  206205. break;
  206206. case WM_KEYUP:
  206207. case WM_SYSKEYUP:
  206208. if (doKeyUp (wParam))
  206209. return 0;
  206210. break;
  206211. case WM_CHAR:
  206212. if (doKeyChar ((int) wParam, lParam))
  206213. return 0;
  206214. break;
  206215. case WM_APPCOMMAND:
  206216. if (doAppCommand (lParam))
  206217. return TRUE;
  206218. break;
  206219. case WM_SETFOCUS:
  206220. updateKeyModifiers();
  206221. handleFocusGain();
  206222. break;
  206223. case WM_KILLFOCUS:
  206224. if (hasCreatedCaret)
  206225. {
  206226. hasCreatedCaret = false;
  206227. DestroyCaret();
  206228. }
  206229. handleFocusLoss();
  206230. break;
  206231. case WM_ACTIVATEAPP:
  206232. // Windows does weird things to process priority when you swap apps,
  206233. // so this forces an update when the app is brought to the front
  206234. if (wParam != FALSE)
  206235. juce_repeatLastProcessPriority();
  206236. else
  206237. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  206238. juce_CheckCurrentlyFocusedTopLevelWindow();
  206239. modifiersAtLastCallback = -1;
  206240. return 0;
  206241. case WM_ACTIVATE:
  206242. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  206243. {
  206244. modifiersAtLastCallback = -1;
  206245. updateKeyModifiers();
  206246. if (isMinimised())
  206247. {
  206248. component->repaint();
  206249. handleMovedOrResized();
  206250. if (! ComponentPeer::isValidPeer (this))
  206251. return 0;
  206252. }
  206253. if (LOWORD (wParam) == WA_CLICKACTIVE
  206254. && component->isCurrentlyBlockedByAnotherModalComponent())
  206255. {
  206256. const Point<int> mousePos (component->getMouseXYRelative());
  206257. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  206258. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  206259. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  206260. return 0;
  206261. }
  206262. handleBroughtToFront();
  206263. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206264. Component::getCurrentlyModalComponent()->toFront (true);
  206265. return 0;
  206266. }
  206267. break;
  206268. case WM_NCACTIVATE:
  206269. // while a temporary window is being shown, prevent Windows from deactivating the
  206270. // title bars of our main windows.
  206271. if (wParam == 0 && ! shouldDeactivateTitleBar)
  206272. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  206273. break;
  206274. case WM_MOUSEACTIVATE:
  206275. if (! component->getMouseClickGrabsKeyboardFocus())
  206276. return MA_NOACTIVATE;
  206277. break;
  206278. case WM_SHOWWINDOW:
  206279. if (wParam != 0)
  206280. handleBroughtToFront();
  206281. break;
  206282. case WM_CLOSE:
  206283. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  206284. handleUserClosingWindow();
  206285. return 0;
  206286. case WM_QUERYENDSESSION:
  206287. if (JUCEApplication::getInstance() != 0)
  206288. {
  206289. JUCEApplication::getInstance()->systemRequestedQuit();
  206290. return MessageManager::getInstance()->hasStopMessageBeenSent();
  206291. }
  206292. return TRUE;
  206293. case WM_TRAYNOTIFY:
  206294. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206295. {
  206296. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206297. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206298. {
  206299. Component* const current = Component::getCurrentlyModalComponent();
  206300. if (current != 0)
  206301. current->inputAttemptWhenModal();
  206302. }
  206303. }
  206304. else
  206305. {
  206306. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206307. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206308. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206309. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206310. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206311. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206312. eventMods = eventMods.withoutMouseButtons();
  206313. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206314. Point<int>(), eventMods, component, component, getMouseEventTime(),
  206315. Point<int>(), getMouseEventTime(), 1, false);
  206316. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206317. {
  206318. SetFocus (hwnd);
  206319. SetForegroundWindow (hwnd);
  206320. component->mouseDown (e);
  206321. }
  206322. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206323. {
  206324. component->mouseUp (e);
  206325. }
  206326. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206327. {
  206328. component->mouseDoubleClick (e);
  206329. }
  206330. else if (lParam == WM_MOUSEMOVE)
  206331. {
  206332. component->mouseMove (e);
  206333. }
  206334. }
  206335. break;
  206336. case WM_SYNCPAINT:
  206337. return 0;
  206338. case WM_PALETTECHANGED:
  206339. InvalidateRect (h, 0, 0);
  206340. break;
  206341. case WM_DISPLAYCHANGE:
  206342. InvalidateRect (h, 0, 0);
  206343. createPaletteIfNeeded = true;
  206344. // intentional fall-through...
  206345. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  206346. doSettingChange();
  206347. break;
  206348. case WM_INITMENU:
  206349. if (! hasTitleBar())
  206350. {
  206351. if (isFullScreen())
  206352. {
  206353. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  206354. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  206355. }
  206356. else if (! isMinimised())
  206357. {
  206358. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  206359. }
  206360. }
  206361. break;
  206362. case WM_SYSCOMMAND:
  206363. switch (wParam & 0xfff0)
  206364. {
  206365. case SC_CLOSE:
  206366. if (sendInputAttemptWhenModalMessage())
  206367. return 0;
  206368. if (hasTitleBar())
  206369. {
  206370. PostMessage (h, WM_CLOSE, 0, 0);
  206371. return 0;
  206372. }
  206373. break;
  206374. case SC_KEYMENU:
  206375. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  206376. // obscure situations that can arise if a modal loop is started from an alt-key
  206377. // keypress).
  206378. if (hasTitleBar() && h == GetCapture())
  206379. ReleaseCapture();
  206380. break;
  206381. case SC_MAXIMIZE:
  206382. if (sendInputAttemptWhenModalMessage())
  206383. return 0;
  206384. setFullScreen (true);
  206385. return 0;
  206386. case SC_MINIMIZE:
  206387. if (sendInputAttemptWhenModalMessage())
  206388. return 0;
  206389. if (! hasTitleBar())
  206390. {
  206391. setMinimised (true);
  206392. return 0;
  206393. }
  206394. break;
  206395. case SC_RESTORE:
  206396. if (sendInputAttemptWhenModalMessage())
  206397. return 0;
  206398. if (hasTitleBar())
  206399. {
  206400. if (isFullScreen())
  206401. {
  206402. setFullScreen (false);
  206403. return 0;
  206404. }
  206405. }
  206406. else
  206407. {
  206408. if (isMinimised())
  206409. setMinimised (false);
  206410. else if (isFullScreen())
  206411. setFullScreen (false);
  206412. return 0;
  206413. }
  206414. break;
  206415. }
  206416. break;
  206417. case WM_NCLBUTTONDOWN:
  206418. case WM_NCRBUTTONDOWN:
  206419. case WM_NCMBUTTONDOWN:
  206420. sendInputAttemptWhenModalMessage();
  206421. break;
  206422. //case WM_IME_STARTCOMPOSITION;
  206423. // return 0;
  206424. case WM_GETDLGCODE:
  206425. return DLGC_WANTALLKEYS;
  206426. default:
  206427. break;
  206428. }
  206429. }
  206430. return DefWindowProcW (h, message, wParam, lParam);
  206431. }
  206432. bool sendInputAttemptWhenModalMessage()
  206433. {
  206434. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206435. {
  206436. Component* const current = Component::getCurrentlyModalComponent();
  206437. if (current != 0)
  206438. current->inputAttemptWhenModal();
  206439. return true;
  206440. }
  206441. return false;
  206442. }
  206443. Win32ComponentPeer (const Win32ComponentPeer&);
  206444. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206445. };
  206446. ModifierKeys Win32ComponentPeer::currentModifiers;
  206447. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  206448. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206449. {
  206450. return new Win32ComponentPeer (this, styleFlags);
  206451. }
  206452. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206453. void ModifierKeys::updateCurrentModifiers() throw()
  206454. {
  206455. currentModifiers = Win32ComponentPeer::currentModifiers;
  206456. }
  206457. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  206458. {
  206459. Win32ComponentPeer::updateKeyModifiers();
  206460. int keyMods = 0;
  206461. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  206462. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  206463. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  206464. Win32ComponentPeer::currentModifiers
  206465. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206466. return Win32ComponentPeer::currentModifiers;
  206467. }
  206468. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206469. {
  206470. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206471. if (wp != 0)
  206472. wp->setTaskBarIcon (newImage);
  206473. }
  206474. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206475. {
  206476. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206477. if (wp != 0)
  206478. wp->setTaskBarIconToolTip (tooltip);
  206479. }
  206480. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206481. {
  206482. DWORD val = GetWindowLong (h, styleType);
  206483. if (bitIsSet)
  206484. val |= feature;
  206485. else
  206486. val &= ~feature;
  206487. SetWindowLongPtr (h, styleType, val);
  206488. SetWindowPos (h, 0, 0, 0, 0, 0,
  206489. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206490. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206491. }
  206492. bool Process::isForegroundProcess()
  206493. {
  206494. HWND fg = GetForegroundWindow();
  206495. if (fg == 0)
  206496. return true;
  206497. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  206498. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  206499. // have to see if any of our windows are children of the foreground window
  206500. fg = GetAncestor (fg, GA_ROOT);
  206501. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  206502. {
  206503. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  206504. if (wp != 0 && wp->isInside (fg))
  206505. return true;
  206506. }
  206507. return false;
  206508. }
  206509. bool AlertWindow::showNativeDialogBox (const String& title,
  206510. const String& bodyText,
  206511. bool isOkCancel)
  206512. {
  206513. return MessageBox (0, bodyText, title,
  206514. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  206515. : MB_OK)) == IDOK;
  206516. }
  206517. void Desktop::createMouseInputSources()
  206518. {
  206519. mouseSources.add (new MouseInputSource (0, true));
  206520. }
  206521. const Point<int> Desktop::getMousePosition()
  206522. {
  206523. POINT mousePos;
  206524. GetCursorPos (&mousePos);
  206525. return Point<int> (mousePos.x, mousePos.y);
  206526. }
  206527. void Desktop::setMousePosition (const Point<int>& newPosition)
  206528. {
  206529. SetCursorPos (newPosition.getX(), newPosition.getY());
  206530. }
  206531. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  206532. {
  206533. return createSoftwareImage (format, width, height, clearImage);
  206534. }
  206535. class ScreenSaverDefeater : public Timer,
  206536. public DeletedAtShutdown
  206537. {
  206538. public:
  206539. ScreenSaverDefeater()
  206540. {
  206541. startTimer (10000);
  206542. timerCallback();
  206543. }
  206544. ~ScreenSaverDefeater() {}
  206545. void timerCallback()
  206546. {
  206547. if (Process::isForegroundProcess())
  206548. {
  206549. // simulate a shift key getting pressed..
  206550. INPUT input[2];
  206551. input[0].type = INPUT_KEYBOARD;
  206552. input[0].ki.wVk = VK_SHIFT;
  206553. input[0].ki.dwFlags = 0;
  206554. input[0].ki.dwExtraInfo = 0;
  206555. input[1].type = INPUT_KEYBOARD;
  206556. input[1].ki.wVk = VK_SHIFT;
  206557. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  206558. input[1].ki.dwExtraInfo = 0;
  206559. SendInput (2, input, sizeof (INPUT));
  206560. }
  206561. }
  206562. };
  206563. static ScreenSaverDefeater* screenSaverDefeater = 0;
  206564. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  206565. {
  206566. if (isEnabled)
  206567. deleteAndZero (screenSaverDefeater);
  206568. else if (screenSaverDefeater == 0)
  206569. screenSaverDefeater = new ScreenSaverDefeater();
  206570. }
  206571. bool Desktop::isScreenSaverEnabled()
  206572. {
  206573. return screenSaverDefeater == 0;
  206574. }
  206575. /* (The code below is the "correct" way to disable the screen saver, but it
  206576. completely fails on winXP when the saver is password-protected...)
  206577. static bool juce_screenSaverEnabled = true;
  206578. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206579. {
  206580. juce_screenSaverEnabled = isEnabled;
  206581. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  206582. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  206583. }
  206584. bool Desktop::isScreenSaverEnabled() throw()
  206585. {
  206586. return juce_screenSaverEnabled;
  206587. }
  206588. */
  206589. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  206590. {
  206591. if (enableOrDisable)
  206592. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  206593. }
  206594. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206595. {
  206596. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  206597. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206598. return TRUE;
  206599. }
  206600. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  206601. {
  206602. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206603. // make sure the first in the list is the main monitor
  206604. for (int i = 1; i < monitorCoords.size(); ++i)
  206605. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206606. monitorCoords.swap (i, 0);
  206607. if (monitorCoords.size() == 0)
  206608. {
  206609. RECT r;
  206610. GetWindowRect (GetDesktopWindow(), &r);
  206611. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206612. }
  206613. if (clipToWorkArea)
  206614. {
  206615. // clip the main monitor to the active non-taskbar area
  206616. RECT r;
  206617. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206618. Rectangle<int>& screen = monitorCoords.getReference (0);
  206619. screen.setPosition (jmax (screen.getX(), (int) r.left),
  206620. jmax (screen.getY(), (int) r.top));
  206621. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  206622. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  206623. }
  206624. }
  206625. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  206626. {
  206627. Image im;
  206628. if (bitmap != 0)
  206629. {
  206630. BITMAP bm;
  206631. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206632. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206633. {
  206634. HDC tempDC = GetDC (0);
  206635. HDC dc = CreateCompatibleDC (tempDC);
  206636. ReleaseDC (0, tempDC);
  206637. SelectObject (dc, bitmap);
  206638. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206639. Image::BitmapData imageData (im, true);
  206640. for (int y = bm.bmHeight; --y >= 0;)
  206641. {
  206642. for (int x = bm.bmWidth; --x >= 0;)
  206643. {
  206644. COLORREF col = GetPixel (dc, x, y);
  206645. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206646. (uint8) GetGValue (col),
  206647. (uint8) GetBValue (col)));
  206648. }
  206649. }
  206650. DeleteDC (dc);
  206651. }
  206652. }
  206653. return im;
  206654. }
  206655. static const Image createImageFromHICON (HICON icon)
  206656. {
  206657. ICONINFO info;
  206658. if (GetIconInfo (icon, &info))
  206659. {
  206660. Image mask (createImageFromHBITMAP (info.hbmMask));
  206661. Image image (createImageFromHBITMAP (info.hbmColor));
  206662. if (mask.isValid() && image.isValid())
  206663. {
  206664. for (int y = image.getHeight(); --y >= 0;)
  206665. {
  206666. for (int x = image.getWidth(); --x >= 0;)
  206667. {
  206668. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206669. if (brightness > 0.0f)
  206670. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206671. }
  206672. }
  206673. return image;
  206674. }
  206675. }
  206676. return Image::null;
  206677. }
  206678. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206679. {
  206680. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206681. Image bitmap (nativeBitmap);
  206682. {
  206683. Graphics g (bitmap);
  206684. g.drawImageAt (image, 0, 0);
  206685. }
  206686. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206687. ICONINFO info;
  206688. info.fIcon = isIcon;
  206689. info.xHotspot = hotspotX;
  206690. info.yHotspot = hotspotY;
  206691. info.hbmMask = mask;
  206692. info.hbmColor = nativeBitmap->hBitmap;
  206693. HICON hi = CreateIconIndirect (&info);
  206694. DeleteObject (mask);
  206695. return hi;
  206696. }
  206697. const Image juce_createIconForFile (const File& file)
  206698. {
  206699. Image image;
  206700. WCHAR filename [1024];
  206701. file.getFullPathName().copyToUnicode (filename, 1023);
  206702. WORD iconNum = 0;
  206703. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206704. filename, &iconNum);
  206705. if (icon != 0)
  206706. {
  206707. image = createImageFromHICON (icon);
  206708. DestroyIcon (icon);
  206709. }
  206710. return image;
  206711. }
  206712. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  206713. {
  206714. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206715. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206716. Image im (image);
  206717. if (im.getWidth() > maxW || im.getHeight() > maxH)
  206718. {
  206719. im = im.rescaled (maxW, maxH);
  206720. hotspotX = (hotspotX * maxW) / image.getWidth();
  206721. hotspotY = (hotspotY * maxH) / image.getHeight();
  206722. }
  206723. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  206724. }
  206725. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  206726. {
  206727. if (cursorHandle != 0 && ! isStandard)
  206728. DestroyCursor ((HCURSOR) cursorHandle);
  206729. }
  206730. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  206731. {
  206732. LPCTSTR cursorName = IDC_ARROW;
  206733. switch (type)
  206734. {
  206735. case NormalCursor: break;
  206736. case NoCursor: return 0;
  206737. case WaitCursor: cursorName = IDC_WAIT; break;
  206738. case IBeamCursor: cursorName = IDC_IBEAM; break;
  206739. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  206740. case CrosshairCursor: cursorName = IDC_CROSS; break;
  206741. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  206742. case LeftRightResizeCursor:
  206743. case LeftEdgeResizeCursor:
  206744. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  206745. case UpDownResizeCursor:
  206746. case TopEdgeResizeCursor:
  206747. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  206748. case TopLeftCornerResizeCursor:
  206749. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  206750. case TopRightCornerResizeCursor:
  206751. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  206752. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  206753. case DraggingHandCursor:
  206754. {
  206755. static void* dragHandCursor = 0;
  206756. if (dragHandCursor == 0)
  206757. {
  206758. static const unsigned char dragHandData[] =
  206759. { 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,
  206760. 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,
  206761. 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 };
  206762. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  206763. }
  206764. return dragHandCursor;
  206765. }
  206766. default:
  206767. jassertfalse; break;
  206768. }
  206769. HCURSOR cursorH = LoadCursor (0, cursorName);
  206770. if (cursorH == 0)
  206771. cursorH = LoadCursor (0, IDC_ARROW);
  206772. return cursorH;
  206773. }
  206774. void MouseCursor::showInWindow (ComponentPeer*) const
  206775. {
  206776. SetCursor ((HCURSOR) getHandle());
  206777. }
  206778. void MouseCursor::showInAllWindows() const
  206779. {
  206780. showInWindow (0);
  206781. }
  206782. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  206783. {
  206784. public:
  206785. JuceDropSource() {}
  206786. ~JuceDropSource() {}
  206787. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206788. {
  206789. if (escapePressed)
  206790. return DRAGDROP_S_CANCEL;
  206791. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206792. return DRAGDROP_S_DROP;
  206793. return S_OK;
  206794. }
  206795. HRESULT __stdcall GiveFeedback (DWORD)
  206796. {
  206797. return DRAGDROP_S_USEDEFAULTCURSORS;
  206798. }
  206799. };
  206800. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  206801. {
  206802. public:
  206803. JuceEnumFormatEtc (const FORMATETC* const format_)
  206804. : format (format_),
  206805. index (0)
  206806. {
  206807. }
  206808. ~JuceEnumFormatEtc() {}
  206809. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206810. {
  206811. if (result == 0)
  206812. return E_POINTER;
  206813. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206814. newOne->index = index;
  206815. *result = newOne;
  206816. return S_OK;
  206817. }
  206818. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206819. {
  206820. if (pceltFetched != 0)
  206821. *pceltFetched = 0;
  206822. else if (celt != 1)
  206823. return S_FALSE;
  206824. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206825. {
  206826. copyFormatEtc (lpFormatEtc [0], *format);
  206827. ++index;
  206828. if (pceltFetched != 0)
  206829. *pceltFetched = 1;
  206830. return S_OK;
  206831. }
  206832. return S_FALSE;
  206833. }
  206834. HRESULT __stdcall Skip (ULONG celt)
  206835. {
  206836. if (index + (int) celt >= 1)
  206837. return S_FALSE;
  206838. index += celt;
  206839. return S_OK;
  206840. }
  206841. HRESULT __stdcall Reset()
  206842. {
  206843. index = 0;
  206844. return S_OK;
  206845. }
  206846. private:
  206847. const FORMATETC* const format;
  206848. int index;
  206849. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206850. {
  206851. dest = source;
  206852. if (source.ptd != 0)
  206853. {
  206854. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206855. *(dest.ptd) = *(source.ptd);
  206856. }
  206857. }
  206858. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206859. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206860. };
  206861. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  206862. {
  206863. public:
  206864. JuceDataObject (JuceDropSource* const dropSource_,
  206865. const FORMATETC* const format_,
  206866. const STGMEDIUM* const medium_)
  206867. : dropSource (dropSource_),
  206868. format (format_),
  206869. medium (medium_)
  206870. {
  206871. }
  206872. virtual ~JuceDataObject()
  206873. {
  206874. jassert (refCount == 0);
  206875. }
  206876. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  206877. {
  206878. if ((pFormatEtc->tymed & format->tymed) != 0
  206879. && pFormatEtc->cfFormat == format->cfFormat
  206880. && pFormatEtc->dwAspect == format->dwAspect)
  206881. {
  206882. pMedium->tymed = format->tymed;
  206883. pMedium->pUnkForRelease = 0;
  206884. if (format->tymed == TYMED_HGLOBAL)
  206885. {
  206886. const SIZE_T len = GlobalSize (medium->hGlobal);
  206887. void* const src = GlobalLock (medium->hGlobal);
  206888. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  206889. memcpy (dst, src, len);
  206890. GlobalUnlock (medium->hGlobal);
  206891. pMedium->hGlobal = dst;
  206892. return S_OK;
  206893. }
  206894. }
  206895. return DV_E_FORMATETC;
  206896. }
  206897. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  206898. {
  206899. if (f == 0)
  206900. return E_INVALIDARG;
  206901. if (f->tymed == format->tymed
  206902. && f->cfFormat == format->cfFormat
  206903. && f->dwAspect == format->dwAspect)
  206904. return S_OK;
  206905. return DV_E_FORMATETC;
  206906. }
  206907. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  206908. {
  206909. pFormatEtcOut->ptd = 0;
  206910. return E_NOTIMPL;
  206911. }
  206912. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  206913. {
  206914. if (result == 0)
  206915. return E_POINTER;
  206916. if (direction == DATADIR_GET)
  206917. {
  206918. *result = new JuceEnumFormatEtc (format);
  206919. return S_OK;
  206920. }
  206921. *result = 0;
  206922. return E_NOTIMPL;
  206923. }
  206924. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  206925. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  206926. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  206927. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  206928. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  206929. private:
  206930. JuceDropSource* const dropSource;
  206931. const FORMATETC* const format;
  206932. const STGMEDIUM* const medium;
  206933. JuceDataObject (const JuceDataObject&);
  206934. JuceDataObject& operator= (const JuceDataObject&);
  206935. };
  206936. static HDROP createHDrop (const StringArray& fileNames)
  206937. {
  206938. int totalChars = 0;
  206939. for (int i = fileNames.size(); --i >= 0;)
  206940. totalChars += fileNames[i].length() + 1;
  206941. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  206942. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  206943. if (hDrop != 0)
  206944. {
  206945. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  206946. pDropFiles->pFiles = sizeof (DROPFILES);
  206947. pDropFiles->fWide = true;
  206948. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  206949. for (int i = 0; i < fileNames.size(); ++i)
  206950. {
  206951. fileNames[i].copyToUnicode (fname, 2048);
  206952. fname += fileNames[i].length() + 1;
  206953. }
  206954. *fname = 0;
  206955. GlobalUnlock (hDrop);
  206956. }
  206957. return hDrop;
  206958. }
  206959. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  206960. {
  206961. JuceDropSource* const source = new JuceDropSource();
  206962. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  206963. DWORD effect;
  206964. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  206965. data->Release();
  206966. source->Release();
  206967. return res == DRAGDROP_S_DROP;
  206968. }
  206969. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  206970. {
  206971. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206972. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206973. medium.hGlobal = createHDrop (files);
  206974. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  206975. : DROPEFFECT_COPY);
  206976. }
  206977. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  206978. {
  206979. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206980. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206981. const int numChars = text.length();
  206982. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  206983. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  206984. text.copyToUnicode (data, numChars + 1);
  206985. format.cfFormat = CF_UNICODETEXT;
  206986. GlobalUnlock (medium.hGlobal);
  206987. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  206988. }
  206989. #endif
  206990. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  206991. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  206992. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206993. // compiled on its own).
  206994. #if JUCE_INCLUDED_FILE
  206995. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  206996. NEWTEXTMETRICEXW*,
  206997. int type,
  206998. LPARAM lParam)
  206999. {
  207000. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  207001. {
  207002. const String fontName (lpelfe->elfLogFont.lfFaceName);
  207003. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  207004. }
  207005. return 1;
  207006. }
  207007. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  207008. NEWTEXTMETRICEXW*,
  207009. int type,
  207010. LPARAM lParam)
  207011. {
  207012. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  207013. {
  207014. LOGFONTW lf;
  207015. zerostruct (lf);
  207016. lf.lfWeight = FW_DONTCARE;
  207017. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207018. lf.lfQuality = DEFAULT_QUALITY;
  207019. lf.lfCharSet = DEFAULT_CHARSET;
  207020. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207021. lf.lfPitchAndFamily = FF_DONTCARE;
  207022. const String fontName (lpelfe->elfLogFont.lfFaceName);
  207023. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  207024. HDC dc = CreateCompatibleDC (0);
  207025. EnumFontFamiliesEx (dc, &lf,
  207026. (FONTENUMPROCW) &wfontEnum2,
  207027. lParam, 0);
  207028. DeleteDC (dc);
  207029. }
  207030. return 1;
  207031. }
  207032. const StringArray Font::findAllTypefaceNames()
  207033. {
  207034. StringArray results;
  207035. HDC dc = CreateCompatibleDC (0);
  207036. {
  207037. LOGFONTW lf;
  207038. zerostruct (lf);
  207039. lf.lfWeight = FW_DONTCARE;
  207040. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207041. lf.lfQuality = DEFAULT_QUALITY;
  207042. lf.lfCharSet = DEFAULT_CHARSET;
  207043. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207044. lf.lfPitchAndFamily = FF_DONTCARE;
  207045. lf.lfFaceName[0] = 0;
  207046. EnumFontFamiliesEx (dc, &lf,
  207047. (FONTENUMPROCW) &wfontEnum1,
  207048. (LPARAM) &results, 0);
  207049. }
  207050. DeleteDC (dc);
  207051. results.sort (true);
  207052. return results;
  207053. }
  207054. extern bool juce_IsRunningInWine();
  207055. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  207056. {
  207057. if (juce_IsRunningInWine())
  207058. {
  207059. // If we're running in Wine, then use fonts that might be available on Linux..
  207060. defaultSans = "Bitstream Vera Sans";
  207061. defaultSerif = "Bitstream Vera Serif";
  207062. defaultFixed = "Bitstream Vera Sans Mono";
  207063. }
  207064. else
  207065. {
  207066. defaultSans = "Verdana";
  207067. defaultSerif = "Times";
  207068. defaultFixed = "Lucida Console";
  207069. }
  207070. }
  207071. class FontDCHolder : private DeletedAtShutdown
  207072. {
  207073. public:
  207074. FontDCHolder()
  207075. : dc (0), numKPs (0), size (0),
  207076. bold (false), italic (false)
  207077. {
  207078. }
  207079. ~FontDCHolder()
  207080. {
  207081. if (dc != 0)
  207082. {
  207083. DeleteDC (dc);
  207084. DeleteObject (fontH);
  207085. }
  207086. clearSingletonInstance();
  207087. }
  207088. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  207089. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  207090. {
  207091. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  207092. {
  207093. fontName = fontName_;
  207094. bold = bold_;
  207095. italic = italic_;
  207096. size = size_;
  207097. if (dc != 0)
  207098. {
  207099. DeleteDC (dc);
  207100. DeleteObject (fontH);
  207101. kps.free();
  207102. }
  207103. fontH = 0;
  207104. dc = CreateCompatibleDC (0);
  207105. SetMapperFlags (dc, 0);
  207106. SetMapMode (dc, MM_TEXT);
  207107. LOGFONTW lfw;
  207108. zerostruct (lfw);
  207109. lfw.lfCharSet = DEFAULT_CHARSET;
  207110. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  207111. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  207112. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  207113. lfw.lfQuality = PROOF_QUALITY;
  207114. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  207115. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  207116. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  207117. lfw.lfHeight = size > 0 ? size : -256;
  207118. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  207119. if (standardSizedFont != 0)
  207120. {
  207121. if (SelectObject (dc, standardSizedFont) != 0)
  207122. {
  207123. fontH = standardSizedFont;
  207124. if (size == 0)
  207125. {
  207126. OUTLINETEXTMETRIC otm;
  207127. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  207128. {
  207129. lfw.lfHeight = -(int) otm.otmEMSquare;
  207130. fontH = CreateFontIndirect (&lfw);
  207131. SelectObject (dc, fontH);
  207132. DeleteObject (standardSizedFont);
  207133. }
  207134. }
  207135. }
  207136. else
  207137. {
  207138. jassertfalse;
  207139. }
  207140. }
  207141. else
  207142. {
  207143. jassertfalse;
  207144. }
  207145. }
  207146. return dc;
  207147. }
  207148. KERNINGPAIR* getKerningPairs (int& numKPs_)
  207149. {
  207150. if (kps == 0)
  207151. {
  207152. numKPs = GetKerningPairs (dc, 0, 0);
  207153. kps.calloc (numKPs);
  207154. GetKerningPairs (dc, numKPs, kps);
  207155. }
  207156. numKPs_ = numKPs;
  207157. return kps;
  207158. }
  207159. private:
  207160. HFONT fontH;
  207161. HDC dc;
  207162. String fontName;
  207163. HeapBlock <KERNINGPAIR> kps;
  207164. int numKPs, size;
  207165. bool bold, italic;
  207166. FontDCHolder (const FontDCHolder&);
  207167. FontDCHolder& operator= (const FontDCHolder&);
  207168. };
  207169. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  207170. class WindowsTypeface : public CustomTypeface
  207171. {
  207172. public:
  207173. WindowsTypeface (const Font& font)
  207174. {
  207175. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  207176. font.isBold(), font.isItalic(), 0);
  207177. TEXTMETRIC tm;
  207178. tm.tmAscent = tm.tmHeight = 1;
  207179. tm.tmDefaultChar = 0;
  207180. GetTextMetrics (dc, &tm);
  207181. setCharacteristics (font.getTypefaceName(),
  207182. tm.tmAscent / (float) tm.tmHeight,
  207183. font.isBold(), font.isItalic(),
  207184. tm.tmDefaultChar);
  207185. }
  207186. bool loadGlyphIfPossible (juce_wchar character)
  207187. {
  207188. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  207189. GLYPHMETRICS gm;
  207190. {
  207191. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  207192. WORD index = 0;
  207193. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  207194. && index == 0xffff)
  207195. {
  207196. return false;
  207197. }
  207198. }
  207199. Path glyphPath;
  207200. TEXTMETRIC tm;
  207201. if (! GetTextMetrics (dc, &tm))
  207202. {
  207203. addGlyph (character, glyphPath, 0);
  207204. return true;
  207205. }
  207206. const float height = (float) tm.tmHeight;
  207207. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  207208. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  207209. &gm, 0, 0, &identityMatrix);
  207210. if (bufSize > 0)
  207211. {
  207212. HeapBlock<char> data (bufSize);
  207213. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  207214. bufSize, data, &identityMatrix);
  207215. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  207216. const float scaleX = 1.0f / height;
  207217. const float scaleY = -1.0f / height;
  207218. while ((char*) pheader < data + bufSize)
  207219. {
  207220. float x = scaleX * pheader->pfxStart.x.value;
  207221. float y = scaleY * pheader->pfxStart.y.value;
  207222. glyphPath.startNewSubPath (x, y);
  207223. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  207224. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  207225. while ((const char*) curve < curveEnd)
  207226. {
  207227. if (curve->wType == TT_PRIM_LINE)
  207228. {
  207229. for (int i = 0; i < curve->cpfx; ++i)
  207230. {
  207231. x = scaleX * curve->apfx[i].x.value;
  207232. y = scaleY * curve->apfx[i].y.value;
  207233. glyphPath.lineTo (x, y);
  207234. }
  207235. }
  207236. else if (curve->wType == TT_PRIM_QSPLINE)
  207237. {
  207238. for (int i = 0; i < curve->cpfx - 1; ++i)
  207239. {
  207240. const float x2 = scaleX * curve->apfx[i].x.value;
  207241. const float y2 = scaleY * curve->apfx[i].y.value;
  207242. float x3, y3;
  207243. if (i < curve->cpfx - 2)
  207244. {
  207245. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  207246. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  207247. }
  207248. else
  207249. {
  207250. x3 = scaleX * curve->apfx[i + 1].x.value;
  207251. y3 = scaleY * curve->apfx[i + 1].y.value;
  207252. }
  207253. glyphPath.quadraticTo (x2, y2, x3, y3);
  207254. x = x3;
  207255. y = y3;
  207256. }
  207257. }
  207258. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  207259. }
  207260. pheader = (const TTPOLYGONHEADER*) curve;
  207261. glyphPath.closeSubPath();
  207262. }
  207263. }
  207264. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  207265. int numKPs;
  207266. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  207267. for (int i = 0; i < numKPs; ++i)
  207268. {
  207269. if (kps[i].wFirst == character)
  207270. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  207271. kps[i].iKernAmount / height);
  207272. }
  207273. return true;
  207274. }
  207275. juce_UseDebuggingNewOperator
  207276. };
  207277. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  207278. {
  207279. return new WindowsTypeface (font);
  207280. }
  207281. #endif
  207282. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  207283. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  207284. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207285. // compiled on its own).
  207286. #if JUCE_INCLUDED_FILE
  207287. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  207288. namespace FileChooserHelpers
  207289. {
  207290. static const void* defaultDirPath = 0;
  207291. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  207292. static Component* currentExtraFileWin = 0;
  207293. static bool areThereAnyAlwaysOnTopWindows()
  207294. {
  207295. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  207296. {
  207297. Component* c = Desktop::getInstance().getComponent (i);
  207298. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  207299. return true;
  207300. }
  207301. return false;
  207302. }
  207303. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  207304. {
  207305. if (msg == BFFM_INITIALIZED)
  207306. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  207307. else if (msg == BFFM_VALIDATEFAILEDW)
  207308. returnedString = (LPCWSTR) lParam;
  207309. else if (msg == BFFM_VALIDATEFAILEDA)
  207310. returnedString = (const char*) lParam;
  207311. return 0;
  207312. }
  207313. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  207314. {
  207315. if (currentExtraFileWin != 0)
  207316. {
  207317. if (uiMsg == WM_INITDIALOG)
  207318. {
  207319. HWND dialogH = GetParent (hdlg);
  207320. jassert (dialogH != 0);
  207321. if (dialogH == 0)
  207322. dialogH = hdlg;
  207323. RECT r, cr;
  207324. GetWindowRect (dialogH, &r);
  207325. GetClientRect (dialogH, &cr);
  207326. SetWindowPos (dialogH, 0,
  207327. r.left, r.top,
  207328. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  207329. jmax (150, (int) (r.bottom - r.top)),
  207330. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  207331. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  207332. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  207333. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  207334. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  207335. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  207336. }
  207337. else if (uiMsg == WM_NOTIFY)
  207338. {
  207339. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  207340. if (ofn->hdr.code == CDN_SELCHANGE)
  207341. {
  207342. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  207343. if (comp != 0)
  207344. {
  207345. TCHAR path [MAX_PATH * 2];
  207346. path[0] = 0;
  207347. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  207348. const String fn ((const WCHAR*) path);
  207349. comp->selectedFileChanged (File (fn));
  207350. }
  207351. }
  207352. }
  207353. }
  207354. return 0;
  207355. }
  207356. class FPComponentHolder : public Component
  207357. {
  207358. public:
  207359. FPComponentHolder()
  207360. {
  207361. setVisible (true);
  207362. setOpaque (true);
  207363. }
  207364. ~FPComponentHolder()
  207365. {
  207366. }
  207367. void paint (Graphics& g)
  207368. {
  207369. g.fillAll (Colours::lightgrey);
  207370. }
  207371. private:
  207372. FPComponentHolder (const FPComponentHolder&);
  207373. FPComponentHolder& operator= (const FPComponentHolder&);
  207374. };
  207375. }
  207376. void FileChooser::showPlatformDialog (Array<File>& results,
  207377. const String& title,
  207378. const File& currentFileOrDirectory,
  207379. const String& filter,
  207380. bool selectsDirectory,
  207381. bool /*selectsFiles*/,
  207382. bool isSaveDialogue,
  207383. bool warnAboutOverwritingExistingFiles,
  207384. bool selectMultipleFiles,
  207385. FilePreviewComponent* extraInfoComponent)
  207386. {
  207387. using namespace FileChooserHelpers;
  207388. const int numCharsAvailable = 32768;
  207389. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  207390. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  207391. int fnameIdx = 0;
  207392. JUCE_TRY
  207393. {
  207394. // use a modal window as the parent for this dialog box
  207395. // to block input from other app windows
  207396. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  207397. Component w (String::empty);
  207398. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  207399. mainMon.getY() + mainMon.getHeight() / 4,
  207400. 0, 0);
  207401. w.setOpaque (true);
  207402. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  207403. w.addToDesktop (0);
  207404. if (extraInfoComponent == 0)
  207405. w.enterModalState();
  207406. String initialDir;
  207407. if (currentFileOrDirectory.isDirectory())
  207408. {
  207409. initialDir = currentFileOrDirectory.getFullPathName();
  207410. }
  207411. else
  207412. {
  207413. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  207414. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  207415. }
  207416. if (currentExtraFileWin->isValidComponent())
  207417. {
  207418. jassertfalse;
  207419. return;
  207420. }
  207421. if (selectsDirectory)
  207422. {
  207423. LPITEMIDLIST list = 0;
  207424. filenameSpace.fillWith (0);
  207425. {
  207426. BROWSEINFO bi;
  207427. zerostruct (bi);
  207428. bi.hwndOwner = (HWND) w.getWindowHandle();
  207429. bi.pszDisplayName = fname;
  207430. bi.lpszTitle = title;
  207431. bi.lpfn = browseCallbackProc;
  207432. #ifdef BIF_USENEWUI
  207433. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  207434. #else
  207435. bi.ulFlags = 0x50;
  207436. #endif
  207437. defaultDirPath = (const WCHAR*) initialDir;
  207438. list = SHBrowseForFolder (&bi);
  207439. if (! SHGetPathFromIDListW (list, fname))
  207440. {
  207441. fname[0] = 0;
  207442. returnedString = String::empty;
  207443. }
  207444. }
  207445. LPMALLOC al;
  207446. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  207447. al->Free (list);
  207448. defaultDirPath = 0;
  207449. if (returnedString.isNotEmpty())
  207450. {
  207451. const String stringFName (fname);
  207452. results.add (File (stringFName).getSiblingFile (returnedString));
  207453. returnedString = String::empty;
  207454. return;
  207455. }
  207456. }
  207457. else
  207458. {
  207459. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  207460. if (warnAboutOverwritingExistingFiles)
  207461. flags |= OFN_OVERWRITEPROMPT;
  207462. if (selectMultipleFiles)
  207463. flags |= OFN_ALLOWMULTISELECT;
  207464. if (extraInfoComponent != 0)
  207465. {
  207466. flags |= OFN_ENABLEHOOK;
  207467. currentExtraFileWin = new FPComponentHolder();
  207468. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  207469. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  207470. extraInfoComponent->getHeight());
  207471. currentExtraFileWin->addToDesktop (0);
  207472. currentExtraFileWin->enterModalState();
  207473. }
  207474. {
  207475. WCHAR filters [1024];
  207476. zeromem (filters, sizeof (filters));
  207477. filter.copyToUnicode (filters, 1024);
  207478. filter.copyToUnicode (filters + filter.length() + 1,
  207479. 1022 - filter.length());
  207480. OPENFILENAMEW of;
  207481. zerostruct (of);
  207482. #ifdef OPENFILENAME_SIZE_VERSION_400W
  207483. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  207484. #else
  207485. of.lStructSize = sizeof (of);
  207486. #endif
  207487. of.hwndOwner = (HWND) w.getWindowHandle();
  207488. of.lpstrFilter = filters;
  207489. of.nFilterIndex = 1;
  207490. of.lpstrFile = fname;
  207491. of.nMaxFile = numCharsAvailable;
  207492. of.lpstrInitialDir = initialDir;
  207493. of.lpstrTitle = title;
  207494. of.Flags = flags;
  207495. if (extraInfoComponent != 0)
  207496. of.lpfnHook = &openCallback;
  207497. if (isSaveDialogue)
  207498. {
  207499. if (! GetSaveFileName (&of))
  207500. fname[0] = 0;
  207501. else
  207502. fnameIdx = of.nFileOffset;
  207503. }
  207504. else
  207505. {
  207506. if (! GetOpenFileName (&of))
  207507. fname[0] = 0;
  207508. else
  207509. fnameIdx = of.nFileOffset;
  207510. }
  207511. }
  207512. }
  207513. }
  207514. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  207515. catch (...)
  207516. {
  207517. fname[0] = 0;
  207518. }
  207519. #endif
  207520. deleteAndZero (currentExtraFileWin);
  207521. const WCHAR* const files = fname;
  207522. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  207523. {
  207524. const WCHAR* filename = files + fnameIdx;
  207525. while (*filename != 0)
  207526. {
  207527. const String filepath (String (files) + "\\" + String (filename));
  207528. results.add (File (filepath));
  207529. filename += CharacterFunctions::length (filename) + 1;
  207530. }
  207531. }
  207532. else if (files[0] != 0)
  207533. {
  207534. results.add (File (files));
  207535. }
  207536. }
  207537. #endif
  207538. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  207539. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  207540. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207541. // compiled on its own).
  207542. #if JUCE_INCLUDED_FILE
  207543. void SystemClipboard::copyTextToClipboard (const String& text)
  207544. {
  207545. if (OpenClipboard (0) != 0)
  207546. {
  207547. if (EmptyClipboard() != 0)
  207548. {
  207549. const int len = text.length();
  207550. if (len > 0)
  207551. {
  207552. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  207553. (len + 1) * sizeof (wchar_t));
  207554. if (bufH != 0)
  207555. {
  207556. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  207557. text.copyToUnicode (data, len);
  207558. GlobalUnlock (bufH);
  207559. SetClipboardData (CF_UNICODETEXT, bufH);
  207560. }
  207561. }
  207562. }
  207563. CloseClipboard();
  207564. }
  207565. }
  207566. const String SystemClipboard::getTextFromClipboard()
  207567. {
  207568. String result;
  207569. if (OpenClipboard (0) != 0)
  207570. {
  207571. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  207572. if (bufH != 0)
  207573. {
  207574. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  207575. if (data != 0)
  207576. {
  207577. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  207578. GlobalUnlock (bufH);
  207579. }
  207580. }
  207581. CloseClipboard();
  207582. }
  207583. return result;
  207584. }
  207585. #endif
  207586. /*** End of inlined file: juce_win32_Misc.cpp ***/
  207587. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207588. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207589. // compiled on its own).
  207590. #if JUCE_INCLUDED_FILE
  207591. namespace ActiveXHelpers
  207592. {
  207593. class JuceIStorage : public ComBaseClassHelper <IStorage>
  207594. {
  207595. public:
  207596. JuceIStorage() {}
  207597. ~JuceIStorage() {}
  207598. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207599. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207600. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207601. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207602. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207603. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207604. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207605. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207606. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207607. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207608. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207609. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207610. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207611. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207612. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207613. juce_UseDebuggingNewOperator
  207614. };
  207615. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  207616. {
  207617. HWND window;
  207618. public:
  207619. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  207620. ~JuceOleInPlaceFrame() {}
  207621. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207622. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207623. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207624. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207625. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207626. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207627. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207628. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207629. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207630. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207631. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207632. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207633. juce_UseDebuggingNewOperator
  207634. };
  207635. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  207636. {
  207637. HWND window;
  207638. JuceOleInPlaceFrame* frame;
  207639. public:
  207640. JuceIOleInPlaceSite (HWND window_)
  207641. : window (window_),
  207642. frame (new JuceOleInPlaceFrame (window))
  207643. {}
  207644. ~JuceIOleInPlaceSite()
  207645. {
  207646. frame->Release();
  207647. }
  207648. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207649. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207650. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207651. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207652. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207653. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207654. {
  207655. *lplpFrame = frame;
  207656. *lplpDoc = 0;
  207657. lpFrameInfo->fMDIApp = FALSE;
  207658. lpFrameInfo->hwndFrame = window;
  207659. lpFrameInfo->haccel = 0;
  207660. lpFrameInfo->cAccelEntries = 0;
  207661. return S_OK;
  207662. }
  207663. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207664. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207665. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207666. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207667. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207668. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207669. juce_UseDebuggingNewOperator
  207670. };
  207671. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  207672. {
  207673. JuceIOleInPlaceSite* inplaceSite;
  207674. public:
  207675. JuceIOleClientSite (HWND window)
  207676. : inplaceSite (new JuceIOleInPlaceSite (window))
  207677. {}
  207678. ~JuceIOleClientSite()
  207679. {
  207680. inplaceSite->Release();
  207681. }
  207682. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  207683. {
  207684. if (type == IID_IOleInPlaceSite)
  207685. {
  207686. inplaceSite->AddRef();
  207687. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  207688. return S_OK;
  207689. }
  207690. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  207691. }
  207692. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207693. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207694. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207695. HRESULT __stdcall ShowObject() { return S_OK; }
  207696. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207697. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207698. juce_UseDebuggingNewOperator
  207699. };
  207700. static Array<ActiveXControlComponent*> activeXComps;
  207701. static HWND getHWND (const ActiveXControlComponent* const component)
  207702. {
  207703. HWND hwnd = 0;
  207704. const IID iid = IID_IOleWindow;
  207705. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207706. if (window != 0)
  207707. {
  207708. window->GetWindow (&hwnd);
  207709. window->Release();
  207710. }
  207711. return hwnd;
  207712. }
  207713. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207714. {
  207715. RECT activeXRect, peerRect;
  207716. GetWindowRect (hwnd, &activeXRect);
  207717. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207718. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  207719. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  207720. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  207721. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207722. switch (message)
  207723. {
  207724. case WM_MOUSEMOVE:
  207725. case WM_LBUTTONDOWN:
  207726. case WM_MBUTTONDOWN:
  207727. case WM_RBUTTONDOWN:
  207728. case WM_LBUTTONUP:
  207729. case WM_MBUTTONUP:
  207730. case WM_RBUTTONUP:
  207731. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  207732. break;
  207733. default:
  207734. break;
  207735. }
  207736. }
  207737. }
  207738. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  207739. {
  207740. ActiveXControlComponent* const owner;
  207741. bool wasShowing;
  207742. public:
  207743. HWND controlHWND;
  207744. IStorage* storage;
  207745. IOleClientSite* clientSite;
  207746. IOleObject* control;
  207747. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  207748. : ComponentMovementWatcher (owner_),
  207749. owner (owner_),
  207750. wasShowing (owner_ != 0 && owner_->isShowing()),
  207751. controlHWND (0),
  207752. storage (new ActiveXHelpers::JuceIStorage()),
  207753. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  207754. control (0)
  207755. {
  207756. }
  207757. ~Pimpl()
  207758. {
  207759. if (control != 0)
  207760. {
  207761. control->Close (OLECLOSE_NOSAVE);
  207762. control->Release();
  207763. }
  207764. clientSite->Release();
  207765. storage->Release();
  207766. }
  207767. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207768. {
  207769. Component* const topComp = owner->getTopLevelComponent();
  207770. if (topComp->getPeer() != 0)
  207771. {
  207772. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  207773. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  207774. }
  207775. }
  207776. void componentPeerChanged()
  207777. {
  207778. const bool isShowingNow = owner->isShowing();
  207779. if (wasShowing != isShowingNow)
  207780. {
  207781. wasShowing = isShowingNow;
  207782. owner->setControlVisible (isShowingNow);
  207783. }
  207784. componentMovedOrResized (true, true);
  207785. }
  207786. void componentVisibilityChanged (Component&)
  207787. {
  207788. componentPeerChanged();
  207789. }
  207790. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207791. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207792. {
  207793. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  207794. {
  207795. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  207796. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  207797. {
  207798. switch (message)
  207799. {
  207800. case WM_MOUSEMOVE:
  207801. case WM_LBUTTONDOWN:
  207802. case WM_MBUTTONDOWN:
  207803. case WM_RBUTTONDOWN:
  207804. case WM_LBUTTONUP:
  207805. case WM_MBUTTONUP:
  207806. case WM_RBUTTONUP:
  207807. case WM_LBUTTONDBLCLK:
  207808. case WM_MBUTTONDBLCLK:
  207809. case WM_RBUTTONDBLCLK:
  207810. if (ax->isShowing())
  207811. {
  207812. ComponentPeer* const peer = ax->getPeer();
  207813. if (peer != 0)
  207814. {
  207815. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207816. if (! ax->areMouseEventsAllowed())
  207817. return 0;
  207818. }
  207819. }
  207820. break;
  207821. default:
  207822. break;
  207823. }
  207824. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  207825. }
  207826. }
  207827. return DefWindowProc (hwnd, message, wParam, lParam);
  207828. }
  207829. };
  207830. ActiveXControlComponent::ActiveXControlComponent()
  207831. : originalWndProc (0),
  207832. mouseEventsAllowed (true)
  207833. {
  207834. ActiveXHelpers::activeXComps.add (this);
  207835. }
  207836. ActiveXControlComponent::~ActiveXControlComponent()
  207837. {
  207838. deleteControl();
  207839. ActiveXHelpers::activeXComps.removeValue (this);
  207840. }
  207841. void ActiveXControlComponent::paint (Graphics& g)
  207842. {
  207843. if (control == 0)
  207844. g.fillAll (Colours::lightgrey);
  207845. }
  207846. bool ActiveXControlComponent::createControl (const void* controlIID)
  207847. {
  207848. deleteControl();
  207849. ComponentPeer* const peer = getPeer();
  207850. // the component must have already been added to a real window when you call this!
  207851. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207852. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207853. {
  207854. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  207855. HWND hwnd = (HWND) peer->getNativeHandle();
  207856. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  207857. HRESULT hr;
  207858. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207859. newControl->clientSite, newControl->storage,
  207860. (void**) &(newControl->control))) == S_OK)
  207861. {
  207862. newControl->control->SetHostNames (L"Juce", 0);
  207863. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  207864. {
  207865. RECT rect;
  207866. rect.left = pos.getX();
  207867. rect.top = pos.getY();
  207868. rect.right = pos.getX() + getWidth();
  207869. rect.bottom = pos.getY() + getHeight();
  207870. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  207871. {
  207872. control = newControl;
  207873. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  207874. control->controlHWND = ActiveXHelpers::getHWND (this);
  207875. if (control->controlHWND != 0)
  207876. {
  207877. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  207878. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  207879. }
  207880. return true;
  207881. }
  207882. }
  207883. }
  207884. }
  207885. return false;
  207886. }
  207887. void ActiveXControlComponent::deleteControl()
  207888. {
  207889. control = 0;
  207890. originalWndProc = 0;
  207891. }
  207892. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207893. {
  207894. void* result = 0;
  207895. if (control != 0 && control->control != 0
  207896. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  207897. return result;
  207898. return 0;
  207899. }
  207900. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  207901. {
  207902. if (control->controlHWND != 0)
  207903. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207904. }
  207905. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207906. {
  207907. if (control->controlHWND != 0)
  207908. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207909. }
  207910. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207911. {
  207912. mouseEventsAllowed = eventsCanReachControl;
  207913. }
  207914. #endif
  207915. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207916. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207917. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207918. // compiled on its own).
  207919. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  207920. using namespace QTOLibrary;
  207921. using namespace QTOControlLib;
  207922. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  207923. static bool isQTAvailable = false;
  207924. class QuickTimeMovieComponent::Pimpl
  207925. {
  207926. public:
  207927. Pimpl() : dataHandle (0)
  207928. {
  207929. }
  207930. ~Pimpl()
  207931. {
  207932. clearHandle();
  207933. }
  207934. void clearHandle()
  207935. {
  207936. if (dataHandle != 0)
  207937. {
  207938. DisposeHandle (dataHandle);
  207939. dataHandle = 0;
  207940. }
  207941. }
  207942. IQTControlPtr qtControl;
  207943. IQTMoviePtr qtMovie;
  207944. Handle dataHandle;
  207945. };
  207946. QuickTimeMovieComponent::QuickTimeMovieComponent()
  207947. : movieLoaded (false),
  207948. controllerVisible (true)
  207949. {
  207950. pimpl = new Pimpl();
  207951. setMouseEventsAllowed (false);
  207952. }
  207953. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  207954. {
  207955. closeMovie();
  207956. pimpl->qtControl = 0;
  207957. deleteControl();
  207958. pimpl = 0;
  207959. }
  207960. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  207961. {
  207962. if (! isQTAvailable)
  207963. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  207964. return isQTAvailable;
  207965. }
  207966. void QuickTimeMovieComponent::createControlIfNeeded()
  207967. {
  207968. if (isShowing() && ! isControlCreated())
  207969. {
  207970. const IID qtIID = __uuidof (QTControl);
  207971. if (createControl (&qtIID))
  207972. {
  207973. const IID qtInterfaceIID = __uuidof (IQTControl);
  207974. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  207975. if (pimpl->qtControl != 0)
  207976. {
  207977. pimpl->qtControl->Release(); // it has one ref too many at this point
  207978. pimpl->qtControl->QuickTimeInitialize();
  207979. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  207980. if (movieFile != File::nonexistent)
  207981. loadMovie (movieFile, controllerVisible);
  207982. }
  207983. }
  207984. }
  207985. }
  207986. bool QuickTimeMovieComponent::isControlCreated() const
  207987. {
  207988. return isControlOpen();
  207989. }
  207990. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  207991. const bool isControllerVisible)
  207992. {
  207993. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  207994. movieFile = File::nonexistent;
  207995. movieLoaded = false;
  207996. pimpl->qtMovie = 0;
  207997. controllerVisible = isControllerVisible;
  207998. createControlIfNeeded();
  207999. if (isControlCreated())
  208000. {
  208001. if (pimpl->qtControl != 0)
  208002. {
  208003. pimpl->qtControl->Put_MovieHandle (0);
  208004. pimpl->clearHandle();
  208005. Movie movie;
  208006. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  208007. {
  208008. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  208009. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  208010. if (pimpl->qtMovie != 0)
  208011. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  208012. : qtMovieControllerTypeNone);
  208013. }
  208014. if (movie == 0)
  208015. pimpl->clearHandle();
  208016. }
  208017. movieLoaded = (pimpl->qtMovie != 0);
  208018. }
  208019. else
  208020. {
  208021. // You're trying to open a movie when the control hasn't yet been created, probably because
  208022. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  208023. jassertfalse;
  208024. }
  208025. return movieLoaded;
  208026. }
  208027. void QuickTimeMovieComponent::closeMovie()
  208028. {
  208029. stop();
  208030. movieFile = File::nonexistent;
  208031. movieLoaded = false;
  208032. pimpl->qtMovie = 0;
  208033. if (pimpl->qtControl != 0)
  208034. pimpl->qtControl->Put_MovieHandle (0);
  208035. pimpl->clearHandle();
  208036. }
  208037. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  208038. {
  208039. return movieFile;
  208040. }
  208041. bool QuickTimeMovieComponent::isMovieOpen() const
  208042. {
  208043. return movieLoaded;
  208044. }
  208045. double QuickTimeMovieComponent::getMovieDuration() const
  208046. {
  208047. if (pimpl->qtMovie != 0)
  208048. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  208049. return 0.0;
  208050. }
  208051. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  208052. {
  208053. if (pimpl->qtMovie != 0)
  208054. {
  208055. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  208056. width = r.right - r.left;
  208057. height = r.bottom - r.top;
  208058. }
  208059. else
  208060. {
  208061. width = height = 0;
  208062. }
  208063. }
  208064. void QuickTimeMovieComponent::play()
  208065. {
  208066. if (pimpl->qtMovie != 0)
  208067. pimpl->qtMovie->Play();
  208068. }
  208069. void QuickTimeMovieComponent::stop()
  208070. {
  208071. if (pimpl->qtMovie != 0)
  208072. pimpl->qtMovie->Stop();
  208073. }
  208074. bool QuickTimeMovieComponent::isPlaying() const
  208075. {
  208076. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  208077. }
  208078. void QuickTimeMovieComponent::setPosition (const double seconds)
  208079. {
  208080. if (pimpl->qtMovie != 0)
  208081. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  208082. }
  208083. double QuickTimeMovieComponent::getPosition() const
  208084. {
  208085. if (pimpl->qtMovie != 0)
  208086. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  208087. return 0.0;
  208088. }
  208089. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  208090. {
  208091. if (pimpl->qtMovie != 0)
  208092. pimpl->qtMovie->PutRate (newSpeed);
  208093. }
  208094. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  208095. {
  208096. if (pimpl->qtMovie != 0)
  208097. {
  208098. pimpl->qtMovie->PutAudioVolume (newVolume);
  208099. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  208100. }
  208101. }
  208102. float QuickTimeMovieComponent::getMovieVolume() const
  208103. {
  208104. if (pimpl->qtMovie != 0)
  208105. return pimpl->qtMovie->GetAudioVolume();
  208106. return 0.0f;
  208107. }
  208108. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  208109. {
  208110. if (pimpl->qtMovie != 0)
  208111. pimpl->qtMovie->PutLoop (shouldLoop);
  208112. }
  208113. bool QuickTimeMovieComponent::isLooping() const
  208114. {
  208115. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  208116. }
  208117. bool QuickTimeMovieComponent::isControllerVisible() const
  208118. {
  208119. return controllerVisible;
  208120. }
  208121. void QuickTimeMovieComponent::parentHierarchyChanged()
  208122. {
  208123. createControlIfNeeded();
  208124. QTCompBaseClass::parentHierarchyChanged();
  208125. }
  208126. void QuickTimeMovieComponent::visibilityChanged()
  208127. {
  208128. createControlIfNeeded();
  208129. QTCompBaseClass::visibilityChanged();
  208130. }
  208131. void QuickTimeMovieComponent::paint (Graphics& g)
  208132. {
  208133. if (! isControlCreated())
  208134. g.fillAll (Colours::black);
  208135. }
  208136. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  208137. {
  208138. Handle dataRef = 0;
  208139. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  208140. if (err == noErr)
  208141. {
  208142. Str255 suffix;
  208143. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  208144. StringPtr name = suffix;
  208145. err = PtrAndHand (name, dataRef, name[0] + 1);
  208146. if (err == noErr)
  208147. {
  208148. long atoms[3];
  208149. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  208150. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  208151. atoms[2] = EndianU32_NtoB (MovieFileType);
  208152. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  208153. if (err == noErr)
  208154. return dataRef;
  208155. }
  208156. DisposeHandle (dataRef);
  208157. }
  208158. return 0;
  208159. }
  208160. static CFStringRef juceStringToCFString (const String& s)
  208161. {
  208162. const int len = s.length();
  208163. const juce_wchar* const t = s;
  208164. HeapBlock <UniChar> temp (len + 2);
  208165. for (int i = 0; i <= len; ++i)
  208166. temp[i] = t[i];
  208167. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  208168. }
  208169. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  208170. {
  208171. Boolean trueBool = true;
  208172. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  208173. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  208174. props[prop].propValueSize = sizeof (trueBool);
  208175. props[prop].propValueAddress = &trueBool;
  208176. ++prop;
  208177. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  208178. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  208179. props[prop].propValueSize = sizeof (trueBool);
  208180. props[prop].propValueAddress = &trueBool;
  208181. ++prop;
  208182. Boolean isActive = true;
  208183. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  208184. props[prop].propID = kQTNewMoviePropertyID_Active;
  208185. props[prop].propValueSize = sizeof (isActive);
  208186. props[prop].propValueAddress = &isActive;
  208187. ++prop;
  208188. MacSetPort (0);
  208189. jassert (prop <= 5);
  208190. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  208191. return err == noErr;
  208192. }
  208193. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  208194. {
  208195. if (input == 0)
  208196. return false;
  208197. dataHandle = 0;
  208198. bool ok = false;
  208199. QTNewMoviePropertyElement props[5];
  208200. zeromem (props, sizeof (props));
  208201. int prop = 0;
  208202. DataReferenceRecord dr;
  208203. props[prop].propClass = kQTPropertyClass_DataLocation;
  208204. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  208205. props[prop].propValueSize = sizeof (dr);
  208206. props[prop].propValueAddress = &dr;
  208207. ++prop;
  208208. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  208209. if (fin != 0)
  208210. {
  208211. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  208212. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  208213. &dr.dataRef, &dr.dataRefType);
  208214. ok = openMovie (props, prop, movie);
  208215. DisposeHandle (dr.dataRef);
  208216. CFRelease (filePath);
  208217. }
  208218. else
  208219. {
  208220. // sanity-check because this currently needs to load the whole stream into memory..
  208221. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  208222. dataHandle = NewHandle ((Size) input->getTotalLength());
  208223. HLock (dataHandle);
  208224. // read the entire stream into memory - this is a pain, but can't get it to work
  208225. // properly using a custom callback to supply the data.
  208226. input->read (*dataHandle, (int) input->getTotalLength());
  208227. HUnlock (dataHandle);
  208228. // different types to get QT to try. (We should really be a bit smarter here by
  208229. // working out in advance which one the stream contains, rather than just trying
  208230. // each one)
  208231. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  208232. "\04.avi", "\04.m4a" };
  208233. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  208234. {
  208235. /* // this fails for some bizarre reason - it can be bodged to work with
  208236. // movies, but can't seem to do it for other file types..
  208237. QTNewMovieUserProcRecord procInfo;
  208238. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  208239. procInfo.getMovieUserProcRefcon = this;
  208240. procInfo.defaultDataRef.dataRef = dataRef;
  208241. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  208242. props[prop].propClass = kQTPropertyClass_DataLocation;
  208243. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  208244. props[prop].propValueSize = sizeof (procInfo);
  208245. props[prop].propValueAddress = (void*) &procInfo;
  208246. ++prop; */
  208247. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  208248. dr.dataRefType = HandleDataHandlerSubType;
  208249. ok = openMovie (props, prop, movie);
  208250. DisposeHandle (dr.dataRef);
  208251. }
  208252. }
  208253. return ok;
  208254. }
  208255. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  208256. const bool isControllerVisible)
  208257. {
  208258. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  208259. movieFile = movieFile_;
  208260. return ok;
  208261. }
  208262. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  208263. const bool isControllerVisible)
  208264. {
  208265. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  208266. }
  208267. void QuickTimeMovieComponent::goToStart()
  208268. {
  208269. setPosition (0.0);
  208270. }
  208271. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  208272. const RectanglePlacement& placement)
  208273. {
  208274. int normalWidth, normalHeight;
  208275. getMovieNormalSize (normalWidth, normalHeight);
  208276. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  208277. {
  208278. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  208279. placement.applyTo (x, y, w, h,
  208280. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  208281. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  208282. if (w > 0 && h > 0)
  208283. {
  208284. setBounds (roundToInt (x), roundToInt (y),
  208285. roundToInt (w), roundToInt (h));
  208286. }
  208287. }
  208288. else
  208289. {
  208290. setBounds (spaceToFitWithin);
  208291. }
  208292. }
  208293. #endif
  208294. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  208295. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208296. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208297. // compiled on its own).
  208298. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  208299. class WebBrowserComponentInternal : public ActiveXControlComponent
  208300. {
  208301. public:
  208302. WebBrowserComponentInternal()
  208303. : browser (0),
  208304. connectionPoint (0),
  208305. adviseCookie (0)
  208306. {
  208307. }
  208308. ~WebBrowserComponentInternal()
  208309. {
  208310. if (connectionPoint != 0)
  208311. connectionPoint->Unadvise (adviseCookie);
  208312. if (browser != 0)
  208313. browser->Release();
  208314. }
  208315. void createBrowser()
  208316. {
  208317. createControl (&CLSID_WebBrowser);
  208318. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  208319. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  208320. if (connectionPointContainer != 0)
  208321. {
  208322. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  208323. &connectionPoint);
  208324. if (connectionPoint != 0)
  208325. {
  208326. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  208327. jassert (owner != 0);
  208328. EventHandler* handler = new EventHandler (owner);
  208329. connectionPoint->Advise (handler, &adviseCookie);
  208330. handler->Release();
  208331. }
  208332. }
  208333. }
  208334. void goToURL (const String& url,
  208335. const StringArray* headers,
  208336. const MemoryBlock* postData)
  208337. {
  208338. if (browser != 0)
  208339. {
  208340. LPSAFEARRAY sa = 0;
  208341. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  208342. VariantInit (&flags);
  208343. VariantInit (&frame);
  208344. VariantInit (&postDataVar);
  208345. VariantInit (&headersVar);
  208346. if (headers != 0)
  208347. {
  208348. V_VT (&headersVar) = VT_BSTR;
  208349. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  208350. }
  208351. if (postData != 0 && postData->getSize() > 0)
  208352. {
  208353. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  208354. if (sa != 0)
  208355. {
  208356. void* data = 0;
  208357. SafeArrayAccessData (sa, &data);
  208358. jassert (data != 0);
  208359. if (data != 0)
  208360. {
  208361. postData->copyTo (data, 0, postData->getSize());
  208362. SafeArrayUnaccessData (sa);
  208363. VARIANT postDataVar2;
  208364. VariantInit (&postDataVar2);
  208365. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  208366. V_ARRAY (&postDataVar2) = sa;
  208367. postDataVar = postDataVar2;
  208368. }
  208369. }
  208370. }
  208371. browser->Navigate ((BSTR) (const OLECHAR*) url,
  208372. &flags, &frame,
  208373. &postDataVar, &headersVar);
  208374. if (sa != 0)
  208375. SafeArrayDestroy (sa);
  208376. VariantClear (&flags);
  208377. VariantClear (&frame);
  208378. VariantClear (&postDataVar);
  208379. VariantClear (&headersVar);
  208380. }
  208381. }
  208382. IWebBrowser2* browser;
  208383. juce_UseDebuggingNewOperator
  208384. private:
  208385. IConnectionPoint* connectionPoint;
  208386. DWORD adviseCookie;
  208387. class EventHandler : public ComBaseClassHelper <IDispatch>,
  208388. public ComponentMovementWatcher
  208389. {
  208390. public:
  208391. EventHandler (WebBrowserComponent* owner_)
  208392. : ComponentMovementWatcher (owner_),
  208393. owner (owner_)
  208394. {
  208395. }
  208396. ~EventHandler()
  208397. {
  208398. }
  208399. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  208400. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  208401. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  208402. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  208403. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  208404. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  208405. UINT __RPC_FAR* /*puArgErr*/)
  208406. {
  208407. switch (dispIdMember)
  208408. {
  208409. case DISPID_BEFORENAVIGATE2:
  208410. {
  208411. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  208412. String url;
  208413. if ((vurl->vt & VT_BYREF) != 0)
  208414. url = *vurl->pbstrVal;
  208415. else
  208416. url = vurl->bstrVal;
  208417. *pDispParams->rgvarg->pboolVal
  208418. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  208419. : VARIANT_TRUE;
  208420. return S_OK;
  208421. }
  208422. default:
  208423. break;
  208424. }
  208425. return E_NOTIMPL;
  208426. }
  208427. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  208428. void componentPeerChanged() {}
  208429. void componentVisibilityChanged (Component&)
  208430. {
  208431. owner->visibilityChanged();
  208432. }
  208433. juce_UseDebuggingNewOperator
  208434. private:
  208435. WebBrowserComponent* const owner;
  208436. EventHandler (const EventHandler&);
  208437. EventHandler& operator= (const EventHandler&);
  208438. };
  208439. };
  208440. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  208441. : browser (0),
  208442. blankPageShown (false),
  208443. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  208444. {
  208445. setOpaque (true);
  208446. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  208447. }
  208448. WebBrowserComponent::~WebBrowserComponent()
  208449. {
  208450. delete browser;
  208451. }
  208452. void WebBrowserComponent::goToURL (const String& url,
  208453. const StringArray* headers,
  208454. const MemoryBlock* postData)
  208455. {
  208456. lastURL = url;
  208457. lastHeaders.clear();
  208458. if (headers != 0)
  208459. lastHeaders = *headers;
  208460. lastPostData.setSize (0);
  208461. if (postData != 0)
  208462. lastPostData = *postData;
  208463. blankPageShown = false;
  208464. browser->goToURL (url, headers, postData);
  208465. }
  208466. void WebBrowserComponent::stop()
  208467. {
  208468. if (browser->browser != 0)
  208469. browser->browser->Stop();
  208470. }
  208471. void WebBrowserComponent::goBack()
  208472. {
  208473. lastURL = String::empty;
  208474. blankPageShown = false;
  208475. if (browser->browser != 0)
  208476. browser->browser->GoBack();
  208477. }
  208478. void WebBrowserComponent::goForward()
  208479. {
  208480. lastURL = String::empty;
  208481. if (browser->browser != 0)
  208482. browser->browser->GoForward();
  208483. }
  208484. void WebBrowserComponent::refresh()
  208485. {
  208486. if (browser->browser != 0)
  208487. browser->browser->Refresh();
  208488. }
  208489. void WebBrowserComponent::paint (Graphics& g)
  208490. {
  208491. if (browser->browser == 0)
  208492. g.fillAll (Colours::white);
  208493. }
  208494. void WebBrowserComponent::checkWindowAssociation()
  208495. {
  208496. if (isShowing())
  208497. {
  208498. if (browser->browser == 0 && getPeer() != 0)
  208499. {
  208500. browser->createBrowser();
  208501. reloadLastURL();
  208502. }
  208503. else
  208504. {
  208505. if (blankPageShown)
  208506. goBack();
  208507. }
  208508. }
  208509. else
  208510. {
  208511. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  208512. {
  208513. // when the component becomes invisible, some stuff like flash
  208514. // carries on playing audio, so we need to force it onto a blank
  208515. // page to avoid this..
  208516. blankPageShown = true;
  208517. browser->goToURL ("about:blank", 0, 0);
  208518. }
  208519. }
  208520. }
  208521. void WebBrowserComponent::reloadLastURL()
  208522. {
  208523. if (lastURL.isNotEmpty())
  208524. {
  208525. goToURL (lastURL, &lastHeaders, &lastPostData);
  208526. lastURL = String::empty;
  208527. }
  208528. }
  208529. void WebBrowserComponent::parentHierarchyChanged()
  208530. {
  208531. checkWindowAssociation();
  208532. }
  208533. void WebBrowserComponent::resized()
  208534. {
  208535. browser->setSize (getWidth(), getHeight());
  208536. }
  208537. void WebBrowserComponent::visibilityChanged()
  208538. {
  208539. checkWindowAssociation();
  208540. }
  208541. bool WebBrowserComponent::pageAboutToLoad (const String&)
  208542. {
  208543. return true;
  208544. }
  208545. #endif
  208546. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208547. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208548. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208549. // compiled on its own).
  208550. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  208551. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  208552. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  208553. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  208554. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  208555. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  208556. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  208557. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  208558. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  208559. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  208560. #define WGL_ACCELERATION_ARB 0x2003
  208561. #define WGL_SWAP_METHOD_ARB 0x2007
  208562. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  208563. #define WGL_PIXEL_TYPE_ARB 0x2013
  208564. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  208565. #define WGL_COLOR_BITS_ARB 0x2014
  208566. #define WGL_RED_BITS_ARB 0x2015
  208567. #define WGL_GREEN_BITS_ARB 0x2017
  208568. #define WGL_BLUE_BITS_ARB 0x2019
  208569. #define WGL_ALPHA_BITS_ARB 0x201B
  208570. #define WGL_DEPTH_BITS_ARB 0x2022
  208571. #define WGL_STENCIL_BITS_ARB 0x2023
  208572. #define WGL_FULL_ACCELERATION_ARB 0x2027
  208573. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  208574. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  208575. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  208576. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  208577. #define WGL_STEREO_ARB 0x2012
  208578. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  208579. #define WGL_SAMPLES_ARB 0x2042
  208580. #define WGL_TYPE_RGBA_ARB 0x202B
  208581. static void getWglExtensions (HDC dc, StringArray& result) throw()
  208582. {
  208583. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  208584. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  208585. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  208586. else
  208587. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  208588. }
  208589. class WindowedGLContext : public OpenGLContext
  208590. {
  208591. public:
  208592. WindowedGLContext (Component* const component_,
  208593. HGLRC contextToShareWith,
  208594. const OpenGLPixelFormat& pixelFormat)
  208595. : renderContext (0),
  208596. nativeWindow (0),
  208597. dc (0),
  208598. component (component_)
  208599. {
  208600. jassert (component != 0);
  208601. createNativeWindow();
  208602. // Use a default pixel format that should be supported everywhere
  208603. PIXELFORMATDESCRIPTOR pfd;
  208604. zerostruct (pfd);
  208605. pfd.nSize = sizeof (pfd);
  208606. pfd.nVersion = 1;
  208607. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  208608. pfd.iPixelType = PFD_TYPE_RGBA;
  208609. pfd.cColorBits = 24;
  208610. pfd.cDepthBits = 16;
  208611. const int format = ChoosePixelFormat (dc, &pfd);
  208612. if (format != 0)
  208613. SetPixelFormat (dc, format, &pfd);
  208614. renderContext = wglCreateContext (dc);
  208615. makeActive();
  208616. setPixelFormat (pixelFormat);
  208617. if (contextToShareWith != 0 && renderContext != 0)
  208618. wglShareLists (contextToShareWith, renderContext);
  208619. }
  208620. ~WindowedGLContext()
  208621. {
  208622. deleteContext();
  208623. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208624. delete nativeWindow;
  208625. }
  208626. void deleteContext()
  208627. {
  208628. makeInactive();
  208629. if (renderContext != 0)
  208630. {
  208631. wglDeleteContext (renderContext);
  208632. renderContext = 0;
  208633. }
  208634. }
  208635. bool makeActive() const throw()
  208636. {
  208637. jassert (renderContext != 0);
  208638. return wglMakeCurrent (dc, renderContext) != 0;
  208639. }
  208640. bool makeInactive() const throw()
  208641. {
  208642. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208643. }
  208644. bool isActive() const throw()
  208645. {
  208646. return wglGetCurrentContext() == renderContext;
  208647. }
  208648. const OpenGLPixelFormat getPixelFormat() const
  208649. {
  208650. OpenGLPixelFormat pf;
  208651. makeActive();
  208652. StringArray availableExtensions;
  208653. getWglExtensions (dc, availableExtensions);
  208654. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208655. return pf;
  208656. }
  208657. void* getRawContext() const throw()
  208658. {
  208659. return renderContext;
  208660. }
  208661. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208662. {
  208663. makeActive();
  208664. PIXELFORMATDESCRIPTOR pfd;
  208665. zerostruct (pfd);
  208666. pfd.nSize = sizeof (pfd);
  208667. pfd.nVersion = 1;
  208668. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208669. pfd.iPixelType = PFD_TYPE_RGBA;
  208670. pfd.iLayerType = PFD_MAIN_PLANE;
  208671. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  208672. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  208673. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  208674. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  208675. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  208676. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  208677. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  208678. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208679. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  208680. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  208681. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  208682. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  208683. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  208684. int format = 0;
  208685. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208686. StringArray availableExtensions;
  208687. getWglExtensions (dc, availableExtensions);
  208688. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208689. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208690. {
  208691. int attributes[64];
  208692. int n = 0;
  208693. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208694. attributes[n++] = GL_TRUE;
  208695. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208696. attributes[n++] = GL_TRUE;
  208697. attributes[n++] = WGL_ACCELERATION_ARB;
  208698. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208699. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208700. attributes[n++] = GL_TRUE;
  208701. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208702. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208703. attributes[n++] = WGL_COLOR_BITS_ARB;
  208704. attributes[n++] = pfd.cColorBits;
  208705. attributes[n++] = WGL_RED_BITS_ARB;
  208706. attributes[n++] = pixelFormat.redBits;
  208707. attributes[n++] = WGL_GREEN_BITS_ARB;
  208708. attributes[n++] = pixelFormat.greenBits;
  208709. attributes[n++] = WGL_BLUE_BITS_ARB;
  208710. attributes[n++] = pixelFormat.blueBits;
  208711. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208712. attributes[n++] = pixelFormat.alphaBits;
  208713. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208714. attributes[n++] = pixelFormat.depthBufferBits;
  208715. if (pixelFormat.stencilBufferBits > 0)
  208716. {
  208717. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208718. attributes[n++] = pixelFormat.stencilBufferBits;
  208719. }
  208720. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208721. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208722. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208723. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208724. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208725. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208726. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208727. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208728. if (availableExtensions.contains ("WGL_ARB_multisample")
  208729. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208730. {
  208731. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208732. attributes[n++] = 1;
  208733. attributes[n++] = WGL_SAMPLES_ARB;
  208734. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208735. }
  208736. attributes[n++] = 0;
  208737. UINT formatsCount;
  208738. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208739. (void) ok;
  208740. jassert (ok);
  208741. }
  208742. else
  208743. {
  208744. format = ChoosePixelFormat (dc, &pfd);
  208745. }
  208746. if (format != 0)
  208747. {
  208748. makeInactive();
  208749. // win32 can't change the pixel format of a window, so need to delete the
  208750. // old one and create a new one..
  208751. jassert (nativeWindow != 0);
  208752. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208753. delete nativeWindow;
  208754. createNativeWindow();
  208755. if (SetPixelFormat (dc, format, &pfd))
  208756. {
  208757. wglDeleteContext (renderContext);
  208758. renderContext = wglCreateContext (dc);
  208759. jassert (renderContext != 0);
  208760. return renderContext != 0;
  208761. }
  208762. }
  208763. return false;
  208764. }
  208765. void updateWindowPosition (int x, int y, int w, int h, int)
  208766. {
  208767. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208768. x, y, w, h,
  208769. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208770. }
  208771. void repaint()
  208772. {
  208773. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  208774. }
  208775. void swapBuffers()
  208776. {
  208777. SwapBuffers (dc);
  208778. }
  208779. bool setSwapInterval (int numFramesPerSwap)
  208780. {
  208781. makeActive();
  208782. StringArray availableExtensions;
  208783. getWglExtensions (dc, availableExtensions);
  208784. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208785. return availableExtensions.contains ("WGL_EXT_swap_control")
  208786. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208787. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208788. }
  208789. int getSwapInterval() const
  208790. {
  208791. makeActive();
  208792. StringArray availableExtensions;
  208793. getWglExtensions (dc, availableExtensions);
  208794. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208795. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208796. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208797. return wglGetSwapIntervalEXT();
  208798. return 0;
  208799. }
  208800. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208801. {
  208802. jassert (isActive());
  208803. StringArray availableExtensions;
  208804. getWglExtensions (dc, availableExtensions);
  208805. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208806. int numTypes = 0;
  208807. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208808. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208809. {
  208810. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208811. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208812. jassertfalse;
  208813. }
  208814. else
  208815. {
  208816. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208817. }
  208818. OpenGLPixelFormat pf;
  208819. for (int i = 0; i < numTypes; ++i)
  208820. {
  208821. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208822. {
  208823. bool alreadyListed = false;
  208824. for (int j = results.size(); --j >= 0;)
  208825. if (pf == *results.getUnchecked(j))
  208826. alreadyListed = true;
  208827. if (! alreadyListed)
  208828. results.add (new OpenGLPixelFormat (pf));
  208829. }
  208830. }
  208831. }
  208832. void* getNativeWindowHandle() const
  208833. {
  208834. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  208835. }
  208836. juce_UseDebuggingNewOperator
  208837. HGLRC renderContext;
  208838. private:
  208839. Win32ComponentPeer* nativeWindow;
  208840. Component* const component;
  208841. HDC dc;
  208842. void createNativeWindow()
  208843. {
  208844. nativeWindow = new Win32ComponentPeer (component, 0);
  208845. nativeWindow->dontRepaint = true;
  208846. nativeWindow->setVisible (true);
  208847. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208848. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208849. if (peer != 0)
  208850. {
  208851. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208852. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208853. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208854. }
  208855. dc = GetDC (hwnd);
  208856. }
  208857. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208858. OpenGLPixelFormat& result,
  208859. const StringArray& availableExtensions) const throw()
  208860. {
  208861. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208862. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208863. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208864. {
  208865. int attributes[32];
  208866. int numAttributes = 0;
  208867. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208868. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208869. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208870. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208871. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208872. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208873. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208874. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208875. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208876. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208877. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208878. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208879. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208880. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208881. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208882. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208883. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208884. int values[32];
  208885. zeromem (values, sizeof (values));
  208886. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208887. {
  208888. int n = 0;
  208889. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208890. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208891. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208892. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208893. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208894. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208895. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208896. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208897. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208898. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208899. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208900. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208901. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208902. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208903. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208904. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  208905. return isValidFormat;
  208906. }
  208907. else
  208908. {
  208909. jassertfalse;
  208910. }
  208911. }
  208912. else
  208913. {
  208914. PIXELFORMATDESCRIPTOR pfd;
  208915. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208916. {
  208917. result.redBits = pfd.cRedBits;
  208918. result.greenBits = pfd.cGreenBits;
  208919. result.blueBits = pfd.cBlueBits;
  208920. result.alphaBits = pfd.cAlphaBits;
  208921. result.depthBufferBits = pfd.cDepthBits;
  208922. result.stencilBufferBits = pfd.cStencilBits;
  208923. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208924. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208925. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208926. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208927. result.fullSceneAntiAliasingNumSamples = 0;
  208928. return true;
  208929. }
  208930. else
  208931. {
  208932. jassertfalse;
  208933. }
  208934. }
  208935. return false;
  208936. }
  208937. WindowedGLContext (const WindowedGLContext&);
  208938. WindowedGLContext& operator= (const WindowedGLContext&);
  208939. };
  208940. OpenGLContext* OpenGLComponent::createContext()
  208941. {
  208942. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  208943. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  208944. preferredPixelFormat));
  208945. return (c->renderContext != 0) ? c.release() : 0;
  208946. }
  208947. void* OpenGLComponent::getNativeWindowHandle() const
  208948. {
  208949. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  208950. }
  208951. void juce_glViewport (const int w, const int h)
  208952. {
  208953. glViewport (0, 0, w, h);
  208954. }
  208955. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208956. OwnedArray <OpenGLPixelFormat>& results)
  208957. {
  208958. Component tempComp;
  208959. {
  208960. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208961. wc.makeActive();
  208962. wc.findAlternativeOpenGLPixelFormats (results);
  208963. }
  208964. }
  208965. #endif
  208966. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208967. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  208968. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208969. // compiled on its own).
  208970. #if JUCE_INCLUDED_FILE
  208971. #if JUCE_USE_CDREADER
  208972. namespace CDReaderHelpers
  208973. {
  208974. //***************************************************************************
  208975. // %%% TARGET STATUS VALUES %%%
  208976. //***************************************************************************
  208977. #define STATUS_GOOD 0x00 // Status Good
  208978. #define STATUS_CHKCOND 0x02 // Check Condition
  208979. #define STATUS_CONDMET 0x04 // Condition Met
  208980. #define STATUS_BUSY 0x08 // Busy
  208981. #define STATUS_INTERM 0x10 // Intermediate
  208982. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  208983. #define STATUS_RESCONF 0x18 // Reservation conflict
  208984. #define STATUS_COMTERM 0x22 // Command Terminated
  208985. #define STATUS_QFULL 0x28 // Queue full
  208986. //***************************************************************************
  208987. // %%% SCSI MISCELLANEOUS EQUATES %%%
  208988. //***************************************************************************
  208989. #define MAXLUN 7 // Maximum Logical Unit Id
  208990. #define MAXTARG 7 // Maximum Target Id
  208991. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  208992. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  208993. //***************************************************************************
  208994. // %%% Commands for all Device Types %%%
  208995. //***************************************************************************
  208996. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  208997. #define SCSI_COMPARE 0x39 // Compare (O)
  208998. #define SCSI_COPY 0x18 // Copy (O)
  208999. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  209000. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  209001. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  209002. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  209003. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  209004. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  209005. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  209006. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  209007. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  209008. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  209009. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  209010. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  209011. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  209012. //***************************************************************************
  209013. // %%% Commands Unique to Direct Access Devices %%%
  209014. //***************************************************************************
  209015. #define SCSI_COMPARE 0x39 // Compare (O)
  209016. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  209017. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  209018. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  209019. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  209020. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  209021. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  209022. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  209023. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  209024. #define SCSI_READ_LONG 0x3E // Read Long (O)
  209025. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  209026. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  209027. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  209028. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  209029. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  209030. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  209031. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  209032. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  209033. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  209034. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  209035. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  209036. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  209037. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  209038. #define SCSI_VERIFY 0x2F // Verify (O)
  209039. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  209040. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  209041. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  209042. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  209043. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  209044. //***************************************************************************
  209045. // %%% Commands Unique to Sequential Access Devices %%%
  209046. //***************************************************************************
  209047. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  209048. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  209049. #define SCSI_LOCATE 0x2B // Locate (O)
  209050. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  209051. #define SCSI_READ_POS 0x34 // Read Position (O)
  209052. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  209053. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  209054. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  209055. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  209056. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  209057. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  209058. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  209059. //***************************************************************************
  209060. // %%% Commands Unique to Printer Devices %%%
  209061. //***************************************************************************
  209062. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  209063. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  209064. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  209065. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  209066. //***************************************************************************
  209067. // %%% Commands Unique to Processor Devices %%%
  209068. //***************************************************************************
  209069. #define SCSI_RECEIVE 0x08 // Receive (O)
  209070. #define SCSI_SEND 0x0A // Send (O)
  209071. //***************************************************************************
  209072. // %%% Commands Unique to Write-Once Devices %%%
  209073. //***************************************************************************
  209074. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  209075. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  209076. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  209077. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  209078. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  209079. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  209080. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  209081. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  209082. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  209083. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  209084. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  209085. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  209086. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  209087. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  209088. //***************************************************************************
  209089. // %%% Commands Unique to CD-ROM Devices %%%
  209090. //***************************************************************************
  209091. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  209092. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  209093. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  209094. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  209095. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  209096. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  209097. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  209098. #define SCSI_READHEADER 0x44 // Read Header (O)
  209099. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  209100. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  209101. //***************************************************************************
  209102. // %%% Commands Unique to Scanner Devices %%%
  209103. //***************************************************************************
  209104. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  209105. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  209106. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  209107. #define SCSI_SCAN 0x1B // Scan (O)
  209108. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  209109. //***************************************************************************
  209110. // %%% Commands Unique to Optical Memory Devices %%%
  209111. //***************************************************************************
  209112. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  209113. //***************************************************************************
  209114. // %%% Commands Unique to Medium Changer Devices %%%
  209115. //***************************************************************************
  209116. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  209117. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  209118. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  209119. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  209120. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  209121. //***************************************************************************
  209122. // %%% Commands Unique to Communication Devices %%%
  209123. //***************************************************************************
  209124. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  209125. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  209126. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  209127. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  209128. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  209129. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  209130. //***************************************************************************
  209131. // %%% Request Sense Data Format %%%
  209132. //***************************************************************************
  209133. typedef struct {
  209134. BYTE ErrorCode; // Error Code (70H or 71H)
  209135. BYTE SegmentNum; // Number of current segment descriptor
  209136. BYTE SenseKey; // Sense Key(See bit definitions too)
  209137. BYTE InfoByte0; // Information MSB
  209138. BYTE InfoByte1; // Information MID
  209139. BYTE InfoByte2; // Information MID
  209140. BYTE InfoByte3; // Information LSB
  209141. BYTE AddSenLen; // Additional Sense Length
  209142. BYTE ComSpecInf0; // Command Specific Information MSB
  209143. BYTE ComSpecInf1; // Command Specific Information MID
  209144. BYTE ComSpecInf2; // Command Specific Information MID
  209145. BYTE ComSpecInf3; // Command Specific Information LSB
  209146. BYTE AddSenseCode; // Additional Sense Code
  209147. BYTE AddSenQual; // Additional Sense Code Qualifier
  209148. BYTE FieldRepUCode; // Field Replaceable Unit Code
  209149. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  209150. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  209151. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  209152. BYTE AddSenseBytes; // Additional Sense Bytes
  209153. } SENSE_DATA_FMT;
  209154. //***************************************************************************
  209155. // %%% REQUEST SENSE ERROR CODE %%%
  209156. //***************************************************************************
  209157. #define SERROR_CURRENT 0x70 // Current Errors
  209158. #define SERROR_DEFERED 0x71 // Deferred Errors
  209159. //***************************************************************************
  209160. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  209161. //***************************************************************************
  209162. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  209163. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  209164. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  209165. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  209166. //***************************************************************************
  209167. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  209168. //***************************************************************************
  209169. #define KEY_NOSENSE 0x00 // No Sense
  209170. #define KEY_RECERROR 0x01 // Recovered Error
  209171. #define KEY_NOTREADY 0x02 // Not Ready
  209172. #define KEY_MEDIUMERR 0x03 // Medium Error
  209173. #define KEY_HARDERROR 0x04 // Hardware Error
  209174. #define KEY_ILLGLREQ 0x05 // Illegal Request
  209175. #define KEY_UNITATT 0x06 // Unit Attention
  209176. #define KEY_DATAPROT 0x07 // Data Protect
  209177. #define KEY_BLANKCHK 0x08 // Blank Check
  209178. #define KEY_VENDSPEC 0x09 // Vendor Specific
  209179. #define KEY_COPYABORT 0x0A // Copy Abort
  209180. #define KEY_EQUAL 0x0C // Equal (Search)
  209181. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  209182. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  209183. #define KEY_RESERVED 0x0F // Reserved
  209184. //***************************************************************************
  209185. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  209186. //***************************************************************************
  209187. #define DTYPE_DASD 0x00 // Disk Device
  209188. #define DTYPE_SEQD 0x01 // Tape Device
  209189. #define DTYPE_PRNT 0x02 // Printer
  209190. #define DTYPE_PROC 0x03 // Processor
  209191. #define DTYPE_WORM 0x04 // Write-once read-multiple
  209192. #define DTYPE_CROM 0x05 // CD-ROM device
  209193. #define DTYPE_SCAN 0x06 // Scanner device
  209194. #define DTYPE_OPTI 0x07 // Optical memory device
  209195. #define DTYPE_JUKE 0x08 // Medium Changer device
  209196. #define DTYPE_COMM 0x09 // Communications device
  209197. #define DTYPE_RESL 0x0A // Reserved (low)
  209198. #define DTYPE_RESH 0x1E // Reserved (high)
  209199. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  209200. //***************************************************************************
  209201. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  209202. //***************************************************************************
  209203. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  209204. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  209205. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  209206. #define ANSI_RESLO 0x3 // Reserved (low)
  209207. #define ANSI_RESHI 0x7 // Reserved (high)
  209208. typedef struct
  209209. {
  209210. USHORT Length;
  209211. UCHAR ScsiStatus;
  209212. UCHAR PathId;
  209213. UCHAR TargetId;
  209214. UCHAR Lun;
  209215. UCHAR CdbLength;
  209216. UCHAR SenseInfoLength;
  209217. UCHAR DataIn;
  209218. ULONG DataTransferLength;
  209219. ULONG TimeOutValue;
  209220. ULONG DataBufferOffset;
  209221. ULONG SenseInfoOffset;
  209222. UCHAR Cdb[16];
  209223. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  209224. typedef struct
  209225. {
  209226. USHORT Length;
  209227. UCHAR ScsiStatus;
  209228. UCHAR PathId;
  209229. UCHAR TargetId;
  209230. UCHAR Lun;
  209231. UCHAR CdbLength;
  209232. UCHAR SenseInfoLength;
  209233. UCHAR DataIn;
  209234. ULONG DataTransferLength;
  209235. ULONG TimeOutValue;
  209236. PVOID DataBuffer;
  209237. ULONG SenseInfoOffset;
  209238. UCHAR Cdb[16];
  209239. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  209240. typedef struct
  209241. {
  209242. SCSI_PASS_THROUGH_DIRECT spt;
  209243. ULONG Filler;
  209244. UCHAR ucSenseBuf[32];
  209245. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  209246. typedef struct
  209247. {
  209248. ULONG Length;
  209249. UCHAR PortNumber;
  209250. UCHAR PathId;
  209251. UCHAR TargetId;
  209252. UCHAR Lun;
  209253. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  209254. #define METHOD_BUFFERED 0
  209255. #define METHOD_IN_DIRECT 1
  209256. #define METHOD_OUT_DIRECT 2
  209257. #define METHOD_NEITHER 3
  209258. #define FILE_ANY_ACCESS 0
  209259. #ifndef FILE_READ_ACCESS
  209260. #define FILE_READ_ACCESS (0x0001)
  209261. #endif
  209262. #ifndef FILE_WRITE_ACCESS
  209263. #define FILE_WRITE_ACCESS (0x0002)
  209264. #endif
  209265. #define IOCTL_SCSI_BASE 0x00000004
  209266. #define SCSI_IOCTL_DATA_OUT 0
  209267. #define SCSI_IOCTL_DATA_IN 1
  209268. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  209269. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  209270. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  209271. )
  209272. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  209273. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  209274. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  209275. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  209276. #define SENSE_LEN 14
  209277. #define SRB_DIR_SCSI 0x00
  209278. #define SRB_POSTING 0x01
  209279. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  209280. #define SRB_DIR_IN 0x08
  209281. #define SRB_DIR_OUT 0x10
  209282. #define SRB_EVENT_NOTIFY 0x40
  209283. #define RESIDUAL_COUNT_SUPPORTED 0x02
  209284. #define MAX_SRB_TIMEOUT 1080001u
  209285. #define DEFAULT_SRB_TIMEOUT 1080001u
  209286. #define SC_HA_INQUIRY 0x00
  209287. #define SC_GET_DEV_TYPE 0x01
  209288. #define SC_EXEC_SCSI_CMD 0x02
  209289. #define SC_ABORT_SRB 0x03
  209290. #define SC_RESET_DEV 0x04
  209291. #define SC_SET_HA_PARMS 0x05
  209292. #define SC_GET_DISK_INFO 0x06
  209293. #define SC_RESCAN_SCSI_BUS 0x07
  209294. #define SC_GETSET_TIMEOUTS 0x08
  209295. #define SS_PENDING 0x00
  209296. #define SS_COMP 0x01
  209297. #define SS_ABORTED 0x02
  209298. #define SS_ABORT_FAIL 0x03
  209299. #define SS_ERR 0x04
  209300. #define SS_INVALID_CMD 0x80
  209301. #define SS_INVALID_HA 0x81
  209302. #define SS_NO_DEVICE 0x82
  209303. #define SS_INVALID_SRB 0xE0
  209304. #define SS_OLD_MANAGER 0xE1
  209305. #define SS_BUFFER_ALIGN 0xE1
  209306. #define SS_ILLEGAL_MODE 0xE2
  209307. #define SS_NO_ASPI 0xE3
  209308. #define SS_FAILED_INIT 0xE4
  209309. #define SS_ASPI_IS_BUSY 0xE5
  209310. #define SS_BUFFER_TO_BIG 0xE6
  209311. #define SS_BUFFER_TOO_BIG 0xE6
  209312. #define SS_MISMATCHED_COMPONENTS 0xE7
  209313. #define SS_NO_ADAPTERS 0xE8
  209314. #define SS_INSUFFICIENT_RESOURCES 0xE9
  209315. #define SS_ASPI_IS_SHUTDOWN 0xEA
  209316. #define SS_BAD_INSTALL 0xEB
  209317. #define HASTAT_OK 0x00
  209318. #define HASTAT_SEL_TO 0x11
  209319. #define HASTAT_DO_DU 0x12
  209320. #define HASTAT_BUS_FREE 0x13
  209321. #define HASTAT_PHASE_ERR 0x14
  209322. #define HASTAT_TIMEOUT 0x09
  209323. #define HASTAT_COMMAND_TIMEOUT 0x0B
  209324. #define HASTAT_MESSAGE_REJECT 0x0D
  209325. #define HASTAT_BUS_RESET 0x0E
  209326. #define HASTAT_PARITY_ERROR 0x0F
  209327. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  209328. #define PACKED
  209329. #pragma pack(1)
  209330. typedef struct
  209331. {
  209332. BYTE SRB_Cmd;
  209333. BYTE SRB_Status;
  209334. BYTE SRB_HaID;
  209335. BYTE SRB_Flags;
  209336. DWORD SRB_Hdr_Rsvd;
  209337. BYTE HA_Count;
  209338. BYTE HA_SCSI_ID;
  209339. BYTE HA_ManagerId[16];
  209340. BYTE HA_Identifier[16];
  209341. BYTE HA_Unique[16];
  209342. WORD HA_Rsvd1;
  209343. BYTE pad[20];
  209344. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  209345. typedef struct
  209346. {
  209347. BYTE SRB_Cmd;
  209348. BYTE SRB_Status;
  209349. BYTE SRB_HaID;
  209350. BYTE SRB_Flags;
  209351. DWORD SRB_Hdr_Rsvd;
  209352. BYTE SRB_Target;
  209353. BYTE SRB_Lun;
  209354. BYTE SRB_DeviceType;
  209355. BYTE SRB_Rsvd1;
  209356. BYTE pad[68];
  209357. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  209358. typedef struct
  209359. {
  209360. BYTE SRB_Cmd;
  209361. BYTE SRB_Status;
  209362. BYTE SRB_HaID;
  209363. BYTE SRB_Flags;
  209364. DWORD SRB_Hdr_Rsvd;
  209365. BYTE SRB_Target;
  209366. BYTE SRB_Lun;
  209367. WORD SRB_Rsvd1;
  209368. DWORD SRB_BufLen;
  209369. BYTE FAR *SRB_BufPointer;
  209370. BYTE SRB_SenseLen;
  209371. BYTE SRB_CDBLen;
  209372. BYTE SRB_HaStat;
  209373. BYTE SRB_TargStat;
  209374. VOID FAR *SRB_PostProc;
  209375. BYTE SRB_Rsvd2[20];
  209376. BYTE CDBByte[16];
  209377. BYTE SenseArea[SENSE_LEN+2];
  209378. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  209379. typedef struct
  209380. {
  209381. BYTE SRB_Cmd;
  209382. BYTE SRB_Status;
  209383. BYTE SRB_HaId;
  209384. BYTE SRB_Flags;
  209385. DWORD SRB_Hdr_Rsvd;
  209386. } PACKED SRB, *PSRB, FAR *LPSRB;
  209387. #pragma pack()
  209388. struct CDDeviceInfo
  209389. {
  209390. char vendor[9];
  209391. char productId[17];
  209392. char rev[5];
  209393. char vendorSpec[21];
  209394. BYTE ha;
  209395. BYTE tgt;
  209396. BYTE lun;
  209397. char scsiDriveLetter; // will be 0 if not using scsi
  209398. };
  209399. class CDReadBuffer
  209400. {
  209401. public:
  209402. int startFrame;
  209403. int numFrames;
  209404. int dataStartOffset;
  209405. int dataLength;
  209406. int bufferSize;
  209407. HeapBlock<BYTE> buffer;
  209408. int index;
  209409. bool wantsIndex;
  209410. CDReadBuffer (const int numberOfFrames)
  209411. : startFrame (0),
  209412. numFrames (0),
  209413. dataStartOffset (0),
  209414. dataLength (0),
  209415. bufferSize (2352 * numberOfFrames),
  209416. buffer (bufferSize),
  209417. index (0),
  209418. wantsIndex (false)
  209419. {
  209420. }
  209421. bool isZero() const throw()
  209422. {
  209423. BYTE* p = buffer + dataStartOffset;
  209424. for (int i = dataLength; --i >= 0;)
  209425. if (*p++ != 0)
  209426. return false;
  209427. return true;
  209428. }
  209429. };
  209430. class CDDeviceHandle;
  209431. class CDController
  209432. {
  209433. public:
  209434. CDController();
  209435. virtual ~CDController();
  209436. virtual bool read (CDReadBuffer* t) = 0;
  209437. virtual void shutDown();
  209438. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  209439. int getLastIndex();
  209440. public:
  209441. bool initialised;
  209442. CDDeviceHandle* deviceInfo;
  209443. int framesToCheck, framesOverlap;
  209444. void prepare (SRB_ExecSCSICmd& s);
  209445. void perform (SRB_ExecSCSICmd& s);
  209446. void setPaused (bool paused);
  209447. };
  209448. #pragma pack(1)
  209449. struct TOCTRACK
  209450. {
  209451. BYTE rsvd;
  209452. BYTE ADR;
  209453. BYTE trackNumber;
  209454. BYTE rsvd2;
  209455. BYTE addr[4];
  209456. };
  209457. struct TOC
  209458. {
  209459. WORD tocLen;
  209460. BYTE firstTrack;
  209461. BYTE lastTrack;
  209462. TOCTRACK tracks[100];
  209463. };
  209464. #pragma pack()
  209465. enum
  209466. {
  209467. READTYPE_ANY = 0,
  209468. READTYPE_ATAPI1 = 1,
  209469. READTYPE_ATAPI2 = 2,
  209470. READTYPE_READ6 = 3,
  209471. READTYPE_READ10 = 4,
  209472. READTYPE_READ_D8 = 5,
  209473. READTYPE_READ_D4 = 6,
  209474. READTYPE_READ_D4_1 = 7,
  209475. READTYPE_READ10_2 = 8
  209476. };
  209477. class CDDeviceHandle
  209478. {
  209479. public:
  209480. CDDeviceHandle (const CDDeviceInfo* const device)
  209481. : scsiHandle (0),
  209482. readType (READTYPE_ANY),
  209483. controller (0)
  209484. {
  209485. memcpy (&info, device, sizeof (info));
  209486. }
  209487. ~CDDeviceHandle()
  209488. {
  209489. if (controller != 0)
  209490. {
  209491. controller->shutDown();
  209492. controller = 0;
  209493. }
  209494. if (scsiHandle != 0)
  209495. CloseHandle (scsiHandle);
  209496. }
  209497. bool readTOC (TOC* lpToc, bool useMSF);
  209498. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  209499. void openDrawer (bool shouldBeOpen);
  209500. CDDeviceInfo info;
  209501. HANDLE scsiHandle;
  209502. BYTE readType;
  209503. private:
  209504. ScopedPointer<CDController> controller;
  209505. bool testController (const int readType,
  209506. CDController* const newController,
  209507. CDReadBuffer* const bufferToUse);
  209508. };
  209509. DWORD (*fGetASPI32SupportInfo)(void);
  209510. DWORD (*fSendASPI32Command)(LPSRB);
  209511. static HINSTANCE winAspiLib = 0;
  209512. static bool usingScsi = false;
  209513. static bool initialised = false;
  209514. static bool InitialiseCDRipper()
  209515. {
  209516. if (! initialised)
  209517. {
  209518. initialised = true;
  209519. OSVERSIONINFO info;
  209520. info.dwOSVersionInfoSize = sizeof (info);
  209521. GetVersionEx (&info);
  209522. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  209523. if (! usingScsi)
  209524. {
  209525. fGetASPI32SupportInfo = 0;
  209526. fSendASPI32Command = 0;
  209527. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  209528. if (winAspiLib != 0)
  209529. {
  209530. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  209531. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  209532. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  209533. return false;
  209534. }
  209535. else
  209536. {
  209537. usingScsi = true;
  209538. }
  209539. }
  209540. }
  209541. return true;
  209542. }
  209543. static void DeinitialiseCDRipper()
  209544. {
  209545. if (winAspiLib != 0)
  209546. {
  209547. fGetASPI32SupportInfo = 0;
  209548. fSendASPI32Command = 0;
  209549. FreeLibrary (winAspiLib);
  209550. winAspiLib = 0;
  209551. }
  209552. initialised = false;
  209553. }
  209554. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  209555. {
  209556. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  209557. OSVERSIONINFO info;
  209558. info.dwOSVersionInfoSize = sizeof (info);
  209559. GetVersionEx (&info);
  209560. DWORD flags = GENERIC_READ;
  209561. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  209562. flags = GENERIC_READ | GENERIC_WRITE;
  209563. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209564. if (h == INVALID_HANDLE_VALUE)
  209565. {
  209566. flags ^= GENERIC_WRITE;
  209567. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209568. }
  209569. return h;
  209570. }
  209571. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  209572. const char driveLetter,
  209573. HANDLE& deviceHandle,
  209574. const bool retryOnFailure = true)
  209575. {
  209576. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  209577. zerostruct (s);
  209578. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  209579. s.spt.CdbLength = srb->SRB_CDBLen;
  209580. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  209581. ? SCSI_IOCTL_DATA_IN
  209582. : ((srb->SRB_Flags & SRB_DIR_OUT)
  209583. ? SCSI_IOCTL_DATA_OUT
  209584. : SCSI_IOCTL_DATA_UNSPECIFIED));
  209585. s.spt.DataTransferLength = srb->SRB_BufLen;
  209586. s.spt.TimeOutValue = 5;
  209587. s.spt.DataBuffer = srb->SRB_BufPointer;
  209588. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209589. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  209590. srb->SRB_Status = SS_ERR;
  209591. srb->SRB_TargStat = 0x0004;
  209592. DWORD bytesReturned = 0;
  209593. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209594. &s, sizeof (s),
  209595. &s, sizeof (s),
  209596. &bytesReturned, 0) != 0)
  209597. {
  209598. srb->SRB_Status = SS_COMP;
  209599. }
  209600. else if (retryOnFailure)
  209601. {
  209602. const DWORD error = GetLastError();
  209603. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  209604. {
  209605. if (error != ERROR_INVALID_HANDLE)
  209606. CloseHandle (deviceHandle);
  209607. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  209608. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  209609. }
  209610. }
  209611. return srb->SRB_Status;
  209612. }
  209613. // Controller types..
  209614. class ControllerType1 : public CDController
  209615. {
  209616. public:
  209617. ControllerType1() {}
  209618. ~ControllerType1() {}
  209619. bool read (CDReadBuffer* rb)
  209620. {
  209621. if (rb->numFrames * 2352 > rb->bufferSize)
  209622. return false;
  209623. SRB_ExecSCSICmd s;
  209624. prepare (s);
  209625. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209626. s.SRB_BufLen = rb->bufferSize;
  209627. s.SRB_BufPointer = rb->buffer;
  209628. s.SRB_CDBLen = 12;
  209629. s.CDBByte[0] = 0xBE;
  209630. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209631. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209632. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209633. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209634. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  209635. perform (s);
  209636. if (s.SRB_Status != SS_COMP)
  209637. return false;
  209638. rb->dataLength = rb->numFrames * 2352;
  209639. rb->dataStartOffset = 0;
  209640. return true;
  209641. }
  209642. };
  209643. class ControllerType2 : public CDController
  209644. {
  209645. public:
  209646. ControllerType2() {}
  209647. ~ControllerType2() {}
  209648. void shutDown()
  209649. {
  209650. if (initialised)
  209651. {
  209652. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  209653. SRB_ExecSCSICmd s;
  209654. prepare (s);
  209655. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  209656. s.SRB_BufLen = 0x0C;
  209657. s.SRB_BufPointer = bufPointer;
  209658. s.SRB_CDBLen = 6;
  209659. s.CDBByte[0] = 0x15;
  209660. s.CDBByte[4] = 0x0C;
  209661. perform (s);
  209662. }
  209663. }
  209664. bool init()
  209665. {
  209666. SRB_ExecSCSICmd s;
  209667. s.SRB_Status = SS_ERR;
  209668. if (deviceInfo->readType == READTYPE_READ10_2)
  209669. {
  209670. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  209671. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  209672. for (int i = 0; i < 2; ++i)
  209673. {
  209674. prepare (s);
  209675. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209676. s.SRB_BufLen = 0x14;
  209677. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  209678. s.SRB_CDBLen = 6;
  209679. s.CDBByte[0] = 0x15;
  209680. s.CDBByte[1] = 0x10;
  209681. s.CDBByte[4] = 0x14;
  209682. perform (s);
  209683. if (s.SRB_Status != SS_COMP)
  209684. return false;
  209685. }
  209686. }
  209687. else
  209688. {
  209689. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  209690. prepare (s);
  209691. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209692. s.SRB_BufLen = 0x0C;
  209693. s.SRB_BufPointer = bufPointer;
  209694. s.SRB_CDBLen = 6;
  209695. s.CDBByte[0] = 0x15;
  209696. s.CDBByte[4] = 0x0C;
  209697. perform (s);
  209698. }
  209699. return s.SRB_Status == SS_COMP;
  209700. }
  209701. bool read (CDReadBuffer* rb)
  209702. {
  209703. if (rb->numFrames * 2352 > rb->bufferSize)
  209704. return false;
  209705. if (!initialised)
  209706. {
  209707. initialised = init();
  209708. if (!initialised)
  209709. return false;
  209710. }
  209711. SRB_ExecSCSICmd s;
  209712. prepare (s);
  209713. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209714. s.SRB_BufLen = rb->bufferSize;
  209715. s.SRB_BufPointer = rb->buffer;
  209716. s.SRB_CDBLen = 10;
  209717. s.CDBByte[0] = 0x28;
  209718. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209719. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209720. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209721. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209722. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209723. perform (s);
  209724. if (s.SRB_Status != SS_COMP)
  209725. return false;
  209726. rb->dataLength = rb->numFrames * 2352;
  209727. rb->dataStartOffset = 0;
  209728. return true;
  209729. }
  209730. };
  209731. class ControllerType3 : public CDController
  209732. {
  209733. public:
  209734. ControllerType3() {}
  209735. ~ControllerType3() {}
  209736. bool read (CDReadBuffer* rb)
  209737. {
  209738. if (rb->numFrames * 2352 > rb->bufferSize)
  209739. return false;
  209740. if (!initialised)
  209741. {
  209742. setPaused (false);
  209743. initialised = true;
  209744. }
  209745. SRB_ExecSCSICmd s;
  209746. prepare (s);
  209747. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209748. s.SRB_BufLen = rb->numFrames * 2352;
  209749. s.SRB_BufPointer = rb->buffer;
  209750. s.SRB_CDBLen = 12;
  209751. s.CDBByte[0] = 0xD8;
  209752. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209753. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209754. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209755. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  209756. perform (s);
  209757. if (s.SRB_Status != SS_COMP)
  209758. return false;
  209759. rb->dataLength = rb->numFrames * 2352;
  209760. rb->dataStartOffset = 0;
  209761. return true;
  209762. }
  209763. };
  209764. class ControllerType4 : public CDController
  209765. {
  209766. public:
  209767. ControllerType4() {}
  209768. ~ControllerType4() {}
  209769. bool selectD4Mode()
  209770. {
  209771. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  209772. SRB_ExecSCSICmd s;
  209773. prepare (s);
  209774. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209775. s.SRB_CDBLen = 6;
  209776. s.SRB_BufLen = 12;
  209777. s.SRB_BufPointer = bufPointer;
  209778. s.CDBByte[0] = 0x15;
  209779. s.CDBByte[1] = 0x10;
  209780. s.CDBByte[4] = 0x08;
  209781. perform (s);
  209782. return s.SRB_Status == SS_COMP;
  209783. }
  209784. bool read (CDReadBuffer* rb)
  209785. {
  209786. if (rb->numFrames * 2352 > rb->bufferSize)
  209787. return false;
  209788. if (!initialised)
  209789. {
  209790. setPaused (true);
  209791. if (deviceInfo->readType == READTYPE_READ_D4_1)
  209792. selectD4Mode();
  209793. initialised = true;
  209794. }
  209795. SRB_ExecSCSICmd s;
  209796. prepare (s);
  209797. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209798. s.SRB_BufLen = rb->bufferSize;
  209799. s.SRB_BufPointer = rb->buffer;
  209800. s.SRB_CDBLen = 10;
  209801. s.CDBByte[0] = 0xD4;
  209802. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209803. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209804. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209805. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209806. perform (s);
  209807. if (s.SRB_Status != SS_COMP)
  209808. return false;
  209809. rb->dataLength = rb->numFrames * 2352;
  209810. rb->dataStartOffset = 0;
  209811. return true;
  209812. }
  209813. };
  209814. CDController::CDController() : initialised (false)
  209815. {
  209816. }
  209817. CDController::~CDController()
  209818. {
  209819. }
  209820. void CDController::prepare (SRB_ExecSCSICmd& s)
  209821. {
  209822. zerostruct (s);
  209823. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209824. s.SRB_HaID = deviceInfo->info.ha;
  209825. s.SRB_Target = deviceInfo->info.tgt;
  209826. s.SRB_Lun = deviceInfo->info.lun;
  209827. s.SRB_SenseLen = SENSE_LEN;
  209828. }
  209829. void CDController::perform (SRB_ExecSCSICmd& s)
  209830. {
  209831. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209832. s.SRB_PostProc = event;
  209833. ResetEvent (event);
  209834. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  209835. deviceInfo->info.scsiDriveLetter,
  209836. deviceInfo->scsiHandle)
  209837. : fSendASPI32Command ((LPSRB)&s);
  209838. if (status == SS_PENDING)
  209839. WaitForSingleObject (event, 4000);
  209840. CloseHandle (event);
  209841. }
  209842. void CDController::setPaused (bool paused)
  209843. {
  209844. SRB_ExecSCSICmd s;
  209845. prepare (s);
  209846. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209847. s.SRB_CDBLen = 10;
  209848. s.CDBByte[0] = 0x4B;
  209849. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  209850. perform (s);
  209851. }
  209852. void CDController::shutDown()
  209853. {
  209854. }
  209855. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  209856. {
  209857. if (overlapBuffer != 0)
  209858. {
  209859. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  209860. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  209861. if (doJitter
  209862. && overlapBuffer->startFrame > 0
  209863. && overlapBuffer->numFrames > 0
  209864. && overlapBuffer->dataLength > 0)
  209865. {
  209866. const int numFrames = rb->numFrames;
  209867. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  209868. {
  209869. rb->startFrame -= framesOverlap;
  209870. if (framesToCheck < framesOverlap
  209871. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  209872. rb->numFrames += framesOverlap;
  209873. }
  209874. else
  209875. {
  209876. overlapBuffer->dataLength = 0;
  209877. overlapBuffer->startFrame = 0;
  209878. overlapBuffer->numFrames = 0;
  209879. }
  209880. }
  209881. if (! read (rb))
  209882. return false;
  209883. if (doJitter)
  209884. {
  209885. const int checkLen = framesToCheck * 2352;
  209886. const int maxToCheck = rb->dataLength - checkLen;
  209887. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  209888. return true;
  209889. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  209890. bool found = false;
  209891. for (int i = 0; i < maxToCheck; ++i)
  209892. {
  209893. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  209894. {
  209895. i += checkLen;
  209896. rb->dataStartOffset = i;
  209897. rb->dataLength -= i;
  209898. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  209899. found = true;
  209900. break;
  209901. }
  209902. }
  209903. rb->numFrames = rb->dataLength / 2352;
  209904. rb->dataLength = 2352 * rb->numFrames;
  209905. if (!found)
  209906. return false;
  209907. }
  209908. if (canDoJitter)
  209909. {
  209910. memcpy (overlapBuffer->buffer,
  209911. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  209912. 2352 * framesToCheck);
  209913. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  209914. overlapBuffer->numFrames = framesToCheck;
  209915. overlapBuffer->dataLength = 2352 * framesToCheck;
  209916. overlapBuffer->dataStartOffset = 0;
  209917. }
  209918. else
  209919. {
  209920. overlapBuffer->startFrame = 0;
  209921. overlapBuffer->numFrames = 0;
  209922. overlapBuffer->dataLength = 0;
  209923. }
  209924. return true;
  209925. }
  209926. else
  209927. {
  209928. return read (rb);
  209929. }
  209930. }
  209931. int CDController::getLastIndex()
  209932. {
  209933. char qdata[100];
  209934. SRB_ExecSCSICmd s;
  209935. prepare (s);
  209936. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209937. s.SRB_BufLen = sizeof (qdata);
  209938. s.SRB_BufPointer = (BYTE*)qdata;
  209939. s.SRB_CDBLen = 12;
  209940. s.CDBByte[0] = 0x42;
  209941. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209942. s.CDBByte[2] = 64;
  209943. s.CDBByte[3] = 1; // get current position
  209944. s.CDBByte[7] = 0;
  209945. s.CDBByte[8] = (BYTE)sizeof (qdata);
  209946. perform (s);
  209947. if (s.SRB_Status == SS_COMP)
  209948. return qdata[7];
  209949. return 0;
  209950. }
  209951. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  209952. {
  209953. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209954. SRB_ExecSCSICmd s;
  209955. zerostruct (s);
  209956. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209957. s.SRB_HaID = info.ha;
  209958. s.SRB_Target = info.tgt;
  209959. s.SRB_Lun = info.lun;
  209960. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209961. s.SRB_BufLen = 0x324;
  209962. s.SRB_BufPointer = (BYTE*)lpToc;
  209963. s.SRB_SenseLen = 0x0E;
  209964. s.SRB_CDBLen = 0x0A;
  209965. s.SRB_PostProc = event;
  209966. s.CDBByte[0] = 0x43;
  209967. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  209968. s.CDBByte[7] = 0x03;
  209969. s.CDBByte[8] = 0x24;
  209970. ResetEvent (event);
  209971. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209972. : fSendASPI32Command ((LPSRB)&s);
  209973. if (status == SS_PENDING)
  209974. WaitForSingleObject (event, 4000);
  209975. CloseHandle (event);
  209976. return (s.SRB_Status == SS_COMP);
  209977. }
  209978. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  209979. CDReadBuffer* const overlapBuffer)
  209980. {
  209981. if (controller == 0)
  209982. {
  209983. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  209984. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  209985. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  209986. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  209987. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  209988. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  209989. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  209990. }
  209991. buffer->index = 0;
  209992. if ((controller != 0)
  209993. && controller->readAudio (buffer, overlapBuffer))
  209994. {
  209995. if (buffer->wantsIndex)
  209996. buffer->index = controller->getLastIndex();
  209997. return true;
  209998. }
  209999. return false;
  210000. }
  210001. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  210002. {
  210003. if (shouldBeOpen)
  210004. {
  210005. if (controller != 0)
  210006. {
  210007. controller->shutDown();
  210008. controller = 0;
  210009. }
  210010. if (scsiHandle != 0)
  210011. {
  210012. CloseHandle (scsiHandle);
  210013. scsiHandle = 0;
  210014. }
  210015. }
  210016. SRB_ExecSCSICmd s;
  210017. zerostruct (s);
  210018. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210019. s.SRB_HaID = info.ha;
  210020. s.SRB_Target = info.tgt;
  210021. s.SRB_Lun = info.lun;
  210022. s.SRB_SenseLen = SENSE_LEN;
  210023. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210024. s.SRB_BufLen = 0;
  210025. s.SRB_BufPointer = 0;
  210026. s.SRB_CDBLen = 12;
  210027. s.CDBByte[0] = 0x1b;
  210028. s.CDBByte[1] = (BYTE)(info.lun << 5);
  210029. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  210030. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  210031. s.SRB_PostProc = event;
  210032. ResetEvent (event);
  210033. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  210034. : fSendASPI32Command ((LPSRB)&s);
  210035. if (status == SS_PENDING)
  210036. WaitForSingleObject (event, 4000);
  210037. CloseHandle (event);
  210038. }
  210039. bool CDDeviceHandle::testController (const int type,
  210040. CDController* const newController,
  210041. CDReadBuffer* const rb)
  210042. {
  210043. controller = newController;
  210044. readType = (BYTE)type;
  210045. controller->deviceInfo = this;
  210046. controller->framesToCheck = 1;
  210047. controller->framesOverlap = 3;
  210048. bool passed = false;
  210049. memset (rb->buffer, 0xcd, rb->bufferSize);
  210050. if (controller->read (rb))
  210051. {
  210052. passed = true;
  210053. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  210054. int wrong = 0;
  210055. for (int i = rb->dataLength / 4; --i >= 0;)
  210056. {
  210057. if (*p++ == (int) 0xcdcdcdcd)
  210058. {
  210059. if (++wrong == 4)
  210060. {
  210061. passed = false;
  210062. break;
  210063. }
  210064. }
  210065. else
  210066. {
  210067. wrong = 0;
  210068. }
  210069. }
  210070. }
  210071. if (! passed)
  210072. {
  210073. controller->shutDown();
  210074. controller = 0;
  210075. }
  210076. return passed;
  210077. }
  210078. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  210079. {
  210080. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  210081. const int bufSize = 128;
  210082. BYTE buffer[bufSize];
  210083. zeromem (buffer, bufSize);
  210084. SRB_ExecSCSICmd s;
  210085. zerostruct (s);
  210086. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210087. s.SRB_HaID = ha;
  210088. s.SRB_Target = tgt;
  210089. s.SRB_Lun = lun;
  210090. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210091. s.SRB_BufLen = bufSize;
  210092. s.SRB_BufPointer = buffer;
  210093. s.SRB_SenseLen = SENSE_LEN;
  210094. s.SRB_CDBLen = 6;
  210095. s.SRB_PostProc = event;
  210096. s.CDBByte[0] = SCSI_INQUIRY;
  210097. s.CDBByte[4] = 100;
  210098. ResetEvent (event);
  210099. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  210100. WaitForSingleObject (event, 4000);
  210101. CloseHandle (event);
  210102. if (s.SRB_Status == SS_COMP)
  210103. {
  210104. memcpy (dev->vendor, &buffer[8], 8);
  210105. memcpy (dev->productId, &buffer[16], 16);
  210106. memcpy (dev->rev, &buffer[32], 4);
  210107. memcpy (dev->vendorSpec, &buffer[36], 20);
  210108. }
  210109. }
  210110. static int FindCDDevices (CDDeviceInfo* const list,
  210111. int maxItems)
  210112. {
  210113. int count = 0;
  210114. if (usingScsi)
  210115. {
  210116. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210117. {
  210118. TCHAR drivePath[8];
  210119. drivePath[0] = driveLetter;
  210120. drivePath[1] = ':';
  210121. drivePath[2] = '\\';
  210122. drivePath[3] = 0;
  210123. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210124. {
  210125. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  210126. if (h != INVALID_HANDLE_VALUE)
  210127. {
  210128. BYTE buffer[100], passThroughStruct[1024];
  210129. zeromem (buffer, sizeof (buffer));
  210130. zeromem (passThroughStruct, sizeof (passThroughStruct));
  210131. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  210132. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  210133. p->spt.CdbLength = 6;
  210134. p->spt.SenseInfoLength = 24;
  210135. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  210136. p->spt.DataTransferLength = 100;
  210137. p->spt.TimeOutValue = 2;
  210138. p->spt.DataBuffer = buffer;
  210139. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210140. p->spt.Cdb[0] = 0x12;
  210141. p->spt.Cdb[4] = 100;
  210142. DWORD bytesReturned = 0;
  210143. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210144. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  210145. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  210146. &bytesReturned, 0) != 0)
  210147. {
  210148. zeromem (&list[count], sizeof (CDDeviceInfo));
  210149. list[count].scsiDriveLetter = driveLetter;
  210150. memcpy (list[count].vendor, &buffer[8], 8);
  210151. memcpy (list[count].productId, &buffer[16], 16);
  210152. memcpy (list[count].rev, &buffer[32], 4);
  210153. memcpy (list[count].vendorSpec, &buffer[36], 20);
  210154. zeromem (passThroughStruct, sizeof (passThroughStruct));
  210155. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  210156. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  210157. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210158. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  210159. &bytesReturned, 0) != 0)
  210160. {
  210161. list[count].ha = scsiAddr->PortNumber;
  210162. list[count].tgt = scsiAddr->TargetId;
  210163. list[count].lun = scsiAddr->Lun;
  210164. ++count;
  210165. }
  210166. }
  210167. CloseHandle (h);
  210168. }
  210169. }
  210170. }
  210171. }
  210172. else
  210173. {
  210174. const DWORD d = fGetASPI32SupportInfo();
  210175. BYTE status = HIBYTE (LOWORD (d));
  210176. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  210177. return 0;
  210178. const int numAdapters = LOBYTE (LOWORD (d));
  210179. for (BYTE ha = 0; ha < numAdapters; ++ha)
  210180. {
  210181. SRB_HAInquiry s;
  210182. zerostruct (s);
  210183. s.SRB_Cmd = SC_HA_INQUIRY;
  210184. s.SRB_HaID = ha;
  210185. fSendASPI32Command ((LPSRB)&s);
  210186. if (s.SRB_Status == SS_COMP)
  210187. {
  210188. maxItems = (int)s.HA_Unique[3];
  210189. if (maxItems == 0)
  210190. maxItems = 8;
  210191. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  210192. {
  210193. for (BYTE lun = 0; lun < 8; ++lun)
  210194. {
  210195. SRB_GDEVBlock sb;
  210196. zerostruct (sb);
  210197. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  210198. sb.SRB_HaID = ha;
  210199. sb.SRB_Target = tgt;
  210200. sb.SRB_Lun = lun;
  210201. fSendASPI32Command ((LPSRB) &sb);
  210202. if (sb.SRB_Status == SS_COMP
  210203. && sb.SRB_DeviceType == DTYPE_CROM)
  210204. {
  210205. zeromem (&list[count], sizeof (CDDeviceInfo));
  210206. list[count].ha = ha;
  210207. list[count].tgt = tgt;
  210208. list[count].lun = lun;
  210209. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  210210. ++count;
  210211. }
  210212. }
  210213. }
  210214. }
  210215. }
  210216. }
  210217. return count;
  210218. }
  210219. static int ripperUsers = 0;
  210220. static bool initialisedOk = false;
  210221. class DeinitialiseTimer : private Timer,
  210222. private DeletedAtShutdown
  210223. {
  210224. DeinitialiseTimer (const DeinitialiseTimer&);
  210225. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  210226. public:
  210227. DeinitialiseTimer()
  210228. {
  210229. startTimer (4000);
  210230. }
  210231. ~DeinitialiseTimer()
  210232. {
  210233. if (--ripperUsers == 0)
  210234. DeinitialiseCDRipper();
  210235. }
  210236. void timerCallback()
  210237. {
  210238. delete this;
  210239. }
  210240. juce_UseDebuggingNewOperator
  210241. };
  210242. static void incUserCount()
  210243. {
  210244. if (ripperUsers++ == 0)
  210245. initialisedOk = InitialiseCDRipper();
  210246. }
  210247. static void decUserCount()
  210248. {
  210249. new DeinitialiseTimer();
  210250. }
  210251. struct CDDeviceWrapper
  210252. {
  210253. ScopedPointer<CDDeviceHandle> cdH;
  210254. ScopedPointer<CDReadBuffer> overlapBuffer;
  210255. bool jitter;
  210256. };
  210257. static int getAddressOf (const TOCTRACK* const t)
  210258. {
  210259. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  210260. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  210261. }
  210262. static int getMSFAddressOf (const TOCTRACK* const t)
  210263. {
  210264. return 60 * t->addr[1] + t->addr[2];
  210265. }
  210266. static const int samplesPerFrame = 44100 / 75;
  210267. static const int bytesPerFrame = samplesPerFrame * 4;
  210268. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  210269. {
  210270. SRB_GDEVBlock s;
  210271. zerostruct (s);
  210272. s.SRB_Cmd = SC_GET_DEV_TYPE;
  210273. s.SRB_HaID = device->ha;
  210274. s.SRB_Target = device->tgt;
  210275. s.SRB_Lun = device->lun;
  210276. if (usingScsi)
  210277. {
  210278. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  210279. if (h != INVALID_HANDLE_VALUE)
  210280. {
  210281. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  210282. cdh->scsiHandle = h;
  210283. return cdh;
  210284. }
  210285. }
  210286. else
  210287. {
  210288. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  210289. && s.SRB_DeviceType == DTYPE_CROM)
  210290. {
  210291. return new CDDeviceHandle (device);
  210292. }
  210293. }
  210294. return 0;
  210295. }
  210296. }
  210297. const StringArray AudioCDReader::getAvailableCDNames()
  210298. {
  210299. using namespace CDReaderHelpers;
  210300. StringArray results;
  210301. incUserCount();
  210302. if (initialisedOk)
  210303. {
  210304. CDDeviceInfo list[8];
  210305. const int num = FindCDDevices (list, 8);
  210306. decUserCount();
  210307. for (int i = 0; i < num; ++i)
  210308. {
  210309. String s;
  210310. if (list[i].scsiDriveLetter > 0)
  210311. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  210312. s << String (list[i].vendor).trim()
  210313. << ' ' << String (list[i].productId).trim()
  210314. << ' ' << String (list[i].rev).trim();
  210315. results.add (s);
  210316. }
  210317. }
  210318. return results;
  210319. }
  210320. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210321. {
  210322. using namespace CDReaderHelpers;
  210323. incUserCount();
  210324. if (initialisedOk)
  210325. {
  210326. CDDeviceInfo list[8];
  210327. const int num = FindCDDevices (list, 8);
  210328. if (((unsigned int) deviceIndex) < (unsigned int) num)
  210329. {
  210330. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  210331. if (handle != 0)
  210332. {
  210333. CDDeviceWrapper* const d = new CDDeviceWrapper();
  210334. d->cdH = handle;
  210335. d->overlapBuffer = new CDReadBuffer(3);
  210336. return new AudioCDReader (d);
  210337. }
  210338. }
  210339. }
  210340. decUserCount();
  210341. return 0;
  210342. }
  210343. AudioCDReader::AudioCDReader (void* handle_)
  210344. : AudioFormatReader (0, "CD Audio"),
  210345. handle (handle_),
  210346. indexingEnabled (false),
  210347. lastIndex (0),
  210348. firstFrameInBuffer (0),
  210349. samplesInBuffer (0)
  210350. {
  210351. using namespace CDReaderHelpers;
  210352. jassert (handle_ != 0);
  210353. refreshTrackLengths();
  210354. sampleRate = 44100.0;
  210355. bitsPerSample = 16;
  210356. lengthInSamples = getPositionOfTrackStart (numTracks);
  210357. numChannels = 2;
  210358. usesFloatingPointData = false;
  210359. buffer.setSize (4 * bytesPerFrame, true);
  210360. }
  210361. AudioCDReader::~AudioCDReader()
  210362. {
  210363. using namespace CDReaderHelpers;
  210364. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210365. delete device;
  210366. decUserCount();
  210367. }
  210368. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210369. int64 startSampleInFile, int numSamples)
  210370. {
  210371. using namespace CDReaderHelpers;
  210372. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210373. bool ok = true;
  210374. while (numSamples > 0)
  210375. {
  210376. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210377. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210378. if (startSampleInFile >= bufferStartSample
  210379. && startSampleInFile < bufferEndSample)
  210380. {
  210381. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210382. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210383. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210384. const short* src = (const short*) buffer.getData();
  210385. src += 2 * (startSampleInFile - bufferStartSample);
  210386. for (int i = 0; i < toDo; ++i)
  210387. {
  210388. l[i] = src [i << 1] << 16;
  210389. if (r != 0)
  210390. r[i] = src [(i << 1) + 1] << 16;
  210391. }
  210392. startOffsetInDestBuffer += toDo;
  210393. startSampleInFile += toDo;
  210394. numSamples -= toDo;
  210395. }
  210396. else
  210397. {
  210398. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  210399. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  210400. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  210401. {
  210402. device->overlapBuffer->dataLength = 0;
  210403. device->overlapBuffer->startFrame = 0;
  210404. device->overlapBuffer->numFrames = 0;
  210405. device->jitter = false;
  210406. }
  210407. firstFrameInBuffer = frameNeeded;
  210408. lastIndex = 0;
  210409. CDReadBuffer readBuffer (framesInBuffer + 4);
  210410. readBuffer.wantsIndex = indexingEnabled;
  210411. int i;
  210412. for (i = 5; --i >= 0;)
  210413. {
  210414. readBuffer.startFrame = frameNeeded;
  210415. readBuffer.numFrames = framesInBuffer;
  210416. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  210417. break;
  210418. else
  210419. device->overlapBuffer->dataLength = 0;
  210420. }
  210421. if (i >= 0)
  210422. {
  210423. memcpy ((char*) buffer.getData(),
  210424. readBuffer.buffer + readBuffer.dataStartOffset,
  210425. readBuffer.dataLength);
  210426. samplesInBuffer = readBuffer.dataLength >> 2;
  210427. lastIndex = readBuffer.index;
  210428. }
  210429. else
  210430. {
  210431. int* l = destSamples[0] + startOffsetInDestBuffer;
  210432. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210433. while (--numSamples >= 0)
  210434. {
  210435. *l++ = 0;
  210436. if (r != 0)
  210437. *r++ = 0;
  210438. }
  210439. // sometimes the read fails for just the very last couple of blocks, so
  210440. // we'll ignore and errors in the last half-second of the disk..
  210441. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  210442. break;
  210443. }
  210444. }
  210445. }
  210446. return ok;
  210447. }
  210448. bool AudioCDReader::isCDStillPresent() const
  210449. {
  210450. using namespace CDReaderHelpers;
  210451. TOC toc;
  210452. zerostruct (toc);
  210453. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  210454. }
  210455. int AudioCDReader::getNumTracks() const
  210456. {
  210457. return numTracks;
  210458. }
  210459. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  210460. {
  210461. using namespace CDReaderHelpers;
  210462. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  210463. : 0;
  210464. }
  210465. void AudioCDReader::refreshTrackLengths()
  210466. {
  210467. using namespace CDReaderHelpers;
  210468. zeromem (trackStarts, sizeof (trackStarts));
  210469. zeromem (audioTracks, sizeof (audioTracks));
  210470. TOC toc;
  210471. zerostruct (toc);
  210472. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  210473. {
  210474. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  210475. for (int i = 0; i <= numTracks; ++i)
  210476. {
  210477. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  210478. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  210479. }
  210480. }
  210481. else
  210482. {
  210483. numTracks = 0;
  210484. }
  210485. }
  210486. bool AudioCDReader::isTrackAudio (int trackNum) const
  210487. {
  210488. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  210489. : false;
  210490. }
  210491. void AudioCDReader::enableIndexScanning (bool b)
  210492. {
  210493. indexingEnabled = b;
  210494. }
  210495. int AudioCDReader::getLastIndex() const
  210496. {
  210497. return lastIndex;
  210498. }
  210499. const int framesPerIndexRead = 4;
  210500. int AudioCDReader::getIndexAt (int samplePos)
  210501. {
  210502. using namespace CDReaderHelpers;
  210503. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210504. const int frameNeeded = samplePos / samplesPerFrame;
  210505. device->overlapBuffer->dataLength = 0;
  210506. device->overlapBuffer->startFrame = 0;
  210507. device->overlapBuffer->numFrames = 0;
  210508. device->jitter = false;
  210509. firstFrameInBuffer = 0;
  210510. lastIndex = 0;
  210511. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  210512. readBuffer.wantsIndex = true;
  210513. int i;
  210514. for (i = 5; --i >= 0;)
  210515. {
  210516. readBuffer.startFrame = frameNeeded;
  210517. readBuffer.numFrames = framesPerIndexRead;
  210518. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210519. break;
  210520. }
  210521. if (i >= 0)
  210522. return readBuffer.index;
  210523. return -1;
  210524. }
  210525. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210526. {
  210527. using namespace CDReaderHelpers;
  210528. Array <int> indexes;
  210529. const int trackStart = getPositionOfTrackStart (trackNumber);
  210530. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  210531. bool needToScan = true;
  210532. if (trackEnd - trackStart > 20 * 44100)
  210533. {
  210534. // check the end of the track for indexes before scanning the whole thing
  210535. needToScan = false;
  210536. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  210537. bool seenAnIndex = false;
  210538. while (pos <= trackEnd - samplesPerFrame)
  210539. {
  210540. const int index = getIndexAt (pos);
  210541. if (index == 0)
  210542. {
  210543. // lead-out, so skip back a bit if we've not found any indexes yet..
  210544. if (seenAnIndex)
  210545. break;
  210546. pos -= 44100 * 5;
  210547. if (pos < trackStart)
  210548. break;
  210549. }
  210550. else
  210551. {
  210552. if (index > 0)
  210553. seenAnIndex = true;
  210554. if (index > 1)
  210555. {
  210556. needToScan = true;
  210557. break;
  210558. }
  210559. pos += samplesPerFrame * framesPerIndexRead;
  210560. }
  210561. }
  210562. }
  210563. if (needToScan)
  210564. {
  210565. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210566. int pos = trackStart;
  210567. int last = -1;
  210568. while (pos < trackEnd - samplesPerFrame * 10)
  210569. {
  210570. const int frameNeeded = pos / samplesPerFrame;
  210571. device->overlapBuffer->dataLength = 0;
  210572. device->overlapBuffer->startFrame = 0;
  210573. device->overlapBuffer->numFrames = 0;
  210574. device->jitter = false;
  210575. firstFrameInBuffer = 0;
  210576. CDReadBuffer readBuffer (4);
  210577. readBuffer.wantsIndex = true;
  210578. int i;
  210579. for (i = 5; --i >= 0;)
  210580. {
  210581. readBuffer.startFrame = frameNeeded;
  210582. readBuffer.numFrames = framesPerIndexRead;
  210583. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210584. break;
  210585. }
  210586. if (i < 0)
  210587. break;
  210588. if (readBuffer.index > last && readBuffer.index > 1)
  210589. {
  210590. last = readBuffer.index;
  210591. indexes.add (pos);
  210592. }
  210593. pos += samplesPerFrame * framesPerIndexRead;
  210594. }
  210595. indexes.removeValue (trackStart);
  210596. }
  210597. return indexes;
  210598. }
  210599. int AudioCDReader::getCDDBId()
  210600. {
  210601. using namespace CDReaderHelpers;
  210602. refreshTrackLengths();
  210603. if (numTracks > 0)
  210604. {
  210605. TOC toc;
  210606. zerostruct (toc);
  210607. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  210608. {
  210609. int n = 0;
  210610. for (int i = numTracks; --i >= 0;)
  210611. {
  210612. int j = getMSFAddressOf (&toc.tracks[i]);
  210613. while (j > 0)
  210614. {
  210615. n += (j % 10);
  210616. j /= 10;
  210617. }
  210618. }
  210619. if (n != 0)
  210620. {
  210621. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  210622. - getMSFAddressOf (&toc.tracks[0]);
  210623. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  210624. }
  210625. }
  210626. }
  210627. return 0;
  210628. }
  210629. void AudioCDReader::ejectDisk()
  210630. {
  210631. using namespace CDReaderHelpers;
  210632. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  210633. }
  210634. #endif
  210635. #if JUCE_USE_CDBURNER
  210636. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  210637. {
  210638. CoInitialize (0);
  210639. IDiscMaster* dm;
  210640. IDiscRecorder* result = 0;
  210641. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  210642. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  210643. IID_IDiscMaster,
  210644. (void**) &dm)))
  210645. {
  210646. if (SUCCEEDED (dm->Open()))
  210647. {
  210648. IEnumDiscRecorders* drEnum = 0;
  210649. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  210650. {
  210651. IDiscRecorder* dr = 0;
  210652. DWORD dummy;
  210653. int index = 0;
  210654. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  210655. {
  210656. if (indexToOpen == index)
  210657. {
  210658. result = dr;
  210659. break;
  210660. }
  210661. else if (list != 0)
  210662. {
  210663. BSTR path;
  210664. if (SUCCEEDED (dr->GetPath (&path)))
  210665. list->add ((const WCHAR*) path);
  210666. }
  210667. ++index;
  210668. dr->Release();
  210669. }
  210670. drEnum->Release();
  210671. }
  210672. if (master == 0)
  210673. dm->Close();
  210674. }
  210675. if (master != 0)
  210676. *master = dm;
  210677. else
  210678. dm->Release();
  210679. }
  210680. return result;
  210681. }
  210682. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  210683. public Timer
  210684. {
  210685. public:
  210686. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  210687. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  210688. listener (0), progress (0), shouldCancel (false)
  210689. {
  210690. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  210691. jassert (SUCCEEDED (hr));
  210692. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  210693. //jassert (SUCCEEDED (hr));
  210694. lastState = getDiskState();
  210695. startTimer (2000);
  210696. }
  210697. ~Pimpl() {}
  210698. void releaseObjects()
  210699. {
  210700. discRecorder->Close();
  210701. if (redbook != 0)
  210702. redbook->Release();
  210703. discRecorder->Release();
  210704. discMaster->Release();
  210705. Release();
  210706. }
  210707. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  210708. {
  210709. if (listener != 0 && ! shouldCancel)
  210710. shouldCancel = listener->audioCDBurnProgress (progress);
  210711. *pbCancel = shouldCancel;
  210712. return S_OK;
  210713. }
  210714. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  210715. {
  210716. progress = nCompleted / (float) nTotal;
  210717. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  210718. return E_NOTIMPL;
  210719. }
  210720. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  210721. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  210722. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  210723. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210724. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210725. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210726. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210727. class ScopedDiscOpener
  210728. {
  210729. public:
  210730. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  210731. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  210732. private:
  210733. Pimpl& pimpl;
  210734. ScopedDiscOpener (const ScopedDiscOpener&);
  210735. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  210736. };
  210737. DiskState getDiskState()
  210738. {
  210739. const ScopedDiscOpener opener (*this);
  210740. long type, flags;
  210741. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  210742. if (FAILED (hr))
  210743. return unknown;
  210744. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  210745. return writableDiskPresent;
  210746. if (type == 0)
  210747. return noDisc;
  210748. else
  210749. return readOnlyDiskPresent;
  210750. }
  210751. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  210752. {
  210753. ComSmartPtr<IPropertyStorage> prop;
  210754. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210755. return defaultReturn;
  210756. PROPSPEC iPropSpec;
  210757. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210758. iPropSpec.lpwstr = name;
  210759. PROPVARIANT iPropVariant;
  210760. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  210761. ? defaultReturn : (int) iPropVariant.lVal;
  210762. }
  210763. bool setIntProperty (const LPOLESTR name, const int value) const
  210764. {
  210765. ComSmartPtr<IPropertyStorage> prop;
  210766. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210767. return false;
  210768. PROPSPEC iPropSpec;
  210769. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210770. iPropSpec.lpwstr = name;
  210771. PROPVARIANT iPropVariant;
  210772. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  210773. return false;
  210774. iPropVariant.lVal = (long) value;
  210775. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  210776. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  210777. }
  210778. void timerCallback()
  210779. {
  210780. const DiskState state = getDiskState();
  210781. if (state != lastState)
  210782. {
  210783. lastState = state;
  210784. owner.sendChangeMessage (&owner);
  210785. }
  210786. }
  210787. AudioCDBurner& owner;
  210788. DiskState lastState;
  210789. IDiscMaster* discMaster;
  210790. IDiscRecorder* discRecorder;
  210791. IRedbookDiscMaster* redbook;
  210792. AudioCDBurner::BurnProgressListener* listener;
  210793. float progress;
  210794. bool shouldCancel;
  210795. };
  210796. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  210797. {
  210798. IDiscMaster* discMaster = 0;
  210799. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  210800. if (discRecorder != 0)
  210801. pimpl = new Pimpl (*this, discMaster, discRecorder);
  210802. }
  210803. AudioCDBurner::~AudioCDBurner()
  210804. {
  210805. if (pimpl != 0)
  210806. pimpl.release()->releaseObjects();
  210807. }
  210808. const StringArray AudioCDBurner::findAvailableDevices()
  210809. {
  210810. StringArray devs;
  210811. enumCDBurners (&devs, -1, 0);
  210812. return devs;
  210813. }
  210814. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  210815. {
  210816. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  210817. if (b->pimpl == 0)
  210818. b = 0;
  210819. return b.release();
  210820. }
  210821. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210822. {
  210823. return pimpl->getDiskState();
  210824. }
  210825. bool AudioCDBurner::isDiskPresent() const
  210826. {
  210827. return getDiskState() == writableDiskPresent;
  210828. }
  210829. bool AudioCDBurner::openTray()
  210830. {
  210831. const Pimpl::ScopedDiscOpener opener (*pimpl);
  210832. return SUCCEEDED (pimpl->discRecorder->Eject());
  210833. }
  210834. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  210835. {
  210836. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  210837. DiskState oldState = getDiskState();
  210838. DiskState newState = oldState;
  210839. while (newState == oldState && Time::currentTimeMillis() < timeout)
  210840. {
  210841. newState = getDiskState();
  210842. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  210843. }
  210844. return newState;
  210845. }
  210846. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  210847. {
  210848. Array<int> results;
  210849. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  210850. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  210851. for (int i = 0; i < numElementsInArray (speeds); ++i)
  210852. if (speeds[i] <= maxSpeed)
  210853. results.add (speeds[i]);
  210854. results.addIfNotAlreadyThere (maxSpeed);
  210855. return results;
  210856. }
  210857. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  210858. {
  210859. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  210860. return false;
  210861. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  210862. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  210863. }
  210864. int AudioCDBurner::getNumAvailableAudioBlocks() const
  210865. {
  210866. long blocksFree = 0;
  210867. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  210868. return blocksFree;
  210869. }
  210870. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  210871. bool performFakeBurnForTesting, int writeSpeed)
  210872. {
  210873. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  210874. pimpl->listener = listener;
  210875. pimpl->progress = 0;
  210876. pimpl->shouldCancel = false;
  210877. UINT_PTR cookie;
  210878. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  210879. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  210880. ejectDiscAfterwards);
  210881. String error;
  210882. if (hr != S_OK)
  210883. {
  210884. const char* e = "Couldn't open or write to the CD device";
  210885. if (hr == IMAPI_E_USERABORT)
  210886. e = "User cancelled the write operation";
  210887. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  210888. e = "No Disk present";
  210889. error = e;
  210890. }
  210891. pimpl->discMaster->ProgressUnadvise (cookie);
  210892. pimpl->listener = 0;
  210893. return error;
  210894. }
  210895. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  210896. {
  210897. if (audioSource == 0)
  210898. return false;
  210899. ScopedPointer<AudioSource> source (audioSource);
  210900. long bytesPerBlock;
  210901. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  210902. const int samplesPerBlock = bytesPerBlock / 4;
  210903. bool ok = true;
  210904. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  210905. HeapBlock <byte> buffer (bytesPerBlock);
  210906. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  210907. int samplesDone = 0;
  210908. source->prepareToPlay (samplesPerBlock, 44100.0);
  210909. while (ok)
  210910. {
  210911. {
  210912. AudioSourceChannelInfo info;
  210913. info.buffer = &sourceBuffer;
  210914. info.numSamples = samplesPerBlock;
  210915. info.startSample = 0;
  210916. sourceBuffer.clear();
  210917. source->getNextAudioBlock (info);
  210918. }
  210919. zeromem (buffer, bytesPerBlock);
  210920. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  210921. buffer, samplesPerBlock, 4);
  210922. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  210923. buffer + 2, samplesPerBlock, 4);
  210924. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  210925. if (FAILED (hr))
  210926. ok = false;
  210927. samplesDone += samplesPerBlock;
  210928. if (samplesDone >= numSamples)
  210929. break;
  210930. }
  210931. hr = pimpl->redbook->CloseAudioTrack();
  210932. return ok && hr == S_OK;
  210933. }
  210934. #endif
  210935. #endif
  210936. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  210937. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  210938. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210939. // compiled on its own).
  210940. #if JUCE_INCLUDED_FILE
  210941. using ::free;
  210942. namespace MidiConstants
  210943. {
  210944. static const int midiBufferSize = 1024 * 10;
  210945. static const int numInHeaders = 32;
  210946. static const int inBufferSize = 256;
  210947. }
  210948. class MidiInThread : public Thread
  210949. {
  210950. public:
  210951. MidiInThread (MidiInput* const input_,
  210952. MidiInputCallback* const callback_)
  210953. : Thread ("Juce Midi"),
  210954. hIn (0),
  210955. input (input_),
  210956. callback (callback_),
  210957. isStarted (false),
  210958. startTime (0),
  210959. pendingLength(0)
  210960. {
  210961. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210962. {
  210963. zeromem (&hdr[i], sizeof (MIDIHDR));
  210964. hdr[i].lpData = inData[i];
  210965. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  210966. }
  210967. };
  210968. ~MidiInThread()
  210969. {
  210970. stop();
  210971. if (hIn != 0)
  210972. {
  210973. int count = 5;
  210974. while (--count >= 0)
  210975. {
  210976. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  210977. break;
  210978. Sleep (20);
  210979. }
  210980. }
  210981. }
  210982. void handle (const uint32 message, const uint32 timeStamp)
  210983. {
  210984. const int byte = message & 0xff;
  210985. if (byte < 0x80)
  210986. return;
  210987. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  210988. const double time = timeStampToTime (timeStamp);
  210989. {
  210990. const ScopedLock sl (lock);
  210991. if (pendingLength < MidiConstants::midiBufferSize - 12)
  210992. {
  210993. char* const p = pending + pendingLength;
  210994. *(double*) p = time;
  210995. *(uint32*) (p + 8) = numBytes;
  210996. *(uint32*) (p + 12) = message;
  210997. pendingLength += 12 + numBytes;
  210998. }
  210999. else
  211000. {
  211001. jassertfalse; // midi buffer overflow! You might need to increase the size..
  211002. }
  211003. }
  211004. notify();
  211005. }
  211006. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211007. {
  211008. const int num = hdr->dwBytesRecorded;
  211009. if (num > 0)
  211010. {
  211011. const double time = timeStampToTime (timeStamp);
  211012. {
  211013. const ScopedLock sl (lock);
  211014. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  211015. {
  211016. char* const p = pending + pendingLength;
  211017. *(double*) p = time;
  211018. *(uint32*) (p + 8) = num;
  211019. memcpy (p + 12, hdr->lpData, num);
  211020. pendingLength += 12 + num;
  211021. }
  211022. else
  211023. {
  211024. jassertfalse; // midi buffer overflow! You might need to increase the size..
  211025. }
  211026. }
  211027. notify();
  211028. }
  211029. }
  211030. void writeBlock (const int i)
  211031. {
  211032. hdr[i].dwBytesRecorded = 0;
  211033. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  211034. jassert (res == MMSYSERR_NOERROR);
  211035. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  211036. jassert (res == MMSYSERR_NOERROR);
  211037. }
  211038. void run()
  211039. {
  211040. MemoryBlock pendingCopy (64);
  211041. while (! threadShouldExit())
  211042. {
  211043. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  211044. {
  211045. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  211046. {
  211047. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  211048. (void) res;
  211049. jassert (res == MMSYSERR_NOERROR);
  211050. writeBlock (i);
  211051. }
  211052. }
  211053. int len;
  211054. {
  211055. const ScopedLock sl (lock);
  211056. len = pendingLength;
  211057. if (len > 0)
  211058. {
  211059. pendingCopy.ensureSize (len);
  211060. pendingCopy.copyFrom (pending, 0, len);
  211061. pendingLength = 0;
  211062. }
  211063. }
  211064. //xxx needs to figure out if blocks are broken up or not
  211065. if (len == 0)
  211066. {
  211067. wait (500);
  211068. }
  211069. else
  211070. {
  211071. const char* p = (const char*) pendingCopy.getData();
  211072. while (len > 0)
  211073. {
  211074. const double time = *(const double*) p;
  211075. const int messageLen = *(const int*) (p + 8);
  211076. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  211077. callback->handleIncomingMidiMessage (input, message);
  211078. p += 12 + messageLen;
  211079. len -= 12 + messageLen;
  211080. }
  211081. }
  211082. }
  211083. }
  211084. void start()
  211085. {
  211086. jassert (hIn != 0);
  211087. if (hIn != 0 && ! isStarted)
  211088. {
  211089. stop();
  211090. activeMidiThreads.addIfNotAlreadyThere (this);
  211091. int i;
  211092. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  211093. writeBlock (i);
  211094. startTime = Time::getMillisecondCounter();
  211095. MMRESULT res = midiInStart (hIn);
  211096. jassert (res == MMSYSERR_NOERROR);
  211097. if (res == MMSYSERR_NOERROR)
  211098. {
  211099. isStarted = true;
  211100. pendingLength = 0;
  211101. startThread (6);
  211102. }
  211103. }
  211104. }
  211105. void stop()
  211106. {
  211107. if (isStarted)
  211108. {
  211109. stopThread (5000);
  211110. midiInReset (hIn);
  211111. midiInStop (hIn);
  211112. activeMidiThreads.removeValue (this);
  211113. { const ScopedLock sl (lock); }
  211114. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  211115. {
  211116. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  211117. {
  211118. int c = 10;
  211119. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  211120. Sleep (20);
  211121. jassert (c >= 0);
  211122. }
  211123. }
  211124. isStarted = false;
  211125. pendingLength = 0;
  211126. }
  211127. }
  211128. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211129. {
  211130. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  211131. if (thread != 0 && activeMidiThreads.contains (thread))
  211132. {
  211133. if (uMsg == MIM_DATA)
  211134. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  211135. else if (uMsg == MIM_LONGDATA)
  211136. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211137. }
  211138. }
  211139. juce_UseDebuggingNewOperator
  211140. HMIDIIN hIn;
  211141. private:
  211142. static Array <void*, CriticalSection> activeMidiThreads;
  211143. MidiInput* input;
  211144. MidiInputCallback* callback;
  211145. bool isStarted;
  211146. uint32 startTime;
  211147. CriticalSection lock;
  211148. MIDIHDR hdr [MidiConstants::numInHeaders];
  211149. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  211150. int pendingLength;
  211151. char pending [MidiConstants::midiBufferSize];
  211152. double timeStampToTime (uint32 timeStamp)
  211153. {
  211154. timeStamp += startTime;
  211155. const uint32 now = Time::getMillisecondCounter();
  211156. if (timeStamp > now)
  211157. {
  211158. if (timeStamp > now + 2)
  211159. --startTime;
  211160. timeStamp = now;
  211161. }
  211162. return 0.001 * timeStamp;
  211163. }
  211164. MidiInThread (const MidiInThread&);
  211165. MidiInThread& operator= (const MidiInThread&);
  211166. };
  211167. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  211168. const StringArray MidiInput::getDevices()
  211169. {
  211170. StringArray s;
  211171. const int num = midiInGetNumDevs();
  211172. for (int i = 0; i < num; ++i)
  211173. {
  211174. MIDIINCAPS mc;
  211175. zerostruct (mc);
  211176. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211177. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211178. }
  211179. return s;
  211180. }
  211181. int MidiInput::getDefaultDeviceIndex()
  211182. {
  211183. return 0;
  211184. }
  211185. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211186. {
  211187. if (callback == 0)
  211188. return 0;
  211189. UINT deviceId = MIDI_MAPPER;
  211190. int n = 0;
  211191. String name;
  211192. const int num = midiInGetNumDevs();
  211193. for (int i = 0; i < num; ++i)
  211194. {
  211195. MIDIINCAPS mc;
  211196. zerostruct (mc);
  211197. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211198. {
  211199. if (index == n)
  211200. {
  211201. deviceId = i;
  211202. name = String (mc.szPname, sizeof (mc.szPname));
  211203. break;
  211204. }
  211205. ++n;
  211206. }
  211207. }
  211208. ScopedPointer <MidiInput> in (new MidiInput (name));
  211209. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  211210. HMIDIIN h;
  211211. HRESULT err = midiInOpen (&h, deviceId,
  211212. (DWORD_PTR) &MidiInThread::midiInCallback,
  211213. (DWORD_PTR) (MidiInThread*) thread,
  211214. CALLBACK_FUNCTION);
  211215. if (err == MMSYSERR_NOERROR)
  211216. {
  211217. thread->hIn = h;
  211218. in->internal = thread.release();
  211219. return in.release();
  211220. }
  211221. return 0;
  211222. }
  211223. MidiInput::MidiInput (const String& name_)
  211224. : name (name_),
  211225. internal (0)
  211226. {
  211227. }
  211228. MidiInput::~MidiInput()
  211229. {
  211230. delete static_cast <MidiInThread*> (internal);
  211231. }
  211232. void MidiInput::start()
  211233. {
  211234. static_cast <MidiInThread*> (internal)->start();
  211235. }
  211236. void MidiInput::stop()
  211237. {
  211238. static_cast <MidiInThread*> (internal)->stop();
  211239. }
  211240. struct MidiOutHandle
  211241. {
  211242. int refCount;
  211243. UINT deviceId;
  211244. HMIDIOUT handle;
  211245. static Array<MidiOutHandle*> activeHandles;
  211246. juce_UseDebuggingNewOperator
  211247. };
  211248. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211249. const StringArray MidiOutput::getDevices()
  211250. {
  211251. StringArray s;
  211252. const int num = midiOutGetNumDevs();
  211253. for (int i = 0; i < num; ++i)
  211254. {
  211255. MIDIOUTCAPS mc;
  211256. zerostruct (mc);
  211257. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211258. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211259. }
  211260. return s;
  211261. }
  211262. int MidiOutput::getDefaultDeviceIndex()
  211263. {
  211264. const int num = midiOutGetNumDevs();
  211265. int n = 0;
  211266. for (int i = 0; i < num; ++i)
  211267. {
  211268. MIDIOUTCAPS mc;
  211269. zerostruct (mc);
  211270. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211271. {
  211272. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211273. return n;
  211274. ++n;
  211275. }
  211276. }
  211277. return 0;
  211278. }
  211279. MidiOutput* MidiOutput::openDevice (int index)
  211280. {
  211281. UINT deviceId = MIDI_MAPPER;
  211282. const int num = midiOutGetNumDevs();
  211283. int i, n = 0;
  211284. for (i = 0; i < num; ++i)
  211285. {
  211286. MIDIOUTCAPS mc;
  211287. zerostruct (mc);
  211288. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211289. {
  211290. // use the microsoft sw synth as a default - best not to allow deviceId
  211291. // to be MIDI_MAPPER, or else device sharing breaks
  211292. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211293. deviceId = i;
  211294. if (index == n)
  211295. {
  211296. deviceId = i;
  211297. break;
  211298. }
  211299. ++n;
  211300. }
  211301. }
  211302. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211303. {
  211304. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211305. if (han != 0 && han->deviceId == deviceId)
  211306. {
  211307. han->refCount++;
  211308. MidiOutput* const out = new MidiOutput();
  211309. out->internal = han;
  211310. return out;
  211311. }
  211312. }
  211313. for (i = 4; --i >= 0;)
  211314. {
  211315. HMIDIOUT h = 0;
  211316. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211317. if (res == MMSYSERR_NOERROR)
  211318. {
  211319. MidiOutHandle* const han = new MidiOutHandle();
  211320. han->deviceId = deviceId;
  211321. han->refCount = 1;
  211322. han->handle = h;
  211323. MidiOutHandle::activeHandles.add (han);
  211324. MidiOutput* const out = new MidiOutput();
  211325. out->internal = han;
  211326. return out;
  211327. }
  211328. else if (res == MMSYSERR_ALLOCATED)
  211329. {
  211330. Sleep (100);
  211331. }
  211332. else
  211333. {
  211334. break;
  211335. }
  211336. }
  211337. return 0;
  211338. }
  211339. MidiOutput::~MidiOutput()
  211340. {
  211341. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211342. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211343. {
  211344. midiOutClose (h->handle);
  211345. MidiOutHandle::activeHandles.removeValue (h);
  211346. delete h;
  211347. }
  211348. }
  211349. void MidiOutput::reset()
  211350. {
  211351. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211352. midiOutReset (h->handle);
  211353. }
  211354. bool MidiOutput::getVolume (float& leftVol,
  211355. float& rightVol)
  211356. {
  211357. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211358. DWORD n;
  211359. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211360. {
  211361. const unsigned short* const nn = (const unsigned short*) &n;
  211362. rightVol = nn[0] / (float) 0xffff;
  211363. leftVol = nn[1] / (float) 0xffff;
  211364. return true;
  211365. }
  211366. else
  211367. {
  211368. rightVol = leftVol = 1.0f;
  211369. return false;
  211370. }
  211371. }
  211372. void MidiOutput::setVolume (float leftVol,
  211373. float rightVol)
  211374. {
  211375. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211376. DWORD n;
  211377. unsigned short* const nn = (unsigned short*) &n;
  211378. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211379. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211380. midiOutSetVolume (handle->handle, n);
  211381. }
  211382. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211383. {
  211384. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211385. if (message.getRawDataSize() > 3
  211386. || message.isSysEx())
  211387. {
  211388. MIDIHDR h;
  211389. zerostruct (h);
  211390. h.lpData = (char*) message.getRawData();
  211391. h.dwBufferLength = message.getRawDataSize();
  211392. h.dwBytesRecorded = message.getRawDataSize();
  211393. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211394. {
  211395. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211396. if (res == MMSYSERR_NOERROR)
  211397. {
  211398. while ((h.dwFlags & MHDR_DONE) == 0)
  211399. Sleep (1);
  211400. int count = 500; // 1 sec timeout
  211401. while (--count >= 0)
  211402. {
  211403. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211404. if (res == MIDIERR_STILLPLAYING)
  211405. Sleep (2);
  211406. else
  211407. break;
  211408. }
  211409. }
  211410. }
  211411. }
  211412. else
  211413. {
  211414. midiOutShortMsg (handle->handle,
  211415. *(unsigned int*) message.getRawData());
  211416. }
  211417. }
  211418. #endif
  211419. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211420. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211421. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211422. // compiled on its own).
  211423. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211424. #undef WINDOWS
  211425. // #define ASIO_DEBUGGING
  211426. #ifdef ASIO_DEBUGGING
  211427. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211428. #else
  211429. #define log(a) {}
  211430. #endif
  211431. #ifdef ASIO_DEBUGGING
  211432. static void logError (const String& context, long error)
  211433. {
  211434. String err ("unknown error");
  211435. if (error == ASE_NotPresent)
  211436. err = "Not Present";
  211437. else if (error == ASE_HWMalfunction)
  211438. err = "Hardware Malfunction";
  211439. else if (error == ASE_InvalidParameter)
  211440. err = "Invalid Parameter";
  211441. else if (error == ASE_InvalidMode)
  211442. err = "Invalid Mode";
  211443. else if (error == ASE_SPNotAdvancing)
  211444. err = "Sample position not advancing";
  211445. else if (error == ASE_NoClock)
  211446. err = "No Clock";
  211447. else if (error == ASE_NoMemory)
  211448. err = "Out of memory";
  211449. log ("!!error: " + context + " - " + err);
  211450. }
  211451. #else
  211452. #define logError(a, b) {}
  211453. #endif
  211454. class ASIOAudioIODevice;
  211455. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211456. static const int maxASIOChannels = 160;
  211457. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211458. private Timer
  211459. {
  211460. public:
  211461. Component ourWindow;
  211462. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211463. const String& optionalDllForDirectLoading_)
  211464. : AudioIODevice (name_, "ASIO"),
  211465. asioObject (0),
  211466. classId (classId_),
  211467. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211468. currentBitDepth (16),
  211469. currentSampleRate (0),
  211470. isOpen_ (false),
  211471. isStarted (false),
  211472. postOutput (true),
  211473. insideControlPanelModalLoop (false),
  211474. shouldUsePreferredSize (false)
  211475. {
  211476. name = name_;
  211477. ourWindow.addToDesktop (0);
  211478. windowHandle = ourWindow.getWindowHandle();
  211479. jassert (currentASIODev [slotNumber] == 0);
  211480. currentASIODev [slotNumber] = this;
  211481. openDevice();
  211482. }
  211483. ~ASIOAudioIODevice()
  211484. {
  211485. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211486. if (currentASIODev[i] == this)
  211487. currentASIODev[i] = 0;
  211488. close();
  211489. log ("ASIO - exiting");
  211490. removeCurrentDriver();
  211491. }
  211492. void updateSampleRates()
  211493. {
  211494. // find a list of sample rates..
  211495. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211496. sampleRates.clear();
  211497. if (asioObject != 0)
  211498. {
  211499. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211500. {
  211501. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211502. if (err == 0)
  211503. {
  211504. sampleRates.add ((int) possibleSampleRates[index]);
  211505. log ("rate: " + String ((int) possibleSampleRates[index]));
  211506. }
  211507. else if (err != ASE_NoClock)
  211508. {
  211509. logError ("CanSampleRate", err);
  211510. }
  211511. }
  211512. if (sampleRates.size() == 0)
  211513. {
  211514. double cr = 0;
  211515. const long err = asioObject->getSampleRate (&cr);
  211516. log ("No sample rates supported - current rate: " + String ((int) cr));
  211517. if (err == 0)
  211518. sampleRates.add ((int) cr);
  211519. }
  211520. }
  211521. }
  211522. const StringArray getOutputChannelNames()
  211523. {
  211524. return outputChannelNames;
  211525. }
  211526. const StringArray getInputChannelNames()
  211527. {
  211528. return inputChannelNames;
  211529. }
  211530. int getNumSampleRates()
  211531. {
  211532. return sampleRates.size();
  211533. }
  211534. double getSampleRate (int index)
  211535. {
  211536. return sampleRates [index];
  211537. }
  211538. int getNumBufferSizesAvailable()
  211539. {
  211540. return bufferSizes.size();
  211541. }
  211542. int getBufferSizeSamples (int index)
  211543. {
  211544. return bufferSizes [index];
  211545. }
  211546. int getDefaultBufferSize()
  211547. {
  211548. return preferredSize;
  211549. }
  211550. const String open (const BigInteger& inputChannels,
  211551. const BigInteger& outputChannels,
  211552. double sr,
  211553. int bufferSizeSamples)
  211554. {
  211555. close();
  211556. currentCallback = 0;
  211557. if (bufferSizeSamples <= 0)
  211558. shouldUsePreferredSize = true;
  211559. if (asioObject == 0 || ! isASIOOpen)
  211560. {
  211561. log ("Warning: device not open");
  211562. const String err (openDevice());
  211563. if (asioObject == 0 || ! isASIOOpen)
  211564. return err;
  211565. }
  211566. isStarted = false;
  211567. bufferIndex = -1;
  211568. long err = 0;
  211569. long newPreferredSize = 0;
  211570. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  211571. minSize = 0;
  211572. maxSize = 0;
  211573. newPreferredSize = 0;
  211574. granularity = 0;
  211575. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  211576. {
  211577. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  211578. shouldUsePreferredSize = true;
  211579. preferredSize = newPreferredSize;
  211580. }
  211581. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  211582. // dynamic changes to the buffer size...
  211583. shouldUsePreferredSize = shouldUsePreferredSize
  211584. || getName().containsIgnoreCase ("Digidesign");
  211585. if (shouldUsePreferredSize)
  211586. {
  211587. log ("Using preferred size for buffer..");
  211588. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211589. {
  211590. bufferSizeSamples = preferredSize;
  211591. }
  211592. else
  211593. {
  211594. bufferSizeSamples = 1024;
  211595. logError ("GetBufferSize1", err);
  211596. }
  211597. shouldUsePreferredSize = false;
  211598. }
  211599. int sampleRate = roundDoubleToInt (sr);
  211600. currentSampleRate = sampleRate;
  211601. currentBlockSizeSamples = bufferSizeSamples;
  211602. currentChansOut.clear();
  211603. currentChansIn.clear();
  211604. zeromem (inBuffers, sizeof (inBuffers));
  211605. zeromem (outBuffers, sizeof (outBuffers));
  211606. updateSampleRates();
  211607. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  211608. sampleRate = sampleRates[0];
  211609. jassert (sampleRate != 0);
  211610. if (sampleRate == 0)
  211611. sampleRate = 44100;
  211612. long numSources = 32;
  211613. ASIOClockSource clocks[32];
  211614. zeromem (clocks, sizeof (clocks));
  211615. asioObject->getClockSources (clocks, &numSources);
  211616. bool isSourceSet = false;
  211617. // careful not to remove this loop because it does more than just logging!
  211618. int i;
  211619. for (i = 0; i < numSources; ++i)
  211620. {
  211621. String s ("clock: ");
  211622. s += clocks[i].name;
  211623. if (clocks[i].isCurrentSource)
  211624. {
  211625. isSourceSet = true;
  211626. s << " (cur)";
  211627. }
  211628. log (s);
  211629. }
  211630. if (numSources > 1 && ! isSourceSet)
  211631. {
  211632. log ("setting clock source");
  211633. asioObject->setClockSource (clocks[0].index);
  211634. Thread::sleep (20);
  211635. }
  211636. else
  211637. {
  211638. if (numSources == 0)
  211639. {
  211640. log ("ASIO - no clock sources!");
  211641. }
  211642. }
  211643. double cr = 0;
  211644. err = asioObject->getSampleRate (&cr);
  211645. if (err == 0)
  211646. {
  211647. currentSampleRate = cr;
  211648. }
  211649. else
  211650. {
  211651. logError ("GetSampleRate", err);
  211652. currentSampleRate = 0;
  211653. }
  211654. error = String::empty;
  211655. needToReset = false;
  211656. isReSync = false;
  211657. err = 0;
  211658. bool buffersCreated = false;
  211659. if (currentSampleRate != sampleRate)
  211660. {
  211661. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  211662. err = asioObject->setSampleRate (sampleRate);
  211663. if (err == ASE_NoClock && numSources > 0)
  211664. {
  211665. log ("trying to set a clock source..");
  211666. Thread::sleep (10);
  211667. err = asioObject->setClockSource (clocks[0].index);
  211668. if (err != 0)
  211669. {
  211670. logError ("SetClock", err);
  211671. }
  211672. Thread::sleep (10);
  211673. err = asioObject->setSampleRate (sampleRate);
  211674. }
  211675. }
  211676. if (err == 0)
  211677. {
  211678. currentSampleRate = sampleRate;
  211679. if (needToReset)
  211680. {
  211681. if (isReSync)
  211682. {
  211683. log ("Resync request");
  211684. }
  211685. log ("! Resetting ASIO after sample rate change");
  211686. removeCurrentDriver();
  211687. loadDriver();
  211688. const String error (initDriver());
  211689. if (error.isNotEmpty())
  211690. {
  211691. log ("ASIOInit: " + error);
  211692. }
  211693. needToReset = false;
  211694. isReSync = false;
  211695. }
  211696. numActiveInputChans = 0;
  211697. numActiveOutputChans = 0;
  211698. ASIOBufferInfo* info = bufferInfos;
  211699. int i;
  211700. for (i = 0; i < totalNumInputChans; ++i)
  211701. {
  211702. if (inputChannels[i])
  211703. {
  211704. currentChansIn.setBit (i);
  211705. info->isInput = 1;
  211706. info->channelNum = i;
  211707. info->buffers[0] = info->buffers[1] = 0;
  211708. ++info;
  211709. ++numActiveInputChans;
  211710. }
  211711. }
  211712. for (i = 0; i < totalNumOutputChans; ++i)
  211713. {
  211714. if (outputChannels[i])
  211715. {
  211716. currentChansOut.setBit (i);
  211717. info->isInput = 0;
  211718. info->channelNum = i;
  211719. info->buffers[0] = info->buffers[1] = 0;
  211720. ++info;
  211721. ++numActiveOutputChans;
  211722. }
  211723. }
  211724. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  211725. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211726. if (currentASIODev[0] == this)
  211727. {
  211728. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211729. callbacks.asioMessage = &asioMessagesCallback0;
  211730. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211731. }
  211732. else if (currentASIODev[1] == this)
  211733. {
  211734. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211735. callbacks.asioMessage = &asioMessagesCallback1;
  211736. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211737. }
  211738. else if (currentASIODev[2] == this)
  211739. {
  211740. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211741. callbacks.asioMessage = &asioMessagesCallback2;
  211742. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211743. }
  211744. else
  211745. {
  211746. jassertfalse;
  211747. }
  211748. log ("disposing buffers");
  211749. err = asioObject->disposeBuffers();
  211750. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  211751. err = asioObject->createBuffers (bufferInfos,
  211752. totalBuffers,
  211753. currentBlockSizeSamples,
  211754. &callbacks);
  211755. if (err != 0)
  211756. {
  211757. currentBlockSizeSamples = preferredSize;
  211758. logError ("create buffers 2", err);
  211759. asioObject->disposeBuffers();
  211760. err = asioObject->createBuffers (bufferInfos,
  211761. totalBuffers,
  211762. currentBlockSizeSamples,
  211763. &callbacks);
  211764. }
  211765. if (err == 0)
  211766. {
  211767. buffersCreated = true;
  211768. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  211769. int n = 0;
  211770. Array <int> types;
  211771. currentBitDepth = 16;
  211772. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  211773. {
  211774. if (inputChannels[i])
  211775. {
  211776. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  211777. ASIOChannelInfo channelInfo;
  211778. zerostruct (channelInfo);
  211779. channelInfo.channel = i;
  211780. channelInfo.isInput = 1;
  211781. asioObject->getChannelInfo (&channelInfo);
  211782. types.addIfNotAlreadyThere (channelInfo.type);
  211783. typeToFormatParameters (channelInfo.type,
  211784. inputChannelBitDepths[n],
  211785. inputChannelBytesPerSample[n],
  211786. inputChannelIsFloat[n],
  211787. inputChannelLittleEndian[n]);
  211788. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  211789. ++n;
  211790. }
  211791. }
  211792. jassert (numActiveInputChans == n);
  211793. n = 0;
  211794. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  211795. {
  211796. if (outputChannels[i])
  211797. {
  211798. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  211799. ASIOChannelInfo channelInfo;
  211800. zerostruct (channelInfo);
  211801. channelInfo.channel = i;
  211802. channelInfo.isInput = 0;
  211803. asioObject->getChannelInfo (&channelInfo);
  211804. types.addIfNotAlreadyThere (channelInfo.type);
  211805. typeToFormatParameters (channelInfo.type,
  211806. outputChannelBitDepths[n],
  211807. outputChannelBytesPerSample[n],
  211808. outputChannelIsFloat[n],
  211809. outputChannelLittleEndian[n]);
  211810. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  211811. ++n;
  211812. }
  211813. }
  211814. jassert (numActiveOutputChans == n);
  211815. for (i = types.size(); --i >= 0;)
  211816. {
  211817. log ("channel format: " + String (types[i]));
  211818. }
  211819. jassert (n <= totalBuffers);
  211820. for (i = 0; i < numActiveOutputChans; ++i)
  211821. {
  211822. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  211823. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  211824. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  211825. {
  211826. log ("!! Null buffers");
  211827. }
  211828. else
  211829. {
  211830. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  211831. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  211832. }
  211833. }
  211834. inputLatency = outputLatency = 0;
  211835. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211836. {
  211837. log ("ASIO - no latencies");
  211838. }
  211839. else
  211840. {
  211841. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  211842. }
  211843. isOpen_ = true;
  211844. log ("starting ASIO");
  211845. calledback = false;
  211846. err = asioObject->start();
  211847. if (err != 0)
  211848. {
  211849. isOpen_ = false;
  211850. log ("ASIO - stop on failure");
  211851. Thread::sleep (10);
  211852. asioObject->stop();
  211853. error = "Can't start device";
  211854. Thread::sleep (10);
  211855. }
  211856. else
  211857. {
  211858. int count = 300;
  211859. while (--count > 0 && ! calledback)
  211860. Thread::sleep (10);
  211861. isStarted = true;
  211862. if (! calledback)
  211863. {
  211864. error = "Device didn't start correctly";
  211865. log ("ASIO didn't callback - stopping..");
  211866. asioObject->stop();
  211867. }
  211868. }
  211869. }
  211870. else
  211871. {
  211872. error = "Can't create i/o buffers";
  211873. }
  211874. }
  211875. else
  211876. {
  211877. error = "Can't set sample rate: ";
  211878. error << sampleRate;
  211879. }
  211880. if (error.isNotEmpty())
  211881. {
  211882. logError (error, err);
  211883. if (asioObject != 0 && buffersCreated)
  211884. asioObject->disposeBuffers();
  211885. Thread::sleep (20);
  211886. isStarted = false;
  211887. isOpen_ = false;
  211888. const String errorCopy (error);
  211889. close(); // (this resets the error string)
  211890. error = errorCopy;
  211891. }
  211892. needToReset = false;
  211893. isReSync = false;
  211894. return error;
  211895. }
  211896. void close()
  211897. {
  211898. error = String::empty;
  211899. stopTimer();
  211900. stop();
  211901. if (isASIOOpen && isOpen_)
  211902. {
  211903. const ScopedLock sl (callbackLock);
  211904. isOpen_ = false;
  211905. isStarted = false;
  211906. needToReset = false;
  211907. isReSync = false;
  211908. log ("ASIO - stopping");
  211909. if (asioObject != 0)
  211910. {
  211911. Thread::sleep (20);
  211912. asioObject->stop();
  211913. Thread::sleep (10);
  211914. asioObject->disposeBuffers();
  211915. }
  211916. Thread::sleep (10);
  211917. }
  211918. }
  211919. bool isOpen()
  211920. {
  211921. return isOpen_ || insideControlPanelModalLoop;
  211922. }
  211923. int getCurrentBufferSizeSamples()
  211924. {
  211925. return currentBlockSizeSamples;
  211926. }
  211927. double getCurrentSampleRate()
  211928. {
  211929. return currentSampleRate;
  211930. }
  211931. const BigInteger getActiveOutputChannels() const
  211932. {
  211933. return currentChansOut;
  211934. }
  211935. const BigInteger getActiveInputChannels() const
  211936. {
  211937. return currentChansIn;
  211938. }
  211939. int getCurrentBitDepth()
  211940. {
  211941. return currentBitDepth;
  211942. }
  211943. int getOutputLatencyInSamples()
  211944. {
  211945. return outputLatency + currentBlockSizeSamples / 4;
  211946. }
  211947. int getInputLatencyInSamples()
  211948. {
  211949. return inputLatency + currentBlockSizeSamples / 4;
  211950. }
  211951. void start (AudioIODeviceCallback* callback)
  211952. {
  211953. if (callback != 0)
  211954. {
  211955. callback->audioDeviceAboutToStart (this);
  211956. const ScopedLock sl (callbackLock);
  211957. currentCallback = callback;
  211958. }
  211959. }
  211960. void stop()
  211961. {
  211962. AudioIODeviceCallback* const lastCallback = currentCallback;
  211963. {
  211964. const ScopedLock sl (callbackLock);
  211965. currentCallback = 0;
  211966. }
  211967. if (lastCallback != 0)
  211968. lastCallback->audioDeviceStopped();
  211969. }
  211970. bool isPlaying()
  211971. {
  211972. return isASIOOpen && (currentCallback != 0);
  211973. }
  211974. const String getLastError()
  211975. {
  211976. return error;
  211977. }
  211978. bool hasControlPanel() const
  211979. {
  211980. return true;
  211981. }
  211982. bool showControlPanel()
  211983. {
  211984. log ("ASIO - showing control panel");
  211985. Component modalWindow (String::empty);
  211986. modalWindow.setOpaque (true);
  211987. modalWindow.addToDesktop (0);
  211988. modalWindow.enterModalState();
  211989. bool done = false;
  211990. JUCE_TRY
  211991. {
  211992. // are there are devices that need to be closed before showing their control panel?
  211993. // close();
  211994. insideControlPanelModalLoop = true;
  211995. const uint32 started = Time::getMillisecondCounter();
  211996. if (asioObject != 0)
  211997. {
  211998. asioObject->controlPanel();
  211999. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212000. log ("spent: " + String (spent));
  212001. if (spent > 300)
  212002. {
  212003. shouldUsePreferredSize = true;
  212004. done = true;
  212005. }
  212006. }
  212007. }
  212008. JUCE_CATCH_ALL
  212009. insideControlPanelModalLoop = false;
  212010. return done;
  212011. }
  212012. void resetRequest() throw()
  212013. {
  212014. needToReset = true;
  212015. }
  212016. void resyncRequest() throw()
  212017. {
  212018. needToReset = true;
  212019. isReSync = true;
  212020. }
  212021. void timerCallback()
  212022. {
  212023. if (! insideControlPanelModalLoop)
  212024. {
  212025. stopTimer();
  212026. // used to cause a reset
  212027. log ("! ASIO restart request!");
  212028. if (isOpen_)
  212029. {
  212030. AudioIODeviceCallback* const oldCallback = currentCallback;
  212031. close();
  212032. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212033. currentSampleRate, currentBlockSizeSamples);
  212034. if (oldCallback != 0)
  212035. start (oldCallback);
  212036. }
  212037. }
  212038. else
  212039. {
  212040. startTimer (100);
  212041. }
  212042. }
  212043. juce_UseDebuggingNewOperator
  212044. private:
  212045. IASIO* volatile asioObject;
  212046. ASIOCallbacks callbacks;
  212047. void* windowHandle;
  212048. CLSID classId;
  212049. const String optionalDllForDirectLoading;
  212050. String error;
  212051. long totalNumInputChans, totalNumOutputChans;
  212052. StringArray inputChannelNames, outputChannelNames;
  212053. Array<int> sampleRates, bufferSizes;
  212054. long inputLatency, outputLatency;
  212055. long minSize, maxSize, preferredSize, granularity;
  212056. int volatile currentBlockSizeSamples;
  212057. int volatile currentBitDepth;
  212058. double volatile currentSampleRate;
  212059. BigInteger currentChansOut, currentChansIn;
  212060. AudioIODeviceCallback* volatile currentCallback;
  212061. CriticalSection callbackLock;
  212062. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212063. float* inBuffers [maxASIOChannels];
  212064. float* outBuffers [maxASIOChannels];
  212065. int inputChannelBitDepths [maxASIOChannels];
  212066. int outputChannelBitDepths [maxASIOChannels];
  212067. int inputChannelBytesPerSample [maxASIOChannels];
  212068. int outputChannelBytesPerSample [maxASIOChannels];
  212069. bool inputChannelIsFloat [maxASIOChannels];
  212070. bool outputChannelIsFloat [maxASIOChannels];
  212071. bool inputChannelLittleEndian [maxASIOChannels];
  212072. bool outputChannelLittleEndian [maxASIOChannels];
  212073. WaitableEvent event1;
  212074. HeapBlock <float> tempBuffer;
  212075. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212076. bool isOpen_, isStarted;
  212077. bool volatile isASIOOpen;
  212078. bool volatile calledback;
  212079. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212080. bool volatile insideControlPanelModalLoop;
  212081. bool volatile shouldUsePreferredSize;
  212082. void removeCurrentDriver()
  212083. {
  212084. if (asioObject != 0)
  212085. {
  212086. asioObject->Release();
  212087. asioObject = 0;
  212088. }
  212089. }
  212090. bool loadDriver()
  212091. {
  212092. removeCurrentDriver();
  212093. JUCE_TRY
  212094. {
  212095. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212096. classId, (void**) &asioObject) == S_OK)
  212097. {
  212098. return true;
  212099. }
  212100. // If a class isn't registered but we have a path for it, we can fallback to
  212101. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212102. if (optionalDllForDirectLoading.isNotEmpty())
  212103. {
  212104. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  212105. if (h != 0)
  212106. {
  212107. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212108. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212109. if (dllGetClassObject != 0)
  212110. {
  212111. IClassFactory* classFactory = 0;
  212112. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212113. if (classFactory != 0)
  212114. {
  212115. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212116. classFactory->Release();
  212117. }
  212118. return asioObject != 0;
  212119. }
  212120. }
  212121. }
  212122. }
  212123. JUCE_CATCH_ALL
  212124. asioObject = 0;
  212125. return false;
  212126. }
  212127. const String initDriver()
  212128. {
  212129. if (asioObject != 0)
  212130. {
  212131. char buffer [256];
  212132. zeromem (buffer, sizeof (buffer));
  212133. if (! asioObject->init (windowHandle))
  212134. {
  212135. asioObject->getErrorMessage (buffer);
  212136. return String (buffer, sizeof (buffer) - 1);
  212137. }
  212138. // just in case any daft drivers expect this to be called..
  212139. asioObject->getDriverName (buffer);
  212140. return String::empty;
  212141. }
  212142. return "No Driver";
  212143. }
  212144. const String openDevice()
  212145. {
  212146. // use this in case the driver starts opening dialog boxes..
  212147. Component modalWindow (String::empty);
  212148. modalWindow.setOpaque (true);
  212149. modalWindow.addToDesktop (0);
  212150. modalWindow.enterModalState();
  212151. // open the device and get its info..
  212152. log ("opening ASIO device: " + getName());
  212153. needToReset = false;
  212154. isReSync = false;
  212155. outputChannelNames.clear();
  212156. inputChannelNames.clear();
  212157. bufferSizes.clear();
  212158. sampleRates.clear();
  212159. isASIOOpen = false;
  212160. isOpen_ = false;
  212161. totalNumInputChans = 0;
  212162. totalNumOutputChans = 0;
  212163. numActiveInputChans = 0;
  212164. numActiveOutputChans = 0;
  212165. currentCallback = 0;
  212166. error = String::empty;
  212167. if (getName().isEmpty())
  212168. return error;
  212169. long err = 0;
  212170. if (loadDriver())
  212171. {
  212172. if ((error = initDriver()).isEmpty())
  212173. {
  212174. numActiveInputChans = 0;
  212175. numActiveOutputChans = 0;
  212176. totalNumInputChans = 0;
  212177. totalNumOutputChans = 0;
  212178. if (asioObject != 0
  212179. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212180. {
  212181. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212182. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212183. {
  212184. // find a list of buffer sizes..
  212185. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212186. if (granularity >= 0)
  212187. {
  212188. granularity = jmax (1, (int) granularity);
  212189. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212190. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212191. }
  212192. else if (granularity < 0)
  212193. {
  212194. for (int i = 0; i < 18; ++i)
  212195. {
  212196. const int s = (1 << i);
  212197. if (s >= minSize && s <= maxSize)
  212198. bufferSizes.add (s);
  212199. }
  212200. }
  212201. if (! bufferSizes.contains (preferredSize))
  212202. bufferSizes.insert (0, preferredSize);
  212203. double currentRate = 0;
  212204. asioObject->getSampleRate (&currentRate);
  212205. if (currentRate <= 0.0 || currentRate > 192001.0)
  212206. {
  212207. log ("setting sample rate");
  212208. err = asioObject->setSampleRate (44100.0);
  212209. if (err != 0)
  212210. {
  212211. logError ("setting sample rate", err);
  212212. }
  212213. asioObject->getSampleRate (&currentRate);
  212214. }
  212215. currentSampleRate = currentRate;
  212216. postOutput = (asioObject->outputReady() == 0);
  212217. if (postOutput)
  212218. {
  212219. log ("ASIO outputReady = ok");
  212220. }
  212221. updateSampleRates();
  212222. // ..because cubase does it at this point
  212223. inputLatency = outputLatency = 0;
  212224. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212225. {
  212226. log ("ASIO - no latencies");
  212227. }
  212228. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212229. // create some dummy buffers now.. because cubase does..
  212230. numActiveInputChans = 0;
  212231. numActiveOutputChans = 0;
  212232. ASIOBufferInfo* info = bufferInfos;
  212233. int i, numChans = 0;
  212234. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212235. {
  212236. info->isInput = 1;
  212237. info->channelNum = i;
  212238. info->buffers[0] = info->buffers[1] = 0;
  212239. ++info;
  212240. ++numChans;
  212241. }
  212242. const int outputBufferIndex = numChans;
  212243. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212244. {
  212245. info->isInput = 0;
  212246. info->channelNum = i;
  212247. info->buffers[0] = info->buffers[1] = 0;
  212248. ++info;
  212249. ++numChans;
  212250. }
  212251. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212252. if (currentASIODev[0] == this)
  212253. {
  212254. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212255. callbacks.asioMessage = &asioMessagesCallback0;
  212256. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212257. }
  212258. else if (currentASIODev[1] == this)
  212259. {
  212260. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212261. callbacks.asioMessage = &asioMessagesCallback1;
  212262. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212263. }
  212264. else if (currentASIODev[2] == this)
  212265. {
  212266. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212267. callbacks.asioMessage = &asioMessagesCallback2;
  212268. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212269. }
  212270. else
  212271. {
  212272. jassertfalse;
  212273. }
  212274. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212275. if (preferredSize > 0)
  212276. {
  212277. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212278. if (err != 0)
  212279. {
  212280. logError ("dummy buffers", err);
  212281. }
  212282. }
  212283. long newInps = 0, newOuts = 0;
  212284. asioObject->getChannels (&newInps, &newOuts);
  212285. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212286. {
  212287. totalNumInputChans = newInps;
  212288. totalNumOutputChans = newOuts;
  212289. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212290. }
  212291. updateSampleRates();
  212292. ASIOChannelInfo channelInfo;
  212293. channelInfo.type = 0;
  212294. for (i = 0; i < totalNumInputChans; ++i)
  212295. {
  212296. zerostruct (channelInfo);
  212297. channelInfo.channel = i;
  212298. channelInfo.isInput = 1;
  212299. asioObject->getChannelInfo (&channelInfo);
  212300. inputChannelNames.add (String (channelInfo.name));
  212301. }
  212302. for (i = 0; i < totalNumOutputChans; ++i)
  212303. {
  212304. zerostruct (channelInfo);
  212305. channelInfo.channel = i;
  212306. channelInfo.isInput = 0;
  212307. asioObject->getChannelInfo (&channelInfo);
  212308. outputChannelNames.add (String (channelInfo.name));
  212309. typeToFormatParameters (channelInfo.type,
  212310. outputChannelBitDepths[i],
  212311. outputChannelBytesPerSample[i],
  212312. outputChannelIsFloat[i],
  212313. outputChannelLittleEndian[i]);
  212314. if (i < 2)
  212315. {
  212316. // clear the channels that are used with the dummy stuff
  212317. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212318. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212319. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212320. }
  212321. }
  212322. outputChannelNames.trim();
  212323. inputChannelNames.trim();
  212324. outputChannelNames.appendNumbersToDuplicates (false, true);
  212325. inputChannelNames.appendNumbersToDuplicates (false, true);
  212326. // start and stop because cubase does it..
  212327. asioObject->getLatencies (&inputLatency, &outputLatency);
  212328. if ((err = asioObject->start()) != 0)
  212329. {
  212330. // ignore an error here, as it might start later after setting other stuff up
  212331. logError ("ASIO start", err);
  212332. }
  212333. Thread::sleep (100);
  212334. asioObject->stop();
  212335. }
  212336. else
  212337. {
  212338. error = "Can't detect buffer sizes";
  212339. }
  212340. }
  212341. else
  212342. {
  212343. error = "Can't detect asio channels";
  212344. }
  212345. }
  212346. }
  212347. else
  212348. {
  212349. error = "No such device";
  212350. }
  212351. if (error.isNotEmpty())
  212352. {
  212353. logError (error, err);
  212354. if (asioObject != 0)
  212355. asioObject->disposeBuffers();
  212356. removeCurrentDriver();
  212357. isASIOOpen = false;
  212358. }
  212359. else
  212360. {
  212361. isASIOOpen = true;
  212362. log ("ASIO device open");
  212363. }
  212364. isOpen_ = false;
  212365. needToReset = false;
  212366. isReSync = false;
  212367. return error;
  212368. }
  212369. void callback (const long index)
  212370. {
  212371. if (isStarted)
  212372. {
  212373. bufferIndex = index;
  212374. processBuffer();
  212375. }
  212376. else
  212377. {
  212378. if (postOutput && (asioObject != 0))
  212379. asioObject->outputReady();
  212380. }
  212381. calledback = true;
  212382. }
  212383. void processBuffer()
  212384. {
  212385. const ASIOBufferInfo* const infos = bufferInfos;
  212386. const int bi = bufferIndex;
  212387. const ScopedLock sl (callbackLock);
  212388. if (needToReset)
  212389. {
  212390. needToReset = false;
  212391. if (isReSync)
  212392. {
  212393. log ("! ASIO resync");
  212394. isReSync = false;
  212395. }
  212396. else
  212397. {
  212398. startTimer (20);
  212399. }
  212400. }
  212401. if (bi >= 0)
  212402. {
  212403. const int samps = currentBlockSizeSamples;
  212404. if (currentCallback != 0)
  212405. {
  212406. int i;
  212407. for (i = 0; i < numActiveInputChans; ++i)
  212408. {
  212409. float* const dst = inBuffers[i];
  212410. jassert (dst != 0);
  212411. const char* const src = (const char*) (infos[i].buffers[bi]);
  212412. if (inputChannelIsFloat[i])
  212413. {
  212414. memcpy (dst, src, samps * sizeof (float));
  212415. }
  212416. else
  212417. {
  212418. jassert (dst == tempBuffer + (samps * i));
  212419. switch (inputChannelBitDepths[i])
  212420. {
  212421. case 16:
  212422. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212423. samps, inputChannelLittleEndian[i]);
  212424. break;
  212425. case 24:
  212426. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212427. samps, inputChannelLittleEndian[i]);
  212428. break;
  212429. case 32:
  212430. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212431. samps, inputChannelLittleEndian[i]);
  212432. break;
  212433. case 64:
  212434. jassertfalse;
  212435. break;
  212436. }
  212437. }
  212438. }
  212439. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  212440. numActiveInputChans,
  212441. outBuffers,
  212442. numActiveOutputChans,
  212443. samps);
  212444. for (i = 0; i < numActiveOutputChans; ++i)
  212445. {
  212446. float* const src = outBuffers[i];
  212447. jassert (src != 0);
  212448. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212449. if (outputChannelIsFloat[i])
  212450. {
  212451. memcpy (dst, src, samps * sizeof (float));
  212452. }
  212453. else
  212454. {
  212455. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212456. switch (outputChannelBitDepths[i])
  212457. {
  212458. case 16:
  212459. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212460. samps, outputChannelLittleEndian[i]);
  212461. break;
  212462. case 24:
  212463. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212464. samps, outputChannelLittleEndian[i]);
  212465. break;
  212466. case 32:
  212467. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212468. samps, outputChannelLittleEndian[i]);
  212469. break;
  212470. case 64:
  212471. jassertfalse;
  212472. break;
  212473. }
  212474. }
  212475. }
  212476. }
  212477. else
  212478. {
  212479. for (int i = 0; i < numActiveOutputChans; ++i)
  212480. {
  212481. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212482. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212483. }
  212484. }
  212485. }
  212486. if (postOutput)
  212487. asioObject->outputReady();
  212488. }
  212489. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212490. {
  212491. if (currentASIODev[0] != 0)
  212492. currentASIODev[0]->callback (index);
  212493. return 0;
  212494. }
  212495. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212496. {
  212497. if (currentASIODev[1] != 0)
  212498. currentASIODev[1]->callback (index);
  212499. return 0;
  212500. }
  212501. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212502. {
  212503. if (currentASIODev[2] != 0)
  212504. currentASIODev[2]->callback (index);
  212505. return 0;
  212506. }
  212507. static void bufferSwitchCallback0 (long index, long)
  212508. {
  212509. if (currentASIODev[0] != 0)
  212510. currentASIODev[0]->callback (index);
  212511. }
  212512. static void bufferSwitchCallback1 (long index, long)
  212513. {
  212514. if (currentASIODev[1] != 0)
  212515. currentASIODev[1]->callback (index);
  212516. }
  212517. static void bufferSwitchCallback2 (long index, long)
  212518. {
  212519. if (currentASIODev[2] != 0)
  212520. currentASIODev[2]->callback (index);
  212521. }
  212522. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  212523. {
  212524. return asioMessagesCallback (selector, value, 0);
  212525. }
  212526. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  212527. {
  212528. return asioMessagesCallback (selector, value, 1);
  212529. }
  212530. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  212531. {
  212532. return asioMessagesCallback (selector, value, 2);
  212533. }
  212534. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  212535. {
  212536. switch (selector)
  212537. {
  212538. case kAsioSelectorSupported:
  212539. if (value == kAsioResetRequest
  212540. || value == kAsioEngineVersion
  212541. || value == kAsioResyncRequest
  212542. || value == kAsioLatenciesChanged
  212543. || value == kAsioSupportsInputMonitor)
  212544. return 1;
  212545. break;
  212546. case kAsioBufferSizeChange:
  212547. break;
  212548. case kAsioResetRequest:
  212549. if (currentASIODev[deviceIndex] != 0)
  212550. currentASIODev[deviceIndex]->resetRequest();
  212551. return 1;
  212552. case kAsioResyncRequest:
  212553. if (currentASIODev[deviceIndex] != 0)
  212554. currentASIODev[deviceIndex]->resyncRequest();
  212555. return 1;
  212556. case kAsioLatenciesChanged:
  212557. return 1;
  212558. case kAsioEngineVersion:
  212559. return 2;
  212560. case kAsioSupportsTimeInfo:
  212561. case kAsioSupportsTimeCode:
  212562. return 0;
  212563. }
  212564. return 0;
  212565. }
  212566. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  212567. {
  212568. }
  212569. static void convertInt16ToFloat (const char* src,
  212570. float* dest,
  212571. const int srcStrideBytes,
  212572. int numSamples,
  212573. const bool littleEndian) throw()
  212574. {
  212575. const double g = 1.0 / 32768.0;
  212576. if (littleEndian)
  212577. {
  212578. while (--numSamples >= 0)
  212579. {
  212580. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  212581. src += srcStrideBytes;
  212582. }
  212583. }
  212584. else
  212585. {
  212586. while (--numSamples >= 0)
  212587. {
  212588. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  212589. src += srcStrideBytes;
  212590. }
  212591. }
  212592. }
  212593. static void convertFloatToInt16 (const float* src,
  212594. char* dest,
  212595. const int dstStrideBytes,
  212596. int numSamples,
  212597. const bool littleEndian) throw()
  212598. {
  212599. const double maxVal = (double) 0x7fff;
  212600. if (littleEndian)
  212601. {
  212602. while (--numSamples >= 0)
  212603. {
  212604. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212605. dest += dstStrideBytes;
  212606. }
  212607. }
  212608. else
  212609. {
  212610. while (--numSamples >= 0)
  212611. {
  212612. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212613. dest += dstStrideBytes;
  212614. }
  212615. }
  212616. }
  212617. static void convertInt24ToFloat (const char* src,
  212618. float* dest,
  212619. const int srcStrideBytes,
  212620. int numSamples,
  212621. const bool littleEndian) throw()
  212622. {
  212623. const double g = 1.0 / 0x7fffff;
  212624. if (littleEndian)
  212625. {
  212626. while (--numSamples >= 0)
  212627. {
  212628. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  212629. src += srcStrideBytes;
  212630. }
  212631. }
  212632. else
  212633. {
  212634. while (--numSamples >= 0)
  212635. {
  212636. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  212637. src += srcStrideBytes;
  212638. }
  212639. }
  212640. }
  212641. static void convertFloatToInt24 (const float* src,
  212642. char* dest,
  212643. const int dstStrideBytes,
  212644. int numSamples,
  212645. const bool littleEndian) throw()
  212646. {
  212647. const double maxVal = (double) 0x7fffff;
  212648. if (littleEndian)
  212649. {
  212650. while (--numSamples >= 0)
  212651. {
  212652. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212653. dest += dstStrideBytes;
  212654. }
  212655. }
  212656. else
  212657. {
  212658. while (--numSamples >= 0)
  212659. {
  212660. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212661. dest += dstStrideBytes;
  212662. }
  212663. }
  212664. }
  212665. static void convertInt32ToFloat (const char* src,
  212666. float* dest,
  212667. const int srcStrideBytes,
  212668. int numSamples,
  212669. const bool littleEndian) throw()
  212670. {
  212671. const double g = 1.0 / 0x7fffffff;
  212672. if (littleEndian)
  212673. {
  212674. while (--numSamples >= 0)
  212675. {
  212676. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  212677. src += srcStrideBytes;
  212678. }
  212679. }
  212680. else
  212681. {
  212682. while (--numSamples >= 0)
  212683. {
  212684. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  212685. src += srcStrideBytes;
  212686. }
  212687. }
  212688. }
  212689. static void convertFloatToInt32 (const float* src,
  212690. char* dest,
  212691. const int dstStrideBytes,
  212692. int numSamples,
  212693. const bool littleEndian) throw()
  212694. {
  212695. const double maxVal = (double) 0x7fffffff;
  212696. if (littleEndian)
  212697. {
  212698. while (--numSamples >= 0)
  212699. {
  212700. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212701. dest += dstStrideBytes;
  212702. }
  212703. }
  212704. else
  212705. {
  212706. while (--numSamples >= 0)
  212707. {
  212708. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212709. dest += dstStrideBytes;
  212710. }
  212711. }
  212712. }
  212713. static void typeToFormatParameters (const long type,
  212714. int& bitDepth,
  212715. int& byteStride,
  212716. bool& formatIsFloat,
  212717. bool& littleEndian) throw()
  212718. {
  212719. bitDepth = 0;
  212720. littleEndian = false;
  212721. formatIsFloat = false;
  212722. switch (type)
  212723. {
  212724. case ASIOSTInt16MSB:
  212725. case ASIOSTInt16LSB:
  212726. case ASIOSTInt32MSB16:
  212727. case ASIOSTInt32LSB16:
  212728. bitDepth = 16; break;
  212729. case ASIOSTFloat32MSB:
  212730. case ASIOSTFloat32LSB:
  212731. formatIsFloat = true;
  212732. bitDepth = 32; break;
  212733. case ASIOSTInt32MSB:
  212734. case ASIOSTInt32LSB:
  212735. bitDepth = 32; break;
  212736. case ASIOSTInt24MSB:
  212737. case ASIOSTInt24LSB:
  212738. case ASIOSTInt32MSB24:
  212739. case ASIOSTInt32LSB24:
  212740. case ASIOSTInt32MSB18:
  212741. case ASIOSTInt32MSB20:
  212742. case ASIOSTInt32LSB18:
  212743. case ASIOSTInt32LSB20:
  212744. bitDepth = 24; break;
  212745. case ASIOSTFloat64MSB:
  212746. case ASIOSTFloat64LSB:
  212747. default:
  212748. bitDepth = 64;
  212749. break;
  212750. }
  212751. switch (type)
  212752. {
  212753. case ASIOSTInt16MSB:
  212754. case ASIOSTInt32MSB16:
  212755. case ASIOSTFloat32MSB:
  212756. case ASIOSTFloat64MSB:
  212757. case ASIOSTInt32MSB:
  212758. case ASIOSTInt32MSB18:
  212759. case ASIOSTInt32MSB20:
  212760. case ASIOSTInt32MSB24:
  212761. case ASIOSTInt24MSB:
  212762. littleEndian = false; break;
  212763. case ASIOSTInt16LSB:
  212764. case ASIOSTInt32LSB16:
  212765. case ASIOSTFloat32LSB:
  212766. case ASIOSTFloat64LSB:
  212767. case ASIOSTInt32LSB:
  212768. case ASIOSTInt32LSB18:
  212769. case ASIOSTInt32LSB20:
  212770. case ASIOSTInt32LSB24:
  212771. case ASIOSTInt24LSB:
  212772. littleEndian = true; break;
  212773. default:
  212774. break;
  212775. }
  212776. switch (type)
  212777. {
  212778. case ASIOSTInt16LSB:
  212779. case ASIOSTInt16MSB:
  212780. byteStride = 2; break;
  212781. case ASIOSTInt24LSB:
  212782. case ASIOSTInt24MSB:
  212783. byteStride = 3; break;
  212784. case ASIOSTInt32MSB16:
  212785. case ASIOSTInt32LSB16:
  212786. case ASIOSTInt32MSB:
  212787. case ASIOSTInt32MSB18:
  212788. case ASIOSTInt32MSB20:
  212789. case ASIOSTInt32MSB24:
  212790. case ASIOSTInt32LSB:
  212791. case ASIOSTInt32LSB18:
  212792. case ASIOSTInt32LSB20:
  212793. case ASIOSTInt32LSB24:
  212794. case ASIOSTFloat32LSB:
  212795. case ASIOSTFloat32MSB:
  212796. byteStride = 4; break;
  212797. case ASIOSTFloat64MSB:
  212798. case ASIOSTFloat64LSB:
  212799. byteStride = 8; break;
  212800. default:
  212801. break;
  212802. }
  212803. }
  212804. };
  212805. class ASIOAudioIODeviceType : public AudioIODeviceType
  212806. {
  212807. public:
  212808. ASIOAudioIODeviceType()
  212809. : AudioIODeviceType ("ASIO"),
  212810. hasScanned (false)
  212811. {
  212812. CoInitialize (0);
  212813. }
  212814. ~ASIOAudioIODeviceType()
  212815. {
  212816. }
  212817. void scanForDevices()
  212818. {
  212819. hasScanned = true;
  212820. deviceNames.clear();
  212821. classIds.clear();
  212822. HKEY hk = 0;
  212823. int index = 0;
  212824. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  212825. {
  212826. for (;;)
  212827. {
  212828. char name [256];
  212829. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  212830. {
  212831. addDriverInfo (name, hk);
  212832. }
  212833. else
  212834. {
  212835. break;
  212836. }
  212837. }
  212838. RegCloseKey (hk);
  212839. }
  212840. }
  212841. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  212842. {
  212843. jassert (hasScanned); // need to call scanForDevices() before doing this
  212844. return deviceNames;
  212845. }
  212846. int getDefaultDeviceIndex (bool) const
  212847. {
  212848. jassert (hasScanned); // need to call scanForDevices() before doing this
  212849. for (int i = deviceNames.size(); --i >= 0;)
  212850. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  212851. return i; // asio4all is a safe choice for a default..
  212852. #if JUCE_DEBUG
  212853. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  212854. return 1; // (the digi m-box driver crashes the app when you run
  212855. // it in the debugger, which can be a bit annoying)
  212856. #endif
  212857. return 0;
  212858. }
  212859. static int findFreeSlot()
  212860. {
  212861. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212862. if (currentASIODev[i] == 0)
  212863. return i;
  212864. jassertfalse; // unfortunately you can only have a finite number
  212865. // of ASIO devices open at the same time..
  212866. return -1;
  212867. }
  212868. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  212869. {
  212870. jassert (hasScanned); // need to call scanForDevices() before doing this
  212871. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  212872. }
  212873. bool hasSeparateInputsAndOutputs() const { return false; }
  212874. AudioIODevice* createDevice (const String& outputDeviceName,
  212875. const String& inputDeviceName)
  212876. {
  212877. // ASIO can't open two different devices for input and output - they must be the same one.
  212878. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  212879. jassert (hasScanned); // need to call scanForDevices() before doing this
  212880. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  212881. : inputDeviceName);
  212882. if (index >= 0)
  212883. {
  212884. const int freeSlot = findFreeSlot();
  212885. if (freeSlot >= 0)
  212886. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  212887. }
  212888. return 0;
  212889. }
  212890. juce_UseDebuggingNewOperator
  212891. private:
  212892. StringArray deviceNames;
  212893. OwnedArray <CLSID> classIds;
  212894. bool hasScanned;
  212895. static bool checkClassIsOk (const String& classId)
  212896. {
  212897. HKEY hk = 0;
  212898. bool ok = false;
  212899. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  212900. {
  212901. int index = 0;
  212902. for (;;)
  212903. {
  212904. WCHAR buf [512];
  212905. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  212906. {
  212907. if (classId.equalsIgnoreCase (buf))
  212908. {
  212909. HKEY subKey, pathKey;
  212910. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212911. {
  212912. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  212913. {
  212914. WCHAR pathName [1024];
  212915. DWORD dtype = REG_SZ;
  212916. DWORD dsize = sizeof (pathName);
  212917. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  212918. ok = File (pathName).exists();
  212919. RegCloseKey (pathKey);
  212920. }
  212921. RegCloseKey (subKey);
  212922. }
  212923. break;
  212924. }
  212925. }
  212926. else
  212927. {
  212928. break;
  212929. }
  212930. }
  212931. RegCloseKey (hk);
  212932. }
  212933. return ok;
  212934. }
  212935. void addDriverInfo (const String& keyName, HKEY hk)
  212936. {
  212937. HKEY subKey;
  212938. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212939. {
  212940. WCHAR buf [256];
  212941. zerostruct (buf);
  212942. DWORD dtype = REG_SZ;
  212943. DWORD dsize = sizeof (buf);
  212944. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212945. {
  212946. if (dsize > 0 && checkClassIsOk (buf))
  212947. {
  212948. CLSID classId;
  212949. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  212950. {
  212951. dtype = REG_SZ;
  212952. dsize = sizeof (buf);
  212953. String deviceName;
  212954. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212955. deviceName = buf;
  212956. else
  212957. deviceName = keyName;
  212958. log ("found " + deviceName);
  212959. deviceNames.add (deviceName);
  212960. classIds.add (new CLSID (classId));
  212961. }
  212962. }
  212963. RegCloseKey (subKey);
  212964. }
  212965. }
  212966. }
  212967. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  212968. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  212969. };
  212970. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  212971. {
  212972. return new ASIOAudioIODeviceType();
  212973. }
  212974. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  212975. void* guid,
  212976. const String& optionalDllForDirectLoading)
  212977. {
  212978. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  212979. if (freeSlot < 0)
  212980. return 0;
  212981. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  212982. }
  212983. #undef log
  212984. #endif
  212985. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  212986. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  212987. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212988. // compiled on its own).
  212989. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  212990. END_JUCE_NAMESPACE
  212991. extern "C"
  212992. {
  212993. // Declare just the minimum number of interfaces for the DSound objects that we need..
  212994. typedef struct typeDSBUFFERDESC
  212995. {
  212996. DWORD dwSize;
  212997. DWORD dwFlags;
  212998. DWORD dwBufferBytes;
  212999. DWORD dwReserved;
  213000. LPWAVEFORMATEX lpwfxFormat;
  213001. GUID guid3DAlgorithm;
  213002. } DSBUFFERDESC;
  213003. struct IDirectSoundBuffer;
  213004. #undef INTERFACE
  213005. #define INTERFACE IDirectSound
  213006. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213007. {
  213008. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213009. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213010. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213011. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213012. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213013. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213014. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213015. STDMETHOD(Compact) (THIS) PURE;
  213016. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213017. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213018. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213019. };
  213020. #undef INTERFACE
  213021. #define INTERFACE IDirectSoundBuffer
  213022. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213023. {
  213024. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213025. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213026. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213027. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213028. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213029. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213030. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213031. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213032. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213033. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213034. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213035. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213036. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213037. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213038. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213039. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213040. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213041. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213042. STDMETHOD(Stop) (THIS) PURE;
  213043. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213044. STDMETHOD(Restore) (THIS) PURE;
  213045. };
  213046. typedef struct typeDSCBUFFERDESC
  213047. {
  213048. DWORD dwSize;
  213049. DWORD dwFlags;
  213050. DWORD dwBufferBytes;
  213051. DWORD dwReserved;
  213052. LPWAVEFORMATEX lpwfxFormat;
  213053. } DSCBUFFERDESC;
  213054. struct IDirectSoundCaptureBuffer;
  213055. #undef INTERFACE
  213056. #define INTERFACE IDirectSoundCapture
  213057. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213058. {
  213059. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213060. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213061. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213062. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213063. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213064. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213065. };
  213066. #undef INTERFACE
  213067. #define INTERFACE IDirectSoundCaptureBuffer
  213068. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213069. {
  213070. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213071. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213072. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213073. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213074. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213075. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213076. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213077. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213078. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213079. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213080. STDMETHOD(Stop) (THIS) PURE;
  213081. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213082. };
  213083. };
  213084. BEGIN_JUCE_NAMESPACE
  213085. static const String getDSErrorMessage (HRESULT hr)
  213086. {
  213087. const char* result = 0;
  213088. switch (hr)
  213089. {
  213090. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213091. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213092. case E_INVALIDARG: result = "Invalid parameter"; break;
  213093. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213094. case E_FAIL: result = "Generic error"; break;
  213095. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213096. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213097. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213098. case E_NOTIMPL: result = "Unsupported function"; break;
  213099. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213100. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213101. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213102. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213103. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213104. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213105. case E_NOINTERFACE: result = "No interface"; break;
  213106. case S_OK: result = "No error"; break;
  213107. default: return "Unknown error: " + String ((int) hr);
  213108. }
  213109. return result;
  213110. }
  213111. #define DS_DEBUGGING 1
  213112. #ifdef DS_DEBUGGING
  213113. #define CATCH JUCE_CATCH_EXCEPTION
  213114. #undef log
  213115. #define log(a) Logger::writeToLog(a);
  213116. #undef logError
  213117. #define logError(a) logDSError(a, __LINE__);
  213118. static void logDSError (HRESULT hr, int lineNum)
  213119. {
  213120. if (hr != S_OK)
  213121. {
  213122. String error ("DS error at line ");
  213123. error << lineNum << " - " << getDSErrorMessage (hr);
  213124. log (error);
  213125. }
  213126. }
  213127. #else
  213128. #define CATCH JUCE_CATCH_ALL
  213129. #define log(a)
  213130. #define logError(a)
  213131. #endif
  213132. #define DSOUND_FUNCTION(functionName, params) \
  213133. typedef HRESULT (WINAPI *type##functionName) params; \
  213134. static type##functionName ds##functionName = 0;
  213135. #define DSOUND_FUNCTION_LOAD(functionName) \
  213136. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213137. jassert (ds##functionName != 0);
  213138. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213139. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213140. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213141. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213142. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213143. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213144. static void initialiseDSoundFunctions()
  213145. {
  213146. if (dsDirectSoundCreate == 0)
  213147. {
  213148. HMODULE h = LoadLibraryA ("dsound.dll");
  213149. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213150. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213151. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213152. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213153. }
  213154. }
  213155. class DSoundInternalOutChannel
  213156. {
  213157. String name;
  213158. LPGUID guid;
  213159. int sampleRate, bufferSizeSamples;
  213160. float* leftBuffer;
  213161. float* rightBuffer;
  213162. IDirectSound* pDirectSound;
  213163. IDirectSoundBuffer* pOutputBuffer;
  213164. DWORD writeOffset;
  213165. int totalBytesPerBuffer;
  213166. int bytesPerBuffer;
  213167. unsigned int lastPlayCursor;
  213168. public:
  213169. int bitDepth;
  213170. bool doneFlag;
  213171. DSoundInternalOutChannel (const String& name_,
  213172. LPGUID guid_,
  213173. int rate,
  213174. int bufferSize,
  213175. float* left,
  213176. float* right)
  213177. : name (name_),
  213178. guid (guid_),
  213179. sampleRate (rate),
  213180. bufferSizeSamples (bufferSize),
  213181. leftBuffer (left),
  213182. rightBuffer (right),
  213183. pDirectSound (0),
  213184. pOutputBuffer (0),
  213185. bitDepth (16)
  213186. {
  213187. }
  213188. ~DSoundInternalOutChannel()
  213189. {
  213190. close();
  213191. }
  213192. void close()
  213193. {
  213194. HRESULT hr;
  213195. if (pOutputBuffer != 0)
  213196. {
  213197. JUCE_TRY
  213198. {
  213199. log ("closing dsound out: " + name);
  213200. hr = pOutputBuffer->Stop();
  213201. logError (hr);
  213202. }
  213203. CATCH
  213204. JUCE_TRY
  213205. {
  213206. hr = pOutputBuffer->Release();
  213207. logError (hr);
  213208. }
  213209. CATCH
  213210. pOutputBuffer = 0;
  213211. }
  213212. if (pDirectSound != 0)
  213213. {
  213214. JUCE_TRY
  213215. {
  213216. hr = pDirectSound->Release();
  213217. logError (hr);
  213218. }
  213219. CATCH
  213220. pDirectSound = 0;
  213221. }
  213222. }
  213223. const String open()
  213224. {
  213225. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213226. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213227. pDirectSound = 0;
  213228. pOutputBuffer = 0;
  213229. writeOffset = 0;
  213230. String error;
  213231. HRESULT hr = E_NOINTERFACE;
  213232. if (dsDirectSoundCreate != 0)
  213233. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213234. if (hr == S_OK)
  213235. {
  213236. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213237. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213238. const int numChannels = 2;
  213239. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213240. logError (hr);
  213241. if (hr == S_OK)
  213242. {
  213243. IDirectSoundBuffer* pPrimaryBuffer;
  213244. DSBUFFERDESC primaryDesc;
  213245. zerostruct (primaryDesc);
  213246. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213247. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213248. primaryDesc.dwBufferBytes = 0;
  213249. primaryDesc.lpwfxFormat = 0;
  213250. log ("opening dsound out step 2");
  213251. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213252. logError (hr);
  213253. if (hr == S_OK)
  213254. {
  213255. WAVEFORMATEX wfFormat;
  213256. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213257. wfFormat.nChannels = (unsigned short) numChannels;
  213258. wfFormat.nSamplesPerSec = sampleRate;
  213259. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213260. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213261. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213262. wfFormat.cbSize = 0;
  213263. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213264. logError (hr);
  213265. if (hr == S_OK)
  213266. {
  213267. DSBUFFERDESC secondaryDesc;
  213268. zerostruct (secondaryDesc);
  213269. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213270. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213271. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213272. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213273. secondaryDesc.lpwfxFormat = &wfFormat;
  213274. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213275. logError (hr);
  213276. if (hr == S_OK)
  213277. {
  213278. log ("opening dsound out step 3");
  213279. DWORD dwDataLen;
  213280. unsigned char* pDSBuffData;
  213281. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213282. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213283. logError (hr);
  213284. if (hr == S_OK)
  213285. {
  213286. zeromem (pDSBuffData, dwDataLen);
  213287. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213288. if (hr == S_OK)
  213289. {
  213290. hr = pOutputBuffer->SetCurrentPosition (0);
  213291. if (hr == S_OK)
  213292. {
  213293. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213294. if (hr == S_OK)
  213295. return String::empty;
  213296. }
  213297. }
  213298. }
  213299. }
  213300. }
  213301. }
  213302. }
  213303. }
  213304. error = getDSErrorMessage (hr);
  213305. close();
  213306. return error;
  213307. }
  213308. void synchronisePosition()
  213309. {
  213310. if (pOutputBuffer != 0)
  213311. {
  213312. DWORD playCursor;
  213313. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213314. }
  213315. }
  213316. bool service()
  213317. {
  213318. if (pOutputBuffer == 0)
  213319. return true;
  213320. DWORD playCursor, writeCursor;
  213321. for (;;)
  213322. {
  213323. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213324. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213325. {
  213326. pOutputBuffer->Restore();
  213327. continue;
  213328. }
  213329. if (hr == S_OK)
  213330. break;
  213331. logError (hr);
  213332. jassertfalse;
  213333. return true;
  213334. }
  213335. int playWriteGap = writeCursor - playCursor;
  213336. if (playWriteGap < 0)
  213337. playWriteGap += totalBytesPerBuffer;
  213338. int bytesEmpty = playCursor - writeOffset;
  213339. if (bytesEmpty < 0)
  213340. bytesEmpty += totalBytesPerBuffer;
  213341. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213342. {
  213343. writeOffset = writeCursor;
  213344. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213345. }
  213346. if (bytesEmpty >= bytesPerBuffer)
  213347. {
  213348. LPBYTE lpbuf1 = 0;
  213349. LPBYTE lpbuf2 = 0;
  213350. DWORD dwSize1 = 0;
  213351. DWORD dwSize2 = 0;
  213352. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  213353. bytesPerBuffer,
  213354. (void**) &lpbuf1, &dwSize1,
  213355. (void**) &lpbuf2, &dwSize2, 0);
  213356. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213357. {
  213358. pOutputBuffer->Restore();
  213359. hr = pOutputBuffer->Lock (writeOffset,
  213360. bytesPerBuffer,
  213361. (void**) &lpbuf1, &dwSize1,
  213362. (void**) &lpbuf2, &dwSize2, 0);
  213363. }
  213364. if (hr == S_OK)
  213365. {
  213366. if (bitDepth == 16)
  213367. {
  213368. const float gainL = 32767.0f;
  213369. const float gainR = 32767.0f;
  213370. int* dest = (int*)lpbuf1;
  213371. const float* left = leftBuffer;
  213372. const float* right = rightBuffer;
  213373. int samples1 = dwSize1 >> 2;
  213374. int samples2 = dwSize2 >> 2;
  213375. if (left == 0)
  213376. {
  213377. while (--samples1 >= 0)
  213378. {
  213379. int r = roundToInt (gainR * *right++);
  213380. if (r < -32768)
  213381. r = -32768;
  213382. else if (r > 32767)
  213383. r = 32767;
  213384. *dest++ = (r << 16);
  213385. }
  213386. dest = (int*)lpbuf2;
  213387. while (--samples2 >= 0)
  213388. {
  213389. int r = roundToInt (gainR * *right++);
  213390. if (r < -32768)
  213391. r = -32768;
  213392. else if (r > 32767)
  213393. r = 32767;
  213394. *dest++ = (r << 16);
  213395. }
  213396. }
  213397. else if (right == 0)
  213398. {
  213399. while (--samples1 >= 0)
  213400. {
  213401. int l = roundToInt (gainL * *left++);
  213402. if (l < -32768)
  213403. l = -32768;
  213404. else if (l > 32767)
  213405. l = 32767;
  213406. l &= 0xffff;
  213407. *dest++ = l;
  213408. }
  213409. dest = (int*)lpbuf2;
  213410. while (--samples2 >= 0)
  213411. {
  213412. int l = roundToInt (gainL * *left++);
  213413. if (l < -32768)
  213414. l = -32768;
  213415. else if (l > 32767)
  213416. l = 32767;
  213417. l &= 0xffff;
  213418. *dest++ = l;
  213419. }
  213420. }
  213421. else
  213422. {
  213423. while (--samples1 >= 0)
  213424. {
  213425. int l = roundToInt (gainL * *left++);
  213426. if (l < -32768)
  213427. l = -32768;
  213428. else if (l > 32767)
  213429. l = 32767;
  213430. l &= 0xffff;
  213431. int r = roundToInt (gainR * *right++);
  213432. if (r < -32768)
  213433. r = -32768;
  213434. else if (r > 32767)
  213435. r = 32767;
  213436. *dest++ = (r << 16) | l;
  213437. }
  213438. dest = (int*)lpbuf2;
  213439. while (--samples2 >= 0)
  213440. {
  213441. int l = roundToInt (gainL * *left++);
  213442. if (l < -32768)
  213443. l = -32768;
  213444. else if (l > 32767)
  213445. l = 32767;
  213446. l &= 0xffff;
  213447. int r = roundToInt (gainR * *right++);
  213448. if (r < -32768)
  213449. r = -32768;
  213450. else if (r > 32767)
  213451. r = 32767;
  213452. *dest++ = (r << 16) | l;
  213453. }
  213454. }
  213455. }
  213456. else
  213457. {
  213458. jassertfalse;
  213459. }
  213460. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213461. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213462. }
  213463. else
  213464. {
  213465. jassertfalse;
  213466. logError (hr);
  213467. }
  213468. bytesEmpty -= bytesPerBuffer;
  213469. return true;
  213470. }
  213471. else
  213472. {
  213473. return false;
  213474. }
  213475. }
  213476. };
  213477. struct DSoundInternalInChannel
  213478. {
  213479. String name;
  213480. LPGUID guid;
  213481. int sampleRate, bufferSizeSamples;
  213482. float* leftBuffer;
  213483. float* rightBuffer;
  213484. IDirectSound* pDirectSound;
  213485. IDirectSoundCapture* pDirectSoundCapture;
  213486. IDirectSoundCaptureBuffer* pInputBuffer;
  213487. public:
  213488. unsigned int readOffset;
  213489. int bytesPerBuffer, totalBytesPerBuffer;
  213490. int bitDepth;
  213491. bool doneFlag;
  213492. DSoundInternalInChannel (const String& name_,
  213493. LPGUID guid_,
  213494. int rate,
  213495. int bufferSize,
  213496. float* left,
  213497. float* right)
  213498. : name (name_),
  213499. guid (guid_),
  213500. sampleRate (rate),
  213501. bufferSizeSamples (bufferSize),
  213502. leftBuffer (left),
  213503. rightBuffer (right),
  213504. pDirectSound (0),
  213505. pDirectSoundCapture (0),
  213506. pInputBuffer (0),
  213507. bitDepth (16)
  213508. {
  213509. }
  213510. ~DSoundInternalInChannel()
  213511. {
  213512. close();
  213513. }
  213514. void close()
  213515. {
  213516. HRESULT hr;
  213517. if (pInputBuffer != 0)
  213518. {
  213519. JUCE_TRY
  213520. {
  213521. log ("closing dsound in: " + name);
  213522. hr = pInputBuffer->Stop();
  213523. logError (hr);
  213524. }
  213525. CATCH
  213526. JUCE_TRY
  213527. {
  213528. hr = pInputBuffer->Release();
  213529. logError (hr);
  213530. }
  213531. CATCH
  213532. pInputBuffer = 0;
  213533. }
  213534. if (pDirectSoundCapture != 0)
  213535. {
  213536. JUCE_TRY
  213537. {
  213538. hr = pDirectSoundCapture->Release();
  213539. logError (hr);
  213540. }
  213541. CATCH
  213542. pDirectSoundCapture = 0;
  213543. }
  213544. if (pDirectSound != 0)
  213545. {
  213546. JUCE_TRY
  213547. {
  213548. hr = pDirectSound->Release();
  213549. logError (hr);
  213550. }
  213551. CATCH
  213552. pDirectSound = 0;
  213553. }
  213554. }
  213555. const String open()
  213556. {
  213557. log ("opening dsound in device: " + name
  213558. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213559. pDirectSound = 0;
  213560. pDirectSoundCapture = 0;
  213561. pInputBuffer = 0;
  213562. readOffset = 0;
  213563. totalBytesPerBuffer = 0;
  213564. String error;
  213565. HRESULT hr = E_NOINTERFACE;
  213566. if (dsDirectSoundCaptureCreate != 0)
  213567. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213568. logError (hr);
  213569. if (hr == S_OK)
  213570. {
  213571. const int numChannels = 2;
  213572. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213573. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213574. WAVEFORMATEX wfFormat;
  213575. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213576. wfFormat.nChannels = (unsigned short)numChannels;
  213577. wfFormat.nSamplesPerSec = sampleRate;
  213578. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213579. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213580. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213581. wfFormat.cbSize = 0;
  213582. DSCBUFFERDESC captureDesc;
  213583. zerostruct (captureDesc);
  213584. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213585. captureDesc.dwFlags = 0;
  213586. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213587. captureDesc.lpwfxFormat = &wfFormat;
  213588. log ("opening dsound in step 2");
  213589. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213590. logError (hr);
  213591. if (hr == S_OK)
  213592. {
  213593. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213594. logError (hr);
  213595. if (hr == S_OK)
  213596. return String::empty;
  213597. }
  213598. }
  213599. error = getDSErrorMessage (hr);
  213600. close();
  213601. return error;
  213602. }
  213603. void synchronisePosition()
  213604. {
  213605. if (pInputBuffer != 0)
  213606. {
  213607. DWORD capturePos;
  213608. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213609. }
  213610. }
  213611. bool service()
  213612. {
  213613. if (pInputBuffer == 0)
  213614. return true;
  213615. DWORD capturePos, readPos;
  213616. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213617. logError (hr);
  213618. if (hr != S_OK)
  213619. return true;
  213620. int bytesFilled = readPos - readOffset;
  213621. if (bytesFilled < 0)
  213622. bytesFilled += totalBytesPerBuffer;
  213623. if (bytesFilled >= bytesPerBuffer)
  213624. {
  213625. LPBYTE lpbuf1 = 0;
  213626. LPBYTE lpbuf2 = 0;
  213627. DWORD dwsize1 = 0;
  213628. DWORD dwsize2 = 0;
  213629. HRESULT hr = pInputBuffer->Lock (readOffset,
  213630. bytesPerBuffer,
  213631. (void**) &lpbuf1, &dwsize1,
  213632. (void**) &lpbuf2, &dwsize2, 0);
  213633. if (hr == S_OK)
  213634. {
  213635. if (bitDepth == 16)
  213636. {
  213637. const float g = 1.0f / 32768.0f;
  213638. float* destL = leftBuffer;
  213639. float* destR = rightBuffer;
  213640. int samples1 = dwsize1 >> 2;
  213641. int samples2 = dwsize2 >> 2;
  213642. const short* src = (const short*)lpbuf1;
  213643. if (destL == 0)
  213644. {
  213645. while (--samples1 >= 0)
  213646. {
  213647. ++src;
  213648. *destR++ = *src++ * g;
  213649. }
  213650. src = (const short*)lpbuf2;
  213651. while (--samples2 >= 0)
  213652. {
  213653. ++src;
  213654. *destR++ = *src++ * g;
  213655. }
  213656. }
  213657. else if (destR == 0)
  213658. {
  213659. while (--samples1 >= 0)
  213660. {
  213661. *destL++ = *src++ * g;
  213662. ++src;
  213663. }
  213664. src = (const short*)lpbuf2;
  213665. while (--samples2 >= 0)
  213666. {
  213667. *destL++ = *src++ * g;
  213668. ++src;
  213669. }
  213670. }
  213671. else
  213672. {
  213673. while (--samples1 >= 0)
  213674. {
  213675. *destL++ = *src++ * g;
  213676. *destR++ = *src++ * g;
  213677. }
  213678. src = (const short*)lpbuf2;
  213679. while (--samples2 >= 0)
  213680. {
  213681. *destL++ = *src++ * g;
  213682. *destR++ = *src++ * g;
  213683. }
  213684. }
  213685. }
  213686. else
  213687. {
  213688. jassertfalse;
  213689. }
  213690. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213691. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213692. }
  213693. else
  213694. {
  213695. logError (hr);
  213696. jassertfalse;
  213697. }
  213698. bytesFilled -= bytesPerBuffer;
  213699. return true;
  213700. }
  213701. else
  213702. {
  213703. return false;
  213704. }
  213705. }
  213706. };
  213707. class DSoundAudioIODevice : public AudioIODevice,
  213708. public Thread
  213709. {
  213710. public:
  213711. DSoundAudioIODevice (const String& deviceName,
  213712. const int outputDeviceIndex_,
  213713. const int inputDeviceIndex_)
  213714. : AudioIODevice (deviceName, "DirectSound"),
  213715. Thread ("Juce DSound"),
  213716. isOpen_ (false),
  213717. isStarted (false),
  213718. outputDeviceIndex (outputDeviceIndex_),
  213719. inputDeviceIndex (inputDeviceIndex_),
  213720. totalSamplesOut (0),
  213721. sampleRate (0.0),
  213722. inputBuffers (1, 1),
  213723. outputBuffers (1, 1),
  213724. callback (0),
  213725. bufferSizeSamples (0)
  213726. {
  213727. if (outputDeviceIndex_ >= 0)
  213728. {
  213729. outChannels.add (TRANS("Left"));
  213730. outChannels.add (TRANS("Right"));
  213731. }
  213732. if (inputDeviceIndex_ >= 0)
  213733. {
  213734. inChannels.add (TRANS("Left"));
  213735. inChannels.add (TRANS("Right"));
  213736. }
  213737. }
  213738. ~DSoundAudioIODevice()
  213739. {
  213740. close();
  213741. }
  213742. const StringArray getOutputChannelNames()
  213743. {
  213744. return outChannels;
  213745. }
  213746. const StringArray getInputChannelNames()
  213747. {
  213748. return inChannels;
  213749. }
  213750. int getNumSampleRates()
  213751. {
  213752. return 4;
  213753. }
  213754. double getSampleRate (int index)
  213755. {
  213756. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213757. return samps [jlimit (0, 3, index)];
  213758. }
  213759. int getNumBufferSizesAvailable()
  213760. {
  213761. return 50;
  213762. }
  213763. int getBufferSizeSamples (int index)
  213764. {
  213765. int n = 64;
  213766. for (int i = 0; i < index; ++i)
  213767. n += (n < 512) ? 32
  213768. : ((n < 1024) ? 64
  213769. : ((n < 2048) ? 128 : 256));
  213770. return n;
  213771. }
  213772. int getDefaultBufferSize()
  213773. {
  213774. return 2560;
  213775. }
  213776. const String open (const BigInteger& inputChannels,
  213777. const BigInteger& outputChannels,
  213778. double sampleRate,
  213779. int bufferSizeSamples)
  213780. {
  213781. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  213782. isOpen_ = lastError.isEmpty();
  213783. return lastError;
  213784. }
  213785. void close()
  213786. {
  213787. stop();
  213788. if (isOpen_)
  213789. {
  213790. closeDevice();
  213791. isOpen_ = false;
  213792. }
  213793. }
  213794. bool isOpen()
  213795. {
  213796. return isOpen_ && isThreadRunning();
  213797. }
  213798. int getCurrentBufferSizeSamples()
  213799. {
  213800. return bufferSizeSamples;
  213801. }
  213802. double getCurrentSampleRate()
  213803. {
  213804. return sampleRate;
  213805. }
  213806. int getCurrentBitDepth()
  213807. {
  213808. int i, bits = 256;
  213809. for (i = inChans.size(); --i >= 0;)
  213810. bits = jmin (bits, inChans[i]->bitDepth);
  213811. for (i = outChans.size(); --i >= 0;)
  213812. bits = jmin (bits, outChans[i]->bitDepth);
  213813. if (bits > 32)
  213814. bits = 16;
  213815. return bits;
  213816. }
  213817. const BigInteger getActiveOutputChannels() const
  213818. {
  213819. return enabledOutputs;
  213820. }
  213821. const BigInteger getActiveInputChannels() const
  213822. {
  213823. return enabledInputs;
  213824. }
  213825. int getOutputLatencyInSamples()
  213826. {
  213827. return (int) (getCurrentBufferSizeSamples() * 1.5);
  213828. }
  213829. int getInputLatencyInSamples()
  213830. {
  213831. return getOutputLatencyInSamples();
  213832. }
  213833. void start (AudioIODeviceCallback* call)
  213834. {
  213835. if (isOpen_ && call != 0 && ! isStarted)
  213836. {
  213837. if (! isThreadRunning())
  213838. {
  213839. // something gone wrong and the thread's stopped..
  213840. isOpen_ = false;
  213841. return;
  213842. }
  213843. call->audioDeviceAboutToStart (this);
  213844. const ScopedLock sl (startStopLock);
  213845. callback = call;
  213846. isStarted = true;
  213847. }
  213848. }
  213849. void stop()
  213850. {
  213851. if (isStarted)
  213852. {
  213853. AudioIODeviceCallback* const callbackLocal = callback;
  213854. {
  213855. const ScopedLock sl (startStopLock);
  213856. isStarted = false;
  213857. }
  213858. if (callbackLocal != 0)
  213859. callbackLocal->audioDeviceStopped();
  213860. }
  213861. }
  213862. bool isPlaying()
  213863. {
  213864. return isStarted && isOpen_ && isThreadRunning();
  213865. }
  213866. const String getLastError()
  213867. {
  213868. return lastError;
  213869. }
  213870. juce_UseDebuggingNewOperator
  213871. StringArray inChannels, outChannels;
  213872. int outputDeviceIndex, inputDeviceIndex;
  213873. private:
  213874. bool isOpen_;
  213875. bool isStarted;
  213876. String lastError;
  213877. OwnedArray <DSoundInternalInChannel> inChans;
  213878. OwnedArray <DSoundInternalOutChannel> outChans;
  213879. WaitableEvent startEvent;
  213880. int bufferSizeSamples;
  213881. int volatile totalSamplesOut;
  213882. int64 volatile lastBlockTime;
  213883. double sampleRate;
  213884. BigInteger enabledInputs, enabledOutputs;
  213885. AudioSampleBuffer inputBuffers, outputBuffers;
  213886. AudioIODeviceCallback* callback;
  213887. CriticalSection startStopLock;
  213888. DSoundAudioIODevice (const DSoundAudioIODevice&);
  213889. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  213890. const String openDevice (const BigInteger& inputChannels,
  213891. const BigInteger& outputChannels,
  213892. double sampleRate_,
  213893. int bufferSizeSamples_);
  213894. void closeDevice()
  213895. {
  213896. isStarted = false;
  213897. stopThread (5000);
  213898. inChans.clear();
  213899. outChans.clear();
  213900. inputBuffers.setSize (1, 1);
  213901. outputBuffers.setSize (1, 1);
  213902. }
  213903. void resync()
  213904. {
  213905. if (! threadShouldExit())
  213906. {
  213907. sleep (5);
  213908. int i;
  213909. for (i = 0; i < outChans.size(); ++i)
  213910. outChans.getUnchecked(i)->synchronisePosition();
  213911. for (i = 0; i < inChans.size(); ++i)
  213912. inChans.getUnchecked(i)->synchronisePosition();
  213913. }
  213914. }
  213915. public:
  213916. void run()
  213917. {
  213918. while (! threadShouldExit())
  213919. {
  213920. if (wait (100))
  213921. break;
  213922. }
  213923. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  213924. const int maxTimeMS = jmax (5, 3 * latencyMs);
  213925. while (! threadShouldExit())
  213926. {
  213927. int numToDo = 0;
  213928. uint32 startTime = Time::getMillisecondCounter();
  213929. int i;
  213930. for (i = inChans.size(); --i >= 0;)
  213931. {
  213932. inChans.getUnchecked(i)->doneFlag = false;
  213933. ++numToDo;
  213934. }
  213935. for (i = outChans.size(); --i >= 0;)
  213936. {
  213937. outChans.getUnchecked(i)->doneFlag = false;
  213938. ++numToDo;
  213939. }
  213940. if (numToDo > 0)
  213941. {
  213942. const int maxCount = 3;
  213943. int count = maxCount;
  213944. for (;;)
  213945. {
  213946. for (i = inChans.size(); --i >= 0;)
  213947. {
  213948. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  213949. if ((! in->doneFlag) && in->service())
  213950. {
  213951. in->doneFlag = true;
  213952. --numToDo;
  213953. }
  213954. }
  213955. for (i = outChans.size(); --i >= 0;)
  213956. {
  213957. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  213958. if ((! out->doneFlag) && out->service())
  213959. {
  213960. out->doneFlag = true;
  213961. --numToDo;
  213962. }
  213963. }
  213964. if (numToDo <= 0)
  213965. break;
  213966. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  213967. {
  213968. resync();
  213969. break;
  213970. }
  213971. if (--count <= 0)
  213972. {
  213973. Sleep (1);
  213974. count = maxCount;
  213975. }
  213976. if (threadShouldExit())
  213977. return;
  213978. }
  213979. }
  213980. else
  213981. {
  213982. sleep (1);
  213983. }
  213984. const ScopedLock sl (startStopLock);
  213985. if (isStarted)
  213986. {
  213987. JUCE_TRY
  213988. {
  213989. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  213990. inputBuffers.getNumChannels(),
  213991. outputBuffers.getArrayOfChannels(),
  213992. outputBuffers.getNumChannels(),
  213993. bufferSizeSamples);
  213994. }
  213995. JUCE_CATCH_EXCEPTION
  213996. totalSamplesOut += bufferSizeSamples;
  213997. }
  213998. else
  213999. {
  214000. outputBuffers.clear();
  214001. totalSamplesOut = 0;
  214002. sleep (1);
  214003. }
  214004. }
  214005. }
  214006. };
  214007. class DSoundAudioIODeviceType : public AudioIODeviceType
  214008. {
  214009. public:
  214010. DSoundAudioIODeviceType()
  214011. : AudioIODeviceType ("DirectSound"),
  214012. hasScanned (false)
  214013. {
  214014. initialiseDSoundFunctions();
  214015. }
  214016. ~DSoundAudioIODeviceType()
  214017. {
  214018. }
  214019. void scanForDevices()
  214020. {
  214021. hasScanned = true;
  214022. outputDeviceNames.clear();
  214023. outputGuids.clear();
  214024. inputDeviceNames.clear();
  214025. inputGuids.clear();
  214026. if (dsDirectSoundEnumerateW != 0)
  214027. {
  214028. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214029. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214030. }
  214031. }
  214032. const StringArray getDeviceNames (bool wantInputNames) const
  214033. {
  214034. jassert (hasScanned); // need to call scanForDevices() before doing this
  214035. return wantInputNames ? inputDeviceNames
  214036. : outputDeviceNames;
  214037. }
  214038. int getDefaultDeviceIndex (bool /*forInput*/) const
  214039. {
  214040. jassert (hasScanned); // need to call scanForDevices() before doing this
  214041. return 0;
  214042. }
  214043. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214044. {
  214045. jassert (hasScanned); // need to call scanForDevices() before doing this
  214046. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214047. if (d == 0)
  214048. return -1;
  214049. return asInput ? d->inputDeviceIndex
  214050. : d->outputDeviceIndex;
  214051. }
  214052. bool hasSeparateInputsAndOutputs() const { return true; }
  214053. AudioIODevice* createDevice (const String& outputDeviceName,
  214054. const String& inputDeviceName)
  214055. {
  214056. jassert (hasScanned); // need to call scanForDevices() before doing this
  214057. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214058. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214059. if (outputIndex >= 0 || inputIndex >= 0)
  214060. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214061. : inputDeviceName,
  214062. outputIndex, inputIndex);
  214063. return 0;
  214064. }
  214065. juce_UseDebuggingNewOperator
  214066. StringArray outputDeviceNames;
  214067. OwnedArray <GUID> outputGuids;
  214068. StringArray inputDeviceNames;
  214069. OwnedArray <GUID> inputGuids;
  214070. private:
  214071. bool hasScanned;
  214072. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214073. {
  214074. desc = desc.trim();
  214075. if (desc.isNotEmpty())
  214076. {
  214077. const String origDesc (desc);
  214078. int n = 2;
  214079. while (outputDeviceNames.contains (desc))
  214080. desc = origDesc + " (" + String (n++) + ")";
  214081. outputDeviceNames.add (desc);
  214082. if (lpGUID != 0)
  214083. outputGuids.add (new GUID (*lpGUID));
  214084. else
  214085. outputGuids.add (0);
  214086. }
  214087. return TRUE;
  214088. }
  214089. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214090. {
  214091. return ((DSoundAudioIODeviceType*) object)
  214092. ->outputEnumProc (lpGUID, String (description));
  214093. }
  214094. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214095. {
  214096. return ((DSoundAudioIODeviceType*) object)
  214097. ->outputEnumProc (lpGUID, String (description));
  214098. }
  214099. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214100. {
  214101. desc = desc.trim();
  214102. if (desc.isNotEmpty())
  214103. {
  214104. const String origDesc (desc);
  214105. int n = 2;
  214106. while (inputDeviceNames.contains (desc))
  214107. desc = origDesc + " (" + String (n++) + ")";
  214108. inputDeviceNames.add (desc);
  214109. if (lpGUID != 0)
  214110. inputGuids.add (new GUID (*lpGUID));
  214111. else
  214112. inputGuids.add (0);
  214113. }
  214114. return TRUE;
  214115. }
  214116. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214117. {
  214118. return ((DSoundAudioIODeviceType*) object)
  214119. ->inputEnumProc (lpGUID, String (description));
  214120. }
  214121. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214122. {
  214123. return ((DSoundAudioIODeviceType*) object)
  214124. ->inputEnumProc (lpGUID, String (description));
  214125. }
  214126. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  214127. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  214128. };
  214129. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214130. const BigInteger& outputChannels,
  214131. double sampleRate_,
  214132. int bufferSizeSamples_)
  214133. {
  214134. closeDevice();
  214135. totalSamplesOut = 0;
  214136. sampleRate = sampleRate_;
  214137. if (bufferSizeSamples_ <= 0)
  214138. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214139. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214140. DSoundAudioIODeviceType dlh;
  214141. dlh.scanForDevices();
  214142. enabledInputs = inputChannels;
  214143. enabledInputs.setRange (inChannels.size(),
  214144. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214145. false);
  214146. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214147. inputBuffers.clear();
  214148. int i, numIns = 0;
  214149. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214150. {
  214151. float* left = 0;
  214152. if (enabledInputs[i])
  214153. left = inputBuffers.getSampleData (numIns++);
  214154. float* right = 0;
  214155. if (enabledInputs[i + 1])
  214156. right = inputBuffers.getSampleData (numIns++);
  214157. if (left != 0 || right != 0)
  214158. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214159. dlh.inputGuids [inputDeviceIndex],
  214160. (int) sampleRate, bufferSizeSamples,
  214161. left, right));
  214162. }
  214163. enabledOutputs = outputChannels;
  214164. enabledOutputs.setRange (outChannels.size(),
  214165. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214166. false);
  214167. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214168. outputBuffers.clear();
  214169. int numOuts = 0;
  214170. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214171. {
  214172. float* left = 0;
  214173. if (enabledOutputs[i])
  214174. left = outputBuffers.getSampleData (numOuts++);
  214175. float* right = 0;
  214176. if (enabledOutputs[i + 1])
  214177. right = outputBuffers.getSampleData (numOuts++);
  214178. if (left != 0 || right != 0)
  214179. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214180. dlh.outputGuids [outputDeviceIndex],
  214181. (int) sampleRate, bufferSizeSamples,
  214182. left, right));
  214183. }
  214184. String error;
  214185. // boost our priority while opening the devices to try to get better sync between them
  214186. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214187. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214188. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214189. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214190. for (i = 0; i < outChans.size(); ++i)
  214191. {
  214192. error = outChans[i]->open();
  214193. if (error.isNotEmpty())
  214194. {
  214195. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214196. break;
  214197. }
  214198. }
  214199. if (error.isEmpty())
  214200. {
  214201. for (i = 0; i < inChans.size(); ++i)
  214202. {
  214203. error = inChans[i]->open();
  214204. if (error.isNotEmpty())
  214205. {
  214206. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214207. break;
  214208. }
  214209. }
  214210. }
  214211. if (error.isEmpty())
  214212. {
  214213. totalSamplesOut = 0;
  214214. for (i = 0; i < outChans.size(); ++i)
  214215. outChans.getUnchecked(i)->synchronisePosition();
  214216. for (i = 0; i < inChans.size(); ++i)
  214217. inChans.getUnchecked(i)->synchronisePosition();
  214218. startThread (9);
  214219. sleep (10);
  214220. notify();
  214221. }
  214222. else
  214223. {
  214224. log (error);
  214225. }
  214226. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214227. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214228. return error;
  214229. }
  214230. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214231. {
  214232. return new DSoundAudioIODeviceType();
  214233. }
  214234. #undef log
  214235. #endif
  214236. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214237. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214238. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214239. // compiled on its own).
  214240. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214241. #if 1
  214242. const String getAudioErrorDesc (HRESULT hr)
  214243. {
  214244. const char* e = 0;
  214245. switch (hr)
  214246. {
  214247. case E_POINTER: e = "E_POINTER"; break;
  214248. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  214249. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  214250. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214251. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214252. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214253. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  214254. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214255. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  214256. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214257. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  214258. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  214259. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214260. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214261. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214262. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214263. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214264. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214265. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214266. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214267. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214268. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214269. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214270. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  214271. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214272. default: return String::toHexString ((int) hr);
  214273. }
  214274. return e;
  214275. }
  214276. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  214277. #define OK(a) wasapi_checkResult(a)
  214278. static bool wasapi_checkResult (HRESULT hr)
  214279. {
  214280. logFailure (hr);
  214281. return SUCCEEDED (hr);
  214282. }
  214283. #else
  214284. #define logFailure(hr) {}
  214285. #define OK(a) SUCCEEDED(a)
  214286. #endif
  214287. static const String wasapi_getDeviceID (IMMDevice* const device)
  214288. {
  214289. String s;
  214290. WCHAR* deviceId = 0;
  214291. if (OK (device->GetId (&deviceId)))
  214292. {
  214293. s = String (deviceId);
  214294. CoTaskMemFree (deviceId);
  214295. }
  214296. return s;
  214297. }
  214298. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  214299. {
  214300. EDataFlow flow = eRender;
  214301. ComSmartPtr <IMMEndpoint> endPoint;
  214302. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  214303. (void) OK (endPoint->GetDataFlow (&flow));
  214304. return flow;
  214305. }
  214306. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214307. {
  214308. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214309. }
  214310. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214311. {
  214312. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214313. : sizeof (WAVEFORMATEX));
  214314. }
  214315. class WASAPIDeviceBase
  214316. {
  214317. public:
  214318. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214319. : device (device_),
  214320. sampleRate (0),
  214321. numChannels (0),
  214322. actualNumChannels (0),
  214323. defaultSampleRate (0),
  214324. minBufferSize (0),
  214325. defaultBufferSize (0),
  214326. latencySamples (0),
  214327. useExclusiveMode (useExclusiveMode_)
  214328. {
  214329. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214330. ComSmartPtr <IAudioClient> tempClient (createClient());
  214331. if (tempClient == 0)
  214332. return;
  214333. REFERENCE_TIME defaultPeriod, minPeriod;
  214334. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214335. return;
  214336. WAVEFORMATEX* mixFormat = 0;
  214337. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  214338. return;
  214339. WAVEFORMATEXTENSIBLE format;
  214340. wasapi_copyWavFormat (format, mixFormat);
  214341. CoTaskMemFree (mixFormat);
  214342. actualNumChannels = numChannels = format.Format.nChannels;
  214343. defaultSampleRate = format.Format.nSamplesPerSec;
  214344. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  214345. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  214346. rates.addUsingDefaultSort (defaultSampleRate);
  214347. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214348. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214349. {
  214350. if (ratesToTest[i] == defaultSampleRate)
  214351. continue;
  214352. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214353. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214354. (WAVEFORMATEX*) &format, 0)))
  214355. if (! rates.contains (ratesToTest[i]))
  214356. rates.addUsingDefaultSort (ratesToTest[i]);
  214357. }
  214358. }
  214359. ~WASAPIDeviceBase()
  214360. {
  214361. device = 0;
  214362. CloseHandle (clientEvent);
  214363. }
  214364. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214365. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214366. {
  214367. sampleRate = newSampleRate;
  214368. channels = newChannels;
  214369. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214370. numChannels = channels.getHighestBit() + 1;
  214371. if (numChannels == 0)
  214372. return true;
  214373. client = createClient();
  214374. if (client != 0
  214375. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214376. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214377. {
  214378. channelMaps.clear();
  214379. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214380. if (channels[i])
  214381. channelMaps.add (i);
  214382. REFERENCE_TIME latency;
  214383. if (OK (client->GetStreamLatency (&latency)))
  214384. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  214385. (void) OK (client->GetBufferSize (&actualBufferSize));
  214386. return OK (client->SetEventHandle (clientEvent));
  214387. }
  214388. return false;
  214389. }
  214390. void closeClient()
  214391. {
  214392. if (client != 0)
  214393. client->Stop();
  214394. client = 0;
  214395. ResetEvent (clientEvent);
  214396. }
  214397. ComSmartPtr <IMMDevice> device;
  214398. ComSmartPtr <IAudioClient> client;
  214399. double sampleRate, defaultSampleRate;
  214400. int numChannels, actualNumChannels;
  214401. int minBufferSize, defaultBufferSize, latencySamples;
  214402. const bool useExclusiveMode;
  214403. Array <double> rates;
  214404. HANDLE clientEvent;
  214405. BigInteger channels;
  214406. AudioDataConverters::DataFormat dataFormat;
  214407. Array <int> channelMaps;
  214408. UINT32 actualBufferSize;
  214409. int bytesPerSample;
  214410. private:
  214411. const ComSmartPtr <IAudioClient> createClient()
  214412. {
  214413. ComSmartPtr <IAudioClient> client;
  214414. if (device != 0)
  214415. {
  214416. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  214417. logFailure (hr);
  214418. }
  214419. return client;
  214420. }
  214421. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214422. {
  214423. WAVEFORMATEXTENSIBLE format;
  214424. zerostruct (format);
  214425. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214426. {
  214427. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214428. }
  214429. else
  214430. {
  214431. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214432. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214433. }
  214434. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214435. format.Format.nChannels = (WORD) numChannels;
  214436. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214437. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214438. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214439. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214440. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214441. switch (numChannels)
  214442. {
  214443. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214444. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214445. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214446. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214447. 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;
  214448. default: break;
  214449. }
  214450. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214451. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214452. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214453. logFailure (hr);
  214454. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214455. {
  214456. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214457. hr = S_OK;
  214458. }
  214459. CoTaskMemFree (nearestFormat);
  214460. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214461. if (useExclusiveMode)
  214462. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214463. GUID session;
  214464. if (hr == S_OK
  214465. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214466. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214467. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214468. {
  214469. actualNumChannels = format.Format.nChannels;
  214470. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214471. bytesPerSample = format.Format.wBitsPerSample / 8;
  214472. dataFormat = isFloat ? AudioDataConverters::float32LE
  214473. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  214474. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  214475. : AudioDataConverters::int16LE)));
  214476. return true;
  214477. }
  214478. return false;
  214479. }
  214480. WASAPIDeviceBase (const WASAPIDeviceBase&);
  214481. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  214482. };
  214483. class WASAPIInputDevice : public WASAPIDeviceBase
  214484. {
  214485. public:
  214486. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214487. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214488. reservoir (1, 1)
  214489. {
  214490. }
  214491. ~WASAPIInputDevice()
  214492. {
  214493. close();
  214494. }
  214495. bool open (const double newSampleRate, const BigInteger& newChannels)
  214496. {
  214497. reservoirSize = 0;
  214498. reservoirCapacity = 16384;
  214499. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214500. return openClient (newSampleRate, newChannels)
  214501. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  214502. }
  214503. void close()
  214504. {
  214505. closeClient();
  214506. captureClient = 0;
  214507. reservoir.setSize (0);
  214508. }
  214509. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214510. {
  214511. if (numChannels <= 0)
  214512. return;
  214513. int offset = 0;
  214514. while (bufferSize > 0)
  214515. {
  214516. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214517. {
  214518. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214519. for (int i = 0; i < numDestBuffers; ++i)
  214520. {
  214521. float* const dest = destBuffers[i] + offset;
  214522. const int srcChan = channelMaps.getUnchecked(i);
  214523. switch (dataFormat)
  214524. {
  214525. case AudioDataConverters::float32LE:
  214526. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214527. break;
  214528. case AudioDataConverters::int32LE:
  214529. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214530. break;
  214531. case AudioDataConverters::int24LE:
  214532. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214533. break;
  214534. case AudioDataConverters::int16LE:
  214535. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214536. break;
  214537. default: jassertfalse; break;
  214538. }
  214539. }
  214540. bufferSize -= samplesToDo;
  214541. offset += samplesToDo;
  214542. reservoirSize -= samplesToDo;
  214543. }
  214544. else
  214545. {
  214546. UINT32 packetLength = 0;
  214547. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  214548. break;
  214549. if (packetLength == 0)
  214550. {
  214551. if (thread.threadShouldExit())
  214552. break;
  214553. Thread::sleep (1);
  214554. continue;
  214555. }
  214556. uint8* inputData = 0;
  214557. UINT32 numSamplesAvailable;
  214558. DWORD flags;
  214559. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214560. {
  214561. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214562. for (int i = 0; i < numDestBuffers; ++i)
  214563. {
  214564. float* const dest = destBuffers[i] + offset;
  214565. const int srcChan = channelMaps.getUnchecked(i);
  214566. switch (dataFormat)
  214567. {
  214568. case AudioDataConverters::float32LE:
  214569. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214570. break;
  214571. case AudioDataConverters::int32LE:
  214572. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214573. break;
  214574. case AudioDataConverters::int24LE:
  214575. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214576. break;
  214577. case AudioDataConverters::int16LE:
  214578. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214579. break;
  214580. default: jassertfalse; break;
  214581. }
  214582. }
  214583. bufferSize -= samplesToDo;
  214584. offset += samplesToDo;
  214585. if (samplesToDo < (int) numSamplesAvailable)
  214586. {
  214587. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214588. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214589. bytesPerSample * actualNumChannels * reservoirSize);
  214590. }
  214591. captureClient->ReleaseBuffer (numSamplesAvailable);
  214592. }
  214593. }
  214594. }
  214595. }
  214596. ComSmartPtr <IAudioCaptureClient> captureClient;
  214597. MemoryBlock reservoir;
  214598. int reservoirSize, reservoirCapacity;
  214599. private:
  214600. WASAPIInputDevice (const WASAPIInputDevice&);
  214601. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  214602. };
  214603. class WASAPIOutputDevice : public WASAPIDeviceBase
  214604. {
  214605. public:
  214606. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214607. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214608. {
  214609. }
  214610. ~WASAPIOutputDevice()
  214611. {
  214612. close();
  214613. }
  214614. bool open (const double newSampleRate, const BigInteger& newChannels)
  214615. {
  214616. return openClient (newSampleRate, newChannels)
  214617. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  214618. }
  214619. void close()
  214620. {
  214621. closeClient();
  214622. renderClient = 0;
  214623. }
  214624. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214625. {
  214626. if (numChannels <= 0)
  214627. return;
  214628. int offset = 0;
  214629. while (bufferSize > 0)
  214630. {
  214631. UINT32 padding = 0;
  214632. if (! OK (client->GetCurrentPadding (&padding)))
  214633. return;
  214634. int samplesToDo = useExclusiveMode ? bufferSize
  214635. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214636. if (samplesToDo <= 0)
  214637. {
  214638. if (thread.threadShouldExit())
  214639. break;
  214640. Thread::sleep (0);
  214641. continue;
  214642. }
  214643. uint8* outputData = 0;
  214644. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  214645. {
  214646. for (int i = 0; i < numSrcBuffers; ++i)
  214647. {
  214648. const float* const source = srcBuffers[i] + offset;
  214649. const int destChan = channelMaps.getUnchecked(i);
  214650. switch (dataFormat)
  214651. {
  214652. case AudioDataConverters::float32LE:
  214653. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214654. break;
  214655. case AudioDataConverters::int32LE:
  214656. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214657. break;
  214658. case AudioDataConverters::int24LE:
  214659. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  214660. break;
  214661. case AudioDataConverters::int16LE:
  214662. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  214663. break;
  214664. default: jassertfalse; break;
  214665. }
  214666. }
  214667. renderClient->ReleaseBuffer (samplesToDo, 0);
  214668. offset += samplesToDo;
  214669. bufferSize -= samplesToDo;
  214670. }
  214671. }
  214672. }
  214673. ComSmartPtr <IAudioRenderClient> renderClient;
  214674. private:
  214675. WASAPIOutputDevice (const WASAPIOutputDevice&);
  214676. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  214677. };
  214678. class WASAPIAudioIODevice : public AudioIODevice,
  214679. public Thread
  214680. {
  214681. public:
  214682. WASAPIAudioIODevice (const String& deviceName,
  214683. const String& outputDeviceId_,
  214684. const String& inputDeviceId_,
  214685. const bool useExclusiveMode_)
  214686. : AudioIODevice (deviceName, "Windows Audio"),
  214687. Thread ("Juce WASAPI"),
  214688. isOpen_ (false),
  214689. isStarted (false),
  214690. outputDevice (0),
  214691. outputDeviceId (outputDeviceId_),
  214692. inputDevice (0),
  214693. inputDeviceId (inputDeviceId_),
  214694. useExclusiveMode (useExclusiveMode_),
  214695. currentBufferSizeSamples (0),
  214696. currentSampleRate (0),
  214697. callback (0)
  214698. {
  214699. }
  214700. ~WASAPIAudioIODevice()
  214701. {
  214702. close();
  214703. deleteAndZero (inputDevice);
  214704. deleteAndZero (outputDevice);
  214705. }
  214706. bool initialise()
  214707. {
  214708. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214709. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214710. latencyIn = latencyOut = 0;
  214711. Array <double> ratesIn, ratesOut;
  214712. if (createDevices())
  214713. {
  214714. jassert (inputDevice != 0 || outputDevice != 0);
  214715. if (inputDevice != 0 && outputDevice != 0)
  214716. {
  214717. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214718. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214719. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214720. sampleRates = inputDevice->rates;
  214721. sampleRates.removeValuesNotIn (outputDevice->rates);
  214722. }
  214723. else
  214724. {
  214725. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  214726. defaultSampleRate = d->defaultSampleRate;
  214727. minBufferSize = d->minBufferSize;
  214728. defaultBufferSize = d->defaultBufferSize;
  214729. sampleRates = d->rates;
  214730. }
  214731. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214732. if (minBufferSize != defaultBufferSize)
  214733. bufferSizes.addUsingDefaultSort (minBufferSize);
  214734. int n = 64;
  214735. for (int i = 0; i < 40; ++i)
  214736. {
  214737. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214738. bufferSizes.addUsingDefaultSort (n);
  214739. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214740. }
  214741. return true;
  214742. }
  214743. return false;
  214744. }
  214745. const StringArray getOutputChannelNames()
  214746. {
  214747. StringArray outChannels;
  214748. if (outputDevice != 0)
  214749. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214750. outChannels.add ("Output channel " + String (i));
  214751. return outChannels;
  214752. }
  214753. const StringArray getInputChannelNames()
  214754. {
  214755. StringArray inChannels;
  214756. if (inputDevice != 0)
  214757. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214758. inChannels.add ("Input channel " + String (i));
  214759. return inChannels;
  214760. }
  214761. int getNumSampleRates() { return sampleRates.size(); }
  214762. double getSampleRate (int index) { return sampleRates [index]; }
  214763. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214764. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214765. int getDefaultBufferSize() { return defaultBufferSize; }
  214766. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214767. double getCurrentSampleRate() { return currentSampleRate; }
  214768. int getCurrentBitDepth() { return 32; }
  214769. int getOutputLatencyInSamples() { return latencyOut; }
  214770. int getInputLatencyInSamples() { return latencyIn; }
  214771. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214772. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214773. const String getLastError() { return lastError; }
  214774. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214775. double sampleRate, int bufferSizeSamples)
  214776. {
  214777. close();
  214778. lastError = String::empty;
  214779. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214780. {
  214781. lastError = "The input and output devices don't share a common sample rate!";
  214782. return lastError;
  214783. }
  214784. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214785. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214786. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214787. {
  214788. lastError = "Couldn't open the input device!";
  214789. return lastError;
  214790. }
  214791. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214792. {
  214793. close();
  214794. lastError = "Couldn't open the output device!";
  214795. return lastError;
  214796. }
  214797. if (inputDevice != 0)
  214798. ResetEvent (inputDevice->clientEvent);
  214799. if (outputDevice != 0)
  214800. ResetEvent (outputDevice->clientEvent);
  214801. startThread (8);
  214802. Thread::sleep (5);
  214803. if (inputDevice != 0 && inputDevice->client != 0)
  214804. {
  214805. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  214806. HRESULT hr = inputDevice->client->Start();
  214807. logFailure (hr); //xxx handle this
  214808. }
  214809. if (outputDevice != 0 && outputDevice->client != 0)
  214810. {
  214811. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  214812. HRESULT hr = outputDevice->client->Start();
  214813. logFailure (hr); //xxx handle this
  214814. }
  214815. isOpen_ = true;
  214816. return lastError;
  214817. }
  214818. void close()
  214819. {
  214820. stop();
  214821. if (inputDevice != 0)
  214822. SetEvent (inputDevice->clientEvent);
  214823. if (outputDevice != 0)
  214824. SetEvent (outputDevice->clientEvent);
  214825. stopThread (5000);
  214826. if (inputDevice != 0)
  214827. inputDevice->close();
  214828. if (outputDevice != 0)
  214829. outputDevice->close();
  214830. isOpen_ = false;
  214831. }
  214832. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214833. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214834. void start (AudioIODeviceCallback* call)
  214835. {
  214836. if (isOpen_ && call != 0 && ! isStarted)
  214837. {
  214838. if (! isThreadRunning())
  214839. {
  214840. // something's gone wrong and the thread's stopped..
  214841. isOpen_ = false;
  214842. return;
  214843. }
  214844. call->audioDeviceAboutToStart (this);
  214845. const ScopedLock sl (startStopLock);
  214846. callback = call;
  214847. isStarted = true;
  214848. }
  214849. }
  214850. void stop()
  214851. {
  214852. if (isStarted)
  214853. {
  214854. AudioIODeviceCallback* const callbackLocal = callback;
  214855. {
  214856. const ScopedLock sl (startStopLock);
  214857. isStarted = false;
  214858. }
  214859. if (callbackLocal != 0)
  214860. callbackLocal->audioDeviceStopped();
  214861. }
  214862. }
  214863. void setMMThreadPriority()
  214864. {
  214865. DynamicLibraryLoader dll ("avrt.dll");
  214866. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  214867. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  214868. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  214869. {
  214870. DWORD dummy = 0;
  214871. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  214872. if (h != 0)
  214873. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  214874. }
  214875. }
  214876. void run()
  214877. {
  214878. setMMThreadPriority();
  214879. const int bufferSize = currentBufferSizeSamples;
  214880. HANDLE events[2];
  214881. int numEvents = 0;
  214882. if (inputDevice != 0)
  214883. events [numEvents++] = inputDevice->clientEvent;
  214884. if (outputDevice != 0)
  214885. events [numEvents++] = outputDevice->clientEvent;
  214886. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  214887. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  214888. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  214889. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  214890. float** const inputBuffers = ins.getArrayOfChannels();
  214891. float** const outputBuffers = outs.getArrayOfChannels();
  214892. ins.clear();
  214893. while (! threadShouldExit())
  214894. {
  214895. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  214896. : WaitForMultipleObjects (numEvents, events, true, 1000);
  214897. if (result == WAIT_TIMEOUT)
  214898. continue;
  214899. if (threadShouldExit())
  214900. break;
  214901. if (inputDevice != 0)
  214902. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  214903. // Make the callback..
  214904. {
  214905. const ScopedLock sl (startStopLock);
  214906. if (isStarted)
  214907. {
  214908. JUCE_TRY
  214909. {
  214910. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  214911. numInputBuffers,
  214912. outputBuffers,
  214913. numOutputBuffers,
  214914. bufferSize);
  214915. }
  214916. JUCE_CATCH_EXCEPTION
  214917. }
  214918. else
  214919. {
  214920. outs.clear();
  214921. }
  214922. }
  214923. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  214924. continue;
  214925. if (outputDevice != 0)
  214926. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  214927. }
  214928. }
  214929. juce_UseDebuggingNewOperator
  214930. String outputDeviceId, inputDeviceId;
  214931. String lastError;
  214932. private:
  214933. // Device stats...
  214934. WASAPIInputDevice* inputDevice;
  214935. WASAPIOutputDevice* outputDevice;
  214936. const bool useExclusiveMode;
  214937. double defaultSampleRate;
  214938. int minBufferSize, defaultBufferSize;
  214939. int latencyIn, latencyOut;
  214940. Array <double> sampleRates;
  214941. Array <int> bufferSizes;
  214942. // Active state...
  214943. bool isOpen_, isStarted;
  214944. int currentBufferSizeSamples;
  214945. double currentSampleRate;
  214946. AudioIODeviceCallback* callback;
  214947. CriticalSection startStopLock;
  214948. bool createDevices()
  214949. {
  214950. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214951. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214952. return false;
  214953. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214954. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  214955. return false;
  214956. UINT32 numDevices = 0;
  214957. if (! OK (deviceCollection->GetCount (&numDevices)))
  214958. return false;
  214959. for (UINT32 i = 0; i < numDevices; ++i)
  214960. {
  214961. ComSmartPtr <IMMDevice> device;
  214962. if (! OK (deviceCollection->Item (i, &device)))
  214963. continue;
  214964. const String deviceId (wasapi_getDeviceID (device));
  214965. if (deviceId.isEmpty())
  214966. continue;
  214967. const EDataFlow flow = wasapi_getDataFlow (device);
  214968. if (deviceId == inputDeviceId && flow == eCapture)
  214969. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  214970. else if (deviceId == outputDeviceId && flow == eRender)
  214971. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  214972. }
  214973. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  214974. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  214975. }
  214976. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  214977. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  214978. };
  214979. class WASAPIAudioIODeviceType : public AudioIODeviceType
  214980. {
  214981. public:
  214982. WASAPIAudioIODeviceType()
  214983. : AudioIODeviceType ("Windows Audio"),
  214984. hasScanned (false)
  214985. {
  214986. }
  214987. ~WASAPIAudioIODeviceType()
  214988. {
  214989. }
  214990. void scanForDevices()
  214991. {
  214992. hasScanned = true;
  214993. outputDeviceNames.clear();
  214994. inputDeviceNames.clear();
  214995. outputDeviceIds.clear();
  214996. inputDeviceIds.clear();
  214997. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214998. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214999. return;
  215000. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215001. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215002. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215003. UINT32 numDevices = 0;
  215004. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  215005. && OK (deviceCollection->GetCount (&numDevices))))
  215006. return;
  215007. for (UINT32 i = 0; i < numDevices; ++i)
  215008. {
  215009. ComSmartPtr <IMMDevice> device;
  215010. if (! OK (deviceCollection->Item (i, &device)))
  215011. continue;
  215012. const String deviceId (wasapi_getDeviceID (device));
  215013. DWORD state = 0;
  215014. if (! OK (device->GetState (&state)))
  215015. continue;
  215016. if (state != DEVICE_STATE_ACTIVE)
  215017. continue;
  215018. String name;
  215019. {
  215020. ComSmartPtr <IPropertyStore> properties;
  215021. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  215022. continue;
  215023. PROPVARIANT value;
  215024. PropVariantInit (&value);
  215025. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215026. name = value.pwszVal;
  215027. PropVariantClear (&value);
  215028. }
  215029. const EDataFlow flow = wasapi_getDataFlow (device);
  215030. if (flow == eRender)
  215031. {
  215032. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215033. outputDeviceIds.insert (index, deviceId);
  215034. outputDeviceNames.insert (index, name);
  215035. }
  215036. else if (flow == eCapture)
  215037. {
  215038. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215039. inputDeviceIds.insert (index, deviceId);
  215040. inputDeviceNames.insert (index, name);
  215041. }
  215042. }
  215043. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215044. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215045. }
  215046. const StringArray getDeviceNames (bool wantInputNames) const
  215047. {
  215048. jassert (hasScanned); // need to call scanForDevices() before doing this
  215049. return wantInputNames ? inputDeviceNames
  215050. : outputDeviceNames;
  215051. }
  215052. int getDefaultDeviceIndex (bool /*forInput*/) const
  215053. {
  215054. jassert (hasScanned); // need to call scanForDevices() before doing this
  215055. return 0;
  215056. }
  215057. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215058. {
  215059. jassert (hasScanned); // need to call scanForDevices() before doing this
  215060. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215061. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215062. : outputDeviceIds.indexOf (d->outputDeviceId));
  215063. }
  215064. bool hasSeparateInputsAndOutputs() const { return true; }
  215065. AudioIODevice* createDevice (const String& outputDeviceName,
  215066. const String& inputDeviceName)
  215067. {
  215068. jassert (hasScanned); // need to call scanForDevices() before doing this
  215069. const bool useExclusiveMode = false;
  215070. ScopedPointer<WASAPIAudioIODevice> device;
  215071. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215072. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215073. if (outputIndex >= 0 || inputIndex >= 0)
  215074. {
  215075. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215076. : inputDeviceName,
  215077. outputDeviceIds [outputIndex],
  215078. inputDeviceIds [inputIndex],
  215079. useExclusiveMode);
  215080. if (! device->initialise())
  215081. device = 0;
  215082. }
  215083. return device.release();
  215084. }
  215085. juce_UseDebuggingNewOperator
  215086. StringArray outputDeviceNames, outputDeviceIds;
  215087. StringArray inputDeviceNames, inputDeviceIds;
  215088. private:
  215089. bool hasScanned;
  215090. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215091. {
  215092. String s;
  215093. IMMDevice* dev = 0;
  215094. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215095. eMultimedia, &dev)))
  215096. {
  215097. WCHAR* deviceId = 0;
  215098. if (OK (dev->GetId (&deviceId)))
  215099. {
  215100. s = String (deviceId);
  215101. CoTaskMemFree (deviceId);
  215102. }
  215103. dev->Release();
  215104. }
  215105. return s;
  215106. }
  215107. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  215108. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  215109. };
  215110. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215111. {
  215112. return new WASAPIAudioIODeviceType();
  215113. }
  215114. #undef logFailure
  215115. #undef OK
  215116. #endif
  215117. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215118. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215119. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215120. // compiled on its own).
  215121. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215122. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215123. {
  215124. public:
  215125. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215126. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215127. const ComSmartPtr <IBaseFilter>& filter_,
  215128. int minWidth, int minHeight,
  215129. int maxWidth, int maxHeight)
  215130. : owner (owner_),
  215131. captureGraphBuilder (captureGraphBuilder_),
  215132. filter (filter_),
  215133. ok (false),
  215134. imageNeedsFlipping (false),
  215135. width (0),
  215136. height (0),
  215137. activeUsers (0),
  215138. recordNextFrameTime (false)
  215139. {
  215140. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215141. if (FAILED (hr))
  215142. return;
  215143. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215144. if (FAILED (hr))
  215145. return;
  215146. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  215147. if (FAILED (hr))
  215148. return;
  215149. {
  215150. ComSmartPtr <IAMStreamConfig> streamConfig;
  215151. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215152. IID_IAMStreamConfig, (void**) &streamConfig);
  215153. if (streamConfig != 0)
  215154. {
  215155. getVideoSizes (streamConfig);
  215156. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215157. return;
  215158. }
  215159. }
  215160. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215161. if (FAILED (hr))
  215162. return;
  215163. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215164. if (FAILED (hr))
  215165. return;
  215166. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215167. if (FAILED (hr))
  215168. return;
  215169. if (! connectFilters (filter, smartTee))
  215170. return;
  215171. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215172. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215173. if (FAILED (hr))
  215174. return;
  215175. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  215176. if (FAILED (hr))
  215177. return;
  215178. AM_MEDIA_TYPE mt;
  215179. zerostruct (mt);
  215180. mt.majortype = MEDIATYPE_Video;
  215181. mt.subtype = MEDIASUBTYPE_RGB24;
  215182. mt.formattype = FORMAT_VideoInfo;
  215183. sampleGrabber->SetMediaType (&mt);
  215184. callback = new GrabberCallback (*this);
  215185. sampleGrabber->SetCallback (callback, 1);
  215186. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215187. if (FAILED (hr))
  215188. return;
  215189. ComSmartPtr <IPin> grabberInputPin;
  215190. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  215191. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  215192. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  215193. return;
  215194. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215195. if (FAILED (hr))
  215196. return;
  215197. zerostruct (mt);
  215198. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215199. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215200. width = pVih->bmiHeader.biWidth;
  215201. height = pVih->bmiHeader.biHeight;
  215202. ComSmartPtr <IBaseFilter> nullFilter;
  215203. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215204. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215205. if (connectFilters (sampleGrabberBase, nullFilter)
  215206. && addGraphToRot())
  215207. {
  215208. activeImage = Image (Image::RGB, width, height, true);
  215209. loadingImage = Image (Image::RGB, width, height, true);
  215210. ok = true;
  215211. }
  215212. }
  215213. ~DShowCameraDeviceInteral()
  215214. {
  215215. if (mediaControl != 0)
  215216. mediaControl->Stop();
  215217. removeGraphFromRot();
  215218. for (int i = viewerComps.size(); --i >= 0;)
  215219. viewerComps.getUnchecked(i)->ownerDeleted();
  215220. callback = 0;
  215221. graphBuilder = 0;
  215222. sampleGrabber = 0;
  215223. mediaControl = 0;
  215224. filter = 0;
  215225. captureGraphBuilder = 0;
  215226. smartTee = 0;
  215227. smartTeePreviewOutputPin = 0;
  215228. smartTeeCaptureOutputPin = 0;
  215229. asfWriter = 0;
  215230. }
  215231. void addUser()
  215232. {
  215233. if (ok && activeUsers++ == 0)
  215234. mediaControl->Run();
  215235. }
  215236. void removeUser()
  215237. {
  215238. if (ok && --activeUsers == 0)
  215239. mediaControl->Stop();
  215240. }
  215241. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215242. {
  215243. if (recordNextFrameTime)
  215244. {
  215245. const double defaultCameraLatency = 0.1;
  215246. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215247. recordNextFrameTime = false;
  215248. ComSmartPtr <IPin> pin;
  215249. if (getPin (filter, PINDIR_OUTPUT, &pin))
  215250. {
  215251. ComSmartPtr <IAMPushSource> pushSource;
  215252. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  215253. if (pushSource != 0)
  215254. {
  215255. REFERENCE_TIME latency = 0;
  215256. hr = pushSource->GetLatency (&latency);
  215257. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215258. }
  215259. }
  215260. }
  215261. {
  215262. const int lineStride = width * 3;
  215263. const ScopedLock sl (imageSwapLock);
  215264. {
  215265. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215266. for (int i = 0; i < height; ++i)
  215267. memcpy (destData.getLinePointer ((height - 1) - i),
  215268. buffer + lineStride * i,
  215269. lineStride);
  215270. }
  215271. imageNeedsFlipping = true;
  215272. }
  215273. if (listeners.size() > 0)
  215274. callListeners (loadingImage);
  215275. sendChangeMessage (this);
  215276. }
  215277. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215278. {
  215279. if (imageNeedsFlipping)
  215280. {
  215281. const ScopedLock sl (imageSwapLock);
  215282. swapVariables (loadingImage, activeImage);
  215283. imageNeedsFlipping = false;
  215284. }
  215285. RectanglePlacement rp (RectanglePlacement::centred);
  215286. double dx = 0, dy = 0, dw = width, dh = height;
  215287. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215288. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215289. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215290. g.saveState();
  215291. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215292. g.fillAll (Colours::black);
  215293. g.restoreState();
  215294. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215295. }
  215296. bool createFileCaptureFilter (const File& file)
  215297. {
  215298. removeFileCaptureFilter();
  215299. file.deleteFile();
  215300. mediaControl->Stop();
  215301. firstRecordedTime = Time();
  215302. recordNextFrameTime = true;
  215303. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215304. if (SUCCEEDED (hr))
  215305. {
  215306. ComSmartPtr <IFileSinkFilter> fileSink;
  215307. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  215308. if (SUCCEEDED (hr))
  215309. {
  215310. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  215311. if (SUCCEEDED (hr))
  215312. {
  215313. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215314. if (SUCCEEDED (hr))
  215315. {
  215316. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215317. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  215318. asfConfig->SetIndexMode (true);
  215319. ComSmartPtr <IWMProfileManager> profileManager;
  215320. hr = WMCreateProfileManager (&profileManager);
  215321. // This gibberish is the DirectShow profile for a video-only wmv file.
  215322. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  215323. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215324. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215325. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  215326. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  215327. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215328. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  215329. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  215330. prof = prof.replace ("$WIDTH", String (width))
  215331. .replace ("$HEIGHT", String (height));
  215332. ComSmartPtr <IWMProfile> currentProfile;
  215333. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  215334. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215335. if (SUCCEEDED (hr))
  215336. {
  215337. ComSmartPtr <IPin> asfWriterInputPin;
  215338. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  215339. {
  215340. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215341. if (SUCCEEDED (hr)
  215342. && ok && activeUsers > 0
  215343. && SUCCEEDED (mediaControl->Run()))
  215344. {
  215345. return true;
  215346. }
  215347. }
  215348. }
  215349. }
  215350. }
  215351. }
  215352. }
  215353. removeFileCaptureFilter();
  215354. if (ok && activeUsers > 0)
  215355. mediaControl->Run();
  215356. return false;
  215357. }
  215358. void removeFileCaptureFilter()
  215359. {
  215360. mediaControl->Stop();
  215361. if (asfWriter != 0)
  215362. {
  215363. graphBuilder->RemoveFilter (asfWriter);
  215364. asfWriter = 0;
  215365. }
  215366. if (ok && activeUsers > 0)
  215367. mediaControl->Run();
  215368. }
  215369. void addListener (CameraDevice::Listener* listenerToAdd)
  215370. {
  215371. const ScopedLock sl (listenerLock);
  215372. if (listeners.size() == 0)
  215373. addUser();
  215374. listeners.addIfNotAlreadyThere (listenerToAdd);
  215375. }
  215376. void removeListener (CameraDevice::Listener* listenerToRemove)
  215377. {
  215378. const ScopedLock sl (listenerLock);
  215379. listeners.removeValue (listenerToRemove);
  215380. if (listeners.size() == 0)
  215381. removeUser();
  215382. }
  215383. void callListeners (const Image& image)
  215384. {
  215385. const ScopedLock sl (listenerLock);
  215386. for (int i = listeners.size(); --i >= 0;)
  215387. {
  215388. CameraDevice::Listener* const l = listeners[i];
  215389. if (l != 0)
  215390. l->imageReceived (image);
  215391. }
  215392. }
  215393. class DShowCaptureViewerComp : public Component,
  215394. public ChangeListener
  215395. {
  215396. public:
  215397. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215398. : owner (owner_)
  215399. {
  215400. setOpaque (true);
  215401. owner->addChangeListener (this);
  215402. owner->addUser();
  215403. owner->viewerComps.add (this);
  215404. setSize (owner_->width, owner_->height);
  215405. }
  215406. ~DShowCaptureViewerComp()
  215407. {
  215408. if (owner != 0)
  215409. {
  215410. owner->viewerComps.removeValue (this);
  215411. owner->removeUser();
  215412. owner->removeChangeListener (this);
  215413. }
  215414. }
  215415. void ownerDeleted()
  215416. {
  215417. owner = 0;
  215418. }
  215419. void paint (Graphics& g)
  215420. {
  215421. g.setColour (Colours::black);
  215422. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215423. if (owner != 0)
  215424. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215425. else
  215426. g.fillAll (Colours::black);
  215427. }
  215428. void changeListenerCallback (void*)
  215429. {
  215430. repaint();
  215431. }
  215432. private:
  215433. DShowCameraDeviceInteral* owner;
  215434. };
  215435. bool ok;
  215436. int width, height;
  215437. Time firstRecordedTime;
  215438. Array <DShowCaptureViewerComp*> viewerComps;
  215439. private:
  215440. CameraDevice* const owner;
  215441. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215442. ComSmartPtr <IBaseFilter> filter;
  215443. ComSmartPtr <IBaseFilter> smartTee;
  215444. ComSmartPtr <IGraphBuilder> graphBuilder;
  215445. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215446. ComSmartPtr <IMediaControl> mediaControl;
  215447. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215448. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215449. ComSmartPtr <IBaseFilter> asfWriter;
  215450. int activeUsers;
  215451. Array <int> widths, heights;
  215452. DWORD graphRegistrationID;
  215453. CriticalSection imageSwapLock;
  215454. bool imageNeedsFlipping;
  215455. Image loadingImage;
  215456. Image activeImage;
  215457. bool recordNextFrameTime;
  215458. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215459. {
  215460. widths.clear();
  215461. heights.clear();
  215462. int count = 0, size = 0;
  215463. streamConfig->GetNumberOfCapabilities (&count, &size);
  215464. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215465. {
  215466. for (int i = 0; i < count; ++i)
  215467. {
  215468. VIDEO_STREAM_CONFIG_CAPS scc;
  215469. AM_MEDIA_TYPE* config;
  215470. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215471. if (SUCCEEDED (hr))
  215472. {
  215473. const int w = scc.InputSize.cx;
  215474. const int h = scc.InputSize.cy;
  215475. bool duplicate = false;
  215476. for (int j = widths.size(); --j >= 0;)
  215477. {
  215478. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215479. {
  215480. duplicate = true;
  215481. break;
  215482. }
  215483. }
  215484. if (! duplicate)
  215485. {
  215486. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215487. widths.add (w);
  215488. heights.add (h);
  215489. }
  215490. deleteMediaType (config);
  215491. }
  215492. }
  215493. }
  215494. }
  215495. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215496. const int minWidth, const int minHeight,
  215497. const int maxWidth, const int maxHeight)
  215498. {
  215499. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215500. streamConfig->GetNumberOfCapabilities (&count, &size);
  215501. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215502. {
  215503. AM_MEDIA_TYPE* config;
  215504. VIDEO_STREAM_CONFIG_CAPS scc;
  215505. for (int i = 0; i < count; ++i)
  215506. {
  215507. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215508. if (SUCCEEDED (hr))
  215509. {
  215510. if (scc.InputSize.cx >= minWidth
  215511. && scc.InputSize.cy >= minHeight
  215512. && scc.InputSize.cx <= maxWidth
  215513. && scc.InputSize.cy <= maxHeight)
  215514. {
  215515. int area = scc.InputSize.cx * scc.InputSize.cy;
  215516. if (area > bestArea)
  215517. {
  215518. bestIndex = i;
  215519. bestArea = area;
  215520. }
  215521. }
  215522. deleteMediaType (config);
  215523. }
  215524. }
  215525. if (bestIndex >= 0)
  215526. {
  215527. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215528. hr = streamConfig->SetFormat (config);
  215529. deleteMediaType (config);
  215530. return SUCCEEDED (hr);
  215531. }
  215532. }
  215533. return false;
  215534. }
  215535. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  215536. {
  215537. ComSmartPtr <IEnumPins> enumerator;
  215538. ComSmartPtr <IPin> pin;
  215539. filter->EnumPins (&enumerator);
  215540. while (enumerator->Next (1, &pin, 0) == S_OK)
  215541. {
  215542. PIN_DIRECTION dir;
  215543. pin->QueryDirection (&dir);
  215544. if (wantedDirection == dir)
  215545. {
  215546. PIN_INFO info;
  215547. zerostruct (info);
  215548. pin->QueryPinInfo (&info);
  215549. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215550. {
  215551. pin->AddRef();
  215552. *result = pin;
  215553. return true;
  215554. }
  215555. }
  215556. }
  215557. return false;
  215558. }
  215559. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215560. {
  215561. ComSmartPtr <IPin> in, out;
  215562. return getPin (first, PINDIR_OUTPUT, &out)
  215563. && getPin (second, PINDIR_INPUT, &in)
  215564. && SUCCEEDED (graphBuilder->Connect (out, in));
  215565. }
  215566. bool addGraphToRot()
  215567. {
  215568. ComSmartPtr <IRunningObjectTable> rot;
  215569. if (FAILED (GetRunningObjectTable (0, &rot)))
  215570. return false;
  215571. ComSmartPtr <IMoniker> moniker;
  215572. WCHAR buffer[128];
  215573. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  215574. if (FAILED (hr))
  215575. return false;
  215576. graphRegistrationID = 0;
  215577. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215578. }
  215579. void removeGraphFromRot()
  215580. {
  215581. ComSmartPtr <IRunningObjectTable> rot;
  215582. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  215583. rot->Revoke (graphRegistrationID);
  215584. }
  215585. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215586. {
  215587. if (pmt->cbFormat != 0)
  215588. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215589. if (pmt->pUnk != 0)
  215590. pmt->pUnk->Release();
  215591. CoTaskMemFree (pmt);
  215592. }
  215593. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215594. {
  215595. public:
  215596. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215597. : owner (owner_)
  215598. {
  215599. }
  215600. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215601. {
  215602. return E_FAIL;
  215603. }
  215604. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215605. {
  215606. owner.handleFrame (time, buffer, bufferSize);
  215607. return S_OK;
  215608. }
  215609. private:
  215610. DShowCameraDeviceInteral& owner;
  215611. GrabberCallback (const GrabberCallback&);
  215612. GrabberCallback& operator= (const GrabberCallback&);
  215613. };
  215614. ComSmartPtr <GrabberCallback> callback;
  215615. Array <CameraDevice::Listener*> listeners;
  215616. CriticalSection listenerLock;
  215617. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  215618. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  215619. };
  215620. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215621. : name (name_)
  215622. {
  215623. isRecording = false;
  215624. }
  215625. CameraDevice::~CameraDevice()
  215626. {
  215627. stopRecording();
  215628. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215629. internal = 0;
  215630. }
  215631. Component* CameraDevice::createViewerComponent()
  215632. {
  215633. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215634. }
  215635. const String CameraDevice::getFileExtension()
  215636. {
  215637. return ".wmv";
  215638. }
  215639. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215640. {
  215641. stopRecording();
  215642. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215643. d->addUser();
  215644. isRecording = d->createFileCaptureFilter (file);
  215645. }
  215646. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215647. {
  215648. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215649. return d->firstRecordedTime;
  215650. }
  215651. void CameraDevice::stopRecording()
  215652. {
  215653. if (isRecording)
  215654. {
  215655. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215656. d->removeFileCaptureFilter();
  215657. d->removeUser();
  215658. isRecording = false;
  215659. }
  215660. }
  215661. void CameraDevice::addListener (Listener* listenerToAdd)
  215662. {
  215663. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215664. if (listenerToAdd != 0)
  215665. d->addListener (listenerToAdd);
  215666. }
  215667. void CameraDevice::removeListener (Listener* listenerToRemove)
  215668. {
  215669. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215670. if (listenerToRemove != 0)
  215671. d->removeListener (listenerToRemove);
  215672. }
  215673. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215674. const int deviceIndexToOpen,
  215675. String& name)
  215676. {
  215677. int index = 0;
  215678. ComSmartPtr <IBaseFilter> result;
  215679. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215680. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215681. if (SUCCEEDED (hr))
  215682. {
  215683. ComSmartPtr <IEnumMoniker> enumerator;
  215684. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  215685. if (SUCCEEDED (hr) && enumerator != 0)
  215686. {
  215687. ComSmartPtr <IBaseFilter> captureFilter;
  215688. ComSmartPtr <IMoniker> moniker;
  215689. ULONG fetched;
  215690. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  215691. {
  215692. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  215693. if (SUCCEEDED (hr))
  215694. {
  215695. ComSmartPtr <IPropertyBag> propertyBag;
  215696. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  215697. if (SUCCEEDED (hr))
  215698. {
  215699. VARIANT var;
  215700. var.vt = VT_BSTR;
  215701. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215702. propertyBag = 0;
  215703. if (SUCCEEDED (hr))
  215704. {
  215705. if (names != 0)
  215706. names->add (var.bstrVal);
  215707. if (index == deviceIndexToOpen)
  215708. {
  215709. name = var.bstrVal;
  215710. result = captureFilter;
  215711. captureFilter = 0;
  215712. break;
  215713. }
  215714. ++index;
  215715. }
  215716. moniker = 0;
  215717. }
  215718. captureFilter = 0;
  215719. }
  215720. }
  215721. }
  215722. }
  215723. return result;
  215724. }
  215725. const StringArray CameraDevice::getAvailableDevices()
  215726. {
  215727. StringArray devs;
  215728. String dummy;
  215729. enumerateCameras (&devs, -1, dummy);
  215730. return devs;
  215731. }
  215732. CameraDevice* CameraDevice::openDevice (int index,
  215733. int minWidth, int minHeight,
  215734. int maxWidth, int maxHeight)
  215735. {
  215736. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215737. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215738. if (SUCCEEDED (hr))
  215739. {
  215740. String name;
  215741. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215742. if (filter != 0)
  215743. {
  215744. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215745. DShowCameraDeviceInteral* const intern
  215746. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215747. minWidth, minHeight, maxWidth, maxHeight);
  215748. cam->internal = intern;
  215749. if (intern->ok)
  215750. return cam.release();
  215751. }
  215752. }
  215753. return 0;
  215754. }
  215755. #endif
  215756. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215757. #endif
  215758. // Auto-link the other win32 libs that are needed by library calls..
  215759. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215760. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215761. // Auto-links to various win32 libs that are needed by library calls..
  215762. #pragma comment(lib, "kernel32.lib")
  215763. #pragma comment(lib, "user32.lib")
  215764. #pragma comment(lib, "shell32.lib")
  215765. #pragma comment(lib, "gdi32.lib")
  215766. #pragma comment(lib, "vfw32.lib")
  215767. #pragma comment(lib, "comdlg32.lib")
  215768. #pragma comment(lib, "winmm.lib")
  215769. #pragma comment(lib, "wininet.lib")
  215770. #pragma comment(lib, "ole32.lib")
  215771. #pragma comment(lib, "oleaut32.lib")
  215772. #pragma comment(lib, "advapi32.lib")
  215773. #pragma comment(lib, "ws2_32.lib")
  215774. #pragma comment(lib, "comsupp.lib")
  215775. #pragma comment(lib, "version.lib")
  215776. #if JUCE_OPENGL
  215777. #pragma comment(lib, "OpenGL32.Lib")
  215778. #pragma comment(lib, "GlU32.Lib")
  215779. #endif
  215780. #if JUCE_QUICKTIME
  215781. #pragma comment (lib, "QTMLClient.lib")
  215782. #endif
  215783. #if JUCE_USE_CAMERA
  215784. #pragma comment (lib, "Strmiids.lib")
  215785. #pragma comment (lib, "wmvcore.lib")
  215786. #endif
  215787. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215788. #endif
  215789. END_JUCE_NAMESPACE
  215790. #endif
  215791. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  215792. #endif
  215793. #if JUCE_LINUX
  215794. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  215795. /*
  215796. This file wraps together all the mac-specific code, so that
  215797. we can include all the native headers just once, and compile all our
  215798. platform-specific stuff in one big lump, keeping it out of the way of
  215799. the rest of the codebase.
  215800. */
  215801. #if JUCE_LINUX
  215802. BEGIN_JUCE_NAMESPACE
  215803. #define JUCE_INCLUDED_FILE 1
  215804. // Now include the actual code files..
  215805. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  215806. /*
  215807. This file contains posix routines that are common to both the Linux and Mac builds.
  215808. It gets included directly in the cpp files for these platforms.
  215809. */
  215810. CriticalSection::CriticalSection() throw()
  215811. {
  215812. pthread_mutexattr_t atts;
  215813. pthread_mutexattr_init (&atts);
  215814. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  215815. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215816. pthread_mutex_init (&internal, &atts);
  215817. }
  215818. CriticalSection::~CriticalSection() throw()
  215819. {
  215820. pthread_mutex_destroy (&internal);
  215821. }
  215822. void CriticalSection::enter() const throw()
  215823. {
  215824. pthread_mutex_lock (&internal);
  215825. }
  215826. bool CriticalSection::tryEnter() const throw()
  215827. {
  215828. return pthread_mutex_trylock (&internal) == 0;
  215829. }
  215830. void CriticalSection::exit() const throw()
  215831. {
  215832. pthread_mutex_unlock (&internal);
  215833. }
  215834. class WaitableEventImpl
  215835. {
  215836. public:
  215837. WaitableEventImpl (const bool manualReset_)
  215838. : triggered (false),
  215839. manualReset (manualReset_)
  215840. {
  215841. pthread_cond_init (&condition, 0);
  215842. pthread_mutexattr_t atts;
  215843. pthread_mutexattr_init (&atts);
  215844. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215845. pthread_mutex_init (&mutex, &atts);
  215846. }
  215847. ~WaitableEventImpl()
  215848. {
  215849. pthread_cond_destroy (&condition);
  215850. pthread_mutex_destroy (&mutex);
  215851. }
  215852. bool wait (const int timeOutMillisecs) throw()
  215853. {
  215854. pthread_mutex_lock (&mutex);
  215855. if (! triggered)
  215856. {
  215857. if (timeOutMillisecs < 0)
  215858. {
  215859. do
  215860. {
  215861. pthread_cond_wait (&condition, &mutex);
  215862. }
  215863. while (! triggered);
  215864. }
  215865. else
  215866. {
  215867. struct timeval now;
  215868. gettimeofday (&now, 0);
  215869. struct timespec time;
  215870. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  215871. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  215872. if (time.tv_nsec >= 1000000000)
  215873. {
  215874. time.tv_nsec -= 1000000000;
  215875. time.tv_sec++;
  215876. }
  215877. do
  215878. {
  215879. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  215880. {
  215881. pthread_mutex_unlock (&mutex);
  215882. return false;
  215883. }
  215884. }
  215885. while (! triggered);
  215886. }
  215887. }
  215888. if (! manualReset)
  215889. triggered = false;
  215890. pthread_mutex_unlock (&mutex);
  215891. return true;
  215892. }
  215893. void signal() throw()
  215894. {
  215895. pthread_mutex_lock (&mutex);
  215896. triggered = true;
  215897. pthread_cond_broadcast (&condition);
  215898. pthread_mutex_unlock (&mutex);
  215899. }
  215900. void reset() throw()
  215901. {
  215902. pthread_mutex_lock (&mutex);
  215903. triggered = false;
  215904. pthread_mutex_unlock (&mutex);
  215905. }
  215906. private:
  215907. pthread_cond_t condition;
  215908. pthread_mutex_t mutex;
  215909. bool triggered;
  215910. const bool manualReset;
  215911. WaitableEventImpl (const WaitableEventImpl&);
  215912. WaitableEventImpl& operator= (const WaitableEventImpl&);
  215913. };
  215914. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  215915. : internal (new WaitableEventImpl (manualReset))
  215916. {
  215917. }
  215918. WaitableEvent::~WaitableEvent() throw()
  215919. {
  215920. delete static_cast <WaitableEventImpl*> (internal);
  215921. }
  215922. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  215923. {
  215924. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  215925. }
  215926. void WaitableEvent::signal() const throw()
  215927. {
  215928. static_cast <WaitableEventImpl*> (internal)->signal();
  215929. }
  215930. void WaitableEvent::reset() const throw()
  215931. {
  215932. static_cast <WaitableEventImpl*> (internal)->reset();
  215933. }
  215934. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  215935. {
  215936. struct timespec time;
  215937. time.tv_sec = millisecs / 1000;
  215938. time.tv_nsec = (millisecs % 1000) * 1000000;
  215939. nanosleep (&time, 0);
  215940. }
  215941. const juce_wchar File::separator = '/';
  215942. const String File::separatorString ("/");
  215943. const File File::getCurrentWorkingDirectory()
  215944. {
  215945. HeapBlock<char> heapBuffer;
  215946. char localBuffer [1024];
  215947. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  215948. int bufferSize = 4096;
  215949. while (cwd == 0 && errno == ERANGE)
  215950. {
  215951. heapBuffer.malloc (bufferSize);
  215952. cwd = getcwd (heapBuffer, bufferSize - 1);
  215953. bufferSize += 1024;
  215954. }
  215955. return File (String::fromUTF8 (cwd));
  215956. }
  215957. bool File::setAsCurrentWorkingDirectory() const
  215958. {
  215959. return chdir (getFullPathName().toUTF8()) == 0;
  215960. }
  215961. static bool juce_stat (const String& fileName, struct stat& info)
  215962. {
  215963. return fileName.isNotEmpty()
  215964. && (stat (fileName.toUTF8(), &info) == 0);
  215965. }
  215966. bool File::isDirectory() const
  215967. {
  215968. struct stat info;
  215969. return fullPath.isEmpty()
  215970. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  215971. }
  215972. bool File::exists() const
  215973. {
  215974. return fullPath.isNotEmpty()
  215975. && access (fullPath.toUTF8(), F_OK) == 0;
  215976. }
  215977. bool File::existsAsFile() const
  215978. {
  215979. return exists() && ! isDirectory();
  215980. }
  215981. int64 File::getSize() const
  215982. {
  215983. struct stat info;
  215984. return juce_stat (fullPath, info) ? info.st_size : 0;
  215985. }
  215986. bool File::hasWriteAccess() const
  215987. {
  215988. if (exists())
  215989. return access (fullPath.toUTF8(), W_OK) == 0;
  215990. if ((! isDirectory()) && fullPath.containsChar (separator))
  215991. return getParentDirectory().hasWriteAccess();
  215992. return false;
  215993. }
  215994. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  215995. {
  215996. struct stat info;
  215997. const int res = stat (fullPath.toUTF8(), &info);
  215998. if (res != 0)
  215999. return false;
  216000. info.st_mode &= 0777; // Just permissions
  216001. if (shouldBeReadOnly)
  216002. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216003. else
  216004. // Give everybody write permission?
  216005. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216006. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216007. }
  216008. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216009. {
  216010. modificationTime = 0;
  216011. accessTime = 0;
  216012. creationTime = 0;
  216013. struct stat info;
  216014. const int res = stat (fullPath.toUTF8(), &info);
  216015. if (res == 0)
  216016. {
  216017. modificationTime = (int64) info.st_mtime * 1000;
  216018. accessTime = (int64) info.st_atime * 1000;
  216019. creationTime = (int64) info.st_ctime * 1000;
  216020. }
  216021. }
  216022. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216023. {
  216024. struct utimbuf times;
  216025. times.actime = (time_t) (accessTime / 1000);
  216026. times.modtime = (time_t) (modificationTime / 1000);
  216027. return utime (fullPath.toUTF8(), &times) == 0;
  216028. }
  216029. bool File::deleteFile() const
  216030. {
  216031. if (! exists())
  216032. return true;
  216033. else if (isDirectory())
  216034. return rmdir (fullPath.toUTF8()) == 0;
  216035. else
  216036. return remove (fullPath.toUTF8()) == 0;
  216037. }
  216038. bool File::moveInternal (const File& dest) const
  216039. {
  216040. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216041. return true;
  216042. if (hasWriteAccess() && copyInternal (dest))
  216043. {
  216044. if (deleteFile())
  216045. return true;
  216046. dest.deleteFile();
  216047. }
  216048. return false;
  216049. }
  216050. void File::createDirectoryInternal (const String& fileName) const
  216051. {
  216052. mkdir (fileName.toUTF8(), 0777);
  216053. }
  216054. void* juce_fileOpen (const File& file, bool forWriting)
  216055. {
  216056. int flags = O_RDONLY;
  216057. if (forWriting)
  216058. {
  216059. if (file.exists())
  216060. {
  216061. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216062. if (f != -1)
  216063. lseek (f, 0, SEEK_END);
  216064. return (void*) f;
  216065. }
  216066. else
  216067. {
  216068. flags = O_RDWR + O_CREAT;
  216069. }
  216070. }
  216071. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  216072. }
  216073. void juce_fileClose (void* handle)
  216074. {
  216075. if (handle != 0)
  216076. close ((int) (pointer_sized_int) handle);
  216077. }
  216078. int juce_fileRead (void* handle, void* buffer, int size)
  216079. {
  216080. if (handle != 0)
  216081. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  216082. return 0;
  216083. }
  216084. int juce_fileWrite (void* handle, const void* buffer, int size)
  216085. {
  216086. if (handle != 0)
  216087. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  216088. return 0;
  216089. }
  216090. int64 juce_fileSetPosition (void* handle, int64 pos)
  216091. {
  216092. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216093. return pos;
  216094. return -1;
  216095. }
  216096. int64 FileOutputStream::getPositionInternal() const
  216097. {
  216098. if (fileHandle != 0)
  216099. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  216100. return -1;
  216101. }
  216102. void FileOutputStream::flushInternal()
  216103. {
  216104. if (fileHandle != 0)
  216105. fsync ((int) (pointer_sized_int) fileHandle);
  216106. }
  216107. const File juce_getExecutableFile()
  216108. {
  216109. Dl_info exeInfo;
  216110. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  216111. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216112. }
  216113. // if this file doesn't exist, find a parent of it that does..
  216114. static bool juce_doStatFS (File f, struct statfs& result)
  216115. {
  216116. for (int i = 5; --i >= 0;)
  216117. {
  216118. if (f.exists())
  216119. break;
  216120. f = f.getParentDirectory();
  216121. }
  216122. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216123. }
  216124. int64 File::getBytesFreeOnVolume() const
  216125. {
  216126. struct statfs buf;
  216127. if (juce_doStatFS (*this, buf))
  216128. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216129. return 0;
  216130. }
  216131. int64 File::getVolumeTotalSize() const
  216132. {
  216133. struct statfs buf;
  216134. if (juce_doStatFS (*this, buf))
  216135. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216136. return 0;
  216137. }
  216138. const String File::getVolumeLabel() const
  216139. {
  216140. #if JUCE_MAC
  216141. struct VolAttrBuf
  216142. {
  216143. u_int32_t length;
  216144. attrreference_t mountPointRef;
  216145. char mountPointSpace [MAXPATHLEN];
  216146. } attrBuf;
  216147. struct attrlist attrList;
  216148. zerostruct (attrList);
  216149. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216150. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216151. File f (*this);
  216152. for (;;)
  216153. {
  216154. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216155. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216156. (int) attrBuf.mountPointRef.attr_length);
  216157. const File parent (f.getParentDirectory());
  216158. if (f == parent)
  216159. break;
  216160. f = parent;
  216161. }
  216162. #endif
  216163. return String::empty;
  216164. }
  216165. int File::getVolumeSerialNumber() const
  216166. {
  216167. return 0; // xxx
  216168. }
  216169. void juce_runSystemCommand (const String& command)
  216170. {
  216171. int result = system (command.toUTF8());
  216172. (void) result;
  216173. }
  216174. const String juce_getOutputFromCommand (const String& command)
  216175. {
  216176. // slight bodge here, as we just pipe the output into a temp file and read it...
  216177. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216178. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216179. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216180. String result (tempFile.loadFileAsString());
  216181. tempFile.deleteFile();
  216182. return result;
  216183. }
  216184. class InterProcessLock::Pimpl
  216185. {
  216186. public:
  216187. Pimpl (const String& name, const int timeOutMillisecs)
  216188. : handle (0), refCount (1)
  216189. {
  216190. #if JUCE_MAC
  216191. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216192. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216193. #else
  216194. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216195. #endif
  216196. temp.create();
  216197. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216198. if (handle != 0)
  216199. {
  216200. struct flock fl;
  216201. zerostruct (fl);
  216202. fl.l_whence = SEEK_SET;
  216203. fl.l_type = F_WRLCK;
  216204. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216205. for (;;)
  216206. {
  216207. const int result = fcntl (handle, F_SETLK, &fl);
  216208. if (result >= 0)
  216209. return;
  216210. if (errno != EINTR)
  216211. {
  216212. if (timeOutMillisecs == 0
  216213. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216214. break;
  216215. Thread::sleep (10);
  216216. }
  216217. }
  216218. }
  216219. closeFile();
  216220. }
  216221. ~Pimpl()
  216222. {
  216223. closeFile();
  216224. }
  216225. void closeFile()
  216226. {
  216227. if (handle != 0)
  216228. {
  216229. struct flock fl;
  216230. zerostruct (fl);
  216231. fl.l_whence = SEEK_SET;
  216232. fl.l_type = F_UNLCK;
  216233. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216234. {}
  216235. close (handle);
  216236. handle = 0;
  216237. }
  216238. }
  216239. int handle, refCount;
  216240. };
  216241. InterProcessLock::InterProcessLock (const String& name_)
  216242. : name (name_)
  216243. {
  216244. }
  216245. InterProcessLock::~InterProcessLock()
  216246. {
  216247. }
  216248. bool InterProcessLock::enter (const int timeOutMillisecs)
  216249. {
  216250. const ScopedLock sl (lock);
  216251. if (pimpl == 0)
  216252. {
  216253. pimpl = new Pimpl (name, timeOutMillisecs);
  216254. if (pimpl->handle == 0)
  216255. pimpl = 0;
  216256. }
  216257. else
  216258. {
  216259. pimpl->refCount++;
  216260. }
  216261. return pimpl != 0;
  216262. }
  216263. void InterProcessLock::exit()
  216264. {
  216265. const ScopedLock sl (lock);
  216266. // Trying to release the lock too many times!
  216267. jassert (pimpl != 0);
  216268. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216269. pimpl = 0;
  216270. }
  216271. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216272. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216273. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216274. // compiled on its own).
  216275. #if JUCE_INCLUDED_FILE
  216276. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  216277. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  216278. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  216279. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  216280. bool File::copyInternal (const File& dest) const
  216281. {
  216282. FileInputStream in (*this);
  216283. if (dest.deleteFile())
  216284. {
  216285. {
  216286. FileOutputStream out (dest);
  216287. if (out.failedToOpen())
  216288. return false;
  216289. if (out.writeFromInputStream (in, -1) == getSize())
  216290. return true;
  216291. }
  216292. dest.deleteFile();
  216293. }
  216294. return false;
  216295. }
  216296. void File::findFileSystemRoots (Array<File>& destArray)
  216297. {
  216298. destArray.add (File ("/"));
  216299. }
  216300. bool File::isOnCDRomDrive() const
  216301. {
  216302. struct statfs buf;
  216303. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216304. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  216305. }
  216306. bool File::isOnHardDisk() const
  216307. {
  216308. struct statfs buf;
  216309. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216310. {
  216311. switch (buf.f_type)
  216312. {
  216313. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216314. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216315. case U_NFS_SUPER_MAGIC: // Network NFS
  216316. case U_SMB_SUPER_MAGIC: // Network Samba
  216317. return false;
  216318. default:
  216319. // Assume anything else is a hard-disk (but note it could
  216320. // be a RAM disk. There isn't a good way of determining
  216321. // this for sure)
  216322. return true;
  216323. }
  216324. }
  216325. // Assume so if this fails for some reason
  216326. return true;
  216327. }
  216328. bool File::isOnRemovableDrive() const
  216329. {
  216330. jassertfalse; // xxx not implemented for linux!
  216331. return false;
  216332. }
  216333. bool File::isHidden() const
  216334. {
  216335. return getFileName().startsWithChar ('.');
  216336. }
  216337. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216338. const File File::getSpecialLocation (const SpecialLocationType type)
  216339. {
  216340. switch (type)
  216341. {
  216342. case userHomeDirectory:
  216343. {
  216344. const char* homeDir = getenv ("HOME");
  216345. if (homeDir == 0)
  216346. {
  216347. struct passwd* const pw = getpwuid (getuid());
  216348. if (pw != 0)
  216349. homeDir = pw->pw_dir;
  216350. }
  216351. return File (String::fromUTF8 (homeDir));
  216352. }
  216353. case userDocumentsDirectory:
  216354. case userMusicDirectory:
  216355. case userMoviesDirectory:
  216356. case userApplicationDataDirectory:
  216357. return File ("~");
  216358. case userDesktopDirectory:
  216359. return File ("~/Desktop");
  216360. case commonApplicationDataDirectory:
  216361. return File ("/var");
  216362. case globalApplicationsDirectory:
  216363. return File ("/usr");
  216364. case tempDirectory:
  216365. {
  216366. File tmp ("/var/tmp");
  216367. if (! tmp.isDirectory())
  216368. {
  216369. tmp = "/tmp";
  216370. if (! tmp.isDirectory())
  216371. tmp = File::getCurrentWorkingDirectory();
  216372. }
  216373. return tmp;
  216374. }
  216375. case invokedExecutableFile:
  216376. if (juce_Argv0 != 0)
  216377. return File (String::fromUTF8 (juce_Argv0));
  216378. // deliberate fall-through...
  216379. case currentExecutableFile:
  216380. case currentApplicationFile:
  216381. return juce_getExecutableFile();
  216382. default:
  216383. jassertfalse; // unknown type?
  216384. break;
  216385. }
  216386. return File::nonexistent;
  216387. }
  216388. const String File::getVersion() const
  216389. {
  216390. return String::empty; // xxx not yet implemented
  216391. }
  216392. const File File::getLinkedTarget() const
  216393. {
  216394. char buffer [4096];
  216395. size_t numChars = readlink (getFullPathName().toUTF8(),
  216396. buffer, sizeof (buffer));
  216397. if (numChars > 0 && numChars <= sizeof (buffer))
  216398. return File (String::fromUTF8 (buffer, (int) numChars));
  216399. return *this;
  216400. }
  216401. bool File::moveToTrash() const
  216402. {
  216403. if (! exists())
  216404. return true;
  216405. File trashCan ("~/.Trash");
  216406. if (! trashCan.isDirectory())
  216407. trashCan = "~/.local/share/Trash/files";
  216408. if (! trashCan.isDirectory())
  216409. return false;
  216410. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216411. getFileExtension()));
  216412. }
  216413. class DirectoryIterator::NativeIterator::Pimpl
  216414. {
  216415. public:
  216416. Pimpl (const File& directory, const String& wildCard_)
  216417. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216418. wildCard (wildCard_),
  216419. dir (opendir (directory.getFullPathName().toUTF8()))
  216420. {
  216421. if (wildCard == "*.*")
  216422. wildCard = "*";
  216423. wildcardUTF8 = wildCard.toUTF8();
  216424. }
  216425. ~Pimpl()
  216426. {
  216427. if (dir != 0)
  216428. closedir (dir);
  216429. }
  216430. bool next (String& filenameFound,
  216431. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216432. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216433. {
  216434. if (dir == 0)
  216435. return false;
  216436. for (;;)
  216437. {
  216438. struct dirent* const de = readdir (dir);
  216439. if (de == 0)
  216440. return false;
  216441. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216442. {
  216443. filenameFound = String::fromUTF8 (de->d_name);
  216444. const String path (parentDir + filenameFound);
  216445. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216446. {
  216447. struct stat info;
  216448. const bool statOk = juce_stat (path, info);
  216449. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216450. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216451. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  216452. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  216453. }
  216454. if (isHidden != 0)
  216455. *isHidden = filenameFound.startsWithChar ('.');
  216456. if (isReadOnly != 0)
  216457. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216458. return true;
  216459. }
  216460. }
  216461. }
  216462. private:
  216463. String parentDir, wildCard;
  216464. const char* wildcardUTF8;
  216465. DIR* dir;
  216466. Pimpl (const Pimpl&);
  216467. Pimpl& operator= (const Pimpl&);
  216468. };
  216469. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216470. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216471. {
  216472. }
  216473. DirectoryIterator::NativeIterator::~NativeIterator()
  216474. {
  216475. }
  216476. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216477. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216478. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216479. {
  216480. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216481. }
  216482. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216483. {
  216484. String cmdString (fileName.replace (" ", "\\ ",false));
  216485. cmdString << " " << parameters;
  216486. if (URL::isProbablyAWebsiteURL (fileName)
  216487. || cmdString.startsWithIgnoreCase ("file:")
  216488. || URL::isProbablyAnEmailAddress (fileName))
  216489. {
  216490. // create a command that tries to launch a bunch of likely browsers
  216491. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216492. StringArray cmdLines;
  216493. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216494. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216495. cmdString = cmdLines.joinIntoString (" || ");
  216496. }
  216497. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216498. const int cpid = fork();
  216499. if (cpid == 0)
  216500. {
  216501. setsid();
  216502. // Child process
  216503. execve (argv[0], (char**) argv, environ);
  216504. exit (0);
  216505. }
  216506. return cpid >= 0;
  216507. }
  216508. void File::revealToUser() const
  216509. {
  216510. if (isDirectory())
  216511. startAsProcess();
  216512. else if (getParentDirectory().exists())
  216513. getParentDirectory().startAsProcess();
  216514. }
  216515. #endif
  216516. /*** End of inlined file: juce_linux_Files.cpp ***/
  216517. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216518. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216519. // compiled on its own).
  216520. #if JUCE_INCLUDED_FILE
  216521. struct NamedPipeInternal
  216522. {
  216523. String pipeInName, pipeOutName;
  216524. int pipeIn, pipeOut;
  216525. bool volatile createdPipe, blocked, stopReadOperation;
  216526. static void signalHandler (int) {}
  216527. };
  216528. void NamedPipe::cancelPendingReads()
  216529. {
  216530. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  216531. {
  216532. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216533. intern->stopReadOperation = true;
  216534. char buffer [1] = { 0 };
  216535. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216536. (void) bytesWritten;
  216537. int timeout = 2000;
  216538. while (intern->blocked && --timeout >= 0)
  216539. Thread::sleep (2);
  216540. intern->stopReadOperation = false;
  216541. }
  216542. }
  216543. void NamedPipe::close()
  216544. {
  216545. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216546. if (intern != 0)
  216547. {
  216548. internal = 0;
  216549. if (intern->pipeIn != -1)
  216550. ::close (intern->pipeIn);
  216551. if (intern->pipeOut != -1)
  216552. ::close (intern->pipeOut);
  216553. if (intern->createdPipe)
  216554. {
  216555. unlink (intern->pipeInName.toUTF8());
  216556. unlink (intern->pipeOutName.toUTF8());
  216557. }
  216558. delete intern;
  216559. }
  216560. }
  216561. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216562. {
  216563. close();
  216564. NamedPipeInternal* const intern = new NamedPipeInternal();
  216565. internal = intern;
  216566. intern->createdPipe = createPipe;
  216567. intern->blocked = false;
  216568. intern->stopReadOperation = false;
  216569. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216570. siginterrupt (SIGPIPE, 1);
  216571. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216572. intern->pipeInName = pipePath + "_in";
  216573. intern->pipeOutName = pipePath + "_out";
  216574. intern->pipeIn = -1;
  216575. intern->pipeOut = -1;
  216576. if (createPipe)
  216577. {
  216578. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216579. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216580. {
  216581. delete intern;
  216582. internal = 0;
  216583. return false;
  216584. }
  216585. }
  216586. return true;
  216587. }
  216588. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216589. {
  216590. int bytesRead = -1;
  216591. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216592. if (intern != 0)
  216593. {
  216594. intern->blocked = true;
  216595. if (intern->pipeIn == -1)
  216596. {
  216597. if (intern->createdPipe)
  216598. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216599. else
  216600. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216601. if (intern->pipeIn == -1)
  216602. {
  216603. intern->blocked = false;
  216604. return -1;
  216605. }
  216606. }
  216607. bytesRead = 0;
  216608. char* p = (char*) destBuffer;
  216609. while (bytesRead < maxBytesToRead)
  216610. {
  216611. const int bytesThisTime = maxBytesToRead - bytesRead;
  216612. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216613. if (numRead <= 0 || intern->stopReadOperation)
  216614. {
  216615. bytesRead = -1;
  216616. break;
  216617. }
  216618. bytesRead += numRead;
  216619. p += bytesRead;
  216620. }
  216621. intern->blocked = false;
  216622. }
  216623. return bytesRead;
  216624. }
  216625. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216626. {
  216627. int bytesWritten = -1;
  216628. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216629. if (intern != 0)
  216630. {
  216631. if (intern->pipeOut == -1)
  216632. {
  216633. if (intern->createdPipe)
  216634. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  216635. else
  216636. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  216637. if (intern->pipeOut == -1)
  216638. {
  216639. return -1;
  216640. }
  216641. }
  216642. const char* p = (const char*) sourceBuffer;
  216643. bytesWritten = 0;
  216644. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216645. while (bytesWritten < numBytesToWrite
  216646. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216647. {
  216648. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216649. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  216650. if (numWritten <= 0)
  216651. {
  216652. bytesWritten = -1;
  216653. break;
  216654. }
  216655. bytesWritten += numWritten;
  216656. p += bytesWritten;
  216657. }
  216658. }
  216659. return bytesWritten;
  216660. }
  216661. #endif
  216662. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  216663. /*** Start of inlined file: juce_linux_Network.cpp ***/
  216664. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216665. // compiled on its own).
  216666. #if JUCE_INCLUDED_FILE
  216667. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  216668. {
  216669. int numResults = 0;
  216670. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216671. if (s != -1)
  216672. {
  216673. char buf [1024];
  216674. struct ifconf ifc;
  216675. ifc.ifc_len = sizeof (buf);
  216676. ifc.ifc_buf = buf;
  216677. ioctl (s, SIOCGIFCONF, &ifc);
  216678. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216679. {
  216680. struct ifreq ifr;
  216681. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216682. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216683. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216684. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216685. && numResults < maxNum)
  216686. {
  216687. int64 a = 0;
  216688. for (int j = 6; --j >= 0;)
  216689. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  216690. *addresses++ = a;
  216691. ++numResults;
  216692. }
  216693. }
  216694. close (s);
  216695. }
  216696. return numResults;
  216697. }
  216698. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216699. const String& emailSubject,
  216700. const String& bodyText,
  216701. const StringArray& filesToAttach)
  216702. {
  216703. jassertfalse; // xxx todo
  216704. return false;
  216705. }
  216706. /** A HTTP input stream that uses sockets.
  216707. */
  216708. class JUCE_HTTPSocketStream
  216709. {
  216710. public:
  216711. JUCE_HTTPSocketStream()
  216712. : readPosition (0),
  216713. socketHandle (-1),
  216714. levelsOfRedirection (0),
  216715. timeoutSeconds (15)
  216716. {
  216717. }
  216718. ~JUCE_HTTPSocketStream()
  216719. {
  216720. closeSocket();
  216721. }
  216722. bool open (const String& url,
  216723. const String& headers,
  216724. const MemoryBlock& postData,
  216725. const bool isPost,
  216726. URL::OpenStreamProgressCallback* callback,
  216727. void* callbackContext,
  216728. int timeOutMs)
  216729. {
  216730. closeSocket();
  216731. uint32 timeOutTime = Time::getMillisecondCounter();
  216732. if (timeOutMs == 0)
  216733. timeOutTime += 60000;
  216734. else if (timeOutMs < 0)
  216735. timeOutTime = 0xffffffff;
  216736. else
  216737. timeOutTime += timeOutMs;
  216738. String hostName, hostPath;
  216739. int hostPort;
  216740. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216741. return false;
  216742. const struct hostent* host = 0;
  216743. int port = 0;
  216744. String proxyName, proxyPath;
  216745. int proxyPort = 0;
  216746. String proxyURL (getenv ("http_proxy"));
  216747. if (proxyURL.startsWithIgnoreCase ("http://"))
  216748. {
  216749. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216750. return false;
  216751. host = gethostbyname (proxyName.toUTF8());
  216752. port = proxyPort;
  216753. }
  216754. else
  216755. {
  216756. host = gethostbyname (hostName.toUTF8());
  216757. port = hostPort;
  216758. }
  216759. if (host == 0)
  216760. return false;
  216761. struct sockaddr_in address;
  216762. zerostruct (address);
  216763. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  216764. address.sin_family = host->h_addrtype;
  216765. address.sin_port = htons (port);
  216766. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216767. if (socketHandle == -1)
  216768. return false;
  216769. int receiveBufferSize = 16384;
  216770. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216771. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216772. #if JUCE_MAC
  216773. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216774. #endif
  216775. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216776. {
  216777. closeSocket();
  216778. return false;
  216779. }
  216780. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216781. proxyName, proxyPort,
  216782. hostPath, url,
  216783. headers, postData,
  216784. isPost));
  216785. size_t totalHeaderSent = 0;
  216786. while (totalHeaderSent < requestHeader.getSize())
  216787. {
  216788. if (Time::getMillisecondCounter() > timeOutTime)
  216789. {
  216790. closeSocket();
  216791. return false;
  216792. }
  216793. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  216794. if (send (socketHandle,
  216795. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216796. numToSend, 0)
  216797. != numToSend)
  216798. {
  216799. closeSocket();
  216800. return false;
  216801. }
  216802. totalHeaderSent += numToSend;
  216803. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216804. {
  216805. closeSocket();
  216806. return false;
  216807. }
  216808. }
  216809. const String responseHeader (readResponse (timeOutTime));
  216810. if (responseHeader.isNotEmpty())
  216811. {
  216812. //DBG (responseHeader);
  216813. headerLines.clear();
  216814. headerLines.addLines (responseHeader);
  216815. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  216816. .substring (0, 3).getIntValue();
  216817. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  216818. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  216819. String location (findHeaderItem (headerLines, "Location:"));
  216820. if (statusCode >= 300 && statusCode < 400
  216821. && location.isNotEmpty())
  216822. {
  216823. if (! location.startsWithIgnoreCase ("http://"))
  216824. location = "http://" + location;
  216825. if (levelsOfRedirection++ < 3)
  216826. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216827. }
  216828. else
  216829. {
  216830. levelsOfRedirection = 0;
  216831. return true;
  216832. }
  216833. }
  216834. closeSocket();
  216835. return false;
  216836. }
  216837. int read (void* buffer, int bytesToRead)
  216838. {
  216839. fd_set readbits;
  216840. FD_ZERO (&readbits);
  216841. FD_SET (socketHandle, &readbits);
  216842. struct timeval tv;
  216843. tv.tv_sec = timeoutSeconds;
  216844. tv.tv_usec = 0;
  216845. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216846. return 0; // (timeout)
  216847. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216848. readPosition += bytesRead;
  216849. return bytesRead;
  216850. }
  216851. int readPosition;
  216852. StringArray headerLines;
  216853. juce_UseDebuggingNewOperator
  216854. private:
  216855. int socketHandle, levelsOfRedirection;
  216856. const int timeoutSeconds;
  216857. void closeSocket()
  216858. {
  216859. if (socketHandle >= 0)
  216860. close (socketHandle);
  216861. socketHandle = -1;
  216862. }
  216863. const MemoryBlock createRequestHeader (const String& hostName,
  216864. const int hostPort,
  216865. const String& proxyName,
  216866. const int proxyPort,
  216867. const String& hostPath,
  216868. const String& originalURL,
  216869. const String& headers,
  216870. const MemoryBlock& postData,
  216871. const bool isPost)
  216872. {
  216873. String header (isPost ? "POST " : "GET ");
  216874. if (proxyName.isEmpty())
  216875. {
  216876. header << hostPath << " HTTP/1.0\r\nHost: "
  216877. << hostName << ':' << hostPort;
  216878. }
  216879. else
  216880. {
  216881. header << originalURL << " HTTP/1.0\r\nHost: "
  216882. << proxyName << ':' << proxyPort;
  216883. }
  216884. header << "\r\nUser-Agent: JUCE/"
  216885. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216886. << "\r\nConnection: Close\r\nContent-Length: "
  216887. << postData.getSize() << "\r\n"
  216888. << headers << "\r\n";
  216889. MemoryBlock mb;
  216890. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216891. mb.append (postData.getData(), postData.getSize());
  216892. return mb;
  216893. }
  216894. const String readResponse (const uint32 timeOutTime)
  216895. {
  216896. int bytesRead = 0, numConsecutiveLFs = 0;
  216897. MemoryBlock buffer (1024, true);
  216898. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216899. && Time::getMillisecondCounter() <= timeOutTime)
  216900. {
  216901. fd_set readbits;
  216902. FD_ZERO (&readbits);
  216903. FD_SET (socketHandle, &readbits);
  216904. struct timeval tv;
  216905. tv.tv_sec = timeoutSeconds;
  216906. tv.tv_usec = 0;
  216907. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216908. return String::empty; // (timeout)
  216909. buffer.ensureSize (bytesRead + 8, true);
  216910. char* const dest = (char*) buffer.getData() + bytesRead;
  216911. if (recv (socketHandle, dest, 1, 0) == -1)
  216912. return String::empty;
  216913. const char lastByte = *dest;
  216914. ++bytesRead;
  216915. if (lastByte == '\n')
  216916. ++numConsecutiveLFs;
  216917. else if (lastByte != '\r')
  216918. numConsecutiveLFs = 0;
  216919. }
  216920. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  216921. if (header.startsWithIgnoreCase ("HTTP/"))
  216922. return header.trimEnd();
  216923. return String::empty;
  216924. }
  216925. static bool decomposeURL (const String& url,
  216926. String& host, String& path, int& port)
  216927. {
  216928. if (! url.startsWithIgnoreCase ("http://"))
  216929. return false;
  216930. const int nextSlash = url.indexOfChar (7, '/');
  216931. int nextColon = url.indexOfChar (7, ':');
  216932. if (nextColon > nextSlash && nextSlash > 0)
  216933. nextColon = -1;
  216934. if (nextColon >= 0)
  216935. {
  216936. host = url.substring (7, nextColon);
  216937. if (nextSlash >= 0)
  216938. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216939. else
  216940. port = url.substring (nextColon + 1).getIntValue();
  216941. }
  216942. else
  216943. {
  216944. port = 80;
  216945. if (nextSlash >= 0)
  216946. host = url.substring (7, nextSlash);
  216947. else
  216948. host = url.substring (7);
  216949. }
  216950. if (nextSlash >= 0)
  216951. path = url.substring (nextSlash);
  216952. else
  216953. path = "/";
  216954. return true;
  216955. }
  216956. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216957. {
  216958. for (int i = 0; i < lines.size(); ++i)
  216959. if (lines[i].startsWithIgnoreCase (itemName))
  216960. return lines[i].substring (itemName.length()).trim();
  216961. return String::empty;
  216962. }
  216963. };
  216964. void* juce_openInternetFile (const String& url,
  216965. const String& headers,
  216966. const MemoryBlock& postData,
  216967. const bool isPost,
  216968. URL::OpenStreamProgressCallback* callback,
  216969. void* callbackContext,
  216970. int timeOutMs)
  216971. {
  216972. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  216973. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  216974. return s.release();
  216975. return 0;
  216976. }
  216977. void juce_closeInternetFile (void* handle)
  216978. {
  216979. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  216980. }
  216981. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216982. {
  216983. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216984. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  216985. }
  216986. int64 juce_getInternetFileContentLength (void* handle)
  216987. {
  216988. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216989. if (s != 0)
  216990. {
  216991. //xxx todo
  216992. jassertfalse
  216993. }
  216994. return -1;
  216995. }
  216996. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  216997. {
  216998. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216999. if (s != 0)
  217000. {
  217001. for (int i = 0; i < s->headerLines.size(); ++i)
  217002. {
  217003. const String& headersEntry = s->headerLines[i];
  217004. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217005. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217006. const String previousValue (headers [key]);
  217007. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217008. }
  217009. }
  217010. }
  217011. int juce_seekInInternetFile (void* handle, int newPosition)
  217012. {
  217013. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  217014. return s != 0 ? s->readPosition : 0;
  217015. }
  217016. #endif
  217017. /*** End of inlined file: juce_linux_Network.cpp ***/
  217018. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217019. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217020. // compiled on its own).
  217021. #if JUCE_INCLUDED_FILE
  217022. void Logger::outputDebugString (const String& text)
  217023. {
  217024. std::cerr << text << std::endl;
  217025. }
  217026. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217027. {
  217028. return Linux;
  217029. }
  217030. const String SystemStats::getOperatingSystemName()
  217031. {
  217032. return "Linux";
  217033. }
  217034. bool SystemStats::isOperatingSystem64Bit()
  217035. {
  217036. #if JUCE_64BIT
  217037. return true;
  217038. #else
  217039. //xxx not sure how to find this out?..
  217040. return false;
  217041. #endif
  217042. }
  217043. static const String juce_getCpuInfo (const char* const key)
  217044. {
  217045. StringArray lines;
  217046. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217047. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217048. if (lines[i].startsWithIgnoreCase (key))
  217049. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217050. return String::empty;
  217051. }
  217052. const String SystemStats::getCpuVendor()
  217053. {
  217054. return juce_getCpuInfo ("vendor_id");
  217055. }
  217056. int SystemStats::getCpuSpeedInMegaherz()
  217057. {
  217058. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  217059. }
  217060. int SystemStats::getMemorySizeInMegabytes()
  217061. {
  217062. struct sysinfo sysi;
  217063. if (sysinfo (&sysi) == 0)
  217064. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217065. return 0;
  217066. }
  217067. int SystemStats::getPageSize()
  217068. {
  217069. return sysconf (_SC_PAGESIZE);
  217070. }
  217071. const String SystemStats::getLogonName()
  217072. {
  217073. const char* user = getenv ("USER");
  217074. if (user == 0)
  217075. {
  217076. struct passwd* const pw = getpwuid (getuid());
  217077. if (pw != 0)
  217078. user = pw->pw_name;
  217079. }
  217080. return String::fromUTF8 (user);
  217081. }
  217082. const String SystemStats::getFullUserName()
  217083. {
  217084. return getLogonName();
  217085. }
  217086. void SystemStats::initialiseStats()
  217087. {
  217088. const String flags (juce_getCpuInfo ("flags"));
  217089. cpuFlags.hasMMX = flags.contains ("mmx");
  217090. cpuFlags.hasSSE = flags.contains ("sse");
  217091. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217092. cpuFlags.has3DNow = flags.contains ("3dnow");
  217093. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  217094. }
  217095. void PlatformUtilities::fpuReset()
  217096. {
  217097. }
  217098. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  217099. {
  217100. if (gettimeofday (t, 0) != 0)
  217101. return false;
  217102. static unsigned int calibrate = 0;
  217103. static bool calibrated = false;
  217104. if (! calibrated)
  217105. {
  217106. calibrated = true;
  217107. struct sysinfo sysi;
  217108. if (sysinfo (&sysi) == 0)
  217109. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  217110. }
  217111. t->tv_sec -= calibrate;
  217112. return true;
  217113. }
  217114. uint32 juce_millisecondsSinceStartup() throw()
  217115. {
  217116. timeval t;
  217117. if (juce_getTimeSinceStartup (&t))
  217118. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  217119. return 0;
  217120. }
  217121. int64 Time::getHighResolutionTicks() throw()
  217122. {
  217123. timeval t;
  217124. if (juce_getTimeSinceStartup (&t))
  217125. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  217126. return 0;
  217127. }
  217128. int64 Time::getHighResolutionTicksPerSecond() throw()
  217129. {
  217130. return 1000000; // (microseconds)
  217131. }
  217132. double Time::getMillisecondCounterHiRes() throw()
  217133. {
  217134. return getHighResolutionTicks() * 0.001;
  217135. }
  217136. bool Time::setSystemTimeToThisTime() const
  217137. {
  217138. timeval t;
  217139. t.tv_sec = millisSinceEpoch % 1000000;
  217140. t.tv_usec = millisSinceEpoch - t.tv_sec;
  217141. return settimeofday (&t, 0) ? false : true;
  217142. }
  217143. #endif
  217144. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217145. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217146. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217147. // compiled on its own).
  217148. #if JUCE_INCLUDED_FILE
  217149. /*
  217150. Note that a lot of methods that you'd expect to find in this file actually
  217151. live in juce_posix_SharedCode.h!
  217152. */
  217153. void JUCE_API juce_threadEntryPoint (void*);
  217154. void* threadEntryProc (void* value)
  217155. {
  217156. juce_threadEntryPoint (value);
  217157. return 0;
  217158. }
  217159. void* juce_createThread (void* userData)
  217160. {
  217161. pthread_t handle = 0;
  217162. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217163. {
  217164. pthread_detach (handle);
  217165. return (void*) handle;
  217166. }
  217167. return 0;
  217168. }
  217169. void juce_killThread (void* handle)
  217170. {
  217171. if (handle != 0)
  217172. pthread_cancel ((pthread_t) handle);
  217173. }
  217174. void juce_setCurrentThreadName (const String& /*name*/)
  217175. {
  217176. }
  217177. Thread::ThreadID Thread::getCurrentThreadId()
  217178. {
  217179. return (ThreadID) pthread_self();
  217180. }
  217181. /* This is all a bit non-ideal... the trouble is that on Linux you
  217182. need to call setpriority to affect the dynamic priority for
  217183. non-realtime processes, but this requires the pid, which is not
  217184. accessible from the pthread_t. We could get it by calling getpid
  217185. once each thread has started, but then we would need a list of
  217186. running threads etc etc.
  217187. Also there is no such thing as IDLE priority on Linux.
  217188. For the moment, map idle, low and normal process priorities to
  217189. SCHED_OTHER, with the thread priority ignored for these classes.
  217190. Map high priority processes to the lower half of the SCHED_RR
  217191. range, and realtime to the upper half.
  217192. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  217193. priority of the current thread
  217194. */
  217195. bool juce_setThreadPriority (void* handle, int priority)
  217196. {
  217197. struct sched_param param;
  217198. int policy;
  217199. if (handle == 0)
  217200. handle = (void*) pthread_self();
  217201. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  217202. && policy != SCHED_OTHER)
  217203. {
  217204. int minp = sched_get_priority_min (policy);
  217205. int maxp = sched_get_priority_max (policy);
  217206. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  217207. if (param.sched_priority >= (minp + (maxp - minp) / 2))
  217208. param.sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  217209. else
  217210. param.sched_priority = minp + pri; // (high)
  217211. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  217212. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217213. }
  217214. return false;
  217215. }
  217216. /* Remove this macro if you're having problems compiling the cpu affinity
  217217. calls (the API for these has changed about quite a bit in various Linux
  217218. versions, and a lot of distros seem to ship with obsolete versions)
  217219. */
  217220. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217221. #define SUPPORT_AFFINITIES 1
  217222. #endif
  217223. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217224. {
  217225. #if SUPPORT_AFFINITIES
  217226. cpu_set_t affinity;
  217227. CPU_ZERO (&affinity);
  217228. for (int i = 0; i < 32; ++i)
  217229. if ((affinityMask & (1 << i)) != 0)
  217230. CPU_SET (i, &affinity);
  217231. /*
  217232. N.B. If this line causes a compile error, then you've probably not got the latest
  217233. version of glibc installed.
  217234. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217235. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217236. */
  217237. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217238. sched_yield();
  217239. #else
  217240. /* affinities aren't supported because either the appropriate header files weren't found,
  217241. or the SUPPORT_AFFINITIES macro was turned off
  217242. */
  217243. jassertfalse;
  217244. #endif
  217245. }
  217246. void Thread::yield()
  217247. {
  217248. sched_yield();
  217249. }
  217250. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217251. void Process::setPriority (ProcessPriority prior)
  217252. {
  217253. struct sched_param param;
  217254. int policy, maxp, minp;
  217255. const int p = (int) prior;
  217256. if (p <= 1)
  217257. policy = SCHED_OTHER;
  217258. else
  217259. policy = SCHED_RR;
  217260. minp = sched_get_priority_min (policy);
  217261. maxp = sched_get_priority_max (policy);
  217262. if (p < 2)
  217263. param.sched_priority = 0;
  217264. else if (p == 2 )
  217265. // Set to middle of lower realtime priority range
  217266. param.sched_priority = minp + (maxp - minp) / 4;
  217267. else
  217268. // Set to middle of higher realtime priority range
  217269. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217270. pthread_setschedparam (pthread_self(), policy, &param);
  217271. }
  217272. void Process::terminate()
  217273. {
  217274. exit (0);
  217275. }
  217276. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  217277. {
  217278. static char testResult = 0;
  217279. if (testResult == 0)
  217280. {
  217281. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217282. if (testResult >= 0)
  217283. {
  217284. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217285. testResult = 1;
  217286. }
  217287. }
  217288. return testResult < 0;
  217289. }
  217290. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217291. {
  217292. return juce_isRunningUnderDebugger();
  217293. }
  217294. void Process::raisePrivilege()
  217295. {
  217296. // If running suid root, change effective user
  217297. // to root
  217298. if (geteuid() != 0 && getuid() == 0)
  217299. {
  217300. setreuid (geteuid(), getuid());
  217301. setregid (getegid(), getgid());
  217302. }
  217303. }
  217304. void Process::lowerPrivilege()
  217305. {
  217306. // If runing suid root, change effective user
  217307. // back to real user
  217308. if (geteuid() == 0 && getuid() != 0)
  217309. {
  217310. setreuid (geteuid(), getuid());
  217311. setregid (getegid(), getgid());
  217312. }
  217313. }
  217314. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217315. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217316. {
  217317. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217318. }
  217319. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217320. {
  217321. dlclose(handle);
  217322. }
  217323. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217324. {
  217325. return dlsym (libraryHandle, procedureName.toCString());
  217326. }
  217327. #endif
  217328. #endif
  217329. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217330. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217331. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217332. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217333. // compiled on its own).
  217334. #if JUCE_INCLUDED_FILE
  217335. #if JUCE_DEBUG
  217336. #define JUCE_DEBUG_XERRORS 1
  217337. #endif
  217338. extern Display* display;
  217339. extern Window juce_messageWindowHandle;
  217340. namespace ClipboardHelpers
  217341. {
  217342. static String localClipboardContent;
  217343. static Atom atom_UTF8_STRING;
  217344. static Atom atom_CLIPBOARD;
  217345. static Atom atom_TARGETS;
  217346. static void initSelectionAtoms()
  217347. {
  217348. static bool isInitialised = false;
  217349. if (! isInitialised)
  217350. {
  217351. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217352. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217353. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217354. }
  217355. }
  217356. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217357. // works only for strings shorter than 1000000 bytes
  217358. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217359. {
  217360. String returnData;
  217361. char* clipData;
  217362. Atom actualType;
  217363. int actualFormat;
  217364. unsigned long numItems, bytesLeft;
  217365. if (XGetWindowProperty (display, window, prop,
  217366. 0L /* offset */, 1000000 /* length (max) */, False,
  217367. AnyPropertyType /* format */,
  217368. &actualType, &actualFormat, &numItems, &bytesLeft,
  217369. (unsigned char**) &clipData) == Success)
  217370. {
  217371. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217372. returnData = String::fromUTF8 (clipData, numItems);
  217373. else if (actualType == XA_STRING && actualFormat == 8)
  217374. returnData = String (clipData, numItems);
  217375. if (clipData != 0)
  217376. XFree (clipData);
  217377. jassert (bytesLeft == 0 || numItems == 1000000);
  217378. }
  217379. XDeleteProperty (display, window, prop);
  217380. return returnData;
  217381. }
  217382. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217383. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217384. {
  217385. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217386. // The selection owner will be asked to set the JUCE_SEL property on the
  217387. // juce_messageWindowHandle with the selection content
  217388. XConvertSelection (display, selection, requestedFormat, property_name,
  217389. juce_messageWindowHandle, CurrentTime);
  217390. int count = 50; // will wait at most for 200 ms
  217391. while (--count >= 0)
  217392. {
  217393. XEvent event;
  217394. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217395. {
  217396. if (event.xselection.property == property_name)
  217397. {
  217398. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217399. selectionContent = readWindowProperty (event.xselection.requestor,
  217400. event.xselection.property,
  217401. requestedFormat);
  217402. return true;
  217403. }
  217404. else
  217405. {
  217406. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217407. }
  217408. }
  217409. // not very elegant.. we could do a select() or something like that...
  217410. // however clipboard content requesting is inherently slow on x11, it
  217411. // often takes 50ms or more so...
  217412. Thread::sleep (4);
  217413. }
  217414. return false;
  217415. }
  217416. }
  217417. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217418. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217419. {
  217420. ClipboardHelpers::initSelectionAtoms();
  217421. // the selection content is sent to the target window as a window property
  217422. XSelectionEvent reply;
  217423. reply.type = SelectionNotify;
  217424. reply.display = evt.display;
  217425. reply.requestor = evt.requestor;
  217426. reply.selection = evt.selection;
  217427. reply.target = evt.target;
  217428. reply.property = None; // == "fail"
  217429. reply.time = evt.time;
  217430. HeapBlock <char> data;
  217431. int propertyFormat = 0, numDataItems = 0;
  217432. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217433. {
  217434. if (evt.target == XA_STRING)
  217435. {
  217436. // format data according to system locale
  217437. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217438. data.calloc (numDataItems + 1);
  217439. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217440. propertyFormat = 8; // bits/item
  217441. }
  217442. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217443. {
  217444. // translate to utf8
  217445. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217446. data.calloc (numDataItems + 1);
  217447. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217448. propertyFormat = 8; // bits/item
  217449. }
  217450. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217451. {
  217452. // another application wants to know what we are able to send
  217453. numDataItems = 2;
  217454. propertyFormat = 32; // atoms are 32-bit
  217455. data.calloc (numDataItems * 4);
  217456. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217457. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217458. atoms[1] = XA_STRING;
  217459. }
  217460. }
  217461. else
  217462. {
  217463. DBG ("requested unsupported clipboard");
  217464. }
  217465. if (data != 0)
  217466. {
  217467. const int maxReasonableSelectionSize = 1000000;
  217468. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217469. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217470. {
  217471. XChangeProperty (evt.display, evt.requestor,
  217472. evt.property, evt.target,
  217473. propertyFormat /* 8 or 32 */, PropModeReplace,
  217474. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217475. reply.property = evt.property; // " == success"
  217476. }
  217477. }
  217478. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217479. }
  217480. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217481. {
  217482. ClipboardHelpers::initSelectionAtoms();
  217483. ClipboardHelpers::localClipboardContent = clipText;
  217484. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217485. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217486. }
  217487. const String SystemClipboard::getTextFromClipboard()
  217488. {
  217489. ClipboardHelpers::initSelectionAtoms();
  217490. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217491. level" clipboard that is supposed to be filled by ctrl-C
  217492. etc). When a clipboard manager is running, the content of this
  217493. selection is preserved even when the original selection owner
  217494. exits.
  217495. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217496. filled by good old x11 apps such as xterm)
  217497. */
  217498. String content;
  217499. Atom selection = XA_PRIMARY;
  217500. Window selectionOwner = None;
  217501. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217502. {
  217503. selection = ClipboardHelpers::atom_CLIPBOARD;
  217504. selectionOwner = XGetSelectionOwner (display, selection);
  217505. }
  217506. if (selectionOwner != None)
  217507. {
  217508. if (selectionOwner == juce_messageWindowHandle)
  217509. {
  217510. content = ClipboardHelpers::localClipboardContent;
  217511. }
  217512. else
  217513. {
  217514. // first try: we want an utf8 string
  217515. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217516. if (! ok)
  217517. {
  217518. // second chance, ask for a good old locale-dependent string ..
  217519. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217520. }
  217521. }
  217522. }
  217523. return content;
  217524. }
  217525. #endif
  217526. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217527. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217528. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217529. // compiled on its own).
  217530. #if JUCE_INCLUDED_FILE
  217531. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217532. #define JUCE_DEBUG_XERRORS 1
  217533. #endif
  217534. Display* display = 0;
  217535. Window juce_messageWindowHandle = None;
  217536. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217537. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217538. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217539. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217540. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217541. class InternalMessageQueue
  217542. {
  217543. public:
  217544. InternalMessageQueue()
  217545. : bytesInSocket (0),
  217546. totalEventCount (0)
  217547. {
  217548. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217549. (void) ret; jassert (ret == 0);
  217550. //setNonBlocking (fd[0]);
  217551. //setNonBlocking (fd[1]);
  217552. }
  217553. ~InternalMessageQueue()
  217554. {
  217555. close (fd[0]);
  217556. close (fd[1]);
  217557. clearSingletonInstance();
  217558. }
  217559. void postMessage (Message* msg)
  217560. {
  217561. const int maxBytesInSocketQueue = 128;
  217562. ScopedLock sl (lock);
  217563. queue.add (msg);
  217564. if (bytesInSocket < maxBytesInSocketQueue)
  217565. {
  217566. ++bytesInSocket;
  217567. ScopedUnlock ul (lock);
  217568. const unsigned char x = 0xff;
  217569. size_t bytesWritten = write (fd[0], &x, 1);
  217570. (void) bytesWritten;
  217571. }
  217572. }
  217573. bool isEmpty() const
  217574. {
  217575. ScopedLock sl (lock);
  217576. return queue.size() == 0;
  217577. }
  217578. bool dispatchNextEvent()
  217579. {
  217580. // This alternates between giving priority to XEvents or internal messages,
  217581. // to keep everything running smoothly..
  217582. if ((++totalEventCount & 1) != 0)
  217583. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217584. else
  217585. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217586. }
  217587. // Wait for an event (either XEvent, or an internal Message)
  217588. bool sleepUntilEvent (const int timeoutMs)
  217589. {
  217590. if (! isEmpty())
  217591. return true;
  217592. if (display != 0)
  217593. {
  217594. ScopedXLock xlock;
  217595. if (XPending (display))
  217596. return true;
  217597. }
  217598. struct timeval tv;
  217599. tv.tv_sec = 0;
  217600. tv.tv_usec = timeoutMs * 1000;
  217601. int fd0 = getWaitHandle();
  217602. int fdmax = fd0;
  217603. fd_set readset;
  217604. FD_ZERO (&readset);
  217605. FD_SET (fd0, &readset);
  217606. if (display != 0)
  217607. {
  217608. ScopedXLock xlock;
  217609. int fd1 = XConnectionNumber (display);
  217610. FD_SET (fd1, &readset);
  217611. fdmax = jmax (fd0, fd1);
  217612. }
  217613. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217614. return (ret > 0); // ret <= 0 if error or timeout
  217615. }
  217616. struct MessageThreadFuncCall
  217617. {
  217618. enum { uniqueID = 0x73774623 };
  217619. MessageCallbackFunction* func;
  217620. void* parameter;
  217621. void* result;
  217622. CriticalSection lock;
  217623. WaitableEvent event;
  217624. };
  217625. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217626. private:
  217627. CriticalSection lock;
  217628. OwnedArray <Message> queue;
  217629. int fd[2];
  217630. int bytesInSocket;
  217631. int totalEventCount;
  217632. int getWaitHandle() const throw() { return fd[1]; }
  217633. static bool setNonBlocking (int handle)
  217634. {
  217635. int socketFlags = fcntl (handle, F_GETFL, 0);
  217636. if (socketFlags == -1)
  217637. return false;
  217638. socketFlags |= O_NONBLOCK;
  217639. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217640. }
  217641. static bool dispatchNextXEvent()
  217642. {
  217643. if (display == 0)
  217644. return false;
  217645. XEvent evt;
  217646. {
  217647. ScopedXLock xlock;
  217648. if (! XPending (display))
  217649. return false;
  217650. XNextEvent (display, &evt);
  217651. }
  217652. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217653. juce_handleSelectionRequest (evt.xselectionrequest);
  217654. else if (evt.xany.window != juce_messageWindowHandle)
  217655. juce_windowMessageReceive (&evt);
  217656. return true;
  217657. }
  217658. Message* popNextMessage()
  217659. {
  217660. ScopedLock sl (lock);
  217661. if (bytesInSocket > 0)
  217662. {
  217663. --bytesInSocket;
  217664. ScopedUnlock ul (lock);
  217665. unsigned char x;
  217666. size_t numBytes = read (fd[1], &x, 1);
  217667. (void) numBytes;
  217668. }
  217669. return queue.removeAndReturn (0);
  217670. }
  217671. bool dispatchNextInternalMessage()
  217672. {
  217673. ScopedPointer <Message> msg (popNextMessage());
  217674. if (msg == 0)
  217675. return false;
  217676. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217677. {
  217678. // Handle callback message
  217679. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217680. call->result = (*(call->func)) (call->parameter);
  217681. call->event.signal();
  217682. }
  217683. else
  217684. {
  217685. // Handle "normal" messages
  217686. MessageManager::getInstance()->deliverMessage (msg.release());
  217687. }
  217688. return true;
  217689. }
  217690. };
  217691. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217692. namespace LinuxErrorHandling
  217693. {
  217694. static bool errorOccurred = false;
  217695. static bool keyboardBreakOccurred = false;
  217696. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217697. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217698. // Usually happens when client-server connection is broken
  217699. static int ioErrorHandler (Display* display)
  217700. {
  217701. DBG ("ERROR: connection to X server broken.. terminating.");
  217702. if (JUCEApplication::getInstance() != 0)
  217703. MessageManager::getInstance()->stopDispatchLoop();
  217704. errorOccurred = true;
  217705. return 0;
  217706. }
  217707. // A protocol error has occurred
  217708. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217709. {
  217710. #if JUCE_DEBUG_XERRORS
  217711. char errorStr[64] = { 0 };
  217712. char requestStr[64] = { 0 };
  217713. XGetErrorText (display, event->error_code, errorStr, 64);
  217714. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217715. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217716. #endif
  217717. return 0;
  217718. }
  217719. static void installXErrorHandlers()
  217720. {
  217721. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217722. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217723. }
  217724. static void removeXErrorHandlers()
  217725. {
  217726. XSetIOErrorHandler (oldIOErrorHandler);
  217727. oldIOErrorHandler = 0;
  217728. XSetErrorHandler (oldErrorHandler);
  217729. oldErrorHandler = 0;
  217730. }
  217731. static void keyboardBreakSignalHandler (int sig)
  217732. {
  217733. if (sig == SIGINT)
  217734. keyboardBreakOccurred = true;
  217735. }
  217736. static void installKeyboardBreakHandler()
  217737. {
  217738. struct sigaction saction;
  217739. sigset_t maskSet;
  217740. sigemptyset (&maskSet);
  217741. saction.sa_handler = keyboardBreakSignalHandler;
  217742. saction.sa_mask = maskSet;
  217743. saction.sa_flags = 0;
  217744. sigaction (SIGINT, &saction, 0);
  217745. }
  217746. }
  217747. void MessageManager::doPlatformSpecificInitialisation()
  217748. {
  217749. // Initialise xlib for multiple thread support
  217750. static bool initThreadCalled = false;
  217751. if (! initThreadCalled)
  217752. {
  217753. if (! XInitThreads())
  217754. {
  217755. // This is fatal! Print error and closedown
  217756. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  217757. if (JUCEApplication::getInstance() != 0)
  217758. Process::terminate();
  217759. return;
  217760. }
  217761. initThreadCalled = true;
  217762. }
  217763. LinuxErrorHandling::installXErrorHandlers();
  217764. LinuxErrorHandling::installKeyboardBreakHandler();
  217765. // Create the internal message queue
  217766. InternalMessageQueue::getInstance();
  217767. // Try to connect to a display
  217768. String displayName (getenv ("DISPLAY"));
  217769. if (displayName.isEmpty())
  217770. displayName = ":0.0";
  217771. display = XOpenDisplay (displayName.toCString());
  217772. if (display != 0) // This is not fatal! we can run headless.
  217773. {
  217774. // Create a context to store user data associated with Windows we create in WindowDriver
  217775. windowHandleXContext = XUniqueContext();
  217776. // We're only interested in client messages for this window, which are always sent
  217777. XSetWindowAttributes swa;
  217778. swa.event_mask = NoEventMask;
  217779. // Create our message window (this will never be mapped)
  217780. const int screen = DefaultScreen (display);
  217781. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  217782. 0, 0, 1, 1, 0, 0, InputOnly,
  217783. DefaultVisual (display, screen),
  217784. CWEventMask, &swa);
  217785. }
  217786. }
  217787. void MessageManager::doPlatformSpecificShutdown()
  217788. {
  217789. InternalMessageQueue::deleteInstance();
  217790. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  217791. {
  217792. XDestroyWindow (display, juce_messageWindowHandle);
  217793. XCloseDisplay (display);
  217794. juce_messageWindowHandle = 0;
  217795. display = 0;
  217796. LinuxErrorHandling::removeXErrorHandlers();
  217797. }
  217798. }
  217799. bool juce_postMessageToSystemQueue (Message* message)
  217800. {
  217801. if (LinuxErrorHandling::errorOccurred)
  217802. return false;
  217803. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  217804. return true;
  217805. }
  217806. void MessageManager::broadcastMessage (const String& value) throw()
  217807. {
  217808. /* TODO */
  217809. }
  217810. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  217811. void* parameter)
  217812. {
  217813. if (LinuxErrorHandling::errorOccurred)
  217814. return 0;
  217815. if (isThisTheMessageThread())
  217816. return func (parameter);
  217817. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  217818. messageCallContext.func = func;
  217819. messageCallContext.parameter = parameter;
  217820. InternalMessageQueue::getInstanceWithoutCreating()
  217821. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  217822. 0, 0, &messageCallContext));
  217823. // Wait for it to complete before continuing
  217824. messageCallContext.event.wait();
  217825. return messageCallContext.result;
  217826. }
  217827. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  217828. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  217829. {
  217830. while (! LinuxErrorHandling::errorOccurred)
  217831. {
  217832. if (LinuxErrorHandling::keyboardBreakOccurred)
  217833. {
  217834. LinuxErrorHandling::errorOccurred = true;
  217835. if (JUCEApplication::getInstance() != 0)
  217836. Process::terminate();
  217837. break;
  217838. }
  217839. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  217840. return true;
  217841. if (returnIfNoPendingMessages)
  217842. break;
  217843. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  217844. }
  217845. return false;
  217846. }
  217847. #endif
  217848. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  217849. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  217850. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217851. // compiled on its own).
  217852. #if JUCE_INCLUDED_FILE
  217853. class FreeTypeFontFace
  217854. {
  217855. public:
  217856. enum FontStyle
  217857. {
  217858. Plain = 0,
  217859. Bold = 1,
  217860. Italic = 2
  217861. };
  217862. FreeTypeFontFace (const String& familyName)
  217863. : hasSerif (false),
  217864. monospaced (false)
  217865. {
  217866. family = familyName;
  217867. }
  217868. void setFileName (const String& name, const int faceIndex, FontStyle style)
  217869. {
  217870. if (names [(int) style].fileName.isEmpty())
  217871. {
  217872. names [(int) style].fileName = name;
  217873. names [(int) style].faceIndex = faceIndex;
  217874. }
  217875. }
  217876. const String& getFamilyName() const throw() { return family; }
  217877. const String& getFileName (const int style, int& faceIndex) const throw()
  217878. {
  217879. faceIndex = names[style].faceIndex;
  217880. return names[style].fileName;
  217881. }
  217882. void setMonospaced (bool mono) throw() { monospaced = mono; }
  217883. bool getMonospaced() const throw() { return monospaced; }
  217884. void setSerif (const bool serif) throw() { hasSerif = serif; }
  217885. bool getSerif() const throw() { return hasSerif; }
  217886. private:
  217887. String family;
  217888. struct FontNameIndex
  217889. {
  217890. String fileName;
  217891. int faceIndex;
  217892. };
  217893. FontNameIndex names[4];
  217894. bool hasSerif, monospaced;
  217895. };
  217896. class FreeTypeInterface : public DeletedAtShutdown
  217897. {
  217898. public:
  217899. FreeTypeInterface()
  217900. : ftLib (0),
  217901. lastFace (0),
  217902. lastBold (false),
  217903. lastItalic (false)
  217904. {
  217905. if (FT_Init_FreeType (&ftLib) != 0)
  217906. {
  217907. ftLib = 0;
  217908. DBG ("Failed to initialize FreeType");
  217909. }
  217910. StringArray fontDirs;
  217911. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  217912. fontDirs.removeEmptyStrings (true);
  217913. if (fontDirs.size() == 0)
  217914. {
  217915. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  217916. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  217917. if (fontsInfo != 0)
  217918. {
  217919. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  217920. {
  217921. fontDirs.add (e->getAllSubText().trim());
  217922. }
  217923. }
  217924. }
  217925. if (fontDirs.size() == 0)
  217926. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  217927. for (int i = 0; i < fontDirs.size(); ++i)
  217928. enumerateFaces (fontDirs[i]);
  217929. }
  217930. ~FreeTypeInterface()
  217931. {
  217932. if (lastFace != 0)
  217933. FT_Done_Face (lastFace);
  217934. if (ftLib != 0)
  217935. FT_Done_FreeType (ftLib);
  217936. clearSingletonInstance();
  217937. }
  217938. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  217939. {
  217940. for (int i = 0; i < faces.size(); i++)
  217941. if (faces[i]->getFamilyName() == familyName)
  217942. return faces[i];
  217943. if (! create)
  217944. return 0;
  217945. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  217946. faces.add (newFace);
  217947. return newFace;
  217948. }
  217949. // Enumerate all font faces available in a given directory
  217950. void enumerateFaces (const String& path)
  217951. {
  217952. File dirPath (path);
  217953. if (path.isEmpty() || ! dirPath.isDirectory())
  217954. return;
  217955. DirectoryIterator di (dirPath, true);
  217956. while (di.next())
  217957. {
  217958. File possible (di.getFile());
  217959. if (possible.hasFileExtension ("ttf")
  217960. || possible.hasFileExtension ("pfb")
  217961. || possible.hasFileExtension ("pcf"))
  217962. {
  217963. FT_Face face;
  217964. int faceIndex = 0;
  217965. int numFaces = 0;
  217966. do
  217967. {
  217968. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  217969. faceIndex, &face) == 0)
  217970. {
  217971. if (faceIndex == 0)
  217972. numFaces = face->num_faces;
  217973. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  217974. {
  217975. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  217976. int style = (int) FreeTypeFontFace::Plain;
  217977. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  217978. style |= (int) FreeTypeFontFace::Bold;
  217979. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  217980. style |= (int) FreeTypeFontFace::Italic;
  217981. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  217982. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  217983. // Surely there must be a better way to do this?
  217984. const String name (face->family_name);
  217985. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  217986. || name.containsIgnoreCase ("Verdana")
  217987. || name.containsIgnoreCase ("Arial")));
  217988. }
  217989. FT_Done_Face (face);
  217990. }
  217991. ++faceIndex;
  217992. }
  217993. while (faceIndex < numFaces);
  217994. }
  217995. }
  217996. }
  217997. // Create a FreeType face object for a given font
  217998. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  217999. {
  218000. FT_Face face = 0;
  218001. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218002. {
  218003. face = lastFace;
  218004. }
  218005. else
  218006. {
  218007. if (lastFace != 0)
  218008. {
  218009. FT_Done_Face (lastFace);
  218010. lastFace = 0;
  218011. }
  218012. lastFontName = fontName;
  218013. lastBold = bold;
  218014. lastItalic = italic;
  218015. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218016. if (ftFace != 0)
  218017. {
  218018. int style = (int) FreeTypeFontFace::Plain;
  218019. if (bold)
  218020. style |= (int) FreeTypeFontFace::Bold;
  218021. if (italic)
  218022. style |= (int) FreeTypeFontFace::Italic;
  218023. int faceIndex;
  218024. String fileName (ftFace->getFileName (style, faceIndex));
  218025. if (fileName.isEmpty())
  218026. {
  218027. style ^= (int) FreeTypeFontFace::Bold;
  218028. fileName = ftFace->getFileName (style, faceIndex);
  218029. if (fileName.isEmpty())
  218030. {
  218031. style ^= (int) FreeTypeFontFace::Bold;
  218032. style ^= (int) FreeTypeFontFace::Italic;
  218033. fileName = ftFace->getFileName (style, faceIndex);
  218034. if (! fileName.length())
  218035. {
  218036. style ^= (int) FreeTypeFontFace::Bold;
  218037. fileName = ftFace->getFileName (style, faceIndex);
  218038. }
  218039. }
  218040. }
  218041. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218042. {
  218043. face = lastFace;
  218044. // If there isn't a unicode charmap then select the first one.
  218045. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218046. FT_Set_Charmap (face, face->charmaps[0]);
  218047. }
  218048. }
  218049. }
  218050. return face;
  218051. }
  218052. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218053. {
  218054. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218055. const float height = (float) (face->ascender - face->descender);
  218056. const float scaleX = 1.0f / height;
  218057. const float scaleY = -1.0f / height;
  218058. Path destShape;
  218059. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218060. || face->glyph->format != ft_glyph_format_outline)
  218061. {
  218062. return false;
  218063. }
  218064. const FT_Outline* const outline = &face->glyph->outline;
  218065. const short* const contours = outline->contours;
  218066. const char* const tags = outline->tags;
  218067. FT_Vector* const points = outline->points;
  218068. for (int c = 0; c < outline->n_contours; c++)
  218069. {
  218070. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218071. const int endPoint = contours[c];
  218072. for (int p = startPoint; p <= endPoint; p++)
  218073. {
  218074. const float x = scaleX * points[p].x;
  218075. const float y = scaleY * points[p].y;
  218076. if (p == startPoint)
  218077. {
  218078. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218079. {
  218080. float x2 = scaleX * points [endPoint].x;
  218081. float y2 = scaleY * points [endPoint].y;
  218082. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218083. {
  218084. x2 = (x + x2) * 0.5f;
  218085. y2 = (y + y2) * 0.5f;
  218086. }
  218087. destShape.startNewSubPath (x2, y2);
  218088. }
  218089. else
  218090. {
  218091. destShape.startNewSubPath (x, y);
  218092. }
  218093. }
  218094. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218095. {
  218096. if (p != startPoint)
  218097. destShape.lineTo (x, y);
  218098. }
  218099. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218100. {
  218101. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218102. float x2 = scaleX * points [nextIndex].x;
  218103. float y2 = scaleY * points [nextIndex].y;
  218104. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218105. {
  218106. x2 = (x + x2) * 0.5f;
  218107. y2 = (y + y2) * 0.5f;
  218108. }
  218109. else
  218110. {
  218111. ++p;
  218112. }
  218113. destShape.quadraticTo (x, y, x2, y2);
  218114. }
  218115. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218116. {
  218117. if (p >= endPoint)
  218118. return false;
  218119. const int next1 = p + 1;
  218120. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218121. const float x2 = scaleX * points [next1].x;
  218122. const float y2 = scaleY * points [next1].y;
  218123. const float x3 = scaleX * points [next2].x;
  218124. const float y3 = scaleY * points [next2].y;
  218125. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218126. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218127. return false;
  218128. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218129. p += 2;
  218130. }
  218131. }
  218132. destShape.closeSubPath();
  218133. }
  218134. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218135. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218136. addKerning (face, dest, character, glyphIndex);
  218137. return true;
  218138. }
  218139. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218140. {
  218141. const float height = (float) (face->ascender - face->descender);
  218142. uint32 rightGlyphIndex;
  218143. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218144. while (rightGlyphIndex != 0)
  218145. {
  218146. FT_Vector kerning;
  218147. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218148. {
  218149. if (kerning.x != 0)
  218150. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218151. }
  218152. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218153. }
  218154. }
  218155. // Add a glyph to a font
  218156. bool addGlyphToFont (const uint32 character, const String& fontName,
  218157. bool bold, bool italic, CustomTypeface& dest)
  218158. {
  218159. FT_Face face = createFT_Face (fontName, bold, italic);
  218160. return face != 0 && addGlyph (face, dest, character);
  218161. }
  218162. void getFamilyNames (StringArray& familyNames) const
  218163. {
  218164. for (int i = 0; i < faces.size(); i++)
  218165. familyNames.add (faces[i]->getFamilyName());
  218166. }
  218167. void getMonospacedNames (StringArray& monoSpaced) const
  218168. {
  218169. for (int i = 0; i < faces.size(); i++)
  218170. if (faces[i]->getMonospaced())
  218171. monoSpaced.add (faces[i]->getFamilyName());
  218172. }
  218173. void getSerifNames (StringArray& serif) const
  218174. {
  218175. for (int i = 0; i < faces.size(); i++)
  218176. if (faces[i]->getSerif())
  218177. serif.add (faces[i]->getFamilyName());
  218178. }
  218179. void getSansSerifNames (StringArray& sansSerif) const
  218180. {
  218181. for (int i = 0; i < faces.size(); i++)
  218182. if (! faces[i]->getSerif())
  218183. sansSerif.add (faces[i]->getFamilyName());
  218184. }
  218185. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218186. private:
  218187. FT_Library ftLib;
  218188. FT_Face lastFace;
  218189. String lastFontName;
  218190. bool lastBold, lastItalic;
  218191. OwnedArray<FreeTypeFontFace> faces;
  218192. };
  218193. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218194. class FreetypeTypeface : public CustomTypeface
  218195. {
  218196. public:
  218197. FreetypeTypeface (const Font& font)
  218198. {
  218199. FT_Face face = FreeTypeInterface::getInstance()
  218200. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218201. if (face == 0)
  218202. {
  218203. #if JUCE_DEBUG
  218204. String msg ("Failed to create typeface: ");
  218205. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218206. DBG (msg);
  218207. #endif
  218208. }
  218209. else
  218210. {
  218211. setCharacteristics (font.getTypefaceName(),
  218212. face->ascender / (float) (face->ascender - face->descender),
  218213. font.isBold(), font.isItalic(),
  218214. L' ');
  218215. }
  218216. }
  218217. bool loadGlyphIfPossible (juce_wchar character)
  218218. {
  218219. return FreeTypeInterface::getInstance()
  218220. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218221. }
  218222. };
  218223. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218224. {
  218225. return new FreetypeTypeface (font);
  218226. }
  218227. const StringArray Font::findAllTypefaceNames()
  218228. {
  218229. StringArray s;
  218230. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218231. s.sort (true);
  218232. return s;
  218233. }
  218234. static const String pickBestFont (const StringArray& names,
  218235. const char* const choicesString)
  218236. {
  218237. StringArray choices;
  218238. choices.addTokens (String (choicesString), ",", String::empty);
  218239. choices.trim();
  218240. choices.removeEmptyStrings();
  218241. int i, j;
  218242. for (j = 0; j < choices.size(); ++j)
  218243. if (names.contains (choices[j], true))
  218244. return choices[j];
  218245. for (j = 0; j < choices.size(); ++j)
  218246. for (i = 0; i < names.size(); i++)
  218247. if (names[i].startsWithIgnoreCase (choices[j]))
  218248. return names[i];
  218249. for (j = 0; j < choices.size(); ++j)
  218250. for (i = 0; i < names.size(); i++)
  218251. if (names[i].containsIgnoreCase (choices[j]))
  218252. return names[i];
  218253. return names[0];
  218254. }
  218255. static const String linux_getDefaultSansSerifFontName()
  218256. {
  218257. StringArray allFonts;
  218258. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218259. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218260. }
  218261. static const String linux_getDefaultSerifFontName()
  218262. {
  218263. StringArray allFonts;
  218264. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218265. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218266. }
  218267. static const String linux_getDefaultMonospacedFontName()
  218268. {
  218269. StringArray allFonts;
  218270. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218271. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218272. }
  218273. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  218274. {
  218275. defaultSans = linux_getDefaultSansSerifFontName();
  218276. defaultSerif = linux_getDefaultSerifFontName();
  218277. defaultFixed = linux_getDefaultMonospacedFontName();
  218278. }
  218279. #endif
  218280. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218281. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218282. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218283. // compiled on its own).
  218284. #if JUCE_INCLUDED_FILE
  218285. // These are defined in juce_linux_Messaging.cpp
  218286. extern Display* display;
  218287. extern XContext windowHandleXContext;
  218288. namespace Atoms
  218289. {
  218290. enum ProtocolItems
  218291. {
  218292. TAKE_FOCUS = 0,
  218293. DELETE_WINDOW = 1,
  218294. PING = 2
  218295. };
  218296. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218297. ActiveWin, Pid, WindowType, WindowState,
  218298. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218299. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218300. XdndActionDescription, XdndActionCopy,
  218301. allowedActions[5],
  218302. allowedMimeTypes[2];
  218303. const unsigned long DndVersion = 3;
  218304. static void initialiseAtoms()
  218305. {
  218306. static bool atomsInitialised = false;
  218307. if (! atomsInitialised)
  218308. {
  218309. atomsInitialised = true;
  218310. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218311. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218312. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218313. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218314. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218315. State = XInternAtom (display, "WM_STATE", True);
  218316. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218317. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218318. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218319. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218320. XdndAware = XInternAtom (display, "XdndAware", False);
  218321. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218322. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218323. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218324. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218325. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218326. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218327. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218328. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218329. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218330. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218331. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218332. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218333. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218334. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218335. allowedActions[1] = XdndActionCopy;
  218336. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218337. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218338. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218339. }
  218340. }
  218341. }
  218342. namespace Keys
  218343. {
  218344. enum MouseButtons
  218345. {
  218346. NoButton = 0,
  218347. LeftButton = 1,
  218348. MiddleButton = 2,
  218349. RightButton = 3,
  218350. WheelUp = 4,
  218351. WheelDown = 5
  218352. };
  218353. static int AltMask = 0;
  218354. static int NumLockMask = 0;
  218355. static bool numLock = false;
  218356. static bool capsLock = false;
  218357. static char keyStates [32];
  218358. static const int extendedKeyModifier = 0x10000000;
  218359. }
  218360. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218361. {
  218362. int keysym;
  218363. if (keyCode & Keys::extendedKeyModifier)
  218364. {
  218365. keysym = 0xff00 | (keyCode & 0xff);
  218366. }
  218367. else
  218368. {
  218369. keysym = keyCode;
  218370. if (keysym == (XK_Tab & 0xff)
  218371. || keysym == (XK_Return & 0xff)
  218372. || keysym == (XK_Escape & 0xff)
  218373. || keysym == (XK_BackSpace & 0xff))
  218374. {
  218375. keysym |= 0xff00;
  218376. }
  218377. }
  218378. ScopedXLock xlock;
  218379. const int keycode = XKeysymToKeycode (display, keysym);
  218380. const int keybyte = keycode >> 3;
  218381. const int keybit = (1 << (keycode & 7));
  218382. return (Keys::keyStates [keybyte] & keybit) != 0;
  218383. }
  218384. #if JUCE_USE_XSHM
  218385. namespace XSHMHelpers
  218386. {
  218387. static int trappedErrorCode = 0;
  218388. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218389. {
  218390. trappedErrorCode = err->error_code;
  218391. return 0;
  218392. }
  218393. static bool isShmAvailable() throw()
  218394. {
  218395. static bool isChecked = false;
  218396. static bool isAvailable = false;
  218397. if (! isChecked)
  218398. {
  218399. isChecked = true;
  218400. int major, minor;
  218401. Bool pixmaps;
  218402. ScopedXLock xlock;
  218403. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218404. {
  218405. trappedErrorCode = 0;
  218406. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218407. XShmSegmentInfo segmentInfo;
  218408. zerostruct (segmentInfo);
  218409. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218410. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218411. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218412. xImage->bytes_per_line * xImage->height,
  218413. IPC_CREAT | 0777)) >= 0)
  218414. {
  218415. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218416. if (segmentInfo.shmaddr != (void*) -1)
  218417. {
  218418. segmentInfo.readOnly = False;
  218419. xImage->data = segmentInfo.shmaddr;
  218420. XSync (display, False);
  218421. if (XShmAttach (display, &segmentInfo) != 0)
  218422. {
  218423. XSync (display, False);
  218424. XShmDetach (display, &segmentInfo);
  218425. isAvailable = true;
  218426. }
  218427. }
  218428. XFlush (display);
  218429. XDestroyImage (xImage);
  218430. shmdt (segmentInfo.shmaddr);
  218431. }
  218432. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218433. XSetErrorHandler (oldHandler);
  218434. if (trappedErrorCode != 0)
  218435. isAvailable = false;
  218436. }
  218437. }
  218438. return isAvailable;
  218439. }
  218440. }
  218441. #endif
  218442. #if JUCE_USE_XRENDER
  218443. namespace XRender
  218444. {
  218445. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218446. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218447. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218448. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218449. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218450. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218451. static tXRenderFindFormat xRenderFindFormat = 0;
  218452. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218453. static bool isAvailable()
  218454. {
  218455. static bool hasLoaded = false;
  218456. if (! hasLoaded)
  218457. {
  218458. ScopedXLock xlock;
  218459. hasLoaded = true;
  218460. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218461. if (h != 0)
  218462. {
  218463. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218464. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218465. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218466. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218467. }
  218468. if (xRenderQueryVersion != 0
  218469. && xRenderFindStandardFormat != 0
  218470. && xRenderFindFormat != 0
  218471. && xRenderFindVisualFormat != 0)
  218472. {
  218473. int major, minor;
  218474. if (xRenderQueryVersion (display, &major, &minor))
  218475. return true;
  218476. }
  218477. xRenderQueryVersion = 0;
  218478. }
  218479. return xRenderQueryVersion != 0;
  218480. }
  218481. static XRenderPictFormat* findPictureFormat()
  218482. {
  218483. ScopedXLock xlock;
  218484. XRenderPictFormat* pictFormat = 0;
  218485. if (isAvailable())
  218486. {
  218487. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218488. if (pictFormat == 0)
  218489. {
  218490. XRenderPictFormat desiredFormat;
  218491. desiredFormat.type = PictTypeDirect;
  218492. desiredFormat.depth = 32;
  218493. desiredFormat.direct.alphaMask = 0xff;
  218494. desiredFormat.direct.redMask = 0xff;
  218495. desiredFormat.direct.greenMask = 0xff;
  218496. desiredFormat.direct.blueMask = 0xff;
  218497. desiredFormat.direct.alpha = 24;
  218498. desiredFormat.direct.red = 16;
  218499. desiredFormat.direct.green = 8;
  218500. desiredFormat.direct.blue = 0;
  218501. pictFormat = xRenderFindFormat (display,
  218502. PictFormatType | PictFormatDepth
  218503. | PictFormatRedMask | PictFormatRed
  218504. | PictFormatGreenMask | PictFormatGreen
  218505. | PictFormatBlueMask | PictFormatBlue
  218506. | PictFormatAlphaMask | PictFormatAlpha,
  218507. &desiredFormat,
  218508. 0);
  218509. }
  218510. }
  218511. return pictFormat;
  218512. }
  218513. }
  218514. #endif
  218515. namespace Visuals
  218516. {
  218517. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218518. {
  218519. ScopedXLock xlock;
  218520. Visual* visual = 0;
  218521. int numVisuals = 0;
  218522. long desiredMask = VisualNoMask;
  218523. XVisualInfo desiredVisual;
  218524. desiredVisual.screen = DefaultScreen (display);
  218525. desiredVisual.depth = desiredDepth;
  218526. desiredMask = VisualScreenMask | VisualDepthMask;
  218527. if (desiredDepth == 32)
  218528. {
  218529. desiredVisual.c_class = TrueColor;
  218530. desiredVisual.red_mask = 0x00FF0000;
  218531. desiredVisual.green_mask = 0x0000FF00;
  218532. desiredVisual.blue_mask = 0x000000FF;
  218533. desiredVisual.bits_per_rgb = 8;
  218534. desiredMask |= VisualClassMask;
  218535. desiredMask |= VisualRedMaskMask;
  218536. desiredMask |= VisualGreenMaskMask;
  218537. desiredMask |= VisualBlueMaskMask;
  218538. desiredMask |= VisualBitsPerRGBMask;
  218539. }
  218540. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218541. desiredMask,
  218542. &desiredVisual,
  218543. &numVisuals);
  218544. if (xvinfos != 0)
  218545. {
  218546. for (int i = 0; i < numVisuals; i++)
  218547. {
  218548. if (xvinfos[i].depth == desiredDepth)
  218549. {
  218550. visual = xvinfos[i].visual;
  218551. break;
  218552. }
  218553. }
  218554. XFree (xvinfos);
  218555. }
  218556. return visual;
  218557. }
  218558. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218559. {
  218560. Visual* visual = 0;
  218561. if (desiredDepth == 32)
  218562. {
  218563. #if JUCE_USE_XSHM
  218564. if (XSHMHelpers::isShmAvailable())
  218565. {
  218566. #if JUCE_USE_XRENDER
  218567. if (XRender::isAvailable())
  218568. {
  218569. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218570. if (pictFormat != 0)
  218571. {
  218572. int numVisuals = 0;
  218573. XVisualInfo desiredVisual;
  218574. desiredVisual.screen = DefaultScreen (display);
  218575. desiredVisual.depth = 32;
  218576. desiredVisual.bits_per_rgb = 8;
  218577. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218578. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218579. &desiredVisual, &numVisuals);
  218580. if (xvinfos != 0)
  218581. {
  218582. for (int i = 0; i < numVisuals; ++i)
  218583. {
  218584. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218585. if (pictVisualFormat != 0
  218586. && pictVisualFormat->type == PictTypeDirect
  218587. && pictVisualFormat->direct.alphaMask)
  218588. {
  218589. visual = xvinfos[i].visual;
  218590. matchedDepth = 32;
  218591. break;
  218592. }
  218593. }
  218594. XFree (xvinfos);
  218595. }
  218596. }
  218597. }
  218598. #endif
  218599. if (visual == 0)
  218600. {
  218601. visual = findVisualWithDepth (32);
  218602. if (visual != 0)
  218603. matchedDepth = 32;
  218604. }
  218605. }
  218606. #endif
  218607. }
  218608. if (visual == 0 && desiredDepth >= 24)
  218609. {
  218610. visual = findVisualWithDepth (24);
  218611. if (visual != 0)
  218612. matchedDepth = 24;
  218613. }
  218614. if (visual == 0 && desiredDepth >= 16)
  218615. {
  218616. visual = findVisualWithDepth (16);
  218617. if (visual != 0)
  218618. matchedDepth = 16;
  218619. }
  218620. return visual;
  218621. }
  218622. }
  218623. class XBitmapImage : public Image::SharedImage
  218624. {
  218625. public:
  218626. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218627. const bool clearImage, const int imageDepth_, Visual* visual)
  218628. : Image::SharedImage (format_, w, h),
  218629. imageDepth (imageDepth_),
  218630. gc (None)
  218631. {
  218632. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218633. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218634. lineStride = ((w * pixelStride + 3) & ~3);
  218635. ScopedXLock xlock;
  218636. #if JUCE_USE_XSHM
  218637. usingXShm = false;
  218638. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218639. {
  218640. zerostruct (segmentInfo);
  218641. segmentInfo.shmid = -1;
  218642. segmentInfo.shmaddr = (char *) -1;
  218643. segmentInfo.readOnly = False;
  218644. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218645. if (xImage != 0)
  218646. {
  218647. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218648. xImage->bytes_per_line * xImage->height,
  218649. IPC_CREAT | 0777)) >= 0)
  218650. {
  218651. if (segmentInfo.shmid != -1)
  218652. {
  218653. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218654. if (segmentInfo.shmaddr != (void*) -1)
  218655. {
  218656. segmentInfo.readOnly = False;
  218657. xImage->data = segmentInfo.shmaddr;
  218658. imageData = (uint8*) segmentInfo.shmaddr;
  218659. if (XShmAttach (display, &segmentInfo) != 0)
  218660. usingXShm = true;
  218661. else
  218662. jassertfalse;
  218663. }
  218664. else
  218665. {
  218666. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218667. }
  218668. }
  218669. }
  218670. }
  218671. }
  218672. if (! usingXShm)
  218673. #endif
  218674. {
  218675. imageDataAllocated.malloc (lineStride * h);
  218676. imageData = imageDataAllocated;
  218677. if (format_ == Image::ARGB && clearImage)
  218678. zeromem (imageData, h * lineStride);
  218679. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218680. xImage->width = w;
  218681. xImage->height = h;
  218682. xImage->xoffset = 0;
  218683. xImage->format = ZPixmap;
  218684. xImage->data = (char*) imageData;
  218685. xImage->byte_order = ImageByteOrder (display);
  218686. xImage->bitmap_unit = BitmapUnit (display);
  218687. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218688. xImage->bitmap_pad = 32;
  218689. xImage->depth = pixelStride * 8;
  218690. xImage->bytes_per_line = lineStride;
  218691. xImage->bits_per_pixel = pixelStride * 8;
  218692. xImage->red_mask = 0x00FF0000;
  218693. xImage->green_mask = 0x0000FF00;
  218694. xImage->blue_mask = 0x000000FF;
  218695. if (imageDepth == 16)
  218696. {
  218697. const int pixelStride = 2;
  218698. const int lineStride = ((w * pixelStride + 3) & ~3);
  218699. imageData16Bit.malloc (lineStride * h);
  218700. xImage->data = imageData16Bit;
  218701. xImage->bitmap_pad = 16;
  218702. xImage->depth = pixelStride * 8;
  218703. xImage->bytes_per_line = lineStride;
  218704. xImage->bits_per_pixel = pixelStride * 8;
  218705. xImage->red_mask = visual->red_mask;
  218706. xImage->green_mask = visual->green_mask;
  218707. xImage->blue_mask = visual->blue_mask;
  218708. }
  218709. if (! XInitImage (xImage))
  218710. jassertfalse;
  218711. }
  218712. }
  218713. ~XBitmapImage()
  218714. {
  218715. ScopedXLock xlock;
  218716. if (gc != None)
  218717. XFreeGC (display, gc);
  218718. #if JUCE_USE_XSHM
  218719. if (usingXShm)
  218720. {
  218721. XShmDetach (display, &segmentInfo);
  218722. XFlush (display);
  218723. XDestroyImage (xImage);
  218724. shmdt (segmentInfo.shmaddr);
  218725. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218726. }
  218727. else
  218728. #endif
  218729. {
  218730. xImage->data = 0;
  218731. XDestroyImage (xImage);
  218732. }
  218733. }
  218734. Image::ImageType getType() const { return Image::NativeImage; }
  218735. LowLevelGraphicsContext* createLowLevelContext()
  218736. {
  218737. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  218738. }
  218739. SharedImage* clone()
  218740. {
  218741. jassertfalse;
  218742. return 0;
  218743. }
  218744. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  218745. {
  218746. ScopedXLock xlock;
  218747. if (gc == None)
  218748. {
  218749. XGCValues gcvalues;
  218750. gcvalues.foreground = None;
  218751. gcvalues.background = None;
  218752. gcvalues.function = GXcopy;
  218753. gcvalues.plane_mask = AllPlanes;
  218754. gcvalues.clip_mask = None;
  218755. gcvalues.graphics_exposures = False;
  218756. gc = XCreateGC (display, window,
  218757. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  218758. &gcvalues);
  218759. }
  218760. if (imageDepth == 16)
  218761. {
  218762. const uint32 rMask = xImage->red_mask;
  218763. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  218764. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  218765. const uint32 gMask = xImage->green_mask;
  218766. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  218767. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  218768. const uint32 bMask = xImage->blue_mask;
  218769. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  218770. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  218771. const Image::BitmapData srcData (Image (this), false);
  218772. for (int y = sy; y < sy + dh; ++y)
  218773. {
  218774. const uint8* p = srcData.getPixelPointer (sx, y);
  218775. for (int x = sx; x < sx + dw; ++x)
  218776. {
  218777. const PixelRGB* const pixel = (const PixelRGB*) p;
  218778. p += srcData.pixelStride;
  218779. XPutPixel (xImage, x, y,
  218780. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  218781. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  218782. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  218783. }
  218784. }
  218785. }
  218786. // blit results to screen.
  218787. #if JUCE_USE_XSHM
  218788. if (usingXShm)
  218789. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  218790. else
  218791. #endif
  218792. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  218793. }
  218794. juce_UseDebuggingNewOperator
  218795. private:
  218796. XImage* xImage;
  218797. const int imageDepth;
  218798. HeapBlock <uint8> imageDataAllocated;
  218799. HeapBlock <char> imageData16Bit;
  218800. GC gc;
  218801. #if JUCE_USE_XSHM
  218802. XShmSegmentInfo segmentInfo;
  218803. bool usingXShm;
  218804. #endif
  218805. static int getShiftNeeded (const uint32 mask) throw()
  218806. {
  218807. for (int i = 32; --i >= 0;)
  218808. if (((mask >> i) & 1) != 0)
  218809. return i - 7;
  218810. jassertfalse;
  218811. return 0;
  218812. }
  218813. };
  218814. class LinuxComponentPeer : public ComponentPeer
  218815. {
  218816. public:
  218817. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  218818. : ComponentPeer (component, windowStyleFlags),
  218819. windowH (0),
  218820. parentWindow (0),
  218821. wx (0),
  218822. wy (0),
  218823. ww (0),
  218824. wh (0),
  218825. fullScreen (false),
  218826. mapped (false),
  218827. visual (0),
  218828. depth (0)
  218829. {
  218830. // it's dangerous to create a window on a thread other than the message thread..
  218831. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218832. repainter = new LinuxRepaintManager (this);
  218833. createWindow();
  218834. setTitle (component->getName());
  218835. }
  218836. ~LinuxComponentPeer()
  218837. {
  218838. // it's dangerous to delete a window on a thread other than the message thread..
  218839. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218840. deleteIconPixmaps();
  218841. destroyWindow();
  218842. windowH = 0;
  218843. }
  218844. void* getNativeHandle() const
  218845. {
  218846. return (void*) windowH;
  218847. }
  218848. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  218849. {
  218850. XPointer peer = 0;
  218851. ScopedXLock xlock;
  218852. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  218853. {
  218854. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  218855. peer = 0;
  218856. }
  218857. return (LinuxComponentPeer*) peer;
  218858. }
  218859. void setVisible (bool shouldBeVisible)
  218860. {
  218861. ScopedXLock xlock;
  218862. if (shouldBeVisible)
  218863. XMapWindow (display, windowH);
  218864. else
  218865. XUnmapWindow (display, windowH);
  218866. }
  218867. void setTitle (const String& title)
  218868. {
  218869. setWindowTitle (windowH, title);
  218870. }
  218871. void setPosition (int x, int y)
  218872. {
  218873. setBounds (x, y, ww, wh, false);
  218874. }
  218875. void setSize (int w, int h)
  218876. {
  218877. setBounds (wx, wy, w, h, false);
  218878. }
  218879. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  218880. {
  218881. fullScreen = isNowFullScreen;
  218882. if (windowH != 0)
  218883. {
  218884. Component::SafePointer<Component> deletionChecker (component);
  218885. wx = x;
  218886. wy = y;
  218887. ww = jmax (1, w);
  218888. wh = jmax (1, h);
  218889. ScopedXLock xlock;
  218890. // Make sure the Window manager does what we want
  218891. XSizeHints* hints = XAllocSizeHints();
  218892. hints->flags = USSize | USPosition;
  218893. hints->width = ww;
  218894. hints->height = wh;
  218895. hints->x = wx;
  218896. hints->y = wy;
  218897. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  218898. {
  218899. hints->min_width = hints->max_width = hints->width;
  218900. hints->min_height = hints->max_height = hints->height;
  218901. hints->flags |= PMinSize | PMaxSize;
  218902. }
  218903. XSetWMNormalHints (display, windowH, hints);
  218904. XFree (hints);
  218905. XMoveResizeWindow (display, windowH,
  218906. wx - windowBorder.getLeft(),
  218907. wy - windowBorder.getTop(), ww, wh);
  218908. if (deletionChecker != 0)
  218909. {
  218910. updateBorderSize();
  218911. handleMovedOrResized();
  218912. }
  218913. }
  218914. }
  218915. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  218916. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  218917. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  218918. {
  218919. return relativePosition + getScreenPosition();
  218920. }
  218921. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  218922. {
  218923. return screenPosition - getScreenPosition();
  218924. }
  218925. void setMinimised (bool shouldBeMinimised)
  218926. {
  218927. if (shouldBeMinimised)
  218928. {
  218929. Window root = RootWindow (display, DefaultScreen (display));
  218930. XClientMessageEvent clientMsg;
  218931. clientMsg.display = display;
  218932. clientMsg.window = windowH;
  218933. clientMsg.type = ClientMessage;
  218934. clientMsg.format = 32;
  218935. clientMsg.message_type = Atoms::ChangeState;
  218936. clientMsg.data.l[0] = IconicState;
  218937. ScopedXLock xlock;
  218938. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  218939. }
  218940. else
  218941. {
  218942. setVisible (true);
  218943. }
  218944. }
  218945. bool isMinimised() const
  218946. {
  218947. bool minimised = false;
  218948. unsigned char* stateProp;
  218949. unsigned long nitems, bytesLeft;
  218950. Atom actualType;
  218951. int actualFormat;
  218952. ScopedXLock xlock;
  218953. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  218954. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  218955. &stateProp) == Success
  218956. && actualType == Atoms::State
  218957. && actualFormat == 32
  218958. && nitems > 0)
  218959. {
  218960. if (((unsigned long*) stateProp)[0] == IconicState)
  218961. minimised = true;
  218962. XFree (stateProp);
  218963. }
  218964. return minimised;
  218965. }
  218966. void setFullScreen (const bool shouldBeFullScreen)
  218967. {
  218968. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  218969. setMinimised (false);
  218970. if (fullScreen != shouldBeFullScreen)
  218971. {
  218972. if (shouldBeFullScreen)
  218973. r = Desktop::getInstance().getMainMonitorArea();
  218974. if (! r.isEmpty())
  218975. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  218976. getComponent()->repaint();
  218977. }
  218978. }
  218979. bool isFullScreen() const
  218980. {
  218981. return fullScreen;
  218982. }
  218983. bool isChildWindowOf (Window possibleParent) const
  218984. {
  218985. Window* windowList = 0;
  218986. uint32 windowListSize = 0;
  218987. Window parent, root;
  218988. ScopedXLock xlock;
  218989. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  218990. {
  218991. if (windowList != 0)
  218992. XFree (windowList);
  218993. return parent == possibleParent;
  218994. }
  218995. return false;
  218996. }
  218997. bool isFrontWindow() const
  218998. {
  218999. Window* windowList = 0;
  219000. uint32 windowListSize = 0;
  219001. bool result = false;
  219002. ScopedXLock xlock;
  219003. Window parent, root = RootWindow (display, DefaultScreen (display));
  219004. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219005. {
  219006. for (int i = windowListSize; --i >= 0;)
  219007. {
  219008. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219009. if (peer != 0)
  219010. {
  219011. result = (peer == this);
  219012. break;
  219013. }
  219014. }
  219015. }
  219016. if (windowList != 0)
  219017. XFree (windowList);
  219018. return result;
  219019. }
  219020. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219021. {
  219022. int x = position.getX();
  219023. int y = position.getY();
  219024. if (((unsigned int) x) >= (unsigned int) ww
  219025. || ((unsigned int) y) >= (unsigned int) wh)
  219026. return false;
  219027. bool inFront = false;
  219028. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  219029. {
  219030. Component* const c = Desktop::getInstance().getComponent (i);
  219031. if (inFront)
  219032. {
  219033. if (c->contains (x + wx - c->getScreenX(),
  219034. y + wy - c->getScreenY()))
  219035. {
  219036. return false;
  219037. }
  219038. }
  219039. else if (c == getComponent())
  219040. {
  219041. inFront = true;
  219042. }
  219043. }
  219044. if (trueIfInAChildWindow)
  219045. return true;
  219046. ::Window root, child;
  219047. unsigned int bw, depth;
  219048. int wx, wy, w, h;
  219049. ScopedXLock xlock;
  219050. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219051. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219052. &bw, &depth))
  219053. {
  219054. return false;
  219055. }
  219056. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  219057. return false;
  219058. return child == None;
  219059. }
  219060. const BorderSize getFrameSize() const
  219061. {
  219062. return BorderSize();
  219063. }
  219064. bool setAlwaysOnTop (bool alwaysOnTop)
  219065. {
  219066. return false;
  219067. }
  219068. void toFront (bool makeActive)
  219069. {
  219070. if (makeActive)
  219071. {
  219072. setVisible (true);
  219073. grabFocus();
  219074. }
  219075. XEvent ev;
  219076. ev.xclient.type = ClientMessage;
  219077. ev.xclient.serial = 0;
  219078. ev.xclient.send_event = True;
  219079. ev.xclient.message_type = Atoms::ActiveWin;
  219080. ev.xclient.window = windowH;
  219081. ev.xclient.format = 32;
  219082. ev.xclient.data.l[0] = 2;
  219083. ev.xclient.data.l[1] = CurrentTime;
  219084. ev.xclient.data.l[2] = 0;
  219085. ev.xclient.data.l[3] = 0;
  219086. ev.xclient.data.l[4] = 0;
  219087. {
  219088. ScopedXLock xlock;
  219089. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219090. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219091. XWindowAttributes attr;
  219092. XGetWindowAttributes (display, windowH, &attr);
  219093. if (component->isAlwaysOnTop())
  219094. XRaiseWindow (display, windowH);
  219095. XSync (display, False);
  219096. }
  219097. handleBroughtToFront();
  219098. }
  219099. void toBehind (ComponentPeer* other)
  219100. {
  219101. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219102. jassert (otherPeer != 0); // wrong type of window?
  219103. if (otherPeer != 0)
  219104. {
  219105. setMinimised (false);
  219106. Window newStack[] = { otherPeer->windowH, windowH };
  219107. ScopedXLock xlock;
  219108. XRestackWindows (display, newStack, 2);
  219109. }
  219110. }
  219111. bool isFocused() const
  219112. {
  219113. int revert = 0;
  219114. Window focusedWindow = 0;
  219115. ScopedXLock xlock;
  219116. XGetInputFocus (display, &focusedWindow, &revert);
  219117. return focusedWindow == windowH;
  219118. }
  219119. void grabFocus()
  219120. {
  219121. XWindowAttributes atts;
  219122. ScopedXLock xlock;
  219123. if (windowH != 0
  219124. && XGetWindowAttributes (display, windowH, &atts)
  219125. && atts.map_state == IsViewable
  219126. && ! isFocused())
  219127. {
  219128. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219129. isActiveApplication = true;
  219130. }
  219131. }
  219132. void textInputRequired (const Point<int>&)
  219133. {
  219134. }
  219135. void repaint (const Rectangle<int>& area)
  219136. {
  219137. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219138. }
  219139. void performAnyPendingRepaintsNow()
  219140. {
  219141. repainter->performAnyPendingRepaintsNow();
  219142. }
  219143. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  219144. {
  219145. ScopedXLock xlock;
  219146. const int width = image.getWidth();
  219147. const int height = image.getHeight();
  219148. HeapBlock <char> colour (width * height);
  219149. int index = 0;
  219150. for (int y = 0; y < height; ++y)
  219151. for (int x = 0; x < width; ++x)
  219152. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  219153. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219154. 0, colour.getData(),
  219155. width, height, 32, 0);
  219156. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219157. width, height, 24);
  219158. GC gc = XCreateGC (display, pixmap, 0, 0);
  219159. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219160. XFreeGC (display, gc);
  219161. return pixmap;
  219162. }
  219163. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  219164. {
  219165. ScopedXLock xlock;
  219166. const int width = image.getWidth();
  219167. const int height = image.getHeight();
  219168. const int stride = (width + 7) >> 3;
  219169. HeapBlock <char> mask;
  219170. mask.calloc (stride * height);
  219171. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219172. for (int y = 0; y < height; ++y)
  219173. {
  219174. for (int x = 0; x < width; ++x)
  219175. {
  219176. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219177. const int offset = y * stride + (x >> 3);
  219178. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219179. mask[offset] |= bit;
  219180. }
  219181. }
  219182. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219183. mask.getData(), width, height, 1, 0, 1);
  219184. }
  219185. void setIcon (const Image& newIcon)
  219186. {
  219187. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219188. HeapBlock <unsigned long> data (dataSize);
  219189. int index = 0;
  219190. data[index++] = newIcon.getWidth();
  219191. data[index++] = newIcon.getHeight();
  219192. for (int y = 0; y < newIcon.getHeight(); ++y)
  219193. for (int x = 0; x < newIcon.getWidth(); ++x)
  219194. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219195. ScopedXLock xlock;
  219196. XChangeProperty (display, windowH,
  219197. XInternAtom (display, "_NET_WM_ICON", False),
  219198. XA_CARDINAL, 32, PropModeReplace,
  219199. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219200. deleteIconPixmaps();
  219201. XWMHints* wmHints = XGetWMHints (display, windowH);
  219202. if (wmHints == 0)
  219203. wmHints = XAllocWMHints();
  219204. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219205. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  219206. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  219207. XSetWMHints (display, windowH, wmHints);
  219208. XFree (wmHints);
  219209. XSync (display, False);
  219210. }
  219211. void deleteIconPixmaps()
  219212. {
  219213. ScopedXLock xlock;
  219214. XWMHints* wmHints = XGetWMHints (display, windowH);
  219215. if (wmHints != 0)
  219216. {
  219217. if ((wmHints->flags & IconPixmapHint) != 0)
  219218. {
  219219. wmHints->flags &= ~IconPixmapHint;
  219220. XFreePixmap (display, wmHints->icon_pixmap);
  219221. }
  219222. if ((wmHints->flags & IconMaskHint) != 0)
  219223. {
  219224. wmHints->flags &= ~IconMaskHint;
  219225. XFreePixmap (display, wmHints->icon_mask);
  219226. }
  219227. XSetWMHints (display, windowH, wmHints);
  219228. XFree (wmHints);
  219229. }
  219230. }
  219231. void handleWindowMessage (XEvent* event)
  219232. {
  219233. switch (event->xany.type)
  219234. {
  219235. case 2: // 'KeyPress'
  219236. {
  219237. ScopedXLock xlock;
  219238. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  219239. updateKeyStates (keyEvent->keycode, true);
  219240. char utf8 [64];
  219241. zeromem (utf8, sizeof (utf8));
  219242. KeySym sym;
  219243. {
  219244. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219245. ::setlocale (LC_ALL, "");
  219246. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219247. ::setlocale (LC_ALL, oldLocale);
  219248. }
  219249. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219250. int keyCode = (int) unicodeChar;
  219251. if (keyCode < 0x20)
  219252. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219253. const ModifierKeys oldMods (currentModifiers);
  219254. bool keyPressed = false;
  219255. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219256. if ((sym & 0xff00) == 0xff00)
  219257. {
  219258. // Translate keypad
  219259. if (sym == XK_KP_Divide)
  219260. keyCode = XK_slash;
  219261. else if (sym == XK_KP_Multiply)
  219262. keyCode = XK_asterisk;
  219263. else if (sym == XK_KP_Subtract)
  219264. keyCode = XK_hyphen;
  219265. else if (sym == XK_KP_Add)
  219266. keyCode = XK_plus;
  219267. else if (sym == XK_KP_Enter)
  219268. keyCode = XK_Return;
  219269. else if (sym == XK_KP_Decimal)
  219270. keyCode = Keys::numLock ? XK_period : XK_Delete;
  219271. else if (sym == XK_KP_0)
  219272. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  219273. else if (sym == XK_KP_1)
  219274. keyCode = Keys::numLock ? XK_1 : XK_End;
  219275. else if (sym == XK_KP_2)
  219276. keyCode = Keys::numLock ? XK_2 : XK_Down;
  219277. else if (sym == XK_KP_3)
  219278. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  219279. else if (sym == XK_KP_4)
  219280. keyCode = Keys::numLock ? XK_4 : XK_Left;
  219281. else if (sym == XK_KP_5)
  219282. keyCode = XK_5;
  219283. else if (sym == XK_KP_6)
  219284. keyCode = Keys::numLock ? XK_6 : XK_Right;
  219285. else if (sym == XK_KP_7)
  219286. keyCode = Keys::numLock ? XK_7 : XK_Home;
  219287. else if (sym == XK_KP_8)
  219288. keyCode = Keys::numLock ? XK_8 : XK_Up;
  219289. else if (sym == XK_KP_9)
  219290. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  219291. switch (sym)
  219292. {
  219293. case XK_Left:
  219294. case XK_Right:
  219295. case XK_Up:
  219296. case XK_Down:
  219297. case XK_Page_Up:
  219298. case XK_Page_Down:
  219299. case XK_End:
  219300. case XK_Home:
  219301. case XK_Delete:
  219302. case XK_Insert:
  219303. keyPressed = true;
  219304. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219305. break;
  219306. case XK_Tab:
  219307. case XK_Return:
  219308. case XK_Escape:
  219309. case XK_BackSpace:
  219310. keyPressed = true;
  219311. keyCode &= 0xff;
  219312. break;
  219313. default:
  219314. {
  219315. if (sym >= XK_F1 && sym <= XK_F16)
  219316. {
  219317. keyPressed = true;
  219318. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219319. }
  219320. break;
  219321. }
  219322. }
  219323. }
  219324. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219325. keyPressed = true;
  219326. if (oldMods != currentModifiers)
  219327. handleModifierKeysChange();
  219328. if (keyDownChange)
  219329. handleKeyUpOrDown (true);
  219330. if (keyPressed)
  219331. handleKeyPress (keyCode, unicodeChar);
  219332. break;
  219333. }
  219334. case KeyRelease:
  219335. {
  219336. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  219337. updateKeyStates (keyEvent->keycode, false);
  219338. ScopedXLock xlock;
  219339. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219340. const ModifierKeys oldMods (currentModifiers);
  219341. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219342. if (oldMods != currentModifiers)
  219343. handleModifierKeysChange();
  219344. if (keyDownChange)
  219345. handleKeyUpOrDown (false);
  219346. break;
  219347. }
  219348. case ButtonPress:
  219349. {
  219350. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  219351. updateKeyModifiers (buttonPressEvent->state);
  219352. bool buttonMsg = false;
  219353. const int map = pointerMap [buttonPressEvent->button - Button1];
  219354. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219355. {
  219356. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219357. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219358. }
  219359. if (map == Keys::LeftButton)
  219360. {
  219361. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219362. buttonMsg = true;
  219363. }
  219364. else if (map == Keys::RightButton)
  219365. {
  219366. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219367. buttonMsg = true;
  219368. }
  219369. else if (map == Keys::MiddleButton)
  219370. {
  219371. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219372. buttonMsg = true;
  219373. }
  219374. if (buttonMsg)
  219375. {
  219376. toFront (true);
  219377. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219378. getEventTime (buttonPressEvent->time));
  219379. }
  219380. clearLastMousePos();
  219381. break;
  219382. }
  219383. case ButtonRelease:
  219384. {
  219385. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  219386. updateKeyModifiers (buttonRelEvent->state);
  219387. const int map = pointerMap [buttonRelEvent->button - Button1];
  219388. if (map == Keys::LeftButton)
  219389. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219390. else if (map == Keys::RightButton)
  219391. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219392. else if (map == Keys::MiddleButton)
  219393. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219394. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219395. getEventTime (buttonRelEvent->time));
  219396. clearLastMousePos();
  219397. break;
  219398. }
  219399. case MotionNotify:
  219400. {
  219401. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  219402. updateKeyModifiers (movedEvent->state);
  219403. const Point<int> mousePos (Desktop::getMousePosition());
  219404. if (lastMousePos != mousePos)
  219405. {
  219406. lastMousePos = mousePos;
  219407. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219408. {
  219409. Window wRoot = 0, wParent = 0;
  219410. {
  219411. ScopedXLock xlock;
  219412. unsigned int numChildren;
  219413. Window* wChild = 0;
  219414. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219415. }
  219416. if (wParent != 0
  219417. && wParent != windowH
  219418. && wParent != wRoot)
  219419. {
  219420. parentWindow = wParent;
  219421. updateBounds();
  219422. }
  219423. else
  219424. {
  219425. parentWindow = 0;
  219426. }
  219427. }
  219428. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219429. }
  219430. break;
  219431. }
  219432. case EnterNotify:
  219433. {
  219434. clearLastMousePos();
  219435. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  219436. if (! currentModifiers.isAnyMouseButtonDown())
  219437. {
  219438. updateKeyModifiers (enterEvent->state);
  219439. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219440. }
  219441. break;
  219442. }
  219443. case LeaveNotify:
  219444. {
  219445. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  219446. // Suppress the normal leave if we've got a pointer grab, or if
  219447. // it's a bogus one caused by clicking a mouse button when running
  219448. // in a Window manager
  219449. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219450. || leaveEvent->mode == NotifyUngrab)
  219451. {
  219452. updateKeyModifiers (leaveEvent->state);
  219453. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219454. }
  219455. break;
  219456. }
  219457. case FocusIn:
  219458. {
  219459. isActiveApplication = true;
  219460. if (isFocused())
  219461. handleFocusGain();
  219462. break;
  219463. }
  219464. case FocusOut:
  219465. {
  219466. isActiveApplication = false;
  219467. if (! isFocused())
  219468. handleFocusLoss();
  219469. break;
  219470. }
  219471. case Expose:
  219472. {
  219473. // Batch together all pending expose events
  219474. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  219475. XEvent nextEvent;
  219476. ScopedXLock xlock;
  219477. if (exposeEvent->window != windowH)
  219478. {
  219479. Window child;
  219480. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219481. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219482. &child);
  219483. }
  219484. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219485. exposeEvent->width, exposeEvent->height));
  219486. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219487. {
  219488. XPeekEvent (display, (XEvent*) &nextEvent);
  219489. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  219490. break;
  219491. XNextEvent (display, (XEvent*) &nextEvent);
  219492. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219493. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219494. nextExposeEvent->width, nextExposeEvent->height));
  219495. }
  219496. break;
  219497. }
  219498. case CirculateNotify:
  219499. case CreateNotify:
  219500. case DestroyNotify:
  219501. // Think we can ignore these
  219502. break;
  219503. case ConfigureNotify:
  219504. {
  219505. updateBounds();
  219506. updateBorderSize();
  219507. handleMovedOrResized();
  219508. // if the native title bar is dragged, need to tell any active menus, etc.
  219509. if ((styleFlags & windowHasTitleBar) != 0
  219510. && component->isCurrentlyBlockedByAnotherModalComponent())
  219511. {
  219512. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219513. if (currentModalComp != 0)
  219514. currentModalComp->inputAttemptWhenModal();
  219515. }
  219516. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  219517. if (confEvent->window == windowH
  219518. && confEvent->above != 0
  219519. && isFrontWindow())
  219520. {
  219521. handleBroughtToFront();
  219522. }
  219523. break;
  219524. }
  219525. case ReparentNotify:
  219526. {
  219527. parentWindow = 0;
  219528. Window wRoot = 0;
  219529. Window* wChild = 0;
  219530. unsigned int numChildren;
  219531. {
  219532. ScopedXLock xlock;
  219533. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219534. }
  219535. if (parentWindow == windowH || parentWindow == wRoot)
  219536. parentWindow = 0;
  219537. updateBounds();
  219538. updateBorderSize();
  219539. handleMovedOrResized();
  219540. break;
  219541. }
  219542. case GravityNotify:
  219543. {
  219544. updateBounds();
  219545. updateBorderSize();
  219546. handleMovedOrResized();
  219547. break;
  219548. }
  219549. case MapNotify:
  219550. mapped = true;
  219551. handleBroughtToFront();
  219552. break;
  219553. case UnmapNotify:
  219554. mapped = false;
  219555. break;
  219556. case MappingNotify:
  219557. {
  219558. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  219559. if (mappingEvent->request != MappingPointer)
  219560. {
  219561. // Deal with modifier/keyboard mapping
  219562. ScopedXLock xlock;
  219563. XRefreshKeyboardMapping (mappingEvent);
  219564. updateModifierMappings();
  219565. }
  219566. break;
  219567. }
  219568. case ClientMessage:
  219569. {
  219570. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  219571. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219572. {
  219573. const Atom atom = (Atom) clientMsg->data.l[0];
  219574. if (atom == Atoms::ProtocolList [Atoms::PING])
  219575. {
  219576. Window root = RootWindow (display, DefaultScreen (display));
  219577. event->xclient.window = root;
  219578. XSendEvent (display, root, False, NoEventMask, event);
  219579. XFlush (display);
  219580. }
  219581. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219582. {
  219583. XWindowAttributes atts;
  219584. ScopedXLock xlock;
  219585. if (clientMsg->window != 0
  219586. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219587. {
  219588. if (atts.map_state == IsViewable)
  219589. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219590. }
  219591. }
  219592. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219593. {
  219594. handleUserClosingWindow();
  219595. }
  219596. }
  219597. else if (clientMsg->message_type == Atoms::XdndEnter)
  219598. {
  219599. handleDragAndDropEnter (clientMsg);
  219600. }
  219601. else if (clientMsg->message_type == Atoms::XdndLeave)
  219602. {
  219603. resetDragAndDrop();
  219604. }
  219605. else if (clientMsg->message_type == Atoms::XdndPosition)
  219606. {
  219607. handleDragAndDropPosition (clientMsg);
  219608. }
  219609. else if (clientMsg->message_type == Atoms::XdndDrop)
  219610. {
  219611. handleDragAndDropDrop (clientMsg);
  219612. }
  219613. else if (clientMsg->message_type == Atoms::XdndStatus)
  219614. {
  219615. handleDragAndDropStatus (clientMsg);
  219616. }
  219617. else if (clientMsg->message_type == Atoms::XdndFinished)
  219618. {
  219619. resetDragAndDrop();
  219620. }
  219621. break;
  219622. }
  219623. case SelectionNotify:
  219624. handleDragAndDropSelection (event);
  219625. break;
  219626. case SelectionClear:
  219627. case SelectionRequest:
  219628. break;
  219629. default:
  219630. #if JUCE_USE_XSHM
  219631. {
  219632. ScopedXLock xlock;
  219633. if (event->xany.type == XShmGetEventBase (display))
  219634. repainter->notifyPaintCompleted();
  219635. }
  219636. #endif
  219637. break;
  219638. }
  219639. }
  219640. void showMouseCursor (Cursor cursor) throw()
  219641. {
  219642. ScopedXLock xlock;
  219643. XDefineCursor (display, windowH, cursor);
  219644. }
  219645. void setTaskBarIcon (const Image& image)
  219646. {
  219647. ScopedXLock xlock;
  219648. taskbarImage = image;
  219649. Screen* const screen = XDefaultScreenOfDisplay (display);
  219650. const int screenNumber = XScreenNumberOfScreen (screen);
  219651. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219652. screenAtom << screenNumber;
  219653. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219654. XGrabServer (display);
  219655. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219656. if (managerWin != None)
  219657. XSelectInput (display, managerWin, StructureNotifyMask);
  219658. XUngrabServer (display);
  219659. XFlush (display);
  219660. if (managerWin != None)
  219661. {
  219662. XEvent ev;
  219663. zerostruct (ev);
  219664. ev.xclient.type = ClientMessage;
  219665. ev.xclient.window = managerWin;
  219666. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219667. ev.xclient.format = 32;
  219668. ev.xclient.data.l[0] = CurrentTime;
  219669. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219670. ev.xclient.data.l[2] = windowH;
  219671. ev.xclient.data.l[3] = 0;
  219672. ev.xclient.data.l[4] = 0;
  219673. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219674. XSync (display, False);
  219675. }
  219676. // For older KDE's ...
  219677. long atomData = 1;
  219678. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219679. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219680. // For more recent KDE's...
  219681. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219682. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219683. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219684. XSizeHints* hints = XAllocSizeHints();
  219685. hints->flags = PMinSize;
  219686. hints->min_width = 22;
  219687. hints->min_height = 22;
  219688. XSetWMNormalHints (display, windowH, hints);
  219689. XFree (hints);
  219690. }
  219691. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219692. juce_UseDebuggingNewOperator
  219693. bool dontRepaint;
  219694. static ModifierKeys currentModifiers;
  219695. static bool isActiveApplication;
  219696. private:
  219697. class LinuxRepaintManager : public Timer
  219698. {
  219699. public:
  219700. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219701. : peer (peer_),
  219702. lastTimeImageUsed (0)
  219703. {
  219704. #if JUCE_USE_XSHM
  219705. shmCompletedDrawing = true;
  219706. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219707. if (useARGBImagesForRendering)
  219708. {
  219709. ScopedXLock xlock;
  219710. XShmSegmentInfo segmentinfo;
  219711. XImage* const testImage
  219712. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219713. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219714. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219715. XDestroyImage (testImage);
  219716. }
  219717. #endif
  219718. }
  219719. ~LinuxRepaintManager()
  219720. {
  219721. }
  219722. void timerCallback()
  219723. {
  219724. #if JUCE_USE_XSHM
  219725. if (! shmCompletedDrawing)
  219726. return;
  219727. #endif
  219728. if (! regionsNeedingRepaint.isEmpty())
  219729. {
  219730. stopTimer();
  219731. performAnyPendingRepaintsNow();
  219732. }
  219733. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219734. {
  219735. stopTimer();
  219736. image = Image::null;
  219737. }
  219738. }
  219739. void repaint (const Rectangle<int>& area)
  219740. {
  219741. if (! isTimerRunning())
  219742. startTimer (repaintTimerPeriod);
  219743. regionsNeedingRepaint.add (area);
  219744. }
  219745. void performAnyPendingRepaintsNow()
  219746. {
  219747. #if JUCE_USE_XSHM
  219748. if (! shmCompletedDrawing)
  219749. {
  219750. startTimer (repaintTimerPeriod);
  219751. return;
  219752. }
  219753. #endif
  219754. peer->clearMaskedRegion();
  219755. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219756. regionsNeedingRepaint.clear();
  219757. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219758. if (! totalArea.isEmpty())
  219759. {
  219760. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  219761. || image.getHeight() < totalArea.getHeight())
  219762. {
  219763. #if JUCE_USE_XSHM
  219764. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  219765. : Image::RGB,
  219766. #else
  219767. image = Image (new XBitmapImage (Image::RGB,
  219768. #endif
  219769. (totalArea.getWidth() + 31) & ~31,
  219770. (totalArea.getHeight() + 31) & ~31,
  219771. false, peer->depth, peer->visual));
  219772. }
  219773. startTimer (repaintTimerPeriod);
  219774. RectangleList adjustedList (originalRepaintRegion);
  219775. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  219776. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  219777. if (peer->depth == 32)
  219778. {
  219779. RectangleList::Iterator i (originalRepaintRegion);
  219780. while (i.next())
  219781. image.clear (*i.getRectangle() - totalArea.getPosition());
  219782. }
  219783. peer->handlePaint (context);
  219784. if (! peer->maskedRegion.isEmpty())
  219785. originalRepaintRegion.subtract (peer->maskedRegion);
  219786. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  219787. {
  219788. #if JUCE_USE_XSHM
  219789. shmCompletedDrawing = false;
  219790. #endif
  219791. const Rectangle<int>& r = *i.getRectangle();
  219792. static_cast<XBitmapImage*> (image.getSharedImage())
  219793. ->blitToWindow (peer->windowH,
  219794. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  219795. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  219796. }
  219797. }
  219798. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  219799. startTimer (repaintTimerPeriod);
  219800. }
  219801. #if JUCE_USE_XSHM
  219802. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  219803. #endif
  219804. private:
  219805. enum { repaintTimerPeriod = 1000 / 100 };
  219806. LinuxComponentPeer* const peer;
  219807. Image image;
  219808. uint32 lastTimeImageUsed;
  219809. RectangleList regionsNeedingRepaint;
  219810. #if JUCE_USE_XSHM
  219811. bool useARGBImagesForRendering, shmCompletedDrawing;
  219812. #endif
  219813. LinuxRepaintManager (const LinuxRepaintManager&);
  219814. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  219815. };
  219816. ScopedPointer <LinuxRepaintManager> repainter;
  219817. friend class LinuxRepaintManager;
  219818. Window windowH, parentWindow;
  219819. int wx, wy, ww, wh;
  219820. Image taskbarImage;
  219821. bool fullScreen, mapped;
  219822. Visual* visual;
  219823. int depth;
  219824. BorderSize windowBorder;
  219825. struct MotifWmHints
  219826. {
  219827. unsigned long flags;
  219828. unsigned long functions;
  219829. unsigned long decorations;
  219830. long input_mode;
  219831. unsigned long status;
  219832. };
  219833. static void updateKeyStates (const int keycode, const bool press) throw()
  219834. {
  219835. const int keybyte = keycode >> 3;
  219836. const int keybit = (1 << (keycode & 7));
  219837. if (press)
  219838. Keys::keyStates [keybyte] |= keybit;
  219839. else
  219840. Keys::keyStates [keybyte] &= ~keybit;
  219841. }
  219842. static void updateKeyModifiers (const int status) throw()
  219843. {
  219844. int keyMods = 0;
  219845. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  219846. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  219847. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  219848. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  219849. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  219850. Keys::capsLock = ((status & LockMask) != 0);
  219851. }
  219852. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  219853. {
  219854. int modifier = 0;
  219855. bool isModifier = true;
  219856. switch (sym)
  219857. {
  219858. case XK_Shift_L:
  219859. case XK_Shift_R:
  219860. modifier = ModifierKeys::shiftModifier;
  219861. break;
  219862. case XK_Control_L:
  219863. case XK_Control_R:
  219864. modifier = ModifierKeys::ctrlModifier;
  219865. break;
  219866. case XK_Alt_L:
  219867. case XK_Alt_R:
  219868. modifier = ModifierKeys::altModifier;
  219869. break;
  219870. case XK_Num_Lock:
  219871. if (press)
  219872. Keys::numLock = ! Keys::numLock;
  219873. break;
  219874. case XK_Caps_Lock:
  219875. if (press)
  219876. Keys::capsLock = ! Keys::capsLock;
  219877. break;
  219878. case XK_Scroll_Lock:
  219879. break;
  219880. default:
  219881. isModifier = false;
  219882. break;
  219883. }
  219884. if (modifier != 0)
  219885. {
  219886. if (press)
  219887. currentModifiers = currentModifiers.withFlags (modifier);
  219888. else
  219889. currentModifiers = currentModifiers.withoutFlags (modifier);
  219890. }
  219891. return isModifier;
  219892. }
  219893. // Alt and Num lock are not defined by standard X
  219894. // modifier constants: check what they're mapped to
  219895. static void updateModifierMappings() throw()
  219896. {
  219897. ScopedXLock xlock;
  219898. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  219899. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  219900. Keys::AltMask = 0;
  219901. Keys::NumLockMask = 0;
  219902. XModifierKeymap* mapping = XGetModifierMapping (display);
  219903. if (mapping)
  219904. {
  219905. for (int i = 0; i < 8; i++)
  219906. {
  219907. if (mapping->modifiermap [i << 1] == altLeftCode)
  219908. Keys::AltMask = 1 << i;
  219909. else if (mapping->modifiermap [i << 1] == numLockCode)
  219910. Keys::NumLockMask = 1 << i;
  219911. }
  219912. XFreeModifiermap (mapping);
  219913. }
  219914. }
  219915. void removeWindowDecorations (Window wndH)
  219916. {
  219917. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219918. if (hints != None)
  219919. {
  219920. MotifWmHints motifHints;
  219921. zerostruct (motifHints);
  219922. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  219923. motifHints.decorations = 0;
  219924. ScopedXLock xlock;
  219925. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219926. (unsigned char*) &motifHints, 4);
  219927. }
  219928. hints = XInternAtom (display, "_WIN_HINTS", True);
  219929. if (hints != None)
  219930. {
  219931. long gnomeHints = 0;
  219932. ScopedXLock xlock;
  219933. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219934. (unsigned char*) &gnomeHints, 1);
  219935. }
  219936. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  219937. if (hints != None)
  219938. {
  219939. long kwmHints = 2; /*KDE_tinyDecoration*/
  219940. ScopedXLock xlock;
  219941. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219942. (unsigned char*) &kwmHints, 1);
  219943. }
  219944. }
  219945. void addWindowButtons (Window wndH)
  219946. {
  219947. ScopedXLock xlock;
  219948. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219949. if (hints != None)
  219950. {
  219951. MotifWmHints motifHints;
  219952. zerostruct (motifHints);
  219953. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  219954. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  219955. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  219956. if ((styleFlags & windowHasCloseButton) != 0)
  219957. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  219958. if ((styleFlags & windowHasMinimiseButton) != 0)
  219959. {
  219960. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  219961. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  219962. }
  219963. if ((styleFlags & windowHasMaximiseButton) != 0)
  219964. {
  219965. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  219966. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  219967. }
  219968. if ((styleFlags & windowIsResizable) != 0)
  219969. {
  219970. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  219971. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  219972. }
  219973. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  219974. }
  219975. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  219976. if (hints != None)
  219977. {
  219978. int netHints [6];
  219979. int num = 0;
  219980. if ((styleFlags & windowIsResizable) != 0)
  219981. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  219982. if ((styleFlags & windowHasMaximiseButton) != 0)
  219983. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  219984. if ((styleFlags & windowHasMinimiseButton) != 0)
  219985. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  219986. if ((styleFlags & windowHasCloseButton) != 0)
  219987. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  219988. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  219989. }
  219990. }
  219991. void setWindowType()
  219992. {
  219993. int netHints [2];
  219994. int numHints = 0;
  219995. if ((styleFlags & windowIsTemporary) != 0
  219996. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  219997. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  219998. else
  219999. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220000. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220001. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220002. (unsigned char*) &netHints, numHints);
  220003. numHints = 0;
  220004. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220005. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220006. if (component->isAlwaysOnTop())
  220007. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220008. if (numHints > 0)
  220009. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220010. (unsigned char*) &netHints, numHints);
  220011. }
  220012. void createWindow()
  220013. {
  220014. ScopedXLock xlock;
  220015. Atoms::initialiseAtoms();
  220016. resetDragAndDrop();
  220017. // Get defaults for various properties
  220018. const int screen = DefaultScreen (display);
  220019. Window root = RootWindow (display, screen);
  220020. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220021. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220022. if (visual == 0)
  220023. {
  220024. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220025. Process::terminate();
  220026. }
  220027. // Create and install a colormap suitable fr our visual
  220028. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220029. XInstallColormap (display, colormap);
  220030. // Set up the window attributes
  220031. XSetWindowAttributes swa;
  220032. swa.border_pixel = 0;
  220033. swa.background_pixmap = None;
  220034. swa.colormap = colormap;
  220035. swa.event_mask = getAllEventsMask();
  220036. windowH = XCreateWindow (display, root,
  220037. 0, 0, 1, 1,
  220038. 0, depth, InputOutput, visual,
  220039. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220040. &swa);
  220041. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220042. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220043. GrabModeAsync, GrabModeAsync, None, None);
  220044. // Set the window context to identify the window handle object
  220045. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220046. {
  220047. // Failed
  220048. jassertfalse;
  220049. Logger::outputDebugString ("Failed to create context information for window.\n");
  220050. XDestroyWindow (display, windowH);
  220051. windowH = 0;
  220052. return;
  220053. }
  220054. // Set window manager hints
  220055. XWMHints* wmHints = XAllocWMHints();
  220056. wmHints->flags = InputHint | StateHint;
  220057. wmHints->input = True; // Locally active input model
  220058. wmHints->initial_state = NormalState;
  220059. XSetWMHints (display, windowH, wmHints);
  220060. XFree (wmHints);
  220061. // Set the window type
  220062. setWindowType();
  220063. // Define decoration
  220064. if ((styleFlags & windowHasTitleBar) == 0)
  220065. removeWindowDecorations (windowH);
  220066. else
  220067. addWindowButtons (windowH);
  220068. // Set window name
  220069. setWindowTitle (windowH, getComponent()->getName());
  220070. // Associate the PID, allowing to be shut down when something goes wrong
  220071. unsigned long pid = getpid();
  220072. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220073. (unsigned char*) &pid, 1);
  220074. // Set window manager protocols
  220075. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220076. (unsigned char*) Atoms::ProtocolList, 2);
  220077. // Set drag and drop flags
  220078. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220079. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220080. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220081. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220082. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220083. (const unsigned char*) "", 0);
  220084. unsigned long dndVersion = Atoms::DndVersion;
  220085. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220086. (const unsigned char*) &dndVersion, 1);
  220087. // Initialise the pointer and keyboard mapping
  220088. // This is not the same as the logical pointer mapping the X server uses:
  220089. // we don't mess with this.
  220090. static bool mappingInitialised = false;
  220091. if (! mappingInitialised)
  220092. {
  220093. mappingInitialised = true;
  220094. const int numButtons = XGetPointerMapping (display, 0, 0);
  220095. if (numButtons == 2)
  220096. {
  220097. pointerMap[0] = Keys::LeftButton;
  220098. pointerMap[1] = Keys::RightButton;
  220099. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220100. }
  220101. else if (numButtons >= 3)
  220102. {
  220103. pointerMap[0] = Keys::LeftButton;
  220104. pointerMap[1] = Keys::MiddleButton;
  220105. pointerMap[2] = Keys::RightButton;
  220106. if (numButtons >= 5)
  220107. {
  220108. pointerMap[3] = Keys::WheelUp;
  220109. pointerMap[4] = Keys::WheelDown;
  220110. }
  220111. }
  220112. updateModifierMappings();
  220113. }
  220114. }
  220115. void destroyWindow()
  220116. {
  220117. ScopedXLock xlock;
  220118. XPointer handlePointer;
  220119. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220120. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220121. XDestroyWindow (display, windowH);
  220122. // Wait for it to complete and then remove any events for this
  220123. // window from the event queue.
  220124. XSync (display, false);
  220125. XEvent event;
  220126. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220127. {}
  220128. }
  220129. static int getAllEventsMask() throw()
  220130. {
  220131. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220132. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220133. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220134. }
  220135. static int64 getEventTime (::Time t)
  220136. {
  220137. static int64 eventTimeOffset = 0x12345678;
  220138. const int64 thisMessageTime = t;
  220139. if (eventTimeOffset == 0x12345678)
  220140. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220141. return eventTimeOffset + thisMessageTime;
  220142. }
  220143. static void setWindowTitle (Window xwin, const String& title)
  220144. {
  220145. XTextProperty nameProperty;
  220146. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  220147. ScopedXLock xlock;
  220148. if (XStringListToTextProperty (strings, 1, &nameProperty))
  220149. {
  220150. XSetWMName (display, xwin, &nameProperty);
  220151. XSetWMIconName (display, xwin, &nameProperty);
  220152. XFree (nameProperty.value);
  220153. }
  220154. }
  220155. void updateBorderSize()
  220156. {
  220157. if ((styleFlags & windowHasTitleBar) == 0)
  220158. {
  220159. windowBorder = BorderSize (0);
  220160. }
  220161. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220162. {
  220163. ScopedXLock xlock;
  220164. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220165. if (hints != None)
  220166. {
  220167. unsigned char* data = 0;
  220168. unsigned long nitems, bytesLeft;
  220169. Atom actualType;
  220170. int actualFormat;
  220171. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220172. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220173. &data) == Success)
  220174. {
  220175. const unsigned long* const sizes = (const unsigned long*) data;
  220176. if (actualFormat == 32)
  220177. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  220178. (int) sizes[3], (int) sizes[1]);
  220179. XFree (data);
  220180. }
  220181. }
  220182. }
  220183. }
  220184. void updateBounds()
  220185. {
  220186. jassert (windowH != 0);
  220187. if (windowH != 0)
  220188. {
  220189. Window root, child;
  220190. unsigned int bw, depth;
  220191. ScopedXLock xlock;
  220192. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220193. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220194. &bw, &depth))
  220195. {
  220196. wx = wy = ww = wh = 0;
  220197. }
  220198. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220199. {
  220200. wx = wy = 0;
  220201. }
  220202. }
  220203. }
  220204. void resetDragAndDrop()
  220205. {
  220206. dragAndDropFiles.clear();
  220207. lastDropPos = Point<int> (-1, -1);
  220208. dragAndDropCurrentMimeType = 0;
  220209. dragAndDropSourceWindow = 0;
  220210. srcMimeTypeAtomList.clear();
  220211. }
  220212. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220213. {
  220214. msg.type = ClientMessage;
  220215. msg.display = display;
  220216. msg.window = dragAndDropSourceWindow;
  220217. msg.format = 32;
  220218. msg.data.l[0] = windowH;
  220219. ScopedXLock xlock;
  220220. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220221. }
  220222. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220223. {
  220224. XClientMessageEvent msg;
  220225. zerostruct (msg);
  220226. msg.message_type = Atoms::XdndStatus;
  220227. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220228. msg.data.l[4] = dropAction;
  220229. sendDragAndDropMessage (msg);
  220230. }
  220231. void sendDragAndDropLeave()
  220232. {
  220233. XClientMessageEvent msg;
  220234. zerostruct (msg);
  220235. msg.message_type = Atoms::XdndLeave;
  220236. sendDragAndDropMessage (msg);
  220237. }
  220238. void sendDragAndDropFinish()
  220239. {
  220240. XClientMessageEvent msg;
  220241. zerostruct (msg);
  220242. msg.message_type = Atoms::XdndFinished;
  220243. sendDragAndDropMessage (msg);
  220244. }
  220245. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220246. {
  220247. if ((clientMsg->data.l[1] & 1) == 0)
  220248. {
  220249. sendDragAndDropLeave();
  220250. if (dragAndDropFiles.size() > 0)
  220251. handleFileDragExit (dragAndDropFiles);
  220252. dragAndDropFiles.clear();
  220253. }
  220254. }
  220255. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220256. {
  220257. if (dragAndDropSourceWindow == 0)
  220258. return;
  220259. dragAndDropSourceWindow = clientMsg->data.l[0];
  220260. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220261. (int) clientMsg->data.l[2] & 0xffff);
  220262. dropPos -= getScreenPosition();
  220263. if (lastDropPos != dropPos)
  220264. {
  220265. lastDropPos = dropPos;
  220266. dragAndDropTimestamp = clientMsg->data.l[3];
  220267. Atom targetAction = Atoms::XdndActionCopy;
  220268. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220269. {
  220270. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220271. {
  220272. targetAction = Atoms::allowedActions[i];
  220273. break;
  220274. }
  220275. }
  220276. sendDragAndDropStatus (true, targetAction);
  220277. if (dragAndDropFiles.size() == 0)
  220278. updateDraggedFileList (clientMsg);
  220279. if (dragAndDropFiles.size() > 0)
  220280. handleFileDragMove (dragAndDropFiles, dropPos);
  220281. }
  220282. }
  220283. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220284. {
  220285. if (dragAndDropFiles.size() == 0)
  220286. updateDraggedFileList (clientMsg);
  220287. const StringArray files (dragAndDropFiles);
  220288. const Point<int> lastPos (lastDropPos);
  220289. sendDragAndDropFinish();
  220290. resetDragAndDrop();
  220291. if (files.size() > 0)
  220292. handleFileDragDrop (files, lastPos);
  220293. }
  220294. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220295. {
  220296. dragAndDropFiles.clear();
  220297. srcMimeTypeAtomList.clear();
  220298. dragAndDropCurrentMimeType = 0;
  220299. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220300. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220301. {
  220302. dragAndDropSourceWindow = 0;
  220303. return;
  220304. }
  220305. dragAndDropSourceWindow = clientMsg->data.l[0];
  220306. if ((clientMsg->data.l[1] & 1) != 0)
  220307. {
  220308. Atom actual;
  220309. int format;
  220310. unsigned long count = 0, remaining = 0;
  220311. unsigned char* data = 0;
  220312. ScopedXLock xlock;
  220313. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220314. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220315. &count, &remaining, &data);
  220316. if (data != 0)
  220317. {
  220318. if (actual == XA_ATOM && format == 32 && count != 0)
  220319. {
  220320. const unsigned long* const types = (const unsigned long*) data;
  220321. for (unsigned int i = 0; i < count; ++i)
  220322. if (types[i] != None)
  220323. srcMimeTypeAtomList.add (types[i]);
  220324. }
  220325. XFree (data);
  220326. }
  220327. }
  220328. if (srcMimeTypeAtomList.size() == 0)
  220329. {
  220330. for (int i = 2; i < 5; ++i)
  220331. if (clientMsg->data.l[i] != None)
  220332. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220333. if (srcMimeTypeAtomList.size() == 0)
  220334. {
  220335. dragAndDropSourceWindow = 0;
  220336. return;
  220337. }
  220338. }
  220339. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220340. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220341. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220342. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220343. handleDragAndDropPosition (clientMsg);
  220344. }
  220345. void handleDragAndDropSelection (const XEvent* const evt)
  220346. {
  220347. dragAndDropFiles.clear();
  220348. if (evt->xselection.property != 0)
  220349. {
  220350. StringArray lines;
  220351. {
  220352. MemoryBlock dropData;
  220353. for (;;)
  220354. {
  220355. Atom actual;
  220356. uint8* data = 0;
  220357. unsigned long count = 0, remaining = 0;
  220358. int format = 0;
  220359. ScopedXLock xlock;
  220360. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220361. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220362. &format, &count, &remaining, &data) == Success)
  220363. {
  220364. dropData.append (data, count * format / 8);
  220365. XFree (data);
  220366. if (remaining == 0)
  220367. break;
  220368. }
  220369. else
  220370. {
  220371. XFree (data);
  220372. break;
  220373. }
  220374. }
  220375. lines.addLines (dropData.toString());
  220376. }
  220377. for (int i = 0; i < lines.size(); ++i)
  220378. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220379. dragAndDropFiles.trim();
  220380. dragAndDropFiles.removeEmptyStrings();
  220381. }
  220382. }
  220383. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220384. {
  220385. dragAndDropFiles.clear();
  220386. if (dragAndDropSourceWindow != None
  220387. && dragAndDropCurrentMimeType != 0)
  220388. {
  220389. dragAndDropTimestamp = clientMsg->data.l[2];
  220390. ScopedXLock xlock;
  220391. XConvertSelection (display,
  220392. Atoms::XdndSelection,
  220393. dragAndDropCurrentMimeType,
  220394. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220395. windowH,
  220396. dragAndDropTimestamp);
  220397. }
  220398. }
  220399. StringArray dragAndDropFiles;
  220400. int dragAndDropTimestamp;
  220401. Point<int> lastDropPos;
  220402. Atom dragAndDropCurrentMimeType;
  220403. Window dragAndDropSourceWindow;
  220404. Array <Atom> srcMimeTypeAtomList;
  220405. static int pointerMap[5];
  220406. static Point<int> lastMousePos;
  220407. static void clearLastMousePos() throw()
  220408. {
  220409. lastMousePos = Point<int> (0x100000, 0x100000);
  220410. }
  220411. };
  220412. ModifierKeys LinuxComponentPeer::currentModifiers;
  220413. bool LinuxComponentPeer::isActiveApplication = false;
  220414. int LinuxComponentPeer::pointerMap[5];
  220415. Point<int> LinuxComponentPeer::lastMousePos;
  220416. bool Process::isForegroundProcess()
  220417. {
  220418. return LinuxComponentPeer::isActiveApplication;
  220419. }
  220420. void ModifierKeys::updateCurrentModifiers() throw()
  220421. {
  220422. currentModifiers = LinuxComponentPeer::currentModifiers;
  220423. }
  220424. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220425. {
  220426. Window root, child;
  220427. int x, y, winx, winy;
  220428. unsigned int mask;
  220429. int mouseMods = 0;
  220430. ScopedXLock xlock;
  220431. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220432. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220433. {
  220434. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220435. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220436. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220437. }
  220438. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220439. return LinuxComponentPeer::currentModifiers;
  220440. }
  220441. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220442. {
  220443. if (enableOrDisable)
  220444. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220445. }
  220446. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220447. {
  220448. return new LinuxComponentPeer (this, styleFlags);
  220449. }
  220450. // (this callback is hooked up in the messaging code)
  220451. void juce_windowMessageReceive (XEvent* event)
  220452. {
  220453. if (event->xany.window != None)
  220454. {
  220455. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220456. if (ComponentPeer::isValidPeer (peer))
  220457. peer->handleWindowMessage (event);
  220458. }
  220459. else
  220460. {
  220461. switch (event->xany.type)
  220462. {
  220463. case KeymapNotify:
  220464. {
  220465. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220466. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220467. break;
  220468. }
  220469. default:
  220470. break;
  220471. }
  220472. }
  220473. }
  220474. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220475. {
  220476. if (display == 0)
  220477. return;
  220478. #if JUCE_USE_XINERAMA
  220479. int major_opcode, first_event, first_error;
  220480. ScopedXLock xlock;
  220481. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220482. {
  220483. typedef Bool (*tXineramaIsActive) (Display*);
  220484. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220485. static tXineramaIsActive xXineramaIsActive = 0;
  220486. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220487. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220488. {
  220489. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220490. if (h == 0)
  220491. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220492. if (h != 0)
  220493. {
  220494. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220495. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220496. }
  220497. }
  220498. if (xXineramaIsActive != 0
  220499. && xXineramaQueryScreens != 0
  220500. && xXineramaIsActive (display))
  220501. {
  220502. int numMonitors = 0;
  220503. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220504. if (screens != 0)
  220505. {
  220506. for (int i = numMonitors; --i >= 0;)
  220507. {
  220508. int index = screens[i].screen_number;
  220509. if (index >= 0)
  220510. {
  220511. while (monitorCoords.size() < index)
  220512. monitorCoords.add (Rectangle<int>());
  220513. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220514. screens[i].y_org,
  220515. screens[i].width,
  220516. screens[i].height));
  220517. }
  220518. }
  220519. XFree (screens);
  220520. }
  220521. }
  220522. }
  220523. if (monitorCoords.size() == 0)
  220524. #endif
  220525. {
  220526. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220527. if (hints != None)
  220528. {
  220529. const int numMonitors = ScreenCount (display);
  220530. for (int i = 0; i < numMonitors; ++i)
  220531. {
  220532. Window root = RootWindow (display, i);
  220533. unsigned long nitems, bytesLeft;
  220534. Atom actualType;
  220535. int actualFormat;
  220536. unsigned char* data = 0;
  220537. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220538. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220539. &data) == Success)
  220540. {
  220541. const long* const position = (const long*) data;
  220542. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220543. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220544. position[2], position[3]));
  220545. XFree (data);
  220546. }
  220547. }
  220548. }
  220549. if (monitorCoords.size() == 0)
  220550. {
  220551. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220552. DisplayHeight (display, DefaultScreen (display))));
  220553. }
  220554. }
  220555. }
  220556. void Desktop::createMouseInputSources()
  220557. {
  220558. mouseSources.add (new MouseInputSource (0, true));
  220559. }
  220560. bool Desktop::canUseSemiTransparentWindows() throw()
  220561. {
  220562. int matchedDepth = 0;
  220563. const int desiredDepth = 32;
  220564. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220565. && (matchedDepth == desiredDepth);
  220566. }
  220567. const Point<int> Desktop::getMousePosition()
  220568. {
  220569. Window root, child;
  220570. int x, y, winx, winy;
  220571. unsigned int mask;
  220572. ScopedXLock xlock;
  220573. if (XQueryPointer (display,
  220574. RootWindow (display, DefaultScreen (display)),
  220575. &root, &child,
  220576. &x, &y, &winx, &winy, &mask) == False)
  220577. {
  220578. // Pointer not on the default screen
  220579. x = y = -1;
  220580. }
  220581. return Point<int> (x, y);
  220582. }
  220583. void Desktop::setMousePosition (const Point<int>& newPosition)
  220584. {
  220585. ScopedXLock xlock;
  220586. Window root = RootWindow (display, DefaultScreen (display));
  220587. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220588. }
  220589. static bool screenSaverAllowed = true;
  220590. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220591. {
  220592. if (screenSaverAllowed != isEnabled)
  220593. {
  220594. screenSaverAllowed = isEnabled;
  220595. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220596. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220597. if (xScreenSaverSuspend == 0)
  220598. {
  220599. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220600. if (h != 0)
  220601. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220602. }
  220603. ScopedXLock xlock;
  220604. if (xScreenSaverSuspend != 0)
  220605. xScreenSaverSuspend (display, ! isEnabled);
  220606. }
  220607. }
  220608. bool Desktop::isScreenSaverEnabled()
  220609. {
  220610. return screenSaverAllowed;
  220611. }
  220612. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220613. {
  220614. ScopedXLock xlock;
  220615. const unsigned int imageW = image.getWidth();
  220616. const unsigned int imageH = image.getHeight();
  220617. #if JUCE_USE_XCURSOR
  220618. {
  220619. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220620. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220621. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220622. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220623. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220624. static tXcursorImageCreate xXcursorImageCreate = 0;
  220625. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220626. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220627. static bool hasBeenLoaded = false;
  220628. if (! hasBeenLoaded)
  220629. {
  220630. hasBeenLoaded = true;
  220631. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220632. if (h != 0)
  220633. {
  220634. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220635. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220636. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220637. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220638. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220639. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220640. || ! xXcursorSupportsARGB (display))
  220641. xXcursorSupportsARGB = 0;
  220642. }
  220643. }
  220644. if (xXcursorSupportsARGB != 0)
  220645. {
  220646. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220647. if (xcImage != 0)
  220648. {
  220649. xcImage->xhot = hotspotX;
  220650. xcImage->yhot = hotspotY;
  220651. XcursorPixel* dest = xcImage->pixels;
  220652. for (int y = 0; y < (int) imageH; ++y)
  220653. for (int x = 0; x < (int) imageW; ++x)
  220654. *dest++ = image.getPixelAt (x, y).getARGB();
  220655. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220656. xXcursorImageDestroy (xcImage);
  220657. if (result != 0)
  220658. return result;
  220659. }
  220660. }
  220661. }
  220662. #endif
  220663. Window root = RootWindow (display, DefaultScreen (display));
  220664. unsigned int cursorW, cursorH;
  220665. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220666. return 0;
  220667. Image im (Image::ARGB, cursorW, cursorH, true);
  220668. {
  220669. Graphics g (im);
  220670. if (imageW > cursorW || imageH > cursorH)
  220671. {
  220672. hotspotX = (hotspotX * cursorW) / imageW;
  220673. hotspotY = (hotspotY * cursorH) / imageH;
  220674. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220675. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220676. false);
  220677. }
  220678. else
  220679. {
  220680. g.drawImageAt (image, 0, 0);
  220681. }
  220682. }
  220683. const int stride = (cursorW + 7) >> 3;
  220684. HeapBlock <char> maskPlane, sourcePlane;
  220685. maskPlane.calloc (stride * cursorH);
  220686. sourcePlane.calloc (stride * cursorH);
  220687. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220688. for (int y = cursorH; --y >= 0;)
  220689. {
  220690. for (int x = cursorW; --x >= 0;)
  220691. {
  220692. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220693. const int offset = y * stride + (x >> 3);
  220694. const Colour c (im.getPixelAt (x, y));
  220695. if (c.getAlpha() >= 128)
  220696. maskPlane[offset] |= mask;
  220697. if (c.getBrightness() >= 0.5f)
  220698. sourcePlane[offset] |= mask;
  220699. }
  220700. }
  220701. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220702. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220703. XColor white, black;
  220704. black.red = black.green = black.blue = 0;
  220705. white.red = white.green = white.blue = 0xffff;
  220706. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220707. XFreePixmap (display, sourcePixmap);
  220708. XFreePixmap (display, maskPixmap);
  220709. return result;
  220710. }
  220711. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220712. {
  220713. ScopedXLock xlock;
  220714. if (cursorHandle != 0)
  220715. XFreeCursor (display, (Cursor) cursorHandle);
  220716. }
  220717. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220718. {
  220719. unsigned int shape;
  220720. switch (type)
  220721. {
  220722. case NormalCursor: return None; // Use parent cursor
  220723. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220724. case WaitCursor: shape = XC_watch; break;
  220725. case IBeamCursor: shape = XC_xterm; break;
  220726. case PointingHandCursor: shape = XC_hand2; break;
  220727. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220728. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220729. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220730. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220731. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220732. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220733. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220734. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220735. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220736. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220737. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220738. case CrosshairCursor: shape = XC_crosshair; break;
  220739. case DraggingHandCursor:
  220740. {
  220741. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220742. 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,
  220743. 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 };
  220744. const int dragHandDataSize = 99;
  220745. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220746. }
  220747. case CopyingCursor:
  220748. {
  220749. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220750. 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,
  220751. 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,
  220752. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220753. const int copyCursorSize = 119;
  220754. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220755. }
  220756. default:
  220757. jassertfalse;
  220758. return None;
  220759. }
  220760. ScopedXLock xlock;
  220761. return (void*) XCreateFontCursor (display, shape);
  220762. }
  220763. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220764. {
  220765. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220766. if (lp != 0)
  220767. lp->showMouseCursor ((Cursor) getHandle());
  220768. }
  220769. void MouseCursor::showInAllWindows() const
  220770. {
  220771. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220772. showInWindow (ComponentPeer::getPeer (i));
  220773. }
  220774. const Image juce_createIconForFile (const File& file)
  220775. {
  220776. return Image::null;
  220777. }
  220778. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  220779. {
  220780. return createSoftwareImage (format, width, height, clearImage);
  220781. }
  220782. #if JUCE_OPENGL
  220783. class WindowedGLContext : public OpenGLContext
  220784. {
  220785. public:
  220786. WindowedGLContext (Component* const component,
  220787. const OpenGLPixelFormat& pixelFormat_,
  220788. GLXContext sharedContext)
  220789. : renderContext (0),
  220790. embeddedWindow (0),
  220791. pixelFormat (pixelFormat_),
  220792. swapInterval (0)
  220793. {
  220794. jassert (component != 0);
  220795. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  220796. if (peer == 0)
  220797. return;
  220798. ScopedXLock xlock;
  220799. XSync (display, False);
  220800. GLint attribs [64];
  220801. int n = 0;
  220802. attribs[n++] = GLX_RGBA;
  220803. attribs[n++] = GLX_DOUBLEBUFFER;
  220804. attribs[n++] = GLX_RED_SIZE;
  220805. attribs[n++] = pixelFormat.redBits;
  220806. attribs[n++] = GLX_GREEN_SIZE;
  220807. attribs[n++] = pixelFormat.greenBits;
  220808. attribs[n++] = GLX_BLUE_SIZE;
  220809. attribs[n++] = pixelFormat.blueBits;
  220810. attribs[n++] = GLX_ALPHA_SIZE;
  220811. attribs[n++] = pixelFormat.alphaBits;
  220812. attribs[n++] = GLX_DEPTH_SIZE;
  220813. attribs[n++] = pixelFormat.depthBufferBits;
  220814. attribs[n++] = GLX_STENCIL_SIZE;
  220815. attribs[n++] = pixelFormat.stencilBufferBits;
  220816. attribs[n++] = GLX_ACCUM_RED_SIZE;
  220817. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  220818. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  220819. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  220820. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  220821. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  220822. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  220823. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  220824. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  220825. attribs[n++] = None;
  220826. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  220827. if (bestVisual == 0)
  220828. return;
  220829. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  220830. Window windowH = (Window) peer->getNativeHandle();
  220831. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  220832. XSetWindowAttributes swa;
  220833. swa.colormap = colourMap;
  220834. swa.border_pixel = 0;
  220835. swa.event_mask = ExposureMask | StructureNotifyMask;
  220836. embeddedWindow = XCreateWindow (display, windowH,
  220837. 0, 0, 1, 1, 0,
  220838. bestVisual->depth,
  220839. InputOutput,
  220840. bestVisual->visual,
  220841. CWBorderPixel | CWColormap | CWEventMask,
  220842. &swa);
  220843. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  220844. XMapWindow (display, embeddedWindow);
  220845. XFreeColormap (display, colourMap);
  220846. XFree (bestVisual);
  220847. XSync (display, False);
  220848. }
  220849. ~WindowedGLContext()
  220850. {
  220851. ScopedXLock xlock;
  220852. deleteContext();
  220853. XUnmapWindow (display, embeddedWindow);
  220854. XDestroyWindow (display, embeddedWindow);
  220855. }
  220856. void deleteContext()
  220857. {
  220858. makeInactive();
  220859. if (renderContext != 0)
  220860. {
  220861. ScopedXLock xlock;
  220862. glXDestroyContext (display, renderContext);
  220863. renderContext = 0;
  220864. }
  220865. }
  220866. bool makeActive() const throw()
  220867. {
  220868. jassert (renderContext != 0);
  220869. ScopedXLock xlock;
  220870. return glXMakeCurrent (display, embeddedWindow, renderContext)
  220871. && XSync (display, False);
  220872. }
  220873. bool makeInactive() const throw()
  220874. {
  220875. ScopedXLock xlock;
  220876. return (! isActive()) || glXMakeCurrent (display, None, 0);
  220877. }
  220878. bool isActive() const throw()
  220879. {
  220880. ScopedXLock xlock;
  220881. return glXGetCurrentContext() == renderContext;
  220882. }
  220883. const OpenGLPixelFormat getPixelFormat() const
  220884. {
  220885. return pixelFormat;
  220886. }
  220887. void* getRawContext() const throw()
  220888. {
  220889. return renderContext;
  220890. }
  220891. void updateWindowPosition (int x, int y, int w, int h, int)
  220892. {
  220893. ScopedXLock xlock;
  220894. XMoveResizeWindow (display, embeddedWindow,
  220895. x, y, jmax (1, w), jmax (1, h));
  220896. }
  220897. void swapBuffers()
  220898. {
  220899. ScopedXLock xlock;
  220900. glXSwapBuffers (display, embeddedWindow);
  220901. }
  220902. bool setSwapInterval (const int numFramesPerSwap)
  220903. {
  220904. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  220905. if (GLXSwapIntervalSGI != 0)
  220906. {
  220907. swapInterval = numFramesPerSwap;
  220908. GLXSwapIntervalSGI (numFramesPerSwap);
  220909. return true;
  220910. }
  220911. return false;
  220912. }
  220913. int getSwapInterval() const
  220914. {
  220915. return swapInterval;
  220916. }
  220917. void repaint()
  220918. {
  220919. }
  220920. juce_UseDebuggingNewOperator
  220921. GLXContext renderContext;
  220922. private:
  220923. Window embeddedWindow;
  220924. OpenGLPixelFormat pixelFormat;
  220925. int swapInterval;
  220926. WindowedGLContext (const WindowedGLContext&);
  220927. WindowedGLContext& operator= (const WindowedGLContext&);
  220928. };
  220929. OpenGLContext* OpenGLComponent::createContext()
  220930. {
  220931. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  220932. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  220933. return (c->renderContext != 0) ? c.release() : 0;
  220934. }
  220935. void juce_glViewport (const int w, const int h)
  220936. {
  220937. glViewport (0, 0, w, h);
  220938. }
  220939. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  220940. OwnedArray <OpenGLPixelFormat>& results)
  220941. {
  220942. results.add (new OpenGLPixelFormat()); // xxx
  220943. }
  220944. #endif
  220945. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220946. {
  220947. jassertfalse; // not implemented!
  220948. return false;
  220949. }
  220950. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220951. {
  220952. jassertfalse; // not implemented!
  220953. return false;
  220954. }
  220955. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  220956. {
  220957. if (! isOnDesktop ())
  220958. addToDesktop (0);
  220959. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220960. if (wp != 0)
  220961. {
  220962. wp->setTaskBarIcon (newImage);
  220963. setVisible (true);
  220964. toFront (false);
  220965. repaint();
  220966. }
  220967. }
  220968. void SystemTrayIconComponent::paint (Graphics& g)
  220969. {
  220970. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220971. if (wp != 0)
  220972. {
  220973. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  220974. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220975. false);
  220976. }
  220977. }
  220978. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  220979. {
  220980. // xxx not yet implemented!
  220981. }
  220982. void PlatformUtilities::beep()
  220983. {
  220984. std::cout << "\a" << std::flush;
  220985. }
  220986. bool AlertWindow::showNativeDialogBox (const String& title,
  220987. const String& bodyText,
  220988. bool isOkCancel)
  220989. {
  220990. // use a non-native one for the time being..
  220991. if (isOkCancel)
  220992. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  220993. else
  220994. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  220995. return true;
  220996. }
  220997. const int KeyPress::spaceKey = XK_space & 0xff;
  220998. const int KeyPress::returnKey = XK_Return & 0xff;
  220999. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221000. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221001. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221002. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221003. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221004. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221005. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221006. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221007. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221008. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221009. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221010. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221011. const int KeyPress::tabKey = XK_Tab & 0xff;
  221012. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221013. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221014. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221015. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221016. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221017. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221018. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221019. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221020. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221021. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221022. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221023. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221024. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221025. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221026. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221027. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221028. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221029. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221030. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221031. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221032. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221033. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221034. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221035. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221036. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221037. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221038. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221039. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221040. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221041. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221042. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221043. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221044. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221045. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221046. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221047. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221048. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221049. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221050. #endif
  221051. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221052. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221053. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221054. // compiled on its own).
  221055. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221056. static const int maxNumChans = 64;
  221057. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221058. {
  221059. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221060. snd_pcm_hw_params_t* hwParams;
  221061. snd_pcm_hw_params_alloca (&hwParams);
  221062. for (int i = 0; ratesToTry[i] != 0; ++i)
  221063. {
  221064. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221065. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221066. {
  221067. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221068. }
  221069. }
  221070. }
  221071. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221072. {
  221073. snd_pcm_hw_params_t *params;
  221074. snd_pcm_hw_params_alloca (&params);
  221075. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221076. {
  221077. snd_pcm_hw_params_get_channels_min (params, minChans);
  221078. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221079. }
  221080. }
  221081. static void getDeviceProperties (const String& deviceID,
  221082. unsigned int& minChansOut,
  221083. unsigned int& maxChansOut,
  221084. unsigned int& minChansIn,
  221085. unsigned int& maxChansIn,
  221086. Array <int>& rates)
  221087. {
  221088. if (deviceID.isEmpty())
  221089. return;
  221090. snd_ctl_t* handle;
  221091. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221092. {
  221093. snd_pcm_info_t* info;
  221094. snd_pcm_info_alloca (&info);
  221095. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221096. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221097. snd_pcm_info_set_subdevice (info, 0);
  221098. if (snd_ctl_pcm_info (handle, info) >= 0)
  221099. {
  221100. snd_pcm_t* pcmHandle;
  221101. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  221102. {
  221103. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221104. getDeviceSampleRates (pcmHandle, rates);
  221105. snd_pcm_close (pcmHandle);
  221106. }
  221107. }
  221108. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221109. if (snd_ctl_pcm_info (handle, info) >= 0)
  221110. {
  221111. snd_pcm_t* pcmHandle;
  221112. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  221113. {
  221114. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221115. if (rates.size() == 0)
  221116. getDeviceSampleRates (pcmHandle, rates);
  221117. snd_pcm_close (pcmHandle);
  221118. }
  221119. }
  221120. snd_ctl_close (handle);
  221121. }
  221122. }
  221123. class ALSADevice
  221124. {
  221125. public:
  221126. ALSADevice (const String& deviceID,
  221127. const bool forInput)
  221128. : handle (0),
  221129. bitDepth (16),
  221130. numChannelsRunning (0),
  221131. isInput (forInput),
  221132. sampleFormat (AudioDataConverters::int16LE)
  221133. {
  221134. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221135. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221136. SND_PCM_ASYNC));
  221137. }
  221138. ~ALSADevice()
  221139. {
  221140. if (handle != 0)
  221141. snd_pcm_close (handle);
  221142. }
  221143. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221144. {
  221145. if (handle == 0)
  221146. return false;
  221147. snd_pcm_hw_params_t* hwParams;
  221148. snd_pcm_hw_params_alloca (&hwParams);
  221149. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221150. return false;
  221151. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221152. isInterleaved = false;
  221153. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221154. isInterleaved = true;
  221155. else
  221156. {
  221157. jassertfalse;
  221158. return false;
  221159. }
  221160. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  221161. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  221162. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  221163. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  221164. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  221165. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  221166. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  221167. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  221168. bitDepth = 0;
  221169. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  221170. {
  221171. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221172. {
  221173. bitDepth = formatsToTry [i + 1];
  221174. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  221175. break;
  221176. }
  221177. }
  221178. if (bitDepth == 0)
  221179. {
  221180. error = "device doesn't support a compatible PCM format";
  221181. DBG ("ALSA error: " + error + "\n");
  221182. return false;
  221183. }
  221184. int dir = 0;
  221185. unsigned int periods = 4;
  221186. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221187. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221188. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221189. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221190. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221191. || failed (snd_pcm_hw_params (handle, hwParams)))
  221192. {
  221193. return false;
  221194. }
  221195. snd_pcm_sw_params_t* swParams;
  221196. snd_pcm_sw_params_alloca (&swParams);
  221197. snd_pcm_uframes_t boundary;
  221198. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221199. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221200. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221201. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221202. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221203. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221204. || failed (snd_pcm_sw_params (handle, swParams)))
  221205. {
  221206. return false;
  221207. }
  221208. /*
  221209. #if JUCE_DEBUG
  221210. // enable this to dump the config of the devices that get opened
  221211. snd_output_t* out;
  221212. snd_output_stdio_attach (&out, stderr, 0);
  221213. snd_pcm_hw_params_dump (hwParams, out);
  221214. snd_pcm_sw_params_dump (swParams, out);
  221215. #endif
  221216. */
  221217. numChannelsRunning = numChannels;
  221218. return true;
  221219. }
  221220. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221221. {
  221222. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221223. float** const data = outputChannelBuffer.getArrayOfChannels();
  221224. if (isInterleaved)
  221225. {
  221226. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221227. float* interleaved = static_cast <float*> (scratch.getData());
  221228. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  221229. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  221230. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  221231. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221232. return false;
  221233. }
  221234. else
  221235. {
  221236. for (int i = 0; i < numChannelsRunning; ++i)
  221237. if (data[i] != 0)
  221238. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  221239. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  221240. if (failed (num))
  221241. {
  221242. if (num == -EPIPE)
  221243. {
  221244. if (failed (snd_pcm_prepare (handle)))
  221245. return false;
  221246. }
  221247. else if (num != -ESTRPIPE)
  221248. return false;
  221249. }
  221250. }
  221251. return true;
  221252. }
  221253. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221254. {
  221255. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221256. float** const data = inputChannelBuffer.getArrayOfChannels();
  221257. if (isInterleaved)
  221258. {
  221259. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221260. float* interleaved = static_cast <float*> (scratch.getData());
  221261. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  221262. if (failed (num))
  221263. {
  221264. if (num == -EPIPE)
  221265. {
  221266. if (failed (snd_pcm_prepare (handle)))
  221267. return false;
  221268. }
  221269. else if (num != -ESTRPIPE)
  221270. return false;
  221271. }
  221272. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  221273. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  221274. }
  221275. else
  221276. {
  221277. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221278. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221279. return false;
  221280. for (int i = 0; i < numChannelsRunning; ++i)
  221281. if (data[i] != 0)
  221282. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  221283. }
  221284. return true;
  221285. }
  221286. juce_UseDebuggingNewOperator
  221287. snd_pcm_t* handle;
  221288. String error;
  221289. int bitDepth, numChannelsRunning;
  221290. private:
  221291. const bool isInput;
  221292. bool isInterleaved;
  221293. MemoryBlock scratch;
  221294. AudioDataConverters::DataFormat sampleFormat;
  221295. bool failed (const int errorNum)
  221296. {
  221297. if (errorNum >= 0)
  221298. return false;
  221299. error = snd_strerror (errorNum);
  221300. DBG ("ALSA error: " + error + "\n");
  221301. return true;
  221302. }
  221303. };
  221304. class ALSAThread : public Thread
  221305. {
  221306. public:
  221307. ALSAThread (const String& inputId_,
  221308. const String& outputId_)
  221309. : Thread ("Juce ALSA"),
  221310. sampleRate (0),
  221311. bufferSize (0),
  221312. callback (0),
  221313. inputId (inputId_),
  221314. outputId (outputId_),
  221315. numCallbacks (0),
  221316. inputChannelBuffer (1, 1),
  221317. outputChannelBuffer (1, 1)
  221318. {
  221319. initialiseRatesAndChannels();
  221320. }
  221321. ~ALSAThread()
  221322. {
  221323. close();
  221324. }
  221325. void open (BigInteger inputChannels,
  221326. BigInteger outputChannels,
  221327. const double sampleRate_,
  221328. const int bufferSize_)
  221329. {
  221330. close();
  221331. error = String::empty;
  221332. sampleRate = sampleRate_;
  221333. bufferSize = bufferSize_;
  221334. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221335. inputChannelBuffer.clear();
  221336. inputChannelDataForCallback.clear();
  221337. currentInputChans.clear();
  221338. if (inputChannels.getHighestBit() >= 0)
  221339. {
  221340. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221341. {
  221342. if (inputChannels[i])
  221343. {
  221344. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221345. currentInputChans.setBit (i);
  221346. }
  221347. }
  221348. }
  221349. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221350. outputChannelBuffer.clear();
  221351. outputChannelDataForCallback.clear();
  221352. currentOutputChans.clear();
  221353. if (outputChannels.getHighestBit() >= 0)
  221354. {
  221355. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221356. {
  221357. if (outputChannels[i])
  221358. {
  221359. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221360. currentOutputChans.setBit (i);
  221361. }
  221362. }
  221363. }
  221364. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221365. {
  221366. outputDevice = new ALSADevice (outputId, false);
  221367. if (outputDevice->error.isNotEmpty())
  221368. {
  221369. error = outputDevice->error;
  221370. outputDevice = 0;
  221371. return;
  221372. }
  221373. currentOutputChans.setRange (0, minChansOut, true);
  221374. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221375. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221376. bufferSize))
  221377. {
  221378. error = outputDevice->error;
  221379. outputDevice = 0;
  221380. return;
  221381. }
  221382. }
  221383. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221384. {
  221385. inputDevice = new ALSADevice (inputId, true);
  221386. if (inputDevice->error.isNotEmpty())
  221387. {
  221388. error = inputDevice->error;
  221389. inputDevice = 0;
  221390. return;
  221391. }
  221392. currentInputChans.setRange (0, minChansIn, true);
  221393. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221394. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221395. bufferSize))
  221396. {
  221397. error = inputDevice->error;
  221398. inputDevice = 0;
  221399. return;
  221400. }
  221401. }
  221402. if (outputDevice == 0 && inputDevice == 0)
  221403. {
  221404. error = "no channels";
  221405. return;
  221406. }
  221407. if (outputDevice != 0 && inputDevice != 0)
  221408. {
  221409. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221410. }
  221411. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221412. return;
  221413. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221414. return;
  221415. startThread (9);
  221416. int count = 1000;
  221417. while (numCallbacks == 0)
  221418. {
  221419. sleep (5);
  221420. if (--count < 0 || ! isThreadRunning())
  221421. {
  221422. error = "device didn't start";
  221423. break;
  221424. }
  221425. }
  221426. }
  221427. void close()
  221428. {
  221429. stopThread (6000);
  221430. inputDevice = 0;
  221431. outputDevice = 0;
  221432. inputChannelBuffer.setSize (1, 1);
  221433. outputChannelBuffer.setSize (1, 1);
  221434. numCallbacks = 0;
  221435. }
  221436. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221437. {
  221438. const ScopedLock sl (callbackLock);
  221439. callback = newCallback;
  221440. }
  221441. void run()
  221442. {
  221443. while (! threadShouldExit())
  221444. {
  221445. if (inputDevice != 0)
  221446. {
  221447. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  221448. {
  221449. DBG ("ALSA: read failure");
  221450. break;
  221451. }
  221452. }
  221453. if (threadShouldExit())
  221454. break;
  221455. {
  221456. const ScopedLock sl (callbackLock);
  221457. ++numCallbacks;
  221458. if (callback != 0)
  221459. {
  221460. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221461. inputChannelDataForCallback.size(),
  221462. outputChannelDataForCallback.getRawDataPointer(),
  221463. outputChannelDataForCallback.size(),
  221464. bufferSize);
  221465. }
  221466. else
  221467. {
  221468. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221469. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221470. }
  221471. }
  221472. if (outputDevice != 0)
  221473. {
  221474. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221475. if (threadShouldExit())
  221476. break;
  221477. failed (snd_pcm_avail_update (outputDevice->handle));
  221478. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  221479. {
  221480. DBG ("ALSA: write failure");
  221481. break;
  221482. }
  221483. }
  221484. }
  221485. }
  221486. int getBitDepth() const throw()
  221487. {
  221488. if (outputDevice != 0)
  221489. return outputDevice->bitDepth;
  221490. if (inputDevice != 0)
  221491. return inputDevice->bitDepth;
  221492. return 16;
  221493. }
  221494. juce_UseDebuggingNewOperator
  221495. String error;
  221496. double sampleRate;
  221497. int bufferSize;
  221498. BigInteger currentInputChans, currentOutputChans;
  221499. Array <int> sampleRates;
  221500. StringArray channelNamesOut, channelNamesIn;
  221501. AudioIODeviceCallback* callback;
  221502. private:
  221503. const String inputId, outputId;
  221504. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  221505. int numCallbacks;
  221506. CriticalSection callbackLock;
  221507. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221508. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221509. unsigned int minChansOut, maxChansOut;
  221510. unsigned int minChansIn, maxChansIn;
  221511. bool failed (const int errorNum)
  221512. {
  221513. if (errorNum >= 0)
  221514. return false;
  221515. error = snd_strerror (errorNum);
  221516. DBG ("ALSA error: " + error + "\n");
  221517. return true;
  221518. }
  221519. void initialiseRatesAndChannels()
  221520. {
  221521. sampleRates.clear();
  221522. channelNamesOut.clear();
  221523. channelNamesIn.clear();
  221524. minChansOut = 0;
  221525. maxChansOut = 0;
  221526. minChansIn = 0;
  221527. maxChansIn = 0;
  221528. unsigned int dummy = 0;
  221529. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221530. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221531. unsigned int i;
  221532. for (i = 0; i < maxChansOut; ++i)
  221533. channelNamesOut.add ("channel " + String ((int) i + 1));
  221534. for (i = 0; i < maxChansIn; ++i)
  221535. channelNamesIn.add ("channel " + String ((int) i + 1));
  221536. }
  221537. };
  221538. class ALSAAudioIODevice : public AudioIODevice
  221539. {
  221540. public:
  221541. ALSAAudioIODevice (const String& deviceName,
  221542. const String& inputId_,
  221543. const String& outputId_)
  221544. : AudioIODevice (deviceName, "ALSA"),
  221545. inputId (inputId_),
  221546. outputId (outputId_),
  221547. isOpen_ (false),
  221548. isStarted (false),
  221549. internal (inputId_, outputId_)
  221550. {
  221551. }
  221552. ~ALSAAudioIODevice()
  221553. {
  221554. }
  221555. const StringArray getOutputChannelNames()
  221556. {
  221557. return internal.channelNamesOut;
  221558. }
  221559. const StringArray getInputChannelNames()
  221560. {
  221561. return internal.channelNamesIn;
  221562. }
  221563. int getNumSampleRates()
  221564. {
  221565. return internal.sampleRates.size();
  221566. }
  221567. double getSampleRate (int index)
  221568. {
  221569. return internal.sampleRates [index];
  221570. }
  221571. int getNumBufferSizesAvailable()
  221572. {
  221573. return 50;
  221574. }
  221575. int getBufferSizeSamples (int index)
  221576. {
  221577. int n = 16;
  221578. for (int i = 0; i < index; ++i)
  221579. n += n < 64 ? 16
  221580. : (n < 512 ? 32
  221581. : (n < 1024 ? 64
  221582. : (n < 2048 ? 128 : 256)));
  221583. return n;
  221584. }
  221585. int getDefaultBufferSize()
  221586. {
  221587. return 512;
  221588. }
  221589. const String open (const BigInteger& inputChannels,
  221590. const BigInteger& outputChannels,
  221591. double sampleRate,
  221592. int bufferSizeSamples)
  221593. {
  221594. close();
  221595. if (bufferSizeSamples <= 0)
  221596. bufferSizeSamples = getDefaultBufferSize();
  221597. if (sampleRate <= 0)
  221598. {
  221599. for (int i = 0; i < getNumSampleRates(); ++i)
  221600. {
  221601. if (getSampleRate (i) >= 44100)
  221602. {
  221603. sampleRate = getSampleRate (i);
  221604. break;
  221605. }
  221606. }
  221607. }
  221608. internal.open (inputChannels, outputChannels,
  221609. sampleRate, bufferSizeSamples);
  221610. isOpen_ = internal.error.isEmpty();
  221611. return internal.error;
  221612. }
  221613. void close()
  221614. {
  221615. stop();
  221616. internal.close();
  221617. isOpen_ = false;
  221618. }
  221619. bool isOpen()
  221620. {
  221621. return isOpen_;
  221622. }
  221623. int getCurrentBufferSizeSamples()
  221624. {
  221625. return internal.bufferSize;
  221626. }
  221627. double getCurrentSampleRate()
  221628. {
  221629. return internal.sampleRate;
  221630. }
  221631. int getCurrentBitDepth()
  221632. {
  221633. return internal.getBitDepth();
  221634. }
  221635. const BigInteger getActiveOutputChannels() const
  221636. {
  221637. return internal.currentOutputChans;
  221638. }
  221639. const BigInteger getActiveInputChannels() const
  221640. {
  221641. return internal.currentInputChans;
  221642. }
  221643. int getOutputLatencyInSamples()
  221644. {
  221645. return 0;
  221646. }
  221647. int getInputLatencyInSamples()
  221648. {
  221649. return 0;
  221650. }
  221651. void start (AudioIODeviceCallback* callback)
  221652. {
  221653. if (! isOpen_)
  221654. callback = 0;
  221655. if (callback != 0)
  221656. callback->audioDeviceAboutToStart (this);
  221657. internal.setCallback (callback);
  221658. isStarted = (callback != 0);
  221659. }
  221660. void stop()
  221661. {
  221662. AudioIODeviceCallback* const oldCallback = internal.callback;
  221663. start (0);
  221664. if (oldCallback != 0)
  221665. oldCallback->audioDeviceStopped();
  221666. }
  221667. bool isPlaying()
  221668. {
  221669. return isStarted && internal.error.isEmpty();
  221670. }
  221671. const String getLastError()
  221672. {
  221673. return internal.error;
  221674. }
  221675. String inputId, outputId;
  221676. private:
  221677. bool isOpen_, isStarted;
  221678. ALSAThread internal;
  221679. };
  221680. class ALSAAudioIODeviceType : public AudioIODeviceType
  221681. {
  221682. public:
  221683. ALSAAudioIODeviceType()
  221684. : AudioIODeviceType ("ALSA"),
  221685. hasScanned (false)
  221686. {
  221687. }
  221688. ~ALSAAudioIODeviceType()
  221689. {
  221690. }
  221691. void scanForDevices()
  221692. {
  221693. if (hasScanned)
  221694. return;
  221695. hasScanned = true;
  221696. inputNames.clear();
  221697. inputIds.clear();
  221698. outputNames.clear();
  221699. outputIds.clear();
  221700. snd_ctl_t* handle;
  221701. snd_ctl_card_info_t* info;
  221702. snd_ctl_card_info_alloca (&info);
  221703. int cardNum = -1;
  221704. while (outputIds.size() + inputIds.size() <= 32)
  221705. {
  221706. snd_card_next (&cardNum);
  221707. if (cardNum < 0)
  221708. break;
  221709. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221710. {
  221711. if (snd_ctl_card_info (handle, info) >= 0)
  221712. {
  221713. String cardId (snd_ctl_card_info_get_id (info));
  221714. if (cardId.removeCharacters ("0123456789").isEmpty())
  221715. cardId = String (cardNum);
  221716. int device = -1;
  221717. for (;;)
  221718. {
  221719. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221720. break;
  221721. String id, name;
  221722. id << "hw:" << cardId << ',' << device;
  221723. bool isInput, isOutput;
  221724. if (testDevice (id, isInput, isOutput))
  221725. {
  221726. name << snd_ctl_card_info_get_name (info);
  221727. if (name.isEmpty())
  221728. name = id;
  221729. if (isInput)
  221730. {
  221731. inputNames.add (name);
  221732. inputIds.add (id);
  221733. }
  221734. if (isOutput)
  221735. {
  221736. outputNames.add (name);
  221737. outputIds.add (id);
  221738. }
  221739. }
  221740. }
  221741. }
  221742. snd_ctl_close (handle);
  221743. }
  221744. }
  221745. inputNames.appendNumbersToDuplicates (false, true);
  221746. outputNames.appendNumbersToDuplicates (false, true);
  221747. }
  221748. const StringArray getDeviceNames (bool wantInputNames) const
  221749. {
  221750. jassert (hasScanned); // need to call scanForDevices() before doing this
  221751. return wantInputNames ? inputNames : outputNames;
  221752. }
  221753. int getDefaultDeviceIndex (bool forInput) const
  221754. {
  221755. jassert (hasScanned); // need to call scanForDevices() before doing this
  221756. return 0;
  221757. }
  221758. bool hasSeparateInputsAndOutputs() const { return true; }
  221759. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221760. {
  221761. jassert (hasScanned); // need to call scanForDevices() before doing this
  221762. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  221763. if (d == 0)
  221764. return -1;
  221765. return asInput ? inputIds.indexOf (d->inputId)
  221766. : outputIds.indexOf (d->outputId);
  221767. }
  221768. AudioIODevice* createDevice (const String& outputDeviceName,
  221769. const String& inputDeviceName)
  221770. {
  221771. jassert (hasScanned); // need to call scanForDevices() before doing this
  221772. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221773. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221774. String deviceName (outputIndex >= 0 ? outputDeviceName
  221775. : inputDeviceName);
  221776. if (inputIndex >= 0 || outputIndex >= 0)
  221777. return new ALSAAudioIODevice (deviceName,
  221778. inputIds [inputIndex],
  221779. outputIds [outputIndex]);
  221780. return 0;
  221781. }
  221782. juce_UseDebuggingNewOperator
  221783. private:
  221784. StringArray inputNames, outputNames, inputIds, outputIds;
  221785. bool hasScanned;
  221786. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  221787. {
  221788. unsigned int minChansOut = 0, maxChansOut = 0;
  221789. unsigned int minChansIn = 0, maxChansIn = 0;
  221790. Array <int> rates;
  221791. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  221792. DBG ("ALSA device: " + id
  221793. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  221794. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  221795. + " rates=" + String (rates.size()));
  221796. isInput = maxChansIn > 0;
  221797. isOutput = maxChansOut > 0;
  221798. return (isInput || isOutput) && rates.size() > 0;
  221799. }
  221800. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  221801. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  221802. };
  221803. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  221804. {
  221805. return new ALSAAudioIODeviceType();
  221806. }
  221807. #endif
  221808. /*** End of inlined file: juce_linux_Audio.cpp ***/
  221809. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  221810. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221811. // compiled on its own).
  221812. #ifdef JUCE_INCLUDED_FILE
  221813. #if JUCE_JACK
  221814. static void* juce_libjack_handle = 0;
  221815. void* juce_load_jack_function (const char* const name)
  221816. {
  221817. if (juce_libjack_handle == 0)
  221818. return 0;
  221819. return dlsym (juce_libjack_handle, name);
  221820. }
  221821. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  221822. typedef return_type (*fn_name##_ptr_t)argument_types; \
  221823. return_type fn_name argument_types { \
  221824. static fn_name##_ptr_t fn = 0; \
  221825. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221826. if (fn) return (*fn)arguments; \
  221827. else return 0; \
  221828. }
  221829. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  221830. typedef void (*fn_name##_ptr_t)argument_types; \
  221831. void fn_name argument_types { \
  221832. static fn_name##_ptr_t fn = 0; \
  221833. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221834. if (fn) (*fn)arguments; \
  221835. }
  221836. 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));
  221837. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  221838. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  221839. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  221840. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  221841. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  221842. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  221843. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  221844. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  221845. 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));
  221846. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  221847. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  221848. 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));
  221849. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  221850. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  221851. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  221852. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  221853. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  221854. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  221855. #if JUCE_DEBUG
  221856. #define JACK_LOGGING_ENABLED 1
  221857. #endif
  221858. #if JACK_LOGGING_ENABLED
  221859. static void jack_Log (const String& s)
  221860. {
  221861. std::cerr << s << std::endl;
  221862. }
  221863. static void dumpJackErrorMessage (const jack_status_t status)
  221864. {
  221865. if (status & JackServerFailed || status & JackServerError)
  221866. jack_Log ("Unable to connect to JACK server");
  221867. if (status & JackVersionError)
  221868. jack_Log ("Client's protocol version does not match");
  221869. if (status & JackInvalidOption)
  221870. jack_Log ("The operation contained an invalid or unsupported option");
  221871. if (status & JackNameNotUnique)
  221872. jack_Log ("The desired client name was not unique");
  221873. if (status & JackNoSuchClient)
  221874. jack_Log ("Requested client does not exist");
  221875. if (status & JackInitFailure)
  221876. jack_Log ("Unable to initialize client");
  221877. }
  221878. #else
  221879. #define dumpJackErrorMessage(a) {}
  221880. #define jack_Log(...) {}
  221881. #endif
  221882. #ifndef JUCE_JACK_CLIENT_NAME
  221883. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  221884. #endif
  221885. class JackAudioIODevice : public AudioIODevice
  221886. {
  221887. public:
  221888. JackAudioIODevice (const String& deviceName,
  221889. const String& inputId_,
  221890. const String& outputId_)
  221891. : AudioIODevice (deviceName, "JACK"),
  221892. inputId (inputId_),
  221893. outputId (outputId_),
  221894. isOpen_ (false),
  221895. callback (0),
  221896. totalNumberOfInputChannels (0),
  221897. totalNumberOfOutputChannels (0)
  221898. {
  221899. jassert (deviceName.isNotEmpty());
  221900. jack_status_t status;
  221901. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  221902. if (client == 0)
  221903. {
  221904. dumpJackErrorMessage (status);
  221905. }
  221906. else
  221907. {
  221908. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  221909. // open input ports
  221910. const StringArray inputChannels (getInputChannelNames());
  221911. for (int i = 0; i < inputChannels.size(); i++)
  221912. {
  221913. String inputName;
  221914. inputName << "in_" << ++totalNumberOfInputChannels;
  221915. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  221916. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  221917. }
  221918. // open output ports
  221919. const StringArray outputChannels (getOutputChannelNames());
  221920. for (int i = 0; i < outputChannels.size (); i++)
  221921. {
  221922. String outputName;
  221923. outputName << "out_" << ++totalNumberOfOutputChannels;
  221924. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  221925. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  221926. }
  221927. inChans.calloc (totalNumberOfInputChannels + 2);
  221928. outChans.calloc (totalNumberOfOutputChannels + 2);
  221929. }
  221930. }
  221931. ~JackAudioIODevice()
  221932. {
  221933. close();
  221934. if (client != 0)
  221935. {
  221936. JUCE_NAMESPACE::jack_client_close (client);
  221937. client = 0;
  221938. }
  221939. }
  221940. const StringArray getChannelNames (bool forInput) const
  221941. {
  221942. StringArray names;
  221943. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  221944. forInput ? JackPortIsInput : JackPortIsOutput);
  221945. if (ports != 0)
  221946. {
  221947. int j = 0;
  221948. while (ports[j] != 0)
  221949. {
  221950. const String portName (ports [j++]);
  221951. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221952. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  221953. }
  221954. free (ports);
  221955. }
  221956. return names;
  221957. }
  221958. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  221959. const StringArray getInputChannelNames() { return getChannelNames (true); }
  221960. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  221961. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  221962. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  221963. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  221964. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  221965. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  221966. double sampleRate, int bufferSizeSamples)
  221967. {
  221968. if (client == 0)
  221969. {
  221970. lastError = "No JACK client running";
  221971. return lastError;
  221972. }
  221973. lastError = String::empty;
  221974. close();
  221975. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  221976. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  221977. JUCE_NAMESPACE::jack_activate (client);
  221978. isOpen_ = true;
  221979. if (! inputChannels.isZero())
  221980. {
  221981. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221982. if (ports != 0)
  221983. {
  221984. const int numInputChannels = inputChannels.getHighestBit() + 1;
  221985. for (int i = 0; i < numInputChannels; ++i)
  221986. {
  221987. const String portName (ports[i]);
  221988. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221989. {
  221990. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  221991. if (error != 0)
  221992. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221993. }
  221994. }
  221995. free (ports);
  221996. }
  221997. }
  221998. if (! outputChannels.isZero())
  221999. {
  222000. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222001. if (ports != 0)
  222002. {
  222003. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222004. for (int i = 0; i < numOutputChannels; ++i)
  222005. {
  222006. const String portName (ports[i]);
  222007. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222008. {
  222009. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222010. if (error != 0)
  222011. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222012. }
  222013. }
  222014. free (ports);
  222015. }
  222016. }
  222017. return lastError;
  222018. }
  222019. void close()
  222020. {
  222021. stop();
  222022. if (client != 0)
  222023. {
  222024. JUCE_NAMESPACE::jack_deactivate (client);
  222025. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222026. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222027. }
  222028. isOpen_ = false;
  222029. }
  222030. void start (AudioIODeviceCallback* newCallback)
  222031. {
  222032. if (isOpen_ && newCallback != callback)
  222033. {
  222034. if (newCallback != 0)
  222035. newCallback->audioDeviceAboutToStart (this);
  222036. AudioIODeviceCallback* const oldCallback = callback;
  222037. {
  222038. const ScopedLock sl (callbackLock);
  222039. callback = newCallback;
  222040. }
  222041. if (oldCallback != 0)
  222042. oldCallback->audioDeviceStopped();
  222043. }
  222044. }
  222045. void stop()
  222046. {
  222047. start (0);
  222048. }
  222049. bool isOpen() { return isOpen_; }
  222050. bool isPlaying() { return callback != 0; }
  222051. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222052. double getCurrentSampleRate() { return getSampleRate (0); }
  222053. int getCurrentBitDepth() { return 32; }
  222054. const String getLastError() { return lastError; }
  222055. const BigInteger getActiveOutputChannels() const
  222056. {
  222057. BigInteger outputBits;
  222058. for (int i = 0; i < outputPorts.size(); i++)
  222059. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222060. outputBits.setBit (i);
  222061. return outputBits;
  222062. }
  222063. const BigInteger getActiveInputChannels() const
  222064. {
  222065. BigInteger inputBits;
  222066. for (int i = 0; i < inputPorts.size(); i++)
  222067. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222068. inputBits.setBit (i);
  222069. return inputBits;
  222070. }
  222071. int getOutputLatencyInSamples()
  222072. {
  222073. int latency = 0;
  222074. for (int i = 0; i < outputPorts.size(); i++)
  222075. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222076. return latency;
  222077. }
  222078. int getInputLatencyInSamples()
  222079. {
  222080. int latency = 0;
  222081. for (int i = 0; i < inputPorts.size(); i++)
  222082. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222083. return latency;
  222084. }
  222085. String inputId, outputId;
  222086. private:
  222087. void process (const int numSamples)
  222088. {
  222089. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222090. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222091. {
  222092. jack_default_audio_sample_t* in
  222093. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222094. if (in != 0)
  222095. inChans [numActiveInChans++] = (float*) in;
  222096. }
  222097. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222098. {
  222099. jack_default_audio_sample_t* out
  222100. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222101. if (out != 0)
  222102. outChans [numActiveOutChans++] = (float*) out;
  222103. }
  222104. const ScopedLock sl (callbackLock);
  222105. if (callback != 0)
  222106. {
  222107. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222108. outChans, numActiveOutChans, numSamples);
  222109. }
  222110. else
  222111. {
  222112. for (i = 0; i < numActiveOutChans; ++i)
  222113. zeromem (outChans[i], sizeof (float) * numSamples);
  222114. }
  222115. }
  222116. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222117. {
  222118. if (callbackArgument != 0)
  222119. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222120. return 0;
  222121. }
  222122. static void threadInitCallback (void* callbackArgument)
  222123. {
  222124. jack_Log ("JackAudioIODevice::initialise");
  222125. }
  222126. static void shutdownCallback (void* callbackArgument)
  222127. {
  222128. jack_Log ("JackAudioIODevice::shutdown");
  222129. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222130. if (device != 0)
  222131. {
  222132. device->client = 0;
  222133. device->close();
  222134. }
  222135. }
  222136. static void errorCallback (const char* msg)
  222137. {
  222138. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222139. }
  222140. bool isOpen_;
  222141. jack_client_t* client;
  222142. String lastError;
  222143. AudioIODeviceCallback* callback;
  222144. CriticalSection callbackLock;
  222145. HeapBlock <float*> inChans, outChans;
  222146. int totalNumberOfInputChannels;
  222147. int totalNumberOfOutputChannels;
  222148. Array<void*> inputPorts, outputPorts;
  222149. };
  222150. class JackAudioIODeviceType : public AudioIODeviceType
  222151. {
  222152. public:
  222153. JackAudioIODeviceType()
  222154. : AudioIODeviceType ("JACK"),
  222155. hasScanned (false)
  222156. {
  222157. }
  222158. ~JackAudioIODeviceType()
  222159. {
  222160. }
  222161. void scanForDevices()
  222162. {
  222163. hasScanned = true;
  222164. inputNames.clear();
  222165. inputIds.clear();
  222166. outputNames.clear();
  222167. outputIds.clear();
  222168. if (juce_libjack_handle == 0)
  222169. {
  222170. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222171. if (juce_libjack_handle == 0)
  222172. return;
  222173. }
  222174. // open a dummy client
  222175. jack_status_t status;
  222176. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222177. if (client == 0)
  222178. {
  222179. dumpJackErrorMessage (status);
  222180. }
  222181. else
  222182. {
  222183. // scan for output devices
  222184. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222185. if (ports != 0)
  222186. {
  222187. int j = 0;
  222188. while (ports[j] != 0)
  222189. {
  222190. String clientName (ports[j]);
  222191. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222192. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222193. && ! inputNames.contains (clientName))
  222194. {
  222195. inputNames.add (clientName);
  222196. inputIds.add (ports [j]);
  222197. }
  222198. ++j;
  222199. }
  222200. free (ports);
  222201. }
  222202. // scan for input devices
  222203. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222204. if (ports != 0)
  222205. {
  222206. int j = 0;
  222207. while (ports[j] != 0)
  222208. {
  222209. String clientName (ports[j]);
  222210. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222211. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222212. && ! outputNames.contains (clientName))
  222213. {
  222214. outputNames.add (clientName);
  222215. outputIds.add (ports [j]);
  222216. }
  222217. ++j;
  222218. }
  222219. free (ports);
  222220. }
  222221. JUCE_NAMESPACE::jack_client_close (client);
  222222. }
  222223. }
  222224. const StringArray getDeviceNames (bool wantInputNames) const
  222225. {
  222226. jassert (hasScanned); // need to call scanForDevices() before doing this
  222227. return wantInputNames ? inputNames : outputNames;
  222228. }
  222229. int getDefaultDeviceIndex (bool forInput) const
  222230. {
  222231. jassert (hasScanned); // need to call scanForDevices() before doing this
  222232. return 0;
  222233. }
  222234. bool hasSeparateInputsAndOutputs() const { return true; }
  222235. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222236. {
  222237. jassert (hasScanned); // need to call scanForDevices() before doing this
  222238. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222239. if (d == 0)
  222240. return -1;
  222241. return asInput ? inputIds.indexOf (d->inputId)
  222242. : outputIds.indexOf (d->outputId);
  222243. }
  222244. AudioIODevice* createDevice (const String& outputDeviceName,
  222245. const String& inputDeviceName)
  222246. {
  222247. jassert (hasScanned); // need to call scanForDevices() before doing this
  222248. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222249. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222250. if (inputIndex >= 0 || outputIndex >= 0)
  222251. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222252. : inputDeviceName,
  222253. inputIds [inputIndex],
  222254. outputIds [outputIndex]);
  222255. return 0;
  222256. }
  222257. juce_UseDebuggingNewOperator
  222258. private:
  222259. StringArray inputNames, outputNames, inputIds, outputIds;
  222260. bool hasScanned;
  222261. JackAudioIODeviceType (const JackAudioIODeviceType&);
  222262. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  222263. };
  222264. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222265. {
  222266. return new JackAudioIODeviceType();
  222267. }
  222268. #else // if JACK is turned off..
  222269. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222270. #endif
  222271. #endif
  222272. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222273. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222274. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222275. // compiled on its own).
  222276. #if JUCE_INCLUDED_FILE
  222277. #if JUCE_ALSA
  222278. static snd_seq_t* iterateDevices (const bool forInput,
  222279. StringArray& deviceNamesFound,
  222280. const int deviceIndexToOpen)
  222281. {
  222282. snd_seq_t* returnedHandle = 0;
  222283. snd_seq_t* seqHandle;
  222284. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222285. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222286. {
  222287. snd_seq_system_info_t* systemInfo;
  222288. snd_seq_client_info_t* clientInfo;
  222289. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222290. {
  222291. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222292. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222293. {
  222294. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222295. while (--numClients >= 0 && returnedHandle == 0)
  222296. {
  222297. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222298. {
  222299. snd_seq_port_info_t* portInfo;
  222300. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222301. {
  222302. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222303. const int client = snd_seq_client_info_get_client (clientInfo);
  222304. snd_seq_port_info_set_client (portInfo, client);
  222305. snd_seq_port_info_set_port (portInfo, -1);
  222306. while (--numPorts >= 0)
  222307. {
  222308. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222309. && (snd_seq_port_info_get_capability (portInfo)
  222310. & (forInput ? SND_SEQ_PORT_CAP_READ
  222311. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222312. {
  222313. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222314. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222315. {
  222316. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222317. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222318. if (sourcePort != -1)
  222319. {
  222320. snd_seq_set_client_name (seqHandle,
  222321. forInput ? "Juce Midi Input"
  222322. : "Juce Midi Output");
  222323. const int portId
  222324. = snd_seq_create_simple_port (seqHandle,
  222325. forInput ? "Juce Midi In Port"
  222326. : "Juce Midi Out Port",
  222327. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222328. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222329. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222330. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222331. returnedHandle = seqHandle;
  222332. }
  222333. }
  222334. }
  222335. }
  222336. snd_seq_port_info_free (portInfo);
  222337. }
  222338. }
  222339. }
  222340. snd_seq_client_info_free (clientInfo);
  222341. }
  222342. snd_seq_system_info_free (systemInfo);
  222343. }
  222344. if (returnedHandle == 0)
  222345. snd_seq_close (seqHandle);
  222346. }
  222347. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222348. return returnedHandle;
  222349. }
  222350. static snd_seq_t* createDevice (const bool forInput,
  222351. const String& deviceNameToOpen)
  222352. {
  222353. snd_seq_t* seqHandle = 0;
  222354. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222355. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222356. {
  222357. snd_seq_set_client_name (seqHandle,
  222358. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222359. const int portId
  222360. = snd_seq_create_simple_port (seqHandle,
  222361. forInput ? "in"
  222362. : "out",
  222363. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222364. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222365. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222366. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222367. if (portId < 0)
  222368. {
  222369. snd_seq_close (seqHandle);
  222370. seqHandle = 0;
  222371. }
  222372. }
  222373. return seqHandle;
  222374. }
  222375. class MidiOutputDevice
  222376. {
  222377. public:
  222378. MidiOutputDevice (MidiOutput* const midiOutput_,
  222379. snd_seq_t* const seqHandle_)
  222380. :
  222381. midiOutput (midiOutput_),
  222382. seqHandle (seqHandle_),
  222383. maxEventSize (16 * 1024)
  222384. {
  222385. jassert (seqHandle != 0 && midiOutput != 0);
  222386. snd_midi_event_new (maxEventSize, &midiParser);
  222387. }
  222388. ~MidiOutputDevice()
  222389. {
  222390. snd_midi_event_free (midiParser);
  222391. snd_seq_close (seqHandle);
  222392. }
  222393. void sendMessageNow (const MidiMessage& message)
  222394. {
  222395. if (message.getRawDataSize() > maxEventSize)
  222396. {
  222397. maxEventSize = message.getRawDataSize();
  222398. snd_midi_event_free (midiParser);
  222399. snd_midi_event_new (maxEventSize, &midiParser);
  222400. }
  222401. snd_seq_event_t event;
  222402. snd_seq_ev_clear (&event);
  222403. snd_midi_event_encode (midiParser,
  222404. message.getRawData(),
  222405. message.getRawDataSize(),
  222406. &event);
  222407. snd_midi_event_reset_encode (midiParser);
  222408. snd_seq_ev_set_source (&event, 0);
  222409. snd_seq_ev_set_subs (&event);
  222410. snd_seq_ev_set_direct (&event);
  222411. snd_seq_event_output (seqHandle, &event);
  222412. snd_seq_drain_output (seqHandle);
  222413. }
  222414. juce_UseDebuggingNewOperator
  222415. private:
  222416. MidiOutput* const midiOutput;
  222417. snd_seq_t* const seqHandle;
  222418. snd_midi_event_t* midiParser;
  222419. int maxEventSize;
  222420. };
  222421. const StringArray MidiOutput::getDevices()
  222422. {
  222423. StringArray devices;
  222424. iterateDevices (false, devices, -1);
  222425. return devices;
  222426. }
  222427. int MidiOutput::getDefaultDeviceIndex()
  222428. {
  222429. return 0;
  222430. }
  222431. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222432. {
  222433. MidiOutput* newDevice = 0;
  222434. StringArray devices;
  222435. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  222436. if (handle != 0)
  222437. {
  222438. newDevice = new MidiOutput();
  222439. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222440. }
  222441. return newDevice;
  222442. }
  222443. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222444. {
  222445. MidiOutput* newDevice = 0;
  222446. snd_seq_t* const handle = createDevice (false, deviceName);
  222447. if (handle != 0)
  222448. {
  222449. newDevice = new MidiOutput();
  222450. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222451. }
  222452. return newDevice;
  222453. }
  222454. MidiOutput::~MidiOutput()
  222455. {
  222456. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  222457. delete device;
  222458. }
  222459. void MidiOutput::reset()
  222460. {
  222461. }
  222462. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222463. {
  222464. return false;
  222465. }
  222466. void MidiOutput::setVolume (float leftVol, float rightVol)
  222467. {
  222468. }
  222469. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222470. {
  222471. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  222472. }
  222473. class MidiInputThread : public Thread
  222474. {
  222475. public:
  222476. MidiInputThread (MidiInput* const midiInput_,
  222477. snd_seq_t* const seqHandle_,
  222478. MidiInputCallback* const callback_)
  222479. : Thread ("Juce MIDI Input"),
  222480. midiInput (midiInput_),
  222481. seqHandle (seqHandle_),
  222482. callback (callback_)
  222483. {
  222484. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222485. }
  222486. ~MidiInputThread()
  222487. {
  222488. snd_seq_close (seqHandle);
  222489. }
  222490. void run()
  222491. {
  222492. const int maxEventSize = 16 * 1024;
  222493. snd_midi_event_t* midiParser;
  222494. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222495. {
  222496. HeapBlock <uint8> buffer (maxEventSize);
  222497. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222498. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222499. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222500. while (! threadShouldExit())
  222501. {
  222502. if (poll (pfd, numPfds, 500) > 0)
  222503. {
  222504. snd_seq_event_t* inputEvent = 0;
  222505. snd_seq_nonblock (seqHandle, 1);
  222506. do
  222507. {
  222508. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222509. {
  222510. // xxx what about SYSEXes that are too big for the buffer?
  222511. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222512. snd_midi_event_reset_decode (midiParser);
  222513. if (numBytes > 0)
  222514. {
  222515. const MidiMessage message ((const uint8*) buffer,
  222516. numBytes,
  222517. Time::getMillisecondCounter() * 0.001);
  222518. callback->handleIncomingMidiMessage (midiInput, message);
  222519. }
  222520. snd_seq_free_event (inputEvent);
  222521. }
  222522. }
  222523. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222524. snd_seq_free_event (inputEvent);
  222525. }
  222526. }
  222527. snd_midi_event_free (midiParser);
  222528. }
  222529. };
  222530. juce_UseDebuggingNewOperator
  222531. private:
  222532. MidiInput* const midiInput;
  222533. snd_seq_t* const seqHandle;
  222534. MidiInputCallback* const callback;
  222535. };
  222536. MidiInput::MidiInput (const String& name_)
  222537. : name (name_),
  222538. internal (0)
  222539. {
  222540. }
  222541. MidiInput::~MidiInput()
  222542. {
  222543. stop();
  222544. MidiInputThread* const thread = (MidiInputThread*) internal;
  222545. delete thread;
  222546. }
  222547. void MidiInput::start()
  222548. {
  222549. ((MidiInputThread*) internal)->startThread();
  222550. }
  222551. void MidiInput::stop()
  222552. {
  222553. ((MidiInputThread*) internal)->stopThread (3000);
  222554. }
  222555. int MidiInput::getDefaultDeviceIndex()
  222556. {
  222557. return 0;
  222558. }
  222559. const StringArray MidiInput::getDevices()
  222560. {
  222561. StringArray devices;
  222562. iterateDevices (true, devices, -1);
  222563. return devices;
  222564. }
  222565. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222566. {
  222567. MidiInput* newDevice = 0;
  222568. StringArray devices;
  222569. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  222570. if (handle != 0)
  222571. {
  222572. newDevice = new MidiInput (devices [deviceIndex]);
  222573. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222574. }
  222575. return newDevice;
  222576. }
  222577. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222578. {
  222579. MidiInput* newDevice = 0;
  222580. snd_seq_t* const handle = createDevice (true, deviceName);
  222581. if (handle != 0)
  222582. {
  222583. newDevice = new MidiInput (deviceName);
  222584. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222585. }
  222586. return newDevice;
  222587. }
  222588. #else
  222589. // (These are just stub functions if ALSA is unavailable...)
  222590. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222591. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222592. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222593. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222594. MidiOutput::~MidiOutput() {}
  222595. void MidiOutput::reset() {}
  222596. bool MidiOutput::getVolume (float&, float&) { return false; }
  222597. void MidiOutput::setVolume (float, float) {}
  222598. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222599. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222600. MidiInput::~MidiInput() {}
  222601. void MidiInput::start() {}
  222602. void MidiInput::stop() {}
  222603. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222604. const StringArray MidiInput::getDevices() { return StringArray(); }
  222605. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222606. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222607. #endif
  222608. #endif
  222609. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222610. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222611. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222612. // compiled on its own).
  222613. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222614. AudioCDReader::AudioCDReader()
  222615. : AudioFormatReader (0, "CD Audio")
  222616. {
  222617. }
  222618. const StringArray AudioCDReader::getAvailableCDNames()
  222619. {
  222620. StringArray names;
  222621. return names;
  222622. }
  222623. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222624. {
  222625. return 0;
  222626. }
  222627. AudioCDReader::~AudioCDReader()
  222628. {
  222629. }
  222630. void AudioCDReader::refreshTrackLengths()
  222631. {
  222632. }
  222633. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222634. int64 startSampleInFile, int numSamples)
  222635. {
  222636. return false;
  222637. }
  222638. bool AudioCDReader::isCDStillPresent() const
  222639. {
  222640. return false;
  222641. }
  222642. int AudioCDReader::getNumTracks() const
  222643. {
  222644. return 0;
  222645. }
  222646. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  222647. {
  222648. return 0;
  222649. }
  222650. bool AudioCDReader::isTrackAudio (int trackNum) const
  222651. {
  222652. return false;
  222653. }
  222654. void AudioCDReader::enableIndexScanning (bool b)
  222655. {
  222656. }
  222657. int AudioCDReader::getLastIndex() const
  222658. {
  222659. return 0;
  222660. }
  222661. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222662. {
  222663. return Array<int>();
  222664. }
  222665. int AudioCDReader::getCDDBId()
  222666. {
  222667. return 0;
  222668. }
  222669. #endif
  222670. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222671. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222672. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222673. // compiled on its own).
  222674. #if JUCE_INCLUDED_FILE
  222675. void FileChooser::showPlatformDialog (Array<File>& results,
  222676. const String& title,
  222677. const File& file,
  222678. const String& filters,
  222679. bool isDirectory,
  222680. bool selectsFiles,
  222681. bool isSave,
  222682. bool warnAboutOverwritingExistingFiles,
  222683. bool selectMultipleFiles,
  222684. FilePreviewComponent* previewComponent)
  222685. {
  222686. const String separator (":");
  222687. String command ("zenity --file-selection");
  222688. if (title.isNotEmpty())
  222689. command << " --title=\"" << title << "\"";
  222690. if (file != File::nonexistent)
  222691. command << " --filename=\"" << file.getFullPathName () << "\"";
  222692. if (isDirectory)
  222693. command << " --directory";
  222694. if (isSave)
  222695. command << " --save";
  222696. if (selectMultipleFiles)
  222697. command << " --multiple --separator=\"" << separator << "\"";
  222698. command << " 2>&1";
  222699. MemoryOutputStream result;
  222700. int status = -1;
  222701. FILE* stream = popen (command.toUTF8(), "r");
  222702. if (stream != 0)
  222703. {
  222704. for (;;)
  222705. {
  222706. char buffer [1024];
  222707. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222708. if (bytesRead <= 0)
  222709. break;
  222710. result.write (buffer, bytesRead);
  222711. }
  222712. status = pclose (stream);
  222713. }
  222714. if (status == 0)
  222715. {
  222716. StringArray tokens;
  222717. if (selectMultipleFiles)
  222718. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222719. else
  222720. tokens.add (result.toUTF8());
  222721. for (int i = 0; i < tokens.size(); i++)
  222722. results.add (File (tokens[i]));
  222723. return;
  222724. }
  222725. //xxx ain't got one!
  222726. jassertfalse;
  222727. }
  222728. #endif
  222729. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222730. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222731. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222732. // compiled on its own).
  222733. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222734. /*
  222735. Sorry.. This class isn't implemented on Linux!
  222736. */
  222737. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222738. : browser (0),
  222739. blankPageShown (false),
  222740. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222741. {
  222742. setOpaque (true);
  222743. }
  222744. WebBrowserComponent::~WebBrowserComponent()
  222745. {
  222746. }
  222747. void WebBrowserComponent::goToURL (const String& url,
  222748. const StringArray* headers,
  222749. const MemoryBlock* postData)
  222750. {
  222751. lastURL = url;
  222752. lastHeaders.clear();
  222753. if (headers != 0)
  222754. lastHeaders = *headers;
  222755. lastPostData.setSize (0);
  222756. if (postData != 0)
  222757. lastPostData = *postData;
  222758. blankPageShown = false;
  222759. }
  222760. void WebBrowserComponent::stop()
  222761. {
  222762. }
  222763. void WebBrowserComponent::goBack()
  222764. {
  222765. lastURL = String::empty;
  222766. blankPageShown = false;
  222767. }
  222768. void WebBrowserComponent::goForward()
  222769. {
  222770. lastURL = String::empty;
  222771. }
  222772. void WebBrowserComponent::refresh()
  222773. {
  222774. }
  222775. void WebBrowserComponent::paint (Graphics& g)
  222776. {
  222777. g.fillAll (Colours::white);
  222778. }
  222779. void WebBrowserComponent::checkWindowAssociation()
  222780. {
  222781. }
  222782. void WebBrowserComponent::reloadLastURL()
  222783. {
  222784. if (lastURL.isNotEmpty())
  222785. {
  222786. goToURL (lastURL, &lastHeaders, &lastPostData);
  222787. lastURL = String::empty;
  222788. }
  222789. }
  222790. void WebBrowserComponent::parentHierarchyChanged()
  222791. {
  222792. checkWindowAssociation();
  222793. }
  222794. void WebBrowserComponent::resized()
  222795. {
  222796. }
  222797. void WebBrowserComponent::visibilityChanged()
  222798. {
  222799. checkWindowAssociation();
  222800. }
  222801. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222802. {
  222803. return true;
  222804. }
  222805. #endif
  222806. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222807. #endif
  222808. END_JUCE_NAMESPACE
  222809. #endif
  222810. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  222811. #endif
  222812. #if JUCE_MAC || JUCE_IPHONE
  222813. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  222814. /*
  222815. This file wraps together all the mac-specific code, so that
  222816. we can include all the native headers just once, and compile all our
  222817. platform-specific stuff in one big lump, keeping it out of the way of
  222818. the rest of the codebase.
  222819. */
  222820. #if JUCE_MAC || JUCE_IOS
  222821. BEGIN_JUCE_NAMESPACE
  222822. #undef Point
  222823. #define JUCE_INCLUDED_FILE 1
  222824. // Now include the actual code files..
  222825. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  222826. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  222827. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  222828. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  222829. cross-linked so that when you make a call to a class that you thought was private, it ends up
  222830. actually calling into a similarly named class in the other module's address space.
  222831. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  222832. have unique names, and should avoid this problem.
  222833. If you're using the amalgamated version, you can just set this macro to something unique before
  222834. you include juce_amalgamated.cpp.
  222835. */
  222836. #ifndef JUCE_ObjCExtraSuffix
  222837. #define JUCE_ObjCExtraSuffix 3
  222838. #endif
  222839. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  222840. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  222841. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  222842. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  222843. /*** Start of inlined file: juce_mac_Strings.mm ***/
  222844. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222845. // compiled on its own).
  222846. #if JUCE_INCLUDED_FILE
  222847. static const String nsStringToJuce (NSString* s)
  222848. {
  222849. return String::fromUTF8 ([s UTF8String]);
  222850. }
  222851. static NSString* juceStringToNS (const String& s)
  222852. {
  222853. return [NSString stringWithUTF8String: s.toUTF8()];
  222854. }
  222855. static const String convertUTF16ToString (const UniChar* utf16)
  222856. {
  222857. String s;
  222858. while (*utf16 != 0)
  222859. s += (juce_wchar) *utf16++;
  222860. return s;
  222861. }
  222862. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  222863. {
  222864. String result;
  222865. if (cfString != 0)
  222866. {
  222867. CFRange range = { 0, CFStringGetLength (cfString) };
  222868. HeapBlock <UniChar> u (range.length + 1);
  222869. CFStringGetCharacters (cfString, range, u);
  222870. u[range.length] = 0;
  222871. result = convertUTF16ToString (u);
  222872. }
  222873. return result;
  222874. }
  222875. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  222876. {
  222877. const int len = s.length();
  222878. HeapBlock <UniChar> temp (len + 2);
  222879. for (int i = 0; i <= len; ++i)
  222880. temp[i] = s[i];
  222881. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  222882. }
  222883. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  222884. {
  222885. #if JUCE_IOS
  222886. const ScopedAutoReleasePool pool;
  222887. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  222888. #else
  222889. UnicodeMapping map;
  222890. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222891. kUnicodeNoSubset,
  222892. kTextEncodingDefaultFormat);
  222893. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222894. kUnicodeCanonicalCompVariant,
  222895. kTextEncodingDefaultFormat);
  222896. map.mappingVersion = kUnicodeUseLatestMapping;
  222897. UnicodeToTextInfo conversionInfo = 0;
  222898. String result;
  222899. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  222900. {
  222901. const int len = s.length();
  222902. HeapBlock <UniChar> tempIn, tempOut;
  222903. tempIn.calloc (len + 2);
  222904. tempOut.calloc (len + 2);
  222905. for (int i = 0; i <= len; ++i)
  222906. tempIn[i] = s[i];
  222907. ByteCount bytesRead = 0;
  222908. ByteCount outputBufferSize = 0;
  222909. if (ConvertFromUnicodeToText (conversionInfo,
  222910. len * sizeof (UniChar), tempIn,
  222911. kUnicodeDefaultDirectionMask,
  222912. 0, 0, 0, 0,
  222913. len * sizeof (UniChar), &bytesRead,
  222914. &outputBufferSize, tempOut) == noErr)
  222915. {
  222916. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  222917. juce_wchar* t = result;
  222918. unsigned int i;
  222919. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  222920. t[i] = (juce_wchar) tempOut[i];
  222921. t[i] = 0;
  222922. }
  222923. DisposeUnicodeToTextInfo (&conversionInfo);
  222924. }
  222925. return result;
  222926. #endif
  222927. }
  222928. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222929. void SystemClipboard::copyTextToClipboard (const String& text)
  222930. {
  222931. #if JUCE_IOS
  222932. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  222933. forPasteboardType: @"public.text"];
  222934. #else
  222935. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  222936. owner: nil];
  222937. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  222938. forType: NSStringPboardType];
  222939. #endif
  222940. }
  222941. const String SystemClipboard::getTextFromClipboard()
  222942. {
  222943. #if JUCE_IOS
  222944. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  222945. #else
  222946. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  222947. #endif
  222948. return text == 0 ? String::empty
  222949. : nsStringToJuce (text);
  222950. }
  222951. #endif
  222952. #endif
  222953. /*** End of inlined file: juce_mac_Strings.mm ***/
  222954. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  222955. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222956. // compiled on its own).
  222957. #if JUCE_INCLUDED_FILE
  222958. namespace SystemStatsHelpers
  222959. {
  222960. static int64 highResTimerFrequency = 0;
  222961. static double highResTimerToMillisecRatio = 0;
  222962. #if JUCE_INTEL
  222963. static void juce_getCpuVendor (char* const v) throw()
  222964. {
  222965. int vendor[4];
  222966. zerostruct (vendor);
  222967. int dummy = 0;
  222968. asm ("mov %%ebx, %%esi \n\t"
  222969. "cpuid \n\t"
  222970. "xchg %%esi, %%ebx"
  222971. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  222972. memcpy (v, vendor, 16);
  222973. }
  222974. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  222975. {
  222976. unsigned int cpu = 0;
  222977. unsigned int ext = 0;
  222978. unsigned int family = 0;
  222979. unsigned int dummy = 0;
  222980. asm ("mov %%ebx, %%esi \n\t"
  222981. "cpuid \n\t"
  222982. "xchg %%esi, %%ebx"
  222983. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  222984. familyModel = family;
  222985. extFeatures = ext;
  222986. return cpu;
  222987. }
  222988. #endif
  222989. }
  222990. void SystemStats::initialiseStats()
  222991. {
  222992. using namespace SystemStatsHelpers;
  222993. static bool initialised = false;
  222994. if (! initialised)
  222995. {
  222996. initialised = true;
  222997. #if JUCE_MAC
  222998. // extremely annoying: adding this line stops the apple menu items from working. Of
  222999. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  223000. // any events.
  223001. //NSApplicationLoad();
  223002. [NSApplication sharedApplication];
  223003. #endif
  223004. #if JUCE_INTEL
  223005. unsigned int familyModel, extFeatures;
  223006. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  223007. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223008. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223009. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223010. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223011. #else
  223012. cpuFlags.hasMMX = false;
  223013. cpuFlags.hasSSE = false;
  223014. cpuFlags.hasSSE2 = false;
  223015. cpuFlags.has3DNow = false;
  223016. #endif
  223017. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223018. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223019. #else
  223020. cpuFlags.numCpus = (int) MPProcessors();
  223021. #endif
  223022. mach_timebase_info_data_t timebase;
  223023. (void) mach_timebase_info (&timebase);
  223024. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223025. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223026. String s (SystemStats::getJUCEVersion());
  223027. rlimit lim;
  223028. getrlimit (RLIMIT_NOFILE, &lim);
  223029. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223030. setrlimit (RLIMIT_NOFILE, &lim);
  223031. }
  223032. }
  223033. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223034. {
  223035. return MacOSX;
  223036. }
  223037. const String SystemStats::getOperatingSystemName()
  223038. {
  223039. return "Mac OS X";
  223040. }
  223041. bool SystemStats::isOperatingSystem64Bit()
  223042. {
  223043. #if JUCE_64BIT
  223044. return true;
  223045. #else
  223046. //xxx not sure how to find this out?..
  223047. return false;
  223048. #endif
  223049. }
  223050. int SystemStats::getMemorySizeInMegabytes()
  223051. {
  223052. uint64 mem = 0;
  223053. size_t memSize = sizeof (mem);
  223054. int mib[] = { CTL_HW, HW_MEMSIZE };
  223055. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223056. return (int) (mem / (1024 * 1024));
  223057. }
  223058. const String SystemStats::getCpuVendor()
  223059. {
  223060. #if JUCE_INTEL
  223061. char v [16];
  223062. SystemStatsHelpers::juce_getCpuVendor (v);
  223063. return String (v, 16);
  223064. #else
  223065. return String::empty;
  223066. #endif
  223067. }
  223068. int SystemStats::getCpuSpeedInMegaherz()
  223069. {
  223070. uint64 speedHz = 0;
  223071. size_t speedSize = sizeof (speedHz);
  223072. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223073. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223074. #if JUCE_BIG_ENDIAN
  223075. if (speedSize == 4)
  223076. speedHz >>= 32;
  223077. #endif
  223078. return (int) (speedHz / 1000000);
  223079. }
  223080. const String SystemStats::getLogonName()
  223081. {
  223082. return nsStringToJuce (NSUserName());
  223083. }
  223084. const String SystemStats::getFullUserName()
  223085. {
  223086. return nsStringToJuce (NSFullUserName());
  223087. }
  223088. uint32 juce_millisecondsSinceStartup() throw()
  223089. {
  223090. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223091. }
  223092. double Time::getMillisecondCounterHiRes() throw()
  223093. {
  223094. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223095. }
  223096. int64 Time::getHighResolutionTicks() throw()
  223097. {
  223098. return (int64) mach_absolute_time();
  223099. }
  223100. int64 Time::getHighResolutionTicksPerSecond() throw()
  223101. {
  223102. return SystemStatsHelpers::highResTimerFrequency;
  223103. }
  223104. bool Time::setSystemTimeToThisTime() const
  223105. {
  223106. jassertfalse;
  223107. return false;
  223108. }
  223109. int SystemStats::getPageSize()
  223110. {
  223111. return (int) NSPageSize();
  223112. }
  223113. void PlatformUtilities::fpuReset()
  223114. {
  223115. }
  223116. #endif
  223117. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223118. /*** Start of inlined file: juce_mac_Network.mm ***/
  223119. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223120. // compiled on its own).
  223121. #if JUCE_INCLUDED_FILE
  223122. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  223123. {
  223124. #ifndef IFT_ETHER
  223125. #define IFT_ETHER 6
  223126. #endif
  223127. ifaddrs* addrs = 0;
  223128. int numResults = 0;
  223129. if (getifaddrs (&addrs) == 0)
  223130. {
  223131. const ifaddrs* cursor = addrs;
  223132. while (cursor != 0 && numResults < maxNum)
  223133. {
  223134. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223135. if (sto->ss_family == AF_LINK)
  223136. {
  223137. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223138. if (sadd->sdl_type == IFT_ETHER)
  223139. {
  223140. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  223141. uint64 a = 0;
  223142. for (int i = 6; --i >= 0;)
  223143. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  223144. *addresses++ = (int64) a;
  223145. ++numResults;
  223146. }
  223147. }
  223148. cursor = cursor->ifa_next;
  223149. }
  223150. freeifaddrs (addrs);
  223151. }
  223152. return numResults;
  223153. }
  223154. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223155. const String& emailSubject,
  223156. const String& bodyText,
  223157. const StringArray& filesToAttach)
  223158. {
  223159. #if JUCE_IOS
  223160. //xxx probably need to use MFMailComposeViewController
  223161. jassertfalse;
  223162. return false;
  223163. #else
  223164. const ScopedAutoReleasePool pool;
  223165. String script;
  223166. script << "tell application \"Mail\"\r\n"
  223167. "set newMessage to make new outgoing message with properties {subject:\""
  223168. << emailSubject.replace ("\"", "\\\"")
  223169. << "\", content:\""
  223170. << bodyText.replace ("\"", "\\\"")
  223171. << "\" & return & return}\r\n"
  223172. "tell newMessage\r\n"
  223173. "set visible to true\r\n"
  223174. "set sender to \"sdfsdfsdfewf\"\r\n"
  223175. "make new to recipient at end of to recipients with properties {address:\""
  223176. << targetEmailAddress
  223177. << "\"}\r\n";
  223178. for (int i = 0; i < filesToAttach.size(); ++i)
  223179. {
  223180. script << "tell content\r\n"
  223181. "make new attachment with properties {file name:\""
  223182. << filesToAttach[i].replace ("\"", "\\\"")
  223183. << "\"} at after the last paragraph\r\n"
  223184. "end tell\r\n";
  223185. }
  223186. script << "end tell\r\n"
  223187. "end tell\r\n";
  223188. NSAppleScript* s = [[NSAppleScript alloc]
  223189. initWithSource: juceStringToNS (script)];
  223190. NSDictionary* error = 0;
  223191. const bool ok = [s executeAndReturnError: &error] != nil;
  223192. [s release];
  223193. return ok;
  223194. #endif
  223195. }
  223196. END_JUCE_NAMESPACE
  223197. using namespace JUCE_NAMESPACE;
  223198. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223199. @interface JuceURLConnection : NSObject
  223200. {
  223201. @public
  223202. NSURLRequest* request;
  223203. NSURLConnection* connection;
  223204. NSMutableData* data;
  223205. Thread* runLoopThread;
  223206. bool initialised, hasFailed, hasFinished;
  223207. int position;
  223208. int64 contentLength;
  223209. NSDictionary* headers;
  223210. NSLock* dataLock;
  223211. }
  223212. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223213. - (void) dealloc;
  223214. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223215. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223216. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223217. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223218. - (BOOL) isOpen;
  223219. - (int) read: (char*) dest numBytes: (int) num;
  223220. - (int) readPosition;
  223221. - (void) stop;
  223222. - (void) createConnection;
  223223. @end
  223224. class JuceURLConnectionMessageThread : public Thread
  223225. {
  223226. JuceURLConnection* owner;
  223227. public:
  223228. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223229. : Thread ("http connection"),
  223230. owner (owner_)
  223231. {
  223232. }
  223233. ~JuceURLConnectionMessageThread()
  223234. {
  223235. stopThread (10000);
  223236. }
  223237. void run()
  223238. {
  223239. [owner createConnection];
  223240. while (! threadShouldExit())
  223241. {
  223242. const ScopedAutoReleasePool pool;
  223243. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223244. }
  223245. }
  223246. };
  223247. @implementation JuceURLConnection
  223248. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223249. withCallback: (URL::OpenStreamProgressCallback*) callback
  223250. withContext: (void*) context;
  223251. {
  223252. [super init];
  223253. request = req;
  223254. [request retain];
  223255. data = [[NSMutableData data] retain];
  223256. dataLock = [[NSLock alloc] init];
  223257. connection = 0;
  223258. initialised = false;
  223259. hasFailed = false;
  223260. hasFinished = false;
  223261. contentLength = -1;
  223262. headers = 0;
  223263. runLoopThread = new JuceURLConnectionMessageThread (self);
  223264. runLoopThread->startThread();
  223265. while (runLoopThread->isThreadRunning() && ! initialised)
  223266. {
  223267. if (callback != 0)
  223268. callback (context, -1, (int) [[request HTTPBody] length]);
  223269. Thread::sleep (1);
  223270. }
  223271. return self;
  223272. }
  223273. - (void) dealloc
  223274. {
  223275. [self stop];
  223276. deleteAndZero (runLoopThread);
  223277. [connection release];
  223278. [data release];
  223279. [dataLock release];
  223280. [request release];
  223281. [headers release];
  223282. [super dealloc];
  223283. }
  223284. - (void) createConnection
  223285. {
  223286. NSUInteger oldRetainCount = [self retainCount];
  223287. connection = [[NSURLConnection alloc] initWithRequest: request
  223288. delegate: self];
  223289. if (oldRetainCount == [self retainCount])
  223290. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223291. if (connection == nil)
  223292. runLoopThread->signalThreadShouldExit();
  223293. }
  223294. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223295. {
  223296. (void) conn;
  223297. [dataLock lock];
  223298. [data setLength: 0];
  223299. [dataLock unlock];
  223300. initialised = true;
  223301. contentLength = [response expectedContentLength];
  223302. [headers release];
  223303. headers = 0;
  223304. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223305. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223306. }
  223307. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223308. {
  223309. (void) conn;
  223310. DBG (nsStringToJuce ([error description]));
  223311. hasFailed = true;
  223312. initialised = true;
  223313. if (runLoopThread != 0)
  223314. runLoopThread->signalThreadShouldExit();
  223315. }
  223316. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223317. {
  223318. (void) conn;
  223319. [dataLock lock];
  223320. [data appendData: newData];
  223321. [dataLock unlock];
  223322. initialised = true;
  223323. }
  223324. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223325. {
  223326. (void) conn;
  223327. hasFinished = true;
  223328. initialised = true;
  223329. if (runLoopThread != 0)
  223330. runLoopThread->signalThreadShouldExit();
  223331. }
  223332. - (BOOL) isOpen
  223333. {
  223334. return connection != 0 && ! hasFailed;
  223335. }
  223336. - (int) readPosition
  223337. {
  223338. return position;
  223339. }
  223340. - (int) read: (char*) dest numBytes: (int) numNeeded
  223341. {
  223342. int numDone = 0;
  223343. while (numNeeded > 0)
  223344. {
  223345. int available = jmin (numNeeded, (int) [data length]);
  223346. if (available > 0)
  223347. {
  223348. [dataLock lock];
  223349. [data getBytes: dest length: available];
  223350. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223351. [dataLock unlock];
  223352. numDone += available;
  223353. numNeeded -= available;
  223354. dest += available;
  223355. }
  223356. else
  223357. {
  223358. if (hasFailed || hasFinished)
  223359. break;
  223360. Thread::sleep (1);
  223361. }
  223362. }
  223363. position += numDone;
  223364. return numDone;
  223365. }
  223366. - (void) stop
  223367. {
  223368. [connection cancel];
  223369. if (runLoopThread != 0)
  223370. runLoopThread->stopThread (10000);
  223371. }
  223372. @end
  223373. BEGIN_JUCE_NAMESPACE
  223374. void* juce_openInternetFile (const String& url,
  223375. const String& headers,
  223376. const MemoryBlock& postData,
  223377. const bool isPost,
  223378. URL::OpenStreamProgressCallback* callback,
  223379. void* callbackContext,
  223380. int timeOutMs)
  223381. {
  223382. const ScopedAutoReleasePool pool;
  223383. NSMutableURLRequest* req = [NSMutableURLRequest
  223384. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  223385. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223386. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223387. if (req == nil)
  223388. return 0;
  223389. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223390. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223391. StringArray headerLines;
  223392. headerLines.addLines (headers);
  223393. headerLines.removeEmptyStrings (true);
  223394. for (int i = 0; i < headerLines.size(); ++i)
  223395. {
  223396. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223397. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223398. if (key.isNotEmpty() && value.isNotEmpty())
  223399. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223400. }
  223401. if (isPost && postData.getSize() > 0)
  223402. {
  223403. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223404. length: postData.getSize()]];
  223405. }
  223406. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223407. withCallback: callback
  223408. withContext: callbackContext];
  223409. if ([s isOpen])
  223410. return s;
  223411. [s release];
  223412. return 0;
  223413. }
  223414. void juce_closeInternetFile (void* handle)
  223415. {
  223416. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223417. if (s != 0)
  223418. {
  223419. const ScopedAutoReleasePool pool;
  223420. [s stop];
  223421. [s release];
  223422. }
  223423. }
  223424. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  223425. {
  223426. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223427. if (s != 0)
  223428. {
  223429. const ScopedAutoReleasePool pool;
  223430. return [s read: (char*) buffer numBytes: bytesToRead];
  223431. }
  223432. return 0;
  223433. }
  223434. int64 juce_getInternetFileContentLength (void* handle)
  223435. {
  223436. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223437. if (s != 0)
  223438. return s->contentLength;
  223439. return -1;
  223440. }
  223441. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  223442. {
  223443. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223444. if (s != 0 && s->headers != 0)
  223445. {
  223446. NSEnumerator* enumerator = [s->headers keyEnumerator];
  223447. NSString* key;
  223448. while ((key = [enumerator nextObject]) != nil)
  223449. headers.set (nsStringToJuce (key),
  223450. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  223451. }
  223452. }
  223453. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  223454. {
  223455. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223456. if (s != 0)
  223457. return [s readPosition];
  223458. return 0;
  223459. }
  223460. #endif
  223461. /*** End of inlined file: juce_mac_Network.mm ***/
  223462. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223463. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223464. // compiled on its own).
  223465. #if JUCE_INCLUDED_FILE
  223466. struct NamedPipeInternal
  223467. {
  223468. String pipeInName, pipeOutName;
  223469. int pipeIn, pipeOut;
  223470. bool volatile createdPipe, blocked, stopReadOperation;
  223471. static void signalHandler (int) {}
  223472. };
  223473. void NamedPipe::cancelPendingReads()
  223474. {
  223475. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  223476. {
  223477. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223478. intern->stopReadOperation = true;
  223479. char buffer [1] = { 0 };
  223480. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223481. (void) bytesWritten;
  223482. int timeout = 2000;
  223483. while (intern->blocked && --timeout >= 0)
  223484. Thread::sleep (2);
  223485. intern->stopReadOperation = false;
  223486. }
  223487. }
  223488. void NamedPipe::close()
  223489. {
  223490. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223491. if (intern != 0)
  223492. {
  223493. internal = 0;
  223494. if (intern->pipeIn != -1)
  223495. ::close (intern->pipeIn);
  223496. if (intern->pipeOut != -1)
  223497. ::close (intern->pipeOut);
  223498. if (intern->createdPipe)
  223499. {
  223500. unlink (intern->pipeInName.toUTF8());
  223501. unlink (intern->pipeOutName.toUTF8());
  223502. }
  223503. delete intern;
  223504. }
  223505. }
  223506. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223507. {
  223508. close();
  223509. NamedPipeInternal* const intern = new NamedPipeInternal();
  223510. internal = intern;
  223511. intern->createdPipe = createPipe;
  223512. intern->blocked = false;
  223513. intern->stopReadOperation = false;
  223514. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223515. siginterrupt (SIGPIPE, 1);
  223516. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223517. intern->pipeInName = pipePath + "_in";
  223518. intern->pipeOutName = pipePath + "_out";
  223519. intern->pipeIn = -1;
  223520. intern->pipeOut = -1;
  223521. if (createPipe)
  223522. {
  223523. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223524. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223525. {
  223526. delete intern;
  223527. internal = 0;
  223528. return false;
  223529. }
  223530. }
  223531. return true;
  223532. }
  223533. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223534. {
  223535. int bytesRead = -1;
  223536. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223537. if (intern != 0)
  223538. {
  223539. intern->blocked = true;
  223540. if (intern->pipeIn == -1)
  223541. {
  223542. if (intern->createdPipe)
  223543. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223544. else
  223545. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223546. if (intern->pipeIn == -1)
  223547. {
  223548. intern->blocked = false;
  223549. return -1;
  223550. }
  223551. }
  223552. bytesRead = 0;
  223553. char* p = (char*) destBuffer;
  223554. while (bytesRead < maxBytesToRead)
  223555. {
  223556. const int bytesThisTime = maxBytesToRead - bytesRead;
  223557. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223558. if (numRead <= 0 || intern->stopReadOperation)
  223559. {
  223560. bytesRead = -1;
  223561. break;
  223562. }
  223563. bytesRead += numRead;
  223564. p += bytesRead;
  223565. }
  223566. intern->blocked = false;
  223567. }
  223568. return bytesRead;
  223569. }
  223570. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223571. {
  223572. int bytesWritten = -1;
  223573. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223574. if (intern != 0)
  223575. {
  223576. if (intern->pipeOut == -1)
  223577. {
  223578. if (intern->createdPipe)
  223579. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223580. else
  223581. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223582. if (intern->pipeOut == -1)
  223583. {
  223584. return -1;
  223585. }
  223586. }
  223587. const char* p = (const char*) sourceBuffer;
  223588. bytesWritten = 0;
  223589. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223590. while (bytesWritten < numBytesToWrite
  223591. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223592. {
  223593. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223594. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223595. if (numWritten <= 0)
  223596. {
  223597. bytesWritten = -1;
  223598. break;
  223599. }
  223600. bytesWritten += numWritten;
  223601. p += bytesWritten;
  223602. }
  223603. }
  223604. return bytesWritten;
  223605. }
  223606. #endif
  223607. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223608. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223609. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223610. // compiled on its own).
  223611. #if JUCE_INCLUDED_FILE
  223612. /*
  223613. Note that a lot of methods that you'd expect to find in this file actually
  223614. live in juce_posix_SharedCode.h!
  223615. */
  223616. void JUCE_API juce_threadEntryPoint (void*);
  223617. void* threadEntryProc (void* userData)
  223618. {
  223619. const ScopedAutoReleasePool pool;
  223620. juce_threadEntryPoint (userData);
  223621. return 0;
  223622. }
  223623. void* juce_createThread (void* userData)
  223624. {
  223625. pthread_t handle = 0;
  223626. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223627. {
  223628. pthread_detach (handle);
  223629. return (void*) handle;
  223630. }
  223631. return 0;
  223632. }
  223633. void juce_killThread (void* handle)
  223634. {
  223635. if (handle != 0)
  223636. pthread_cancel ((pthread_t) handle);
  223637. }
  223638. void juce_setCurrentThreadName (const String& /*name*/)
  223639. {
  223640. }
  223641. bool juce_setThreadPriority (void* handle, int priority)
  223642. {
  223643. if (handle == 0)
  223644. handle = (void*) pthread_self();
  223645. struct sched_param param;
  223646. int policy;
  223647. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  223648. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  223649. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  223650. }
  223651. Thread::ThreadID Thread::getCurrentThreadId()
  223652. {
  223653. return static_cast <ThreadID> (pthread_self());
  223654. }
  223655. void Thread::yield()
  223656. {
  223657. sched_yield();
  223658. }
  223659. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  223660. {
  223661. // xxx
  223662. jassertfalse;
  223663. }
  223664. bool Process::isForegroundProcess()
  223665. {
  223666. #if JUCE_MAC
  223667. return [NSApp isActive];
  223668. #else
  223669. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223670. #endif
  223671. }
  223672. void Process::raisePrivilege()
  223673. {
  223674. jassertfalse;
  223675. }
  223676. void Process::lowerPrivilege()
  223677. {
  223678. jassertfalse;
  223679. }
  223680. void Process::terminate()
  223681. {
  223682. exit (0);
  223683. }
  223684. void Process::setPriority (ProcessPriority)
  223685. {
  223686. // xxx
  223687. }
  223688. #endif
  223689. /*** End of inlined file: juce_mac_Threads.mm ***/
  223690. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223691. /*
  223692. This file contains posix routines that are common to both the Linux and Mac builds.
  223693. It gets included directly in the cpp files for these platforms.
  223694. */
  223695. CriticalSection::CriticalSection() throw()
  223696. {
  223697. pthread_mutexattr_t atts;
  223698. pthread_mutexattr_init (&atts);
  223699. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223700. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223701. pthread_mutex_init (&internal, &atts);
  223702. }
  223703. CriticalSection::~CriticalSection() throw()
  223704. {
  223705. pthread_mutex_destroy (&internal);
  223706. }
  223707. void CriticalSection::enter() const throw()
  223708. {
  223709. pthread_mutex_lock (&internal);
  223710. }
  223711. bool CriticalSection::tryEnter() const throw()
  223712. {
  223713. return pthread_mutex_trylock (&internal) == 0;
  223714. }
  223715. void CriticalSection::exit() const throw()
  223716. {
  223717. pthread_mutex_unlock (&internal);
  223718. }
  223719. class WaitableEventImpl
  223720. {
  223721. public:
  223722. WaitableEventImpl (const bool manualReset_)
  223723. : triggered (false),
  223724. manualReset (manualReset_)
  223725. {
  223726. pthread_cond_init (&condition, 0);
  223727. pthread_mutexattr_t atts;
  223728. pthread_mutexattr_init (&atts);
  223729. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223730. pthread_mutex_init (&mutex, &atts);
  223731. }
  223732. ~WaitableEventImpl()
  223733. {
  223734. pthread_cond_destroy (&condition);
  223735. pthread_mutex_destroy (&mutex);
  223736. }
  223737. bool wait (const int timeOutMillisecs) throw()
  223738. {
  223739. pthread_mutex_lock (&mutex);
  223740. if (! triggered)
  223741. {
  223742. if (timeOutMillisecs < 0)
  223743. {
  223744. do
  223745. {
  223746. pthread_cond_wait (&condition, &mutex);
  223747. }
  223748. while (! triggered);
  223749. }
  223750. else
  223751. {
  223752. struct timeval now;
  223753. gettimeofday (&now, 0);
  223754. struct timespec time;
  223755. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  223756. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  223757. if (time.tv_nsec >= 1000000000)
  223758. {
  223759. time.tv_nsec -= 1000000000;
  223760. time.tv_sec++;
  223761. }
  223762. do
  223763. {
  223764. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  223765. {
  223766. pthread_mutex_unlock (&mutex);
  223767. return false;
  223768. }
  223769. }
  223770. while (! triggered);
  223771. }
  223772. }
  223773. if (! manualReset)
  223774. triggered = false;
  223775. pthread_mutex_unlock (&mutex);
  223776. return true;
  223777. }
  223778. void signal() throw()
  223779. {
  223780. pthread_mutex_lock (&mutex);
  223781. triggered = true;
  223782. pthread_cond_broadcast (&condition);
  223783. pthread_mutex_unlock (&mutex);
  223784. }
  223785. void reset() throw()
  223786. {
  223787. pthread_mutex_lock (&mutex);
  223788. triggered = false;
  223789. pthread_mutex_unlock (&mutex);
  223790. }
  223791. private:
  223792. pthread_cond_t condition;
  223793. pthread_mutex_t mutex;
  223794. bool triggered;
  223795. const bool manualReset;
  223796. WaitableEventImpl (const WaitableEventImpl&);
  223797. WaitableEventImpl& operator= (const WaitableEventImpl&);
  223798. };
  223799. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  223800. : internal (new WaitableEventImpl (manualReset))
  223801. {
  223802. }
  223803. WaitableEvent::~WaitableEvent() throw()
  223804. {
  223805. delete static_cast <WaitableEventImpl*> (internal);
  223806. }
  223807. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  223808. {
  223809. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  223810. }
  223811. void WaitableEvent::signal() const throw()
  223812. {
  223813. static_cast <WaitableEventImpl*> (internal)->signal();
  223814. }
  223815. void WaitableEvent::reset() const throw()
  223816. {
  223817. static_cast <WaitableEventImpl*> (internal)->reset();
  223818. }
  223819. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  223820. {
  223821. struct timespec time;
  223822. time.tv_sec = millisecs / 1000;
  223823. time.tv_nsec = (millisecs % 1000) * 1000000;
  223824. nanosleep (&time, 0);
  223825. }
  223826. const juce_wchar File::separator = '/';
  223827. const String File::separatorString ("/");
  223828. const File File::getCurrentWorkingDirectory()
  223829. {
  223830. HeapBlock<char> heapBuffer;
  223831. char localBuffer [1024];
  223832. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  223833. int bufferSize = 4096;
  223834. while (cwd == 0 && errno == ERANGE)
  223835. {
  223836. heapBuffer.malloc (bufferSize);
  223837. cwd = getcwd (heapBuffer, bufferSize - 1);
  223838. bufferSize += 1024;
  223839. }
  223840. return File (String::fromUTF8 (cwd));
  223841. }
  223842. bool File::setAsCurrentWorkingDirectory() const
  223843. {
  223844. return chdir (getFullPathName().toUTF8()) == 0;
  223845. }
  223846. static bool juce_stat (const String& fileName, struct stat& info)
  223847. {
  223848. return fileName.isNotEmpty()
  223849. && (stat (fileName.toUTF8(), &info) == 0);
  223850. }
  223851. bool File::isDirectory() const
  223852. {
  223853. struct stat info;
  223854. return fullPath.isEmpty()
  223855. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  223856. }
  223857. bool File::exists() const
  223858. {
  223859. return fullPath.isNotEmpty()
  223860. && access (fullPath.toUTF8(), F_OK) == 0;
  223861. }
  223862. bool File::existsAsFile() const
  223863. {
  223864. return exists() && ! isDirectory();
  223865. }
  223866. int64 File::getSize() const
  223867. {
  223868. struct stat info;
  223869. return juce_stat (fullPath, info) ? info.st_size : 0;
  223870. }
  223871. bool File::hasWriteAccess() const
  223872. {
  223873. if (exists())
  223874. return access (fullPath.toUTF8(), W_OK) == 0;
  223875. if ((! isDirectory()) && fullPath.containsChar (separator))
  223876. return getParentDirectory().hasWriteAccess();
  223877. return false;
  223878. }
  223879. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223880. {
  223881. struct stat info;
  223882. const int res = stat (fullPath.toUTF8(), &info);
  223883. if (res != 0)
  223884. return false;
  223885. info.st_mode &= 0777; // Just permissions
  223886. if (shouldBeReadOnly)
  223887. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  223888. else
  223889. // Give everybody write permission?
  223890. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  223891. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  223892. }
  223893. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  223894. {
  223895. modificationTime = 0;
  223896. accessTime = 0;
  223897. creationTime = 0;
  223898. struct stat info;
  223899. const int res = stat (fullPath.toUTF8(), &info);
  223900. if (res == 0)
  223901. {
  223902. modificationTime = (int64) info.st_mtime * 1000;
  223903. accessTime = (int64) info.st_atime * 1000;
  223904. creationTime = (int64) info.st_ctime * 1000;
  223905. }
  223906. }
  223907. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  223908. {
  223909. struct utimbuf times;
  223910. times.actime = (time_t) (accessTime / 1000);
  223911. times.modtime = (time_t) (modificationTime / 1000);
  223912. return utime (fullPath.toUTF8(), &times) == 0;
  223913. }
  223914. bool File::deleteFile() const
  223915. {
  223916. if (! exists())
  223917. return true;
  223918. else if (isDirectory())
  223919. return rmdir (fullPath.toUTF8()) == 0;
  223920. else
  223921. return remove (fullPath.toUTF8()) == 0;
  223922. }
  223923. bool File::moveInternal (const File& dest) const
  223924. {
  223925. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  223926. return true;
  223927. if (hasWriteAccess() && copyInternal (dest))
  223928. {
  223929. if (deleteFile())
  223930. return true;
  223931. dest.deleteFile();
  223932. }
  223933. return false;
  223934. }
  223935. void File::createDirectoryInternal (const String& fileName) const
  223936. {
  223937. mkdir (fileName.toUTF8(), 0777);
  223938. }
  223939. void* juce_fileOpen (const File& file, bool forWriting)
  223940. {
  223941. int flags = O_RDONLY;
  223942. if (forWriting)
  223943. {
  223944. if (file.exists())
  223945. {
  223946. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  223947. if (f != -1)
  223948. lseek (f, 0, SEEK_END);
  223949. return (void*) f;
  223950. }
  223951. else
  223952. {
  223953. flags = O_RDWR + O_CREAT;
  223954. }
  223955. }
  223956. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  223957. }
  223958. void juce_fileClose (void* handle)
  223959. {
  223960. if (handle != 0)
  223961. close ((int) (pointer_sized_int) handle);
  223962. }
  223963. int juce_fileRead (void* handle, void* buffer, int size)
  223964. {
  223965. if (handle != 0)
  223966. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  223967. return 0;
  223968. }
  223969. int juce_fileWrite (void* handle, const void* buffer, int size)
  223970. {
  223971. if (handle != 0)
  223972. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  223973. return 0;
  223974. }
  223975. int64 juce_fileSetPosition (void* handle, int64 pos)
  223976. {
  223977. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  223978. return pos;
  223979. return -1;
  223980. }
  223981. int64 FileOutputStream::getPositionInternal() const
  223982. {
  223983. if (fileHandle != 0)
  223984. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  223985. return -1;
  223986. }
  223987. void FileOutputStream::flushInternal()
  223988. {
  223989. if (fileHandle != 0)
  223990. fsync ((int) (pointer_sized_int) fileHandle);
  223991. }
  223992. const File juce_getExecutableFile()
  223993. {
  223994. Dl_info exeInfo;
  223995. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  223996. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  223997. }
  223998. // if this file doesn't exist, find a parent of it that does..
  223999. static bool juce_doStatFS (File f, struct statfs& result)
  224000. {
  224001. for (int i = 5; --i >= 0;)
  224002. {
  224003. if (f.exists())
  224004. break;
  224005. f = f.getParentDirectory();
  224006. }
  224007. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224008. }
  224009. int64 File::getBytesFreeOnVolume() const
  224010. {
  224011. struct statfs buf;
  224012. if (juce_doStatFS (*this, buf))
  224013. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224014. return 0;
  224015. }
  224016. int64 File::getVolumeTotalSize() const
  224017. {
  224018. struct statfs buf;
  224019. if (juce_doStatFS (*this, buf))
  224020. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224021. return 0;
  224022. }
  224023. const String File::getVolumeLabel() const
  224024. {
  224025. #if JUCE_MAC
  224026. struct VolAttrBuf
  224027. {
  224028. u_int32_t length;
  224029. attrreference_t mountPointRef;
  224030. char mountPointSpace [MAXPATHLEN];
  224031. } attrBuf;
  224032. struct attrlist attrList;
  224033. zerostruct (attrList);
  224034. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224035. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224036. File f (*this);
  224037. for (;;)
  224038. {
  224039. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224040. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224041. (int) attrBuf.mountPointRef.attr_length);
  224042. const File parent (f.getParentDirectory());
  224043. if (f == parent)
  224044. break;
  224045. f = parent;
  224046. }
  224047. #endif
  224048. return String::empty;
  224049. }
  224050. int File::getVolumeSerialNumber() const
  224051. {
  224052. return 0; // xxx
  224053. }
  224054. void juce_runSystemCommand (const String& command)
  224055. {
  224056. int result = system (command.toUTF8());
  224057. (void) result;
  224058. }
  224059. const String juce_getOutputFromCommand (const String& command)
  224060. {
  224061. // slight bodge here, as we just pipe the output into a temp file and read it...
  224062. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224063. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224064. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224065. String result (tempFile.loadFileAsString());
  224066. tempFile.deleteFile();
  224067. return result;
  224068. }
  224069. class InterProcessLock::Pimpl
  224070. {
  224071. public:
  224072. Pimpl (const String& name, const int timeOutMillisecs)
  224073. : handle (0), refCount (1)
  224074. {
  224075. #if JUCE_MAC
  224076. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224077. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224078. #else
  224079. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224080. #endif
  224081. temp.create();
  224082. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224083. if (handle != 0)
  224084. {
  224085. struct flock fl;
  224086. zerostruct (fl);
  224087. fl.l_whence = SEEK_SET;
  224088. fl.l_type = F_WRLCK;
  224089. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224090. for (;;)
  224091. {
  224092. const int result = fcntl (handle, F_SETLK, &fl);
  224093. if (result >= 0)
  224094. return;
  224095. if (errno != EINTR)
  224096. {
  224097. if (timeOutMillisecs == 0
  224098. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224099. break;
  224100. Thread::sleep (10);
  224101. }
  224102. }
  224103. }
  224104. closeFile();
  224105. }
  224106. ~Pimpl()
  224107. {
  224108. closeFile();
  224109. }
  224110. void closeFile()
  224111. {
  224112. if (handle != 0)
  224113. {
  224114. struct flock fl;
  224115. zerostruct (fl);
  224116. fl.l_whence = SEEK_SET;
  224117. fl.l_type = F_UNLCK;
  224118. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224119. {}
  224120. close (handle);
  224121. handle = 0;
  224122. }
  224123. }
  224124. int handle, refCount;
  224125. };
  224126. InterProcessLock::InterProcessLock (const String& name_)
  224127. : name (name_)
  224128. {
  224129. }
  224130. InterProcessLock::~InterProcessLock()
  224131. {
  224132. }
  224133. bool InterProcessLock::enter (const int timeOutMillisecs)
  224134. {
  224135. const ScopedLock sl (lock);
  224136. if (pimpl == 0)
  224137. {
  224138. pimpl = new Pimpl (name, timeOutMillisecs);
  224139. if (pimpl->handle == 0)
  224140. pimpl = 0;
  224141. }
  224142. else
  224143. {
  224144. pimpl->refCount++;
  224145. }
  224146. return pimpl != 0;
  224147. }
  224148. void InterProcessLock::exit()
  224149. {
  224150. const ScopedLock sl (lock);
  224151. // Trying to release the lock too many times!
  224152. jassert (pimpl != 0);
  224153. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224154. pimpl = 0;
  224155. }
  224156. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224157. /*** Start of inlined file: juce_mac_Files.mm ***/
  224158. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224159. // compiled on its own).
  224160. #if JUCE_INCLUDED_FILE
  224161. /*
  224162. Note that a lot of methods that you'd expect to find in this file actually
  224163. live in juce_posix_SharedCode.h!
  224164. */
  224165. bool File::copyInternal (const File& dest) const
  224166. {
  224167. const ScopedAutoReleasePool pool;
  224168. NSFileManager* fm = [NSFileManager defaultManager];
  224169. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224170. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224171. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224172. toPath: juceStringToNS (dest.getFullPathName())
  224173. error: nil];
  224174. #else
  224175. && [fm copyPath: juceStringToNS (fullPath)
  224176. toPath: juceStringToNS (dest.getFullPathName())
  224177. handler: nil];
  224178. #endif
  224179. }
  224180. void File::findFileSystemRoots (Array<File>& destArray)
  224181. {
  224182. destArray.add (File ("/"));
  224183. }
  224184. static bool isFileOnDriveType (const File& f, const char* const* types)
  224185. {
  224186. struct statfs buf;
  224187. if (juce_doStatFS (f, buf))
  224188. {
  224189. const String type (buf.f_fstypename);
  224190. while (*types != 0)
  224191. if (type.equalsIgnoreCase (*types++))
  224192. return true;
  224193. }
  224194. return false;
  224195. }
  224196. bool File::isOnCDRomDrive() const
  224197. {
  224198. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224199. return isFileOnDriveType (*this, cdTypes);
  224200. }
  224201. bool File::isOnHardDisk() const
  224202. {
  224203. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224204. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  224205. }
  224206. bool File::isOnRemovableDrive() const
  224207. {
  224208. #if JUCE_IOS
  224209. return false; // xxx is this possible?
  224210. #else
  224211. const ScopedAutoReleasePool pool;
  224212. BOOL removable = false;
  224213. [[NSWorkspace sharedWorkspace]
  224214. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224215. isRemovable: &removable
  224216. isWritable: nil
  224217. isUnmountable: nil
  224218. description: nil
  224219. type: nil];
  224220. return removable;
  224221. #endif
  224222. }
  224223. static bool juce_isHiddenFile (const String& path)
  224224. {
  224225. #if JUCE_IOS
  224226. return File (path).getFileName().startsWithChar ('.');
  224227. #else
  224228. FSRef ref;
  224229. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  224230. return false;
  224231. FSCatalogInfo info;
  224232. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  224233. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  224234. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224235. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224236. #endif
  224237. }
  224238. bool File::isHidden() const
  224239. {
  224240. return juce_isHiddenFile (getFullPathName());
  224241. }
  224242. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224243. const File File::getSpecialLocation (const SpecialLocationType type)
  224244. {
  224245. const ScopedAutoReleasePool pool;
  224246. String resultPath;
  224247. switch (type)
  224248. {
  224249. case userHomeDirectory:
  224250. resultPath = nsStringToJuce (NSHomeDirectory());
  224251. break;
  224252. case userDocumentsDirectory:
  224253. resultPath = "~/Documents";
  224254. break;
  224255. case userDesktopDirectory:
  224256. resultPath = "~/Desktop";
  224257. break;
  224258. case userApplicationDataDirectory:
  224259. resultPath = "~/Library";
  224260. break;
  224261. case commonApplicationDataDirectory:
  224262. resultPath = "/Library";
  224263. break;
  224264. case globalApplicationsDirectory:
  224265. resultPath = "/Applications";
  224266. break;
  224267. case userMusicDirectory:
  224268. resultPath = "~/Music";
  224269. break;
  224270. case userMoviesDirectory:
  224271. resultPath = "~/Movies";
  224272. break;
  224273. case tempDirectory:
  224274. {
  224275. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224276. tmp.createDirectory();
  224277. return tmp.getFullPathName();
  224278. }
  224279. case invokedExecutableFile:
  224280. if (juce_Argv0 != 0)
  224281. return File (String::fromUTF8 (juce_Argv0));
  224282. // deliberate fall-through...
  224283. case currentExecutableFile:
  224284. return juce_getExecutableFile();
  224285. case currentApplicationFile:
  224286. {
  224287. const File exe (juce_getExecutableFile());
  224288. const File parent (exe.getParentDirectory());
  224289. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224290. ? parent.getParentDirectory().getParentDirectory()
  224291. : exe;
  224292. }
  224293. default:
  224294. jassertfalse; // unknown type?
  224295. break;
  224296. }
  224297. if (resultPath.isNotEmpty())
  224298. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224299. return File::nonexistent;
  224300. }
  224301. const String File::getVersion() const
  224302. {
  224303. const ScopedAutoReleasePool pool;
  224304. String result;
  224305. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224306. if (bundle != 0)
  224307. {
  224308. NSDictionary* info = [bundle infoDictionary];
  224309. if (info != 0)
  224310. {
  224311. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224312. if (name != nil)
  224313. result = nsStringToJuce (name);
  224314. }
  224315. }
  224316. return result;
  224317. }
  224318. const File File::getLinkedTarget() const
  224319. {
  224320. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224321. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224322. #else
  224323. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224324. #endif
  224325. if (dest != nil)
  224326. return File (nsStringToJuce (dest));
  224327. return *this;
  224328. }
  224329. bool File::moveToTrash() const
  224330. {
  224331. if (! exists())
  224332. return true;
  224333. #if JUCE_IOS
  224334. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224335. #else
  224336. const ScopedAutoReleasePool pool;
  224337. NSString* p = juceStringToNS (getFullPathName());
  224338. return [[NSWorkspace sharedWorkspace]
  224339. performFileOperation: NSWorkspaceRecycleOperation
  224340. source: [p stringByDeletingLastPathComponent]
  224341. destination: @""
  224342. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224343. tag: nil ];
  224344. #endif
  224345. }
  224346. class DirectoryIterator::NativeIterator::Pimpl
  224347. {
  224348. public:
  224349. Pimpl (const File& directory, const String& wildCard_)
  224350. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224351. wildCard (wildCard_),
  224352. enumerator (0)
  224353. {
  224354. ScopedAutoReleasePool pool;
  224355. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224356. wildcardUTF8 = wildCard.toUTF8();
  224357. }
  224358. ~Pimpl()
  224359. {
  224360. [enumerator release];
  224361. }
  224362. bool next (String& filenameFound,
  224363. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224364. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224365. {
  224366. ScopedAutoReleasePool pool;
  224367. for (;;)
  224368. {
  224369. NSString* file;
  224370. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224371. return false;
  224372. [enumerator skipDescendents];
  224373. filenameFound = nsStringToJuce (file);
  224374. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224375. continue;
  224376. const String path (parentDir + filenameFound);
  224377. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224378. {
  224379. struct stat info;
  224380. const bool statOk = juce_stat (path, info);
  224381. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224382. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224383. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  224384. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  224385. }
  224386. if (isHidden != 0)
  224387. *isHidden = juce_isHiddenFile (path);
  224388. if (isReadOnly != 0)
  224389. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224390. return true;
  224391. }
  224392. }
  224393. private:
  224394. String parentDir, wildCard;
  224395. const char* wildcardUTF8;
  224396. NSDirectoryEnumerator* enumerator;
  224397. Pimpl (const Pimpl&);
  224398. Pimpl& operator= (const Pimpl&);
  224399. };
  224400. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224401. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224402. {
  224403. }
  224404. DirectoryIterator::NativeIterator::~NativeIterator()
  224405. {
  224406. }
  224407. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224408. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224409. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224410. {
  224411. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224412. }
  224413. bool juce_launchExecutable (const String& pathAndArguments)
  224414. {
  224415. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224416. const int cpid = fork();
  224417. if (cpid == 0)
  224418. {
  224419. // Child process
  224420. if (execve (argv[0], (char**) argv, 0) < 0)
  224421. exit (0);
  224422. }
  224423. else
  224424. {
  224425. if (cpid < 0)
  224426. return false;
  224427. }
  224428. return true;
  224429. }
  224430. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224431. {
  224432. #if JUCE_IOS
  224433. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224434. #else
  224435. const ScopedAutoReleasePool pool;
  224436. if (parameters.isEmpty())
  224437. {
  224438. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224439. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224440. }
  224441. bool ok = false;
  224442. FSRef ref;
  224443. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  224444. {
  224445. if (PlatformUtilities::isBundle (fileName))
  224446. {
  224447. NSMutableArray* urls = [NSMutableArray array];
  224448. StringArray docs;
  224449. docs.addTokens (parameters, true);
  224450. for (int i = 0; i < docs.size(); ++i)
  224451. [urls addObject: juceStringToNS (docs[i])];
  224452. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224453. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224454. options: 0
  224455. additionalEventParamDescriptor: nil
  224456. launchIdentifiers: nil];
  224457. }
  224458. else
  224459. {
  224460. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  224461. }
  224462. }
  224463. return ok;
  224464. #endif
  224465. }
  224466. void File::revealToUser() const
  224467. {
  224468. #if ! JUCE_IOS
  224469. if (exists())
  224470. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224471. else if (getParentDirectory().exists())
  224472. getParentDirectory().revealToUser();
  224473. #endif
  224474. }
  224475. #if ! JUCE_IOS
  224476. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224477. {
  224478. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  224479. }
  224480. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224481. {
  224482. char path [2048];
  224483. zerostruct (path);
  224484. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224485. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224486. return String::empty;
  224487. }
  224488. #endif
  224489. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224490. {
  224491. const ScopedAutoReleasePool pool;
  224492. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224493. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  224494. #else
  224495. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  224496. #endif
  224497. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  224498. return [fileDict fileHFSTypeCode];
  224499. }
  224500. bool PlatformUtilities::isBundle (const String& filename)
  224501. {
  224502. #if JUCE_IOS
  224503. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  224504. #else
  224505. const ScopedAutoReleasePool pool;
  224506. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224507. #endif
  224508. }
  224509. #endif
  224510. /*** End of inlined file: juce_mac_Files.mm ***/
  224511. #if JUCE_IOS
  224512. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  224513. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224514. // compiled on its own).
  224515. #if JUCE_INCLUDED_FILE
  224516. END_JUCE_NAMESPACE
  224517. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  224518. {
  224519. }
  224520. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  224521. - (void) applicationWillTerminate: (UIApplication*) application;
  224522. @end
  224523. @implementation JuceAppStartupDelegate
  224524. - (void) applicationDidFinishLaunching: (UIApplication*) application
  224525. {
  224526. String dummy;
  224527. if (! JUCEApplication::getInstance()->initialiseApp (dummy))
  224528. exit (0);
  224529. }
  224530. - (void) applicationWillTerminate: (UIApplication*) application
  224531. {
  224532. JUCEApplication::getInstance()->shutdownApp();
  224533. // need to do this stuff because the OS kills the process before our scope-based cleanup code gets executed..
  224534. delete JUCEApplication::getInstance();
  224535. shutdownJuce_GUI();
  224536. }
  224537. @end
  224538. BEGIN_JUCE_NAMESPACE
  224539. int juce_iOSMain (int argc, const char* argv[])
  224540. {
  224541. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  224542. }
  224543. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224544. {
  224545. pool = [[NSAutoreleasePool alloc] init];
  224546. }
  224547. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224548. {
  224549. [((NSAutoreleasePool*) pool) release];
  224550. }
  224551. void PlatformUtilities::beep()
  224552. {
  224553. //xxx
  224554. //AudioServicesPlaySystemSound ();
  224555. }
  224556. void PlatformUtilities::addItemToDock (const File& file)
  224557. {
  224558. }
  224559. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224560. END_JUCE_NAMESPACE
  224561. @interface JuceAlertBoxDelegate : NSObject
  224562. {
  224563. @public
  224564. bool clickedOk;
  224565. }
  224566. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  224567. @end
  224568. @implementation JuceAlertBoxDelegate
  224569. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  224570. {
  224571. clickedOk = (buttonIndex == 0);
  224572. alertView.hidden = true;
  224573. }
  224574. @end
  224575. BEGIN_JUCE_NAMESPACE
  224576. // (This function is used directly by other bits of code)
  224577. bool juce_iPhoneShowModalAlert (const String& title,
  224578. const String& bodyText,
  224579. NSString* okButtonText,
  224580. NSString* cancelButtonText)
  224581. {
  224582. const ScopedAutoReleasePool pool;
  224583. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  224584. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  224585. message: juceStringToNS (bodyText)
  224586. delegate: callback
  224587. cancelButtonTitle: okButtonText
  224588. otherButtonTitles: cancelButtonText, nil];
  224589. [alert retain];
  224590. [alert show];
  224591. while (! alert.hidden && alert.superview != nil)
  224592. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224593. const bool result = callback->clickedOk;
  224594. [alert release];
  224595. [callback release];
  224596. return result;
  224597. }
  224598. bool AlertWindow::showNativeDialogBox (const String& title,
  224599. const String& bodyText,
  224600. bool isOkCancel)
  224601. {
  224602. return juce_iPhoneShowModalAlert (title, bodyText,
  224603. @"OK",
  224604. isOkCancel ? @"Cancel" : nil);
  224605. }
  224606. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224607. {
  224608. jassertfalse; // no such thing on the iphone!
  224609. return false;
  224610. }
  224611. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224612. {
  224613. jassertfalse; // no such thing on the iphone!
  224614. return false;
  224615. }
  224616. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224617. {
  224618. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  224619. }
  224620. bool Desktop::isScreenSaverEnabled()
  224621. {
  224622. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  224623. }
  224624. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  224625. {
  224626. const ScopedAutoReleasePool pool;
  224627. monitorCoords.clear();
  224628. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  224629. : [[UIScreen mainScreen] bounds];
  224630. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224631. (int) r.origin.y,
  224632. (int) r.size.width,
  224633. (int) r.size.height));
  224634. }
  224635. #endif
  224636. #endif
  224637. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  224638. #else
  224639. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  224640. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224641. // compiled on its own).
  224642. #if JUCE_INCLUDED_FILE
  224643. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224644. {
  224645. pool = [[NSAutoreleasePool alloc] init];
  224646. }
  224647. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224648. {
  224649. [((NSAutoreleasePool*) pool) release];
  224650. }
  224651. void PlatformUtilities::beep()
  224652. {
  224653. NSBeep();
  224654. }
  224655. void PlatformUtilities::addItemToDock (const File& file)
  224656. {
  224657. // check that it's not already there...
  224658. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  224659. .containsIgnoreCase (file.getFullPathName()))
  224660. {
  224661. 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>"
  224662. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  224663. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  224664. }
  224665. }
  224666. int PlatformUtilities::getOSXMinorVersionNumber()
  224667. {
  224668. SInt32 versionMinor = 0;
  224669. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224670. (void) err;
  224671. jassert (err == noErr);
  224672. return (int) versionMinor;
  224673. }
  224674. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224675. bool AlertWindow::showNativeDialogBox (const String& title,
  224676. const String& bodyText,
  224677. bool isOkCancel)
  224678. {
  224679. const ScopedAutoReleasePool pool;
  224680. return NSRunAlertPanel (juceStringToNS (title),
  224681. juceStringToNS (bodyText),
  224682. @"Ok",
  224683. isOkCancel ? @"Cancel" : nil,
  224684. nil) == NSAlertDefaultReturn;
  224685. }
  224686. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  224687. {
  224688. if (files.size() == 0)
  224689. return false;
  224690. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  224691. if (draggingSource == 0)
  224692. {
  224693. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224694. return false;
  224695. }
  224696. Component* sourceComp = draggingSource->getComponentUnderMouse();
  224697. if (sourceComp == 0)
  224698. {
  224699. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224700. return false;
  224701. }
  224702. const ScopedAutoReleasePool pool;
  224703. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224704. if (view == 0)
  224705. return false;
  224706. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224707. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224708. owner: nil];
  224709. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224710. for (int i = 0; i < files.size(); ++i)
  224711. [filesArray addObject: juceStringToNS (files[i])];
  224712. [pboard setPropertyList: filesArray
  224713. forType: NSFilenamesPboardType];
  224714. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224715. fromView: nil];
  224716. dragPosition.x -= 16;
  224717. dragPosition.y -= 16;
  224718. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224719. at: dragPosition
  224720. offset: NSMakeSize (0, 0)
  224721. event: [[view window] currentEvent]
  224722. pasteboard: pboard
  224723. source: view
  224724. slideBack: YES];
  224725. return true;
  224726. }
  224727. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  224728. {
  224729. jassertfalse; // not implemented!
  224730. return false;
  224731. }
  224732. bool Desktop::canUseSemiTransparentWindows() throw()
  224733. {
  224734. return true;
  224735. }
  224736. const Point<int> Desktop::getMousePosition()
  224737. {
  224738. const ScopedAutoReleasePool pool;
  224739. const NSPoint p ([NSEvent mouseLocation]);
  224740. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  224741. }
  224742. void Desktop::setMousePosition (const Point<int>& newPosition)
  224743. {
  224744. // this rubbish needs to be done around the warp call, to avoid causing a
  224745. // bizarre glitch..
  224746. CGAssociateMouseAndMouseCursorPosition (false);
  224747. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  224748. CGAssociateMouseAndMouseCursorPosition (true);
  224749. }
  224750. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224751. class ScreenSaverDefeater : public Timer,
  224752. public DeletedAtShutdown
  224753. {
  224754. public:
  224755. ScreenSaverDefeater()
  224756. {
  224757. startTimer (10000);
  224758. timerCallback();
  224759. }
  224760. ~ScreenSaverDefeater() {}
  224761. void timerCallback()
  224762. {
  224763. if (Process::isForegroundProcess())
  224764. UpdateSystemActivity (UsrActivity);
  224765. }
  224766. };
  224767. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224768. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224769. {
  224770. if (isEnabled)
  224771. deleteAndZero (screenSaverDefeater);
  224772. else if (screenSaverDefeater == 0)
  224773. screenSaverDefeater = new ScreenSaverDefeater();
  224774. }
  224775. bool Desktop::isScreenSaverEnabled()
  224776. {
  224777. return screenSaverDefeater == 0;
  224778. }
  224779. #else
  224780. static IOPMAssertionID screenSaverDisablerID = 0;
  224781. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224782. {
  224783. if (isEnabled)
  224784. {
  224785. if (screenSaverDisablerID != 0)
  224786. {
  224787. IOPMAssertionRelease (screenSaverDisablerID);
  224788. screenSaverDisablerID = 0;
  224789. }
  224790. }
  224791. else
  224792. {
  224793. if (screenSaverDisablerID == 0)
  224794. {
  224795. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224796. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224797. CFSTR ("Juce"), &screenSaverDisablerID);
  224798. #else
  224799. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224800. &screenSaverDisablerID);
  224801. #endif
  224802. }
  224803. }
  224804. }
  224805. bool Desktop::isScreenSaverEnabled()
  224806. {
  224807. return screenSaverDisablerID == 0;
  224808. }
  224809. #endif
  224810. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  224811. {
  224812. const ScopedAutoReleasePool pool;
  224813. monitorCoords.clear();
  224814. NSArray* screens = [NSScreen screens];
  224815. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  224816. for (unsigned int i = 0; i < [screens count]; ++i)
  224817. {
  224818. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224819. NSRect r = clipToWorkArea ? [s visibleFrame]
  224820. : [s frame];
  224821. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224822. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224823. (int) r.size.width,
  224824. (int) r.size.height));
  224825. }
  224826. jassert (monitorCoords.size() > 0);
  224827. }
  224828. #endif
  224829. #endif
  224830. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  224831. #endif
  224832. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  224833. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224834. // compiled on its own).
  224835. #if JUCE_INCLUDED_FILE
  224836. void Logger::outputDebugString (const String& text)
  224837. {
  224838. std::cerr << text << std::endl;
  224839. }
  224840. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  224841. {
  224842. static char testResult = 0;
  224843. if (testResult == 0)
  224844. {
  224845. struct kinfo_proc info;
  224846. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224847. size_t sz = sizeof (info);
  224848. sysctl (m, 4, &info, &sz, 0, 0);
  224849. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224850. }
  224851. return testResult > 0;
  224852. }
  224853. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  224854. {
  224855. return juce_isRunningUnderDebugger();
  224856. }
  224857. #endif
  224858. /*** End of inlined file: juce_mac_Debugging.mm ***/
  224859. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224860. #if JUCE_IOS
  224861. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  224862. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224863. // compiled on its own).
  224864. #if JUCE_INCLUDED_FILE
  224865. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224866. #define SUPPORT_10_4_FONTS 1
  224867. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  224868. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224869. #define SUPPORT_ONLY_10_4_FONTS 1
  224870. #endif
  224871. END_JUCE_NAMESPACE
  224872. @interface NSFont (PrivateHack)
  224873. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  224874. @end
  224875. BEGIN_JUCE_NAMESPACE
  224876. #endif
  224877. class MacTypeface : public Typeface
  224878. {
  224879. public:
  224880. MacTypeface (const Font& font)
  224881. : Typeface (font.getTypefaceName())
  224882. {
  224883. const ScopedAutoReleasePool pool;
  224884. renderingTransform = CGAffineTransformIdentity;
  224885. bool needsItalicTransform = false;
  224886. #if JUCE_IOS
  224887. NSString* fontName = juceStringToNS (font.getTypefaceName());
  224888. if (font.isItalic() || font.isBold())
  224889. {
  224890. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  224891. for (NSString* i in familyFonts)
  224892. {
  224893. const String fn (nsStringToJuce (i));
  224894. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  224895. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  224896. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  224897. || afterDash.containsIgnoreCase ("italic")
  224898. || fn.endsWithIgnoreCase ("oblique")
  224899. || fn.endsWithIgnoreCase ("italic");
  224900. if (probablyBold == font.isBold()
  224901. && probablyItalic == font.isItalic())
  224902. {
  224903. fontName = i;
  224904. needsItalicTransform = false;
  224905. break;
  224906. }
  224907. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  224908. {
  224909. fontName = i;
  224910. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  224911. }
  224912. }
  224913. if (needsItalicTransform)
  224914. renderingTransform.c = 0.15f;
  224915. }
  224916. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  224917. const int ascender = abs (CGFontGetAscent (fontRef));
  224918. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  224919. ascent = ascender / totalHeight;
  224920. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224921. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  224922. #else
  224923. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  224924. if (font.isItalic())
  224925. {
  224926. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  224927. toHaveTrait: NSItalicFontMask];
  224928. if (newFont == nsFont)
  224929. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  224930. nsFont = newFont;
  224931. }
  224932. if (font.isBold())
  224933. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  224934. [nsFont retain];
  224935. ascent = std::abs ((float) [nsFont ascender]);
  224936. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  224937. ascent /= totalSize;
  224938. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  224939. if (needsItalicTransform)
  224940. {
  224941. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  224942. renderingTransform.c = 0.15f;
  224943. }
  224944. #if SUPPORT_ONLY_10_4_FONTS
  224945. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224946. if (atsFont == 0)
  224947. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224948. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224949. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224950. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224951. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224952. #else
  224953. #if SUPPORT_10_4_FONTS
  224954. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224955. {
  224956. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224957. if (atsFont == 0)
  224958. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224959. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224960. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224961. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224962. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224963. }
  224964. else
  224965. #endif
  224966. {
  224967. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  224968. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  224969. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224970. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  224971. }
  224972. #endif
  224973. #endif
  224974. }
  224975. ~MacTypeface()
  224976. {
  224977. #if ! JUCE_IOS
  224978. [nsFont release];
  224979. #endif
  224980. if (fontRef != 0)
  224981. CGFontRelease (fontRef);
  224982. }
  224983. float getAscent() const
  224984. {
  224985. return ascent;
  224986. }
  224987. float getDescent() const
  224988. {
  224989. return 1.0f - ascent;
  224990. }
  224991. float getStringWidth (const String& text)
  224992. {
  224993. if (fontRef == 0 || text.isEmpty())
  224994. return 0;
  224995. const int length = text.length();
  224996. HeapBlock <CGGlyph> glyphs;
  224997. createGlyphsForString (text, length, glyphs);
  224998. float x = 0;
  224999. #if SUPPORT_ONLY_10_4_FONTS
  225000. HeapBlock <NSSize> advances (length);
  225001. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225002. for (int i = 0; i < length; ++i)
  225003. x += advances[i].width;
  225004. #else
  225005. #if SUPPORT_10_4_FONTS
  225006. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225007. {
  225008. HeapBlock <NSSize> advances (length);
  225009. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225010. for (int i = 0; i < length; ++i)
  225011. x += advances[i].width;
  225012. }
  225013. else
  225014. #endif
  225015. {
  225016. HeapBlock <int> advances (length);
  225017. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225018. for (int i = 0; i < length; ++i)
  225019. x += advances[i];
  225020. }
  225021. #endif
  225022. return x * unitsToHeightScaleFactor;
  225023. }
  225024. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225025. {
  225026. xOffsets.add (0);
  225027. if (fontRef == 0 || text.isEmpty())
  225028. return;
  225029. const int length = text.length();
  225030. HeapBlock <CGGlyph> glyphs;
  225031. createGlyphsForString (text, length, glyphs);
  225032. #if SUPPORT_ONLY_10_4_FONTS
  225033. HeapBlock <NSSize> advances (length);
  225034. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225035. int x = 0;
  225036. for (int i = 0; i < length; ++i)
  225037. {
  225038. x += advances[i].width;
  225039. xOffsets.add (x * unitsToHeightScaleFactor);
  225040. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225041. }
  225042. #else
  225043. #if SUPPORT_10_4_FONTS
  225044. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225045. {
  225046. HeapBlock <NSSize> advances (length);
  225047. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225048. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225049. float x = 0;
  225050. for (int i = 0; i < length; ++i)
  225051. {
  225052. x += advances[i].width;
  225053. xOffsets.add (x * unitsToHeightScaleFactor);
  225054. resultGlyphs.add (nsGlyphs[i]);
  225055. }
  225056. }
  225057. else
  225058. #endif
  225059. {
  225060. HeapBlock <int> advances (length);
  225061. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225062. {
  225063. int x = 0;
  225064. for (int i = 0; i < length; ++i)
  225065. {
  225066. x += advances [i];
  225067. xOffsets.add (x * unitsToHeightScaleFactor);
  225068. resultGlyphs.add (glyphs[i]);
  225069. }
  225070. }
  225071. }
  225072. #endif
  225073. }
  225074. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225075. {
  225076. #if JUCE_IOS
  225077. return false;
  225078. #else
  225079. if (nsFont == 0)
  225080. return false;
  225081. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225082. jassert (path.isEmpty());
  225083. const ScopedAutoReleasePool pool;
  225084. NSBezierPath* bez = [NSBezierPath bezierPath];
  225085. [bez moveToPoint: NSMakePoint (0, 0)];
  225086. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225087. inFont: nsFont];
  225088. for (int i = 0; i < [bez elementCount]; ++i)
  225089. {
  225090. NSPoint p[3];
  225091. switch ([bez elementAtIndex: i associatedPoints: p])
  225092. {
  225093. case NSMoveToBezierPathElement:
  225094. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  225095. break;
  225096. case NSLineToBezierPathElement:
  225097. path.lineTo ((float) p[0].x, (float) -p[0].y);
  225098. break;
  225099. case NSCurveToBezierPathElement:
  225100. 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);
  225101. break;
  225102. case NSClosePathBezierPathElement:
  225103. path.closeSubPath();
  225104. break;
  225105. default:
  225106. jassertfalse;
  225107. break;
  225108. }
  225109. }
  225110. path.applyTransform (pathTransform);
  225111. return true;
  225112. #endif
  225113. }
  225114. juce_UseDebuggingNewOperator
  225115. CGFontRef fontRef;
  225116. float fontHeightToCGSizeFactor;
  225117. CGAffineTransform renderingTransform;
  225118. private:
  225119. float ascent, unitsToHeightScaleFactor;
  225120. #if JUCE_IOS
  225121. #else
  225122. NSFont* nsFont;
  225123. AffineTransform pathTransform;
  225124. #endif
  225125. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  225126. {
  225127. #if SUPPORT_10_4_FONTS
  225128. #if ! SUPPORT_ONLY_10_4_FONTS
  225129. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225130. #endif
  225131. {
  225132. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225133. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225134. for (int i = 0; i < length; ++i)
  225135. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  225136. return;
  225137. }
  225138. #endif
  225139. #if ! SUPPORT_ONLY_10_4_FONTS
  225140. if (charToGlyphMapper == 0)
  225141. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225142. glyphs.malloc (length);
  225143. for (int i = 0; i < length; ++i)
  225144. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  225145. #endif
  225146. }
  225147. #if ! SUPPORT_ONLY_10_4_FONTS
  225148. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225149. class CharToGlyphMapper
  225150. {
  225151. public:
  225152. CharToGlyphMapper (CGFontRef fontRef)
  225153. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225154. idRangeOffset (0), glyphIndexes (0)
  225155. {
  225156. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225157. if (cmapTable != 0)
  225158. {
  225159. const int numSubtables = getValue16 (cmapTable, 2);
  225160. for (int i = 0; i < numSubtables; ++i)
  225161. {
  225162. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225163. {
  225164. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225165. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225166. {
  225167. const int length = getValue16 (cmapTable, offset + 2);
  225168. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225169. segCount = segCountX2 / 2;
  225170. const int endCodeOffset = offset + 14;
  225171. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225172. const int idDeltaOffset = startCodeOffset + segCountX2;
  225173. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225174. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225175. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225176. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225177. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225178. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225179. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225180. }
  225181. break;
  225182. }
  225183. }
  225184. CFRelease (cmapTable);
  225185. }
  225186. }
  225187. ~CharToGlyphMapper()
  225188. {
  225189. if (endCode != 0)
  225190. {
  225191. CFRelease (endCode);
  225192. CFRelease (startCode);
  225193. CFRelease (idDelta);
  225194. CFRelease (idRangeOffset);
  225195. CFRelease (glyphIndexes);
  225196. }
  225197. }
  225198. int getGlyphForCharacter (const juce_wchar c) const
  225199. {
  225200. for (int i = 0; i < segCount; ++i)
  225201. {
  225202. if (getValue16 (endCode, i * 2) >= c)
  225203. {
  225204. const int start = getValue16 (startCode, i * 2);
  225205. if (start > c)
  225206. break;
  225207. const int delta = getValue16 (idDelta, i * 2);
  225208. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225209. if (rangeOffset == 0)
  225210. return delta + c;
  225211. else
  225212. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225213. }
  225214. }
  225215. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225216. return jmax (-1, c - 29);
  225217. }
  225218. private:
  225219. int segCount;
  225220. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225221. static uint16 getValue16 (CFDataRef data, const int index)
  225222. {
  225223. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225224. }
  225225. static uint32 getValue32 (CFDataRef data, const int index)
  225226. {
  225227. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225228. }
  225229. };
  225230. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225231. #endif
  225232. MacTypeface (const MacTypeface&);
  225233. MacTypeface& operator= (const MacTypeface&);
  225234. };
  225235. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225236. {
  225237. return new MacTypeface (font);
  225238. }
  225239. const StringArray Font::findAllTypefaceNames()
  225240. {
  225241. StringArray names;
  225242. const ScopedAutoReleasePool pool;
  225243. #if JUCE_IOS
  225244. NSArray* fonts = [UIFont familyNames];
  225245. #else
  225246. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225247. #endif
  225248. for (unsigned int i = 0; i < [fonts count]; ++i)
  225249. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225250. names.sort (true);
  225251. return names;
  225252. }
  225253. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  225254. {
  225255. #if JUCE_IOS
  225256. defaultSans = "Helvetica";
  225257. defaultSerif = "Times New Roman";
  225258. defaultFixed = "Courier New";
  225259. #else
  225260. defaultSans = "Lucida Grande";
  225261. defaultSerif = "Times New Roman";
  225262. defaultFixed = "Monaco";
  225263. #endif
  225264. }
  225265. #endif
  225266. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225267. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225268. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225269. // compiled on its own).
  225270. #if JUCE_INCLUDED_FILE
  225271. class CoreGraphicsImage : public Image::SharedImage
  225272. {
  225273. public:
  225274. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225275. : Image::SharedImage (format_, width_, height_)
  225276. {
  225277. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225278. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225279. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225280. imageData = imageDataAllocated;
  225281. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225282. : CGColorSpaceCreateDeviceRGB();
  225283. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225284. colourSpace, getCGImageFlags (format_));
  225285. CGColorSpaceRelease (colourSpace);
  225286. }
  225287. ~CoreGraphicsImage()
  225288. {
  225289. CGContextRelease (context);
  225290. }
  225291. Image::ImageType getType() const { return Image::NativeImage; }
  225292. LowLevelGraphicsContext* createLowLevelContext();
  225293. SharedImage* clone()
  225294. {
  225295. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225296. memcpy (im->imageData, imageData, lineStride * height);
  225297. return im;
  225298. }
  225299. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  225300. {
  225301. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225302. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225303. {
  225304. return CGBitmapContextCreateImage (nativeImage->context);
  225305. }
  225306. else
  225307. {
  225308. const Image::BitmapData srcData (juceImage, false);
  225309. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225310. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225311. 8, srcData.pixelStride * 8, srcData.lineStride,
  225312. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225313. 0, true, kCGRenderingIntentDefault);
  225314. CGDataProviderRelease (provider);
  225315. return imageRef;
  225316. }
  225317. }
  225318. #if JUCE_MAC
  225319. static NSImage* createNSImage (const Image& image)
  225320. {
  225321. const ScopedAutoReleasePool pool;
  225322. NSImage* im = [[NSImage alloc] init];
  225323. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225324. [im lockFocus];
  225325. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225326. CGImageRef imageRef = createImage (image, false, colourSpace);
  225327. CGColorSpaceRelease (colourSpace);
  225328. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225329. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225330. CGImageRelease (imageRef);
  225331. [im unlockFocus];
  225332. return im;
  225333. }
  225334. #endif
  225335. CGContextRef context;
  225336. HeapBlock<uint8> imageDataAllocated;
  225337. private:
  225338. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225339. {
  225340. #if JUCE_BIG_ENDIAN
  225341. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225342. #else
  225343. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225344. #endif
  225345. }
  225346. };
  225347. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225348. {
  225349. #if USE_COREGRAPHICS_RENDERING
  225350. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225351. #else
  225352. return createSoftwareImage (format, width, height, clearImage);
  225353. #endif
  225354. }
  225355. class CoreGraphicsContext : public LowLevelGraphicsContext
  225356. {
  225357. public:
  225358. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225359. : context (context_),
  225360. flipHeight (flipHeight_),
  225361. state (new SavedState()),
  225362. numGradientLookupEntries (0),
  225363. lastClipRectIsValid (false)
  225364. {
  225365. CGContextRetain (context);
  225366. CGContextSaveGState(context);
  225367. CGContextSetShouldSmoothFonts (context, true);
  225368. CGContextSetShouldAntialias (context, true);
  225369. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225370. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225371. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225372. gradientCallbacks.version = 0;
  225373. gradientCallbacks.evaluate = gradientCallback;
  225374. gradientCallbacks.releaseInfo = 0;
  225375. setFont (Font());
  225376. }
  225377. ~CoreGraphicsContext()
  225378. {
  225379. CGContextRestoreGState (context);
  225380. CGContextRelease (context);
  225381. CGColorSpaceRelease (rgbColourSpace);
  225382. CGColorSpaceRelease (greyColourSpace);
  225383. }
  225384. bool isVectorDevice() const { return false; }
  225385. void setOrigin (int x, int y)
  225386. {
  225387. CGContextTranslateCTM (context, x, -y);
  225388. if (lastClipRectIsValid)
  225389. lastClipRect.translate (-x, -y);
  225390. }
  225391. bool clipToRectangle (const Rectangle<int>& r)
  225392. {
  225393. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225394. if (lastClipRectIsValid)
  225395. {
  225396. lastClipRect = lastClipRect.getIntersection (r);
  225397. return ! lastClipRect.isEmpty();
  225398. }
  225399. return ! isClipEmpty();
  225400. }
  225401. bool clipToRectangleList (const RectangleList& clipRegion)
  225402. {
  225403. if (clipRegion.isEmpty())
  225404. {
  225405. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225406. lastClipRectIsValid = true;
  225407. lastClipRect = Rectangle<int>();
  225408. return false;
  225409. }
  225410. else
  225411. {
  225412. const int numRects = clipRegion.getNumRectangles();
  225413. HeapBlock <CGRect> rects (numRects);
  225414. for (int i = 0; i < numRects; ++i)
  225415. {
  225416. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225417. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225418. }
  225419. CGContextClipToRects (context, rects, numRects);
  225420. lastClipRectIsValid = false;
  225421. return ! isClipEmpty();
  225422. }
  225423. }
  225424. void excludeClipRectangle (const Rectangle<int>& r)
  225425. {
  225426. RectangleList remaining (getClipBounds());
  225427. remaining.subtract (r);
  225428. clipToRectangleList (remaining);
  225429. lastClipRectIsValid = false;
  225430. }
  225431. void clipToPath (const Path& path, const AffineTransform& transform)
  225432. {
  225433. createPath (path, transform);
  225434. CGContextClip (context);
  225435. lastClipRectIsValid = false;
  225436. }
  225437. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  225438. {
  225439. if (! transform.isSingularity())
  225440. {
  225441. Image singleChannelImage (sourceImage);
  225442. if (sourceImage.getFormat() != Image::SingleChannel)
  225443. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225444. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  225445. flip();
  225446. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  225447. applyTransform (t);
  225448. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  225449. CGContextClipToMask (context, r, image);
  225450. applyTransform (t.inverted());
  225451. flip();
  225452. CGImageRelease (image);
  225453. lastClipRectIsValid = false;
  225454. }
  225455. }
  225456. bool clipRegionIntersects (const Rectangle<int>& r)
  225457. {
  225458. return getClipBounds().intersects (r);
  225459. }
  225460. const Rectangle<int> getClipBounds() const
  225461. {
  225462. if (! lastClipRectIsValid)
  225463. {
  225464. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225465. lastClipRectIsValid = true;
  225466. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225467. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225468. roundToInt (bounds.size.width),
  225469. roundToInt (bounds.size.height));
  225470. }
  225471. return lastClipRect;
  225472. }
  225473. bool isClipEmpty() const
  225474. {
  225475. return getClipBounds().isEmpty();
  225476. }
  225477. void saveState()
  225478. {
  225479. CGContextSaveGState (context);
  225480. stateStack.add (new SavedState (*state));
  225481. }
  225482. void restoreState()
  225483. {
  225484. CGContextRestoreGState (context);
  225485. SavedState* const top = stateStack.getLast();
  225486. if (top != 0)
  225487. {
  225488. state = top;
  225489. stateStack.removeLast (1, false);
  225490. lastClipRectIsValid = false;
  225491. }
  225492. else
  225493. {
  225494. jassertfalse; // trying to pop with an empty stack!
  225495. }
  225496. }
  225497. void setFill (const FillType& fillType)
  225498. {
  225499. state->fillType = fillType;
  225500. if (fillType.isColour())
  225501. {
  225502. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  225503. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  225504. CGContextSetAlpha (context, 1.0f);
  225505. }
  225506. }
  225507. void setOpacity (float newOpacity)
  225508. {
  225509. state->fillType.setOpacity (newOpacity);
  225510. setFill (state->fillType);
  225511. }
  225512. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  225513. {
  225514. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  225515. ? kCGInterpolationLow
  225516. : kCGInterpolationHigh);
  225517. }
  225518. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  225519. {
  225520. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225521. if (replaceExistingContents)
  225522. {
  225523. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225524. CGContextClearRect (context, cgRect);
  225525. #else
  225526. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225527. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  225528. CGContextClearRect (context, cgRect);
  225529. else
  225530. #endif
  225531. CGContextSetBlendMode (context, kCGBlendModeCopy);
  225532. #endif
  225533. fillRect (r, false);
  225534. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225535. }
  225536. else
  225537. {
  225538. if (state->fillType.isColour())
  225539. {
  225540. CGContextFillRect (context, cgRect);
  225541. }
  225542. else if (state->fillType.isGradient())
  225543. {
  225544. CGContextSaveGState (context);
  225545. CGContextClipToRect (context, cgRect);
  225546. drawGradient();
  225547. CGContextRestoreGState (context);
  225548. }
  225549. else
  225550. {
  225551. CGContextSaveGState (context);
  225552. CGContextClipToRect (context, cgRect);
  225553. drawImage (state->fillType.image, state->fillType.transform, true);
  225554. CGContextRestoreGState (context);
  225555. }
  225556. }
  225557. }
  225558. void fillPath (const Path& path, const AffineTransform& transform)
  225559. {
  225560. CGContextSaveGState (context);
  225561. if (state->fillType.isColour())
  225562. {
  225563. flip();
  225564. applyTransform (transform);
  225565. createPath (path);
  225566. if (path.isUsingNonZeroWinding())
  225567. CGContextFillPath (context);
  225568. else
  225569. CGContextEOFillPath (context);
  225570. }
  225571. else
  225572. {
  225573. createPath (path, transform);
  225574. if (path.isUsingNonZeroWinding())
  225575. CGContextClip (context);
  225576. else
  225577. CGContextEOClip (context);
  225578. if (state->fillType.isGradient())
  225579. drawGradient();
  225580. else
  225581. drawImage (state->fillType.image, state->fillType.transform, true);
  225582. }
  225583. CGContextRestoreGState (context);
  225584. }
  225585. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  225586. {
  225587. const int iw = sourceImage.getWidth();
  225588. const int ih = sourceImage.getHeight();
  225589. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  225590. CGContextSaveGState (context);
  225591. CGContextSetAlpha (context, state->fillType.getOpacity());
  225592. flip();
  225593. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  225594. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  225595. if (fillEntireClipAsTiles)
  225596. {
  225597. #if JUCE_IOS
  225598. CGContextDrawTiledImage (context, imageRect, image);
  225599. #else
  225600. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  225601. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  225602. // if it's doing a transformation - it's quicker to just draw lots of images manually
  225603. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  225604. CGContextDrawTiledImage (context, imageRect, image);
  225605. else
  225606. #endif
  225607. {
  225608. // Fallback to manually doing a tiled fill on 10.4
  225609. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225610. int x = 0, y = 0;
  225611. while (x > clip.origin.x) x -= iw;
  225612. while (y > clip.origin.y) y -= ih;
  225613. const int right = (int) (clip.origin.x + clip.size.width);
  225614. const int bottom = (int) (clip.origin.y + clip.size.height);
  225615. while (y < bottom)
  225616. {
  225617. for (int x2 = x; x2 < right; x2 += iw)
  225618. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  225619. y += ih;
  225620. }
  225621. }
  225622. #endif
  225623. }
  225624. else
  225625. {
  225626. CGContextDrawImage (context, imageRect, image);
  225627. }
  225628. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  225629. CGContextRestoreGState (context);
  225630. }
  225631. void drawLine (const Line<float>& line)
  225632. {
  225633. CGContextSetLineCap (context, kCGLineCapSquare);
  225634. CGContextSetLineWidth (context, 1.0f);
  225635. CGContextSetRGBStrokeColor (context,
  225636. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  225637. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  225638. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  225639. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  225640. CGContextStrokeLineSegments (context, cgLine, 1);
  225641. }
  225642. void drawVerticalLine (const int x, float top, float bottom)
  225643. {
  225644. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225645. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  225646. #else
  225647. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225648. // the x co-ord slightly to trick it..
  225649. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  225650. #endif
  225651. }
  225652. void drawHorizontalLine (const int y, float left, float right)
  225653. {
  225654. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225655. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  225656. #else
  225657. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225658. // the x co-ord slightly to trick it..
  225659. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  225660. #endif
  225661. }
  225662. void setFont (const Font& newFont)
  225663. {
  225664. if (state->font != newFont)
  225665. {
  225666. state->fontRef = 0;
  225667. state->font = newFont;
  225668. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  225669. if (mf != 0)
  225670. {
  225671. state->fontRef = mf->fontRef;
  225672. CGContextSetFont (context, state->fontRef);
  225673. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  225674. state->fontTransform = mf->renderingTransform;
  225675. state->fontTransform.a *= state->font.getHorizontalScale();
  225676. CGContextSetTextMatrix (context, state->fontTransform);
  225677. }
  225678. }
  225679. }
  225680. const Font getFont()
  225681. {
  225682. return state->font;
  225683. }
  225684. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  225685. {
  225686. if (state->fontRef != 0 && state->fillType.isColour())
  225687. {
  225688. if (transform.isOnlyTranslation())
  225689. {
  225690. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  225691. CGGlyph g = glyphNumber;
  225692. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  225693. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  225694. }
  225695. else
  225696. {
  225697. CGContextSaveGState (context);
  225698. flip();
  225699. applyTransform (transform);
  225700. CGAffineTransform t = state->fontTransform;
  225701. t.d = -t.d;
  225702. CGContextSetTextMatrix (context, t);
  225703. CGGlyph g = glyphNumber;
  225704. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  225705. CGContextRestoreGState (context);
  225706. }
  225707. }
  225708. else
  225709. {
  225710. Path p;
  225711. Font& f = state->font;
  225712. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  225713. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  225714. .followedBy (transform));
  225715. }
  225716. }
  225717. private:
  225718. CGContextRef context;
  225719. const CGFloat flipHeight;
  225720. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  225721. CGFunctionCallbacks gradientCallbacks;
  225722. mutable Rectangle<int> lastClipRect;
  225723. mutable bool lastClipRectIsValid;
  225724. struct SavedState
  225725. {
  225726. SavedState()
  225727. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  225728. {
  225729. }
  225730. SavedState (const SavedState& other)
  225731. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  225732. fontTransform (other.fontTransform)
  225733. {
  225734. }
  225735. ~SavedState()
  225736. {
  225737. }
  225738. FillType fillType;
  225739. Font font;
  225740. CGFontRef fontRef;
  225741. CGAffineTransform fontTransform;
  225742. };
  225743. ScopedPointer <SavedState> state;
  225744. OwnedArray <SavedState> stateStack;
  225745. HeapBlock <PixelARGB> gradientLookupTable;
  225746. int numGradientLookupEntries;
  225747. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  225748. {
  225749. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  225750. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  225751. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  225752. colour.unpremultiply();
  225753. outData[0] = colour.getRed() / 255.0f;
  225754. outData[1] = colour.getGreen() / 255.0f;
  225755. outData[2] = colour.getBlue() / 255.0f;
  225756. outData[3] = colour.getAlpha() / 255.0f;
  225757. }
  225758. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  225759. {
  225760. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  225761. --numGradientLookupEntries;
  225762. CGShadingRef result = 0;
  225763. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  225764. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  225765. if (gradient.isRadial)
  225766. {
  225767. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  225768. p1, gradient.point1.getDistanceFrom (gradient.point2),
  225769. function, true, true);
  225770. }
  225771. else
  225772. {
  225773. result = CGShadingCreateAxial (rgbColourSpace, p1,
  225774. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  225775. function, true, true);
  225776. }
  225777. CGFunctionRelease (function);
  225778. return result;
  225779. }
  225780. void drawGradient()
  225781. {
  225782. flip();
  225783. applyTransform (state->fillType.transform);
  225784. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  225785. // you draw a gradient with high quality interp enabled).
  225786. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  225787. CGContextSetAlpha (context, state->fillType.getOpacity());
  225788. CGContextDrawShading (context, shading);
  225789. CGShadingRelease (shading);
  225790. }
  225791. void createPath (const Path& path) const
  225792. {
  225793. CGContextBeginPath (context);
  225794. Path::Iterator i (path);
  225795. while (i.next())
  225796. {
  225797. switch (i.elementType)
  225798. {
  225799. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  225800. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  225801. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  225802. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  225803. case Path::Iterator::closePath: CGContextClosePath (context); break;
  225804. default: jassertfalse; break;
  225805. }
  225806. }
  225807. }
  225808. void createPath (const Path& path, const AffineTransform& transform) const
  225809. {
  225810. CGContextBeginPath (context);
  225811. Path::Iterator i (path);
  225812. while (i.next())
  225813. {
  225814. switch (i.elementType)
  225815. {
  225816. case Path::Iterator::startNewSubPath:
  225817. transform.transformPoint (i.x1, i.y1);
  225818. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  225819. break;
  225820. case Path::Iterator::lineTo:
  225821. transform.transformPoint (i.x1, i.y1);
  225822. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  225823. break;
  225824. case Path::Iterator::quadraticTo:
  225825. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  225826. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  225827. break;
  225828. case Path::Iterator::cubicTo:
  225829. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  225830. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  225831. break;
  225832. case Path::Iterator::closePath:
  225833. CGContextClosePath (context); break;
  225834. default:
  225835. jassertfalse;
  225836. break;
  225837. }
  225838. }
  225839. }
  225840. void flip() const
  225841. {
  225842. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  225843. }
  225844. void applyTransform (const AffineTransform& transform) const
  225845. {
  225846. CGAffineTransform t;
  225847. t.a = transform.mat00;
  225848. t.b = transform.mat10;
  225849. t.c = transform.mat01;
  225850. t.d = transform.mat11;
  225851. t.tx = transform.mat02;
  225852. t.ty = transform.mat12;
  225853. CGContextConcatCTM (context, t);
  225854. }
  225855. CoreGraphicsContext (const CoreGraphicsContext&);
  225856. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  225857. };
  225858. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  225859. {
  225860. return new CoreGraphicsContext (context, height);
  225861. }
  225862. #endif
  225863. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225864. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  225865. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225866. // compiled on its own).
  225867. #if JUCE_INCLUDED_FILE
  225868. class UIViewComponentPeer;
  225869. END_JUCE_NAMESPACE
  225870. #define JuceUIView MakeObjCClassName(JuceUIView)
  225871. @interface JuceUIView : UIView <UITextFieldDelegate>
  225872. {
  225873. @public
  225874. UIViewComponentPeer* owner;
  225875. UITextField *hiddenTextField;
  225876. }
  225877. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  225878. - (void) dealloc;
  225879. - (void) drawRect: (CGRect) r;
  225880. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  225881. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  225882. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  225883. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225884. - (BOOL) becomeFirstResponder;
  225885. - (BOOL) resignFirstResponder;
  225886. - (BOOL) canBecomeFirstResponder;
  225887. - (void) asyncRepaint: (id) rect;
  225888. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  225889. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  225890. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  225891. @end
  225892. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  225893. @interface JuceUIWindow : UIWindow
  225894. {
  225895. @private
  225896. UIViewComponentPeer* owner;
  225897. bool isZooming;
  225898. }
  225899. - (void) setOwner: (UIViewComponentPeer*) owner;
  225900. - (void) becomeKeyWindow;
  225901. @end
  225902. BEGIN_JUCE_NAMESPACE
  225903. class UIViewComponentPeer : public ComponentPeer,
  225904. public FocusChangeListener
  225905. {
  225906. public:
  225907. UIViewComponentPeer (Component* const component,
  225908. const int windowStyleFlags,
  225909. UIView* viewToAttachTo);
  225910. ~UIViewComponentPeer();
  225911. void* getNativeHandle() const;
  225912. void setVisible (bool shouldBeVisible);
  225913. void setTitle (const String& title);
  225914. void setPosition (int x, int y);
  225915. void setSize (int w, int h);
  225916. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  225917. const Rectangle<int> getBounds() const;
  225918. const Rectangle<int> getBounds (const bool global) const;
  225919. const Point<int> getScreenPosition() const;
  225920. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  225921. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  225922. void setMinimised (bool shouldBeMinimised);
  225923. bool isMinimised() const;
  225924. void setFullScreen (bool shouldBeFullScreen);
  225925. bool isFullScreen() const;
  225926. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  225927. const BorderSize getFrameSize() const;
  225928. bool setAlwaysOnTop (bool alwaysOnTop);
  225929. void toFront (bool makeActiveWindow);
  225930. void toBehind (ComponentPeer* other);
  225931. void setIcon (const Image& newIcon);
  225932. virtual void drawRect (CGRect r);
  225933. virtual bool canBecomeKeyWindow();
  225934. virtual bool windowShouldClose();
  225935. virtual void redirectMovedOrResized();
  225936. virtual CGRect constrainRect (CGRect r);
  225937. virtual void viewFocusGain();
  225938. virtual void viewFocusLoss();
  225939. bool isFocused() const;
  225940. void grabFocus();
  225941. void textInputRequired (const Point<int>& position);
  225942. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  225943. virtual BOOL textFieldShouldClear();
  225944. virtual BOOL textFieldShouldReturn();
  225945. void updateHiddenTextContent (TextInputTarget* target);
  225946. void globalFocusChanged (Component*);
  225947. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  225948. void repaint (const Rectangle<int>& area);
  225949. void performAnyPendingRepaintsNow();
  225950. juce_UseDebuggingNewOperator
  225951. UIWindow* window;
  225952. JuceUIView* view;
  225953. bool isSharedWindow, fullScreen, insideDrawRect;
  225954. static ModifierKeys currentModifiers;
  225955. static int64 getMouseTime (UIEvent* e)
  225956. {
  225957. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  225958. + (int64) ([e timestamp] * 1000.0);
  225959. }
  225960. Array <UITouch*> currentTouches;
  225961. };
  225962. END_JUCE_NAMESPACE
  225963. @implementation JuceUIView
  225964. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  225965. withFrame: (CGRect) frame
  225966. {
  225967. [super initWithFrame: frame];
  225968. owner = owner_;
  225969. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  225970. [self addSubview: hiddenTextField];
  225971. hiddenTextField.delegate = self;
  225972. return self;
  225973. }
  225974. - (void) dealloc
  225975. {
  225976. [hiddenTextField removeFromSuperview];
  225977. [hiddenTextField release];
  225978. [super dealloc];
  225979. }
  225980. - (void) drawRect: (CGRect) r
  225981. {
  225982. if (owner != 0)
  225983. owner->drawRect (r);
  225984. }
  225985. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  225986. {
  225987. return false;
  225988. }
  225989. ModifierKeys UIViewComponentPeer::currentModifiers;
  225990. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225991. {
  225992. return UIViewComponentPeer::currentModifiers;
  225993. }
  225994. void ModifierKeys::updateCurrentModifiers() throw()
  225995. {
  225996. currentModifiers = UIViewComponentPeer::currentModifiers;
  225997. }
  225998. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  225999. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  226000. {
  226001. if (owner != 0)
  226002. owner->handleTouches (event, true, false, false);
  226003. }
  226004. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226005. {
  226006. if (owner != 0)
  226007. owner->handleTouches (event, false, false, false);
  226008. }
  226009. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226010. {
  226011. if (owner != 0)
  226012. owner->handleTouches (event, false, true, false);
  226013. }
  226014. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226015. {
  226016. if (owner != 0)
  226017. owner->handleTouches (event, false, true, true);
  226018. [self touchesEnded: touches withEvent: event];
  226019. }
  226020. - (BOOL) becomeFirstResponder
  226021. {
  226022. if (owner != 0)
  226023. owner->viewFocusGain();
  226024. return true;
  226025. }
  226026. - (BOOL) resignFirstResponder
  226027. {
  226028. if (owner != 0)
  226029. owner->viewFocusLoss();
  226030. return true;
  226031. }
  226032. - (BOOL) canBecomeFirstResponder
  226033. {
  226034. return owner != 0 && owner->canBecomeKeyWindow();
  226035. }
  226036. - (void) asyncRepaint: (id) rect
  226037. {
  226038. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226039. [self setNeedsDisplayInRect: *r];
  226040. }
  226041. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  226042. {
  226043. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226044. nsStringToJuce (text));
  226045. }
  226046. - (BOOL) textFieldShouldClear: (UITextField*) textField
  226047. {
  226048. return owner->textFieldShouldClear();
  226049. }
  226050. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  226051. {
  226052. return owner->textFieldShouldReturn();
  226053. }
  226054. @end
  226055. @implementation JuceUIWindow
  226056. - (void) setOwner: (UIViewComponentPeer*) owner_
  226057. {
  226058. owner = owner_;
  226059. isZooming = false;
  226060. }
  226061. - (void) becomeKeyWindow
  226062. {
  226063. [super becomeKeyWindow];
  226064. if (owner != 0)
  226065. owner->grabFocus();
  226066. }
  226067. @end
  226068. BEGIN_JUCE_NAMESPACE
  226069. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226070. const int windowStyleFlags,
  226071. UIView* viewToAttachTo)
  226072. : ComponentPeer (component, windowStyleFlags),
  226073. window (0),
  226074. view (0),
  226075. isSharedWindow (viewToAttachTo != 0),
  226076. fullScreen (false),
  226077. insideDrawRect (false)
  226078. {
  226079. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  226080. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226081. if (isSharedWindow)
  226082. {
  226083. window = [viewToAttachTo window];
  226084. [viewToAttachTo addSubview: view];
  226085. setVisible (component->isVisible());
  226086. }
  226087. else
  226088. {
  226089. r.origin.x = (float) component->getX();
  226090. r.origin.y = (float) component->getY();
  226091. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226092. window = [[JuceUIWindow alloc] init];
  226093. window.frame = r;
  226094. window.opaque = component->isOpaque();
  226095. view.opaque = component->isOpaque();
  226096. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226097. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226098. [((JuceUIWindow*) window) setOwner: this];
  226099. if (component->isAlwaysOnTop())
  226100. window.windowLevel = UIWindowLevelAlert;
  226101. [window addSubview: view];
  226102. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226103. view.hidden = ! component->isVisible();
  226104. window.hidden = ! component->isVisible();
  226105. view.multipleTouchEnabled = YES;
  226106. }
  226107. setTitle (component->getName());
  226108. Desktop::getInstance().addFocusChangeListener (this);
  226109. }
  226110. UIViewComponentPeer::~UIViewComponentPeer()
  226111. {
  226112. Desktop::getInstance().removeFocusChangeListener (this);
  226113. view->owner = 0;
  226114. [view removeFromSuperview];
  226115. [view release];
  226116. if (! isSharedWindow)
  226117. {
  226118. [((JuceUIWindow*) window) setOwner: 0];
  226119. [window release];
  226120. }
  226121. }
  226122. void* UIViewComponentPeer::getNativeHandle() const
  226123. {
  226124. return view;
  226125. }
  226126. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226127. {
  226128. view.hidden = ! shouldBeVisible;
  226129. if (! isSharedWindow)
  226130. window.hidden = ! shouldBeVisible;
  226131. }
  226132. void UIViewComponentPeer::setTitle (const String& title)
  226133. {
  226134. // xxx is this possible?
  226135. }
  226136. void UIViewComponentPeer::setPosition (int x, int y)
  226137. {
  226138. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226139. }
  226140. void UIViewComponentPeer::setSize (int w, int h)
  226141. {
  226142. setBounds (component->getX(), component->getY(), w, h, false);
  226143. }
  226144. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226145. {
  226146. fullScreen = isNowFullScreen;
  226147. w = jmax (0, w);
  226148. h = jmax (0, h);
  226149. CGRect r;
  226150. r.origin.x = (float) x;
  226151. r.origin.y = (float) y;
  226152. r.size.width = (float) w;
  226153. r.size.height = (float) h;
  226154. if (isSharedWindow)
  226155. {
  226156. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  226157. if ([view frame].size.width != r.size.width
  226158. || [view frame].size.height != r.size.height)
  226159. [view setNeedsDisplay];
  226160. view.frame = r;
  226161. }
  226162. else
  226163. {
  226164. window.frame = r;
  226165. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226166. }
  226167. }
  226168. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226169. {
  226170. CGRect r = [view frame];
  226171. if (global && [view window] != 0)
  226172. {
  226173. r = [view convertRect: r toView: nil];
  226174. CGRect wr = [[view window] frame];
  226175. r.origin.x += wr.origin.x;
  226176. r.origin.y += wr.origin.y;
  226177. }
  226178. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  226179. (int) r.size.width, (int) r.size.height);
  226180. }
  226181. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226182. {
  226183. return getBounds (! isSharedWindow);
  226184. }
  226185. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226186. {
  226187. return getBounds (true).getPosition();
  226188. }
  226189. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  226190. {
  226191. return relativePosition + getScreenPosition();
  226192. }
  226193. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  226194. {
  226195. return screenPosition - getScreenPosition();
  226196. }
  226197. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226198. {
  226199. if (constrainer != 0)
  226200. {
  226201. CGRect current = [window frame];
  226202. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226203. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226204. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  226205. (int) r.size.width, (int) r.size.height);
  226206. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  226207. (int) current.size.width, (int) current.size.height);
  226208. constrainer->checkBounds (pos, original,
  226209. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226210. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226211. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226212. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226213. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226214. r.origin.x = pos.getX();
  226215. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226216. r.size.width = pos.getWidth();
  226217. r.size.height = pos.getHeight();
  226218. }
  226219. return r;
  226220. }
  226221. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226222. {
  226223. // xxx
  226224. }
  226225. bool UIViewComponentPeer::isMinimised() const
  226226. {
  226227. return false;
  226228. }
  226229. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226230. {
  226231. if (! isSharedWindow)
  226232. {
  226233. Rectangle<int> r (lastNonFullscreenBounds);
  226234. setMinimised (false);
  226235. if (fullScreen != shouldBeFullScreen)
  226236. {
  226237. if (shouldBeFullScreen)
  226238. r = Desktop::getInstance().getMainMonitorArea();
  226239. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226240. if (r != getComponent()->getBounds() && ! r.isEmpty())
  226241. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226242. }
  226243. }
  226244. }
  226245. bool UIViewComponentPeer::isFullScreen() const
  226246. {
  226247. return fullScreen;
  226248. }
  226249. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226250. {
  226251. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  226252. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  226253. return false;
  226254. CGPoint p;
  226255. p.x = (float) position.getX();
  226256. p.y = (float) position.getY();
  226257. UIView* v = [view hitTest: p withEvent: nil];
  226258. if (trueIfInAChildWindow)
  226259. return v != nil;
  226260. return v == view;
  226261. }
  226262. const BorderSize UIViewComponentPeer::getFrameSize() const
  226263. {
  226264. BorderSize b;
  226265. if (! isSharedWindow)
  226266. {
  226267. CGRect v = [view convertRect: [view frame] toView: nil];
  226268. CGRect w = [window frame];
  226269. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  226270. b.setBottom ((int) v.origin.y);
  226271. b.setLeft ((int) v.origin.x);
  226272. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  226273. }
  226274. return b;
  226275. }
  226276. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  226277. {
  226278. if (! isSharedWindow)
  226279. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  226280. return true;
  226281. }
  226282. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  226283. {
  226284. if (isSharedWindow)
  226285. [[view superview] bringSubviewToFront: view];
  226286. if (window != 0 && component->isVisible())
  226287. [window makeKeyAndVisible];
  226288. }
  226289. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  226290. {
  226291. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  226292. jassert (otherPeer != 0); // wrong type of window?
  226293. if (otherPeer != 0)
  226294. {
  226295. if (isSharedWindow)
  226296. {
  226297. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  226298. }
  226299. else
  226300. {
  226301. jassertfalse; // don't know how to do this
  226302. }
  226303. }
  226304. }
  226305. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  226306. {
  226307. // to do..
  226308. }
  226309. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226310. {
  226311. NSArray* touches = [[event touchesForView: view] allObjects];
  226312. for (unsigned int i = 0; i < [touches count]; ++i)
  226313. {
  226314. UITouch* touch = [touches objectAtIndex: i];
  226315. CGPoint p = [touch locationInView: view];
  226316. const Point<int> pos ((int) p.x, (int) p.y);
  226317. juce_lastMousePos = pos + getScreenPosition();
  226318. const int64 time = getMouseTime (event);
  226319. int touchIndex = currentTouches.indexOf (touch);
  226320. if (touchIndex < 0)
  226321. {
  226322. touchIndex = currentTouches.size();
  226323. currentTouches.add (touch);
  226324. }
  226325. if (isDown)
  226326. {
  226327. currentModifiers = currentModifiers.withoutMouseButtons();
  226328. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226329. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  226330. }
  226331. else if (isUp)
  226332. {
  226333. currentModifiers = currentModifiers.withoutMouseButtons();
  226334. currentTouches.remove (touchIndex);
  226335. }
  226336. if (isCancel)
  226337. currentTouches.clear();
  226338. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226339. }
  226340. }
  226341. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  226342. void UIViewComponentPeer::viewFocusGain()
  226343. {
  226344. if (currentlyFocusedPeer != this)
  226345. {
  226346. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  226347. currentlyFocusedPeer->handleFocusLoss();
  226348. currentlyFocusedPeer = this;
  226349. handleFocusGain();
  226350. }
  226351. }
  226352. void UIViewComponentPeer::viewFocusLoss()
  226353. {
  226354. if (currentlyFocusedPeer == this)
  226355. {
  226356. currentlyFocusedPeer = 0;
  226357. handleFocusLoss();
  226358. }
  226359. }
  226360. void juce_HandleProcessFocusChange()
  226361. {
  226362. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  226363. {
  226364. if (Process::isForegroundProcess())
  226365. {
  226366. currentlyFocusedPeer->handleFocusGain();
  226367. ComponentPeer::bringModalComponentToFront();
  226368. }
  226369. else
  226370. {
  226371. currentlyFocusedPeer->handleFocusLoss();
  226372. // turn kiosk mode off if we lose focus..
  226373. Desktop::getInstance().setKioskModeComponent (0);
  226374. }
  226375. }
  226376. }
  226377. bool UIViewComponentPeer::isFocused() const
  226378. {
  226379. return isSharedWindow ? this == currentlyFocusedPeer
  226380. : (window != 0 && [window isKeyWindow]);
  226381. }
  226382. void UIViewComponentPeer::grabFocus()
  226383. {
  226384. if (window != 0)
  226385. {
  226386. [window makeKeyWindow];
  226387. viewFocusGain();
  226388. }
  226389. }
  226390. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  226391. {
  226392. }
  226393. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  226394. {
  226395. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  226396. }
  226397. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  226398. {
  226399. TextInputTarget* const target = findCurrentTextInputTarget();
  226400. if (target != 0)
  226401. {
  226402. const Range<int> currentSelection (target->getHighlightedRegion());
  226403. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  226404. if (currentSelection.isEmpty())
  226405. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  226406. target->insertTextAtCaret (text);
  226407. updateHiddenTextContent (target);
  226408. }
  226409. return NO;
  226410. }
  226411. BOOL UIViewComponentPeer::textFieldShouldClear()
  226412. {
  226413. TextInputTarget* const target = findCurrentTextInputTarget();
  226414. if (target != 0)
  226415. {
  226416. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  226417. target->insertTextAtCaret (String::empty);
  226418. updateHiddenTextContent (target);
  226419. }
  226420. return YES;
  226421. }
  226422. BOOL UIViewComponentPeer::textFieldShouldReturn()
  226423. {
  226424. TextInputTarget* const target = findCurrentTextInputTarget();
  226425. if (target != 0)
  226426. {
  226427. target->insertTextAtCaret ("\n");
  226428. updateHiddenTextContent (target);
  226429. }
  226430. return YES;
  226431. }
  226432. void UIViewComponentPeer::globalFocusChanged (Component*)
  226433. {
  226434. TextInputTarget* const target = findCurrentTextInputTarget();
  226435. if (target != 0)
  226436. {
  226437. Component* comp = dynamic_cast<Component*> (target);
  226438. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  226439. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  226440. updateHiddenTextContent (target);
  226441. [view->hiddenTextField becomeFirstResponder];
  226442. }
  226443. else
  226444. {
  226445. [view->hiddenTextField resignFirstResponder];
  226446. }
  226447. }
  226448. void UIViewComponentPeer::drawRect (CGRect r)
  226449. {
  226450. if (r.size.width < 1.0f || r.size.height < 1.0f)
  226451. return;
  226452. CGContextRef cg = UIGraphicsGetCurrentContext();
  226453. if (! component->isOpaque())
  226454. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  226455. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  226456. CoreGraphicsContext g (cg, view.bounds.size.height);
  226457. insideDrawRect = true;
  226458. handlePaint (g);
  226459. insideDrawRect = false;
  226460. }
  226461. bool UIViewComponentPeer::canBecomeKeyWindow()
  226462. {
  226463. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  226464. }
  226465. bool UIViewComponentPeer::windowShouldClose()
  226466. {
  226467. if (! isValidPeer (this))
  226468. return YES;
  226469. handleUserClosingWindow();
  226470. return NO;
  226471. }
  226472. void UIViewComponentPeer::redirectMovedOrResized()
  226473. {
  226474. handleMovedOrResized();
  226475. }
  226476. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  226477. {
  226478. }
  226479. class AsyncRepaintMessage : public CallbackMessage
  226480. {
  226481. public:
  226482. UIViewComponentPeer* const peer;
  226483. const Rectangle<int> rect;
  226484. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  226485. : peer (peer_), rect (rect_)
  226486. {
  226487. }
  226488. void messageCallback()
  226489. {
  226490. if (ComponentPeer::isValidPeer (peer))
  226491. peer->repaint (rect);
  226492. }
  226493. };
  226494. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  226495. {
  226496. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  226497. {
  226498. (new AsyncRepaintMessage (this, area))->post();
  226499. }
  226500. else
  226501. {
  226502. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  226503. (float) area.getWidth(), (float) area.getHeight())];
  226504. }
  226505. }
  226506. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  226507. {
  226508. }
  226509. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  226510. {
  226511. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  226512. }
  226513. const Image juce_createIconForFile (const File& file)
  226514. {
  226515. return Image::null;
  226516. }
  226517. void Desktop::createMouseInputSources()
  226518. {
  226519. for (int i = 0; i < 10; ++i)
  226520. mouseSources.add (new MouseInputSource (i, false));
  226521. }
  226522. bool Desktop::canUseSemiTransparentWindows() throw()
  226523. {
  226524. return true;
  226525. }
  226526. const Point<int> Desktop::getMousePosition()
  226527. {
  226528. return juce_lastMousePos;
  226529. }
  226530. void Desktop::setMousePosition (const Point<int>&)
  226531. {
  226532. }
  226533. const int KeyPress::spaceKey = ' ';
  226534. const int KeyPress::returnKey = 0x0d;
  226535. const int KeyPress::escapeKey = 0x1b;
  226536. const int KeyPress::backspaceKey = 0x7f;
  226537. const int KeyPress::leftKey = 0x1000;
  226538. const int KeyPress::rightKey = 0x1001;
  226539. const int KeyPress::upKey = 0x1002;
  226540. const int KeyPress::downKey = 0x1003;
  226541. const int KeyPress::pageUpKey = 0x1004;
  226542. const int KeyPress::pageDownKey = 0x1005;
  226543. const int KeyPress::endKey = 0x1006;
  226544. const int KeyPress::homeKey = 0x1007;
  226545. const int KeyPress::deleteKey = 0x1008;
  226546. const int KeyPress::insertKey = -1;
  226547. const int KeyPress::tabKey = 9;
  226548. const int KeyPress::F1Key = 0x2001;
  226549. const int KeyPress::F2Key = 0x2002;
  226550. const int KeyPress::F3Key = 0x2003;
  226551. const int KeyPress::F4Key = 0x2004;
  226552. const int KeyPress::F5Key = 0x2005;
  226553. const int KeyPress::F6Key = 0x2006;
  226554. const int KeyPress::F7Key = 0x2007;
  226555. const int KeyPress::F8Key = 0x2008;
  226556. const int KeyPress::F9Key = 0x2009;
  226557. const int KeyPress::F10Key = 0x200a;
  226558. const int KeyPress::F11Key = 0x200b;
  226559. const int KeyPress::F12Key = 0x200c;
  226560. const int KeyPress::F13Key = 0x200d;
  226561. const int KeyPress::F14Key = 0x200e;
  226562. const int KeyPress::F15Key = 0x200f;
  226563. const int KeyPress::F16Key = 0x2010;
  226564. const int KeyPress::numberPad0 = 0x30020;
  226565. const int KeyPress::numberPad1 = 0x30021;
  226566. const int KeyPress::numberPad2 = 0x30022;
  226567. const int KeyPress::numberPad3 = 0x30023;
  226568. const int KeyPress::numberPad4 = 0x30024;
  226569. const int KeyPress::numberPad5 = 0x30025;
  226570. const int KeyPress::numberPad6 = 0x30026;
  226571. const int KeyPress::numberPad7 = 0x30027;
  226572. const int KeyPress::numberPad8 = 0x30028;
  226573. const int KeyPress::numberPad9 = 0x30029;
  226574. const int KeyPress::numberPadAdd = 0x3002a;
  226575. const int KeyPress::numberPadSubtract = 0x3002b;
  226576. const int KeyPress::numberPadMultiply = 0x3002c;
  226577. const int KeyPress::numberPadDivide = 0x3002d;
  226578. const int KeyPress::numberPadSeparator = 0x3002e;
  226579. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  226580. const int KeyPress::numberPadEquals = 0x30030;
  226581. const int KeyPress::numberPadDelete = 0x30031;
  226582. const int KeyPress::playKey = 0x30000;
  226583. const int KeyPress::stopKey = 0x30001;
  226584. const int KeyPress::fastForwardKey = 0x30002;
  226585. const int KeyPress::rewindKey = 0x30003;
  226586. #endif
  226587. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226588. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  226589. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226590. // compiled on its own).
  226591. #if JUCE_INCLUDED_FILE
  226592. struct CallbackMessagePayload
  226593. {
  226594. MessageCallbackFunction* function;
  226595. void* parameter;
  226596. void* volatile result;
  226597. bool volatile hasBeenExecuted;
  226598. };
  226599. END_JUCE_NAMESPACE
  226600. @interface JuceCustomMessageHandler : NSObject
  226601. {
  226602. }
  226603. - (void) performCallback: (id) info;
  226604. @end
  226605. @implementation JuceCustomMessageHandler
  226606. - (void) performCallback: (id) info
  226607. {
  226608. if ([info isKindOfClass: [NSData class]])
  226609. {
  226610. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  226611. if (pl != 0)
  226612. {
  226613. pl->result = (*pl->function) (pl->parameter);
  226614. pl->hasBeenExecuted = true;
  226615. }
  226616. }
  226617. else
  226618. {
  226619. jassertfalse; // should never get here!
  226620. }
  226621. }
  226622. @end
  226623. BEGIN_JUCE_NAMESPACE
  226624. void MessageManager::runDispatchLoop()
  226625. {
  226626. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226627. runDispatchLoopUntil (-1);
  226628. }
  226629. void MessageManager::stopDispatchLoop()
  226630. {
  226631. exit (0); // iPhone apps get no mercy..
  226632. }
  226633. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226634. {
  226635. const ScopedAutoReleasePool pool;
  226636. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226637. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226638. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226639. while (! quitMessagePosted)
  226640. {
  226641. const ScopedAutoReleasePool pool;
  226642. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226643. beforeDate: endDate];
  226644. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  226645. break;
  226646. }
  226647. return ! quitMessagePosted;
  226648. }
  226649. static CFRunLoopRef runLoop = 0;
  226650. static CFRunLoopSourceRef runLoopSource = 0;
  226651. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  226652. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  226653. static void runLoopSourceCallback (void*)
  226654. {
  226655. if (pendingMessages != 0)
  226656. {
  226657. int numDispatched = 0;
  226658. do
  226659. {
  226660. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  226661. if (nextMessage == 0)
  226662. return;
  226663. const ScopedAutoReleasePool pool;
  226664. MessageManager::getInstance()->deliverMessage (nextMessage);
  226665. } while (++numDispatched <= 4);
  226666. CFRunLoopSourceSignal (runLoopSource);
  226667. CFRunLoopWakeUp (runLoop);
  226668. }
  226669. }
  226670. void MessageManager::doPlatformSpecificInitialisation()
  226671. {
  226672. pendingMessages = new OwnedArray <Message, CriticalSection>();
  226673. runLoop = CFRunLoopGetCurrent();
  226674. CFRunLoopSourceContext sourceContext;
  226675. zerostruct (sourceContext);
  226676. sourceContext.perform = runLoopSourceCallback;
  226677. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  226678. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  226679. if (juceCustomMessageHandler == 0)
  226680. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  226681. }
  226682. void MessageManager::doPlatformSpecificShutdown()
  226683. {
  226684. CFRunLoopSourceInvalidate (runLoopSource);
  226685. CFRelease (runLoopSource);
  226686. runLoopSource = 0;
  226687. deleteAndZero (pendingMessages);
  226688. if (juceCustomMessageHandler != 0)
  226689. {
  226690. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  226691. [juceCustomMessageHandler release];
  226692. juceCustomMessageHandler = 0;
  226693. }
  226694. }
  226695. bool juce_postMessageToSystemQueue (Message* message)
  226696. {
  226697. if (pendingMessages != 0)
  226698. {
  226699. pendingMessages->add (message);
  226700. CFRunLoopSourceSignal (runLoopSource);
  226701. CFRunLoopWakeUp (runLoop);
  226702. }
  226703. return true;
  226704. }
  226705. void MessageManager::broadcastMessage (const String& value) throw()
  226706. {
  226707. }
  226708. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226709. void* data)
  226710. {
  226711. if (isThisTheMessageThread())
  226712. {
  226713. return (*callback) (data);
  226714. }
  226715. else
  226716. {
  226717. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226718. // deadlock because the message manager is blocked from running, so can never
  226719. // call your function..
  226720. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226721. const ScopedAutoReleasePool pool;
  226722. CallbackMessagePayload cmp;
  226723. cmp.function = callback;
  226724. cmp.parameter = data;
  226725. cmp.result = 0;
  226726. cmp.hasBeenExecuted = false;
  226727. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  226728. withObject: [NSData dataWithBytesNoCopy: &cmp
  226729. length: sizeof (cmp)
  226730. freeWhenDone: NO]
  226731. waitUntilDone: YES];
  226732. return cmp.result;
  226733. }
  226734. }
  226735. #endif
  226736. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  226737. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  226738. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226739. // compiled on its own).
  226740. #if JUCE_INCLUDED_FILE
  226741. #if JUCE_MAC
  226742. END_JUCE_NAMESPACE
  226743. using namespace JUCE_NAMESPACE;
  226744. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  226745. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226746. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  226747. #else
  226748. @interface JuceFileChooserDelegate : NSObject
  226749. #endif
  226750. {
  226751. StringArray* filters;
  226752. }
  226753. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226754. - (void) dealloc;
  226755. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226756. @end
  226757. @implementation JuceFileChooserDelegate
  226758. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226759. {
  226760. [super init];
  226761. filters = filters_;
  226762. return self;
  226763. }
  226764. - (void) dealloc
  226765. {
  226766. delete filters;
  226767. [super dealloc];
  226768. }
  226769. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226770. {
  226771. (void) sender;
  226772. const File f (nsStringToJuce (filename));
  226773. for (int i = filters->size(); --i >= 0;)
  226774. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  226775. return true;
  226776. return f.isDirectory();
  226777. }
  226778. @end
  226779. BEGIN_JUCE_NAMESPACE
  226780. void FileChooser::showPlatformDialog (Array<File>& results,
  226781. const String& title,
  226782. const File& currentFileOrDirectory,
  226783. const String& filter,
  226784. bool selectsDirectory,
  226785. bool selectsFiles,
  226786. bool isSaveDialogue,
  226787. bool warnAboutOverwritingExistingFiles,
  226788. bool selectMultipleFiles,
  226789. FilePreviewComponent* extraInfoComponent)
  226790. {
  226791. const ScopedAutoReleasePool pool;
  226792. StringArray* filters = new StringArray();
  226793. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  226794. filters->trim();
  226795. filters->removeEmptyStrings();
  226796. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226797. [delegate autorelease];
  226798. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226799. : [NSOpenPanel openPanel];
  226800. [panel setTitle: juceStringToNS (title)];
  226801. if (! isSaveDialogue)
  226802. {
  226803. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226804. [openPanel setCanChooseDirectories: selectsDirectory];
  226805. [openPanel setCanChooseFiles: selectsFiles];
  226806. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226807. }
  226808. [panel setDelegate: delegate];
  226809. if (isSaveDialogue || selectsDirectory)
  226810. [panel setCanCreateDirectories: YES];
  226811. String directory, filename;
  226812. if (currentFileOrDirectory.isDirectory())
  226813. {
  226814. directory = currentFileOrDirectory.getFullPathName();
  226815. }
  226816. else
  226817. {
  226818. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226819. filename = currentFileOrDirectory.getFileName();
  226820. }
  226821. if ([panel runModalForDirectory: juceStringToNS (directory)
  226822. file: juceStringToNS (filename)]
  226823. == NSOKButton)
  226824. {
  226825. if (isSaveDialogue)
  226826. {
  226827. results.add (File (nsStringToJuce ([panel filename])));
  226828. }
  226829. else
  226830. {
  226831. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226832. NSArray* urls = [openPanel filenames];
  226833. for (unsigned int i = 0; i < [urls count]; ++i)
  226834. {
  226835. NSString* f = [urls objectAtIndex: i];
  226836. results.add (File (nsStringToJuce (f)));
  226837. }
  226838. }
  226839. }
  226840. [panel setDelegate: nil];
  226841. }
  226842. #else
  226843. void FileChooser::showPlatformDialog (Array<File>& results,
  226844. const String& title,
  226845. const File& currentFileOrDirectory,
  226846. const String& filter,
  226847. bool selectsDirectory,
  226848. bool selectsFiles,
  226849. bool isSaveDialogue,
  226850. bool warnAboutOverwritingExistingFiles,
  226851. bool selectMultipleFiles,
  226852. FilePreviewComponent* extraInfoComponent)
  226853. {
  226854. const ScopedAutoReleasePool pool;
  226855. jassertfalse; //xxx to do
  226856. }
  226857. #endif
  226858. #endif
  226859. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  226860. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  226861. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226862. // compiled on its own).
  226863. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226864. #if JUCE_MAC
  226865. END_JUCE_NAMESPACE
  226866. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  226867. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  226868. {
  226869. CriticalSection* contextLock;
  226870. bool needsUpdate;
  226871. }
  226872. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  226873. - (bool) makeActive;
  226874. - (void) makeInactive;
  226875. - (void) reshape;
  226876. @end
  226877. @implementation ThreadSafeNSOpenGLView
  226878. - (id) initWithFrame: (NSRect) frameRect
  226879. pixelFormat: (NSOpenGLPixelFormat*) format
  226880. {
  226881. contextLock = new CriticalSection();
  226882. self = [super initWithFrame: frameRect pixelFormat: format];
  226883. if (self != nil)
  226884. [[NSNotificationCenter defaultCenter] addObserver: self
  226885. selector: @selector (_surfaceNeedsUpdate:)
  226886. name: NSViewGlobalFrameDidChangeNotification
  226887. object: self];
  226888. return self;
  226889. }
  226890. - (void) dealloc
  226891. {
  226892. [[NSNotificationCenter defaultCenter] removeObserver: self];
  226893. delete contextLock;
  226894. [super dealloc];
  226895. }
  226896. - (bool) makeActive
  226897. {
  226898. const ScopedLock sl (*contextLock);
  226899. if ([self openGLContext] == 0)
  226900. return false;
  226901. [[self openGLContext] makeCurrentContext];
  226902. if (needsUpdate)
  226903. {
  226904. [super update];
  226905. needsUpdate = false;
  226906. }
  226907. return true;
  226908. }
  226909. - (void) makeInactive
  226910. {
  226911. const ScopedLock sl (*contextLock);
  226912. [NSOpenGLContext clearCurrentContext];
  226913. }
  226914. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  226915. {
  226916. const ScopedLock sl (*contextLock);
  226917. needsUpdate = true;
  226918. }
  226919. - (void) update
  226920. {
  226921. const ScopedLock sl (*contextLock);
  226922. needsUpdate = true;
  226923. }
  226924. - (void) reshape
  226925. {
  226926. const ScopedLock sl (*contextLock);
  226927. needsUpdate = true;
  226928. }
  226929. @end
  226930. BEGIN_JUCE_NAMESPACE
  226931. class WindowedGLContext : public OpenGLContext
  226932. {
  226933. public:
  226934. WindowedGLContext (Component* const component,
  226935. const OpenGLPixelFormat& pixelFormat_,
  226936. NSOpenGLContext* sharedContext)
  226937. : renderContext (0),
  226938. pixelFormat (pixelFormat_)
  226939. {
  226940. jassert (component != 0);
  226941. NSOpenGLPixelFormatAttribute attribs [64];
  226942. int n = 0;
  226943. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226944. attribs[n++] = NSOpenGLPFAAccelerated;
  226945. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  226946. attribs[n++] = NSOpenGLPFAColorSize;
  226947. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226948. pixelFormat.greenBits,
  226949. pixelFormat.blueBits);
  226950. attribs[n++] = NSOpenGLPFAAlphaSize;
  226951. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226952. attribs[n++] = NSOpenGLPFADepthSize;
  226953. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226954. attribs[n++] = NSOpenGLPFAStencilSize;
  226955. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226956. attribs[n++] = NSOpenGLPFAAccumSize;
  226957. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226958. pixelFormat.accumulationBufferGreenBits,
  226959. pixelFormat.accumulationBufferBlueBits,
  226960. pixelFormat.accumulationBufferAlphaBits);
  226961. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226962. attribs[n++] = NSOpenGLPFASampleBuffers;
  226963. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226964. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226965. attribs[n++] = NSOpenGLPFANoRecovery;
  226966. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226967. NSOpenGLPixelFormat* format
  226968. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226969. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226970. pixelFormat: format];
  226971. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  226972. shareContext: sharedContext] autorelease];
  226973. const GLint swapInterval = 1;
  226974. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  226975. [view setOpenGLContext: renderContext];
  226976. [renderContext setView: view];
  226977. [format release];
  226978. viewHolder = new NSViewComponentInternal (view, component);
  226979. }
  226980. ~WindowedGLContext()
  226981. {
  226982. deleteContext();
  226983. viewHolder = 0;
  226984. }
  226985. void deleteContext()
  226986. {
  226987. makeInactive();
  226988. [renderContext clearDrawable];
  226989. [renderContext setView: nil];
  226990. [view setOpenGLContext: nil];
  226991. renderContext = nil;
  226992. }
  226993. bool makeActive() const throw()
  226994. {
  226995. jassert (renderContext != 0);
  226996. [view makeActive];
  226997. return isActive();
  226998. }
  226999. bool makeInactive() const throw()
  227000. {
  227001. [view makeInactive];
  227002. return true;
  227003. }
  227004. bool isActive() const throw()
  227005. {
  227006. return [NSOpenGLContext currentContext] == renderContext;
  227007. }
  227008. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227009. void* getRawContext() const throw() { return renderContext; }
  227010. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227011. {
  227012. }
  227013. void swapBuffers()
  227014. {
  227015. [renderContext flushBuffer];
  227016. }
  227017. bool setSwapInterval (const int numFramesPerSwap)
  227018. {
  227019. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227020. forParameter: NSOpenGLCPSwapInterval];
  227021. return true;
  227022. }
  227023. int getSwapInterval() const
  227024. {
  227025. GLint numFrames = 0;
  227026. [renderContext getValues: &numFrames
  227027. forParameter: NSOpenGLCPSwapInterval];
  227028. return numFrames;
  227029. }
  227030. void repaint()
  227031. {
  227032. // we need to invalidate the juce view that holds this gl view, to make it
  227033. // cause a repaint callback
  227034. NSView* v = (NSView*) viewHolder->view;
  227035. NSRect r = [v frame];
  227036. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227037. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227038. // repaint message, thus never causing our paint() callback, and never repainting
  227039. // the comp. So invalidating just a little bit around the edge helps..
  227040. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227041. }
  227042. void* getNativeWindowHandle() const { return viewHolder->view; }
  227043. juce_UseDebuggingNewOperator
  227044. NSOpenGLContext* renderContext;
  227045. ThreadSafeNSOpenGLView* view;
  227046. private:
  227047. OpenGLPixelFormat pixelFormat;
  227048. ScopedPointer <NSViewComponentInternal> viewHolder;
  227049. WindowedGLContext (const WindowedGLContext&);
  227050. WindowedGLContext& operator= (const WindowedGLContext&);
  227051. };
  227052. OpenGLContext* OpenGLComponent::createContext()
  227053. {
  227054. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  227055. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227056. return (c->renderContext != 0) ? c.release() : 0;
  227057. }
  227058. void* OpenGLComponent::getNativeWindowHandle() const
  227059. {
  227060. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227061. : 0;
  227062. }
  227063. void juce_glViewport (const int w, const int h)
  227064. {
  227065. glViewport (0, 0, w, h);
  227066. }
  227067. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227068. OwnedArray <OpenGLPixelFormat>& results)
  227069. {
  227070. /* GLint attribs [64];
  227071. int n = 0;
  227072. attribs[n++] = AGL_RGBA;
  227073. attribs[n++] = AGL_DOUBLEBUFFER;
  227074. attribs[n++] = AGL_ACCELERATED;
  227075. attribs[n++] = AGL_NO_RECOVERY;
  227076. attribs[n++] = AGL_NONE;
  227077. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227078. while (p != 0)
  227079. {
  227080. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227081. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227082. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227083. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227084. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227085. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227086. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227087. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227088. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227089. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227090. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227091. results.add (pf);
  227092. p = aglNextPixelFormat (p);
  227093. }*/
  227094. //jassertfalse //xxx can't see how you do this in cocoa!
  227095. }
  227096. #else
  227097. END_JUCE_NAMESPACE
  227098. @interface JuceGLView : UIView
  227099. {
  227100. }
  227101. + (Class) layerClass;
  227102. @end
  227103. @implementation JuceGLView
  227104. + (Class) layerClass
  227105. {
  227106. return [CAEAGLLayer class];
  227107. }
  227108. @end
  227109. BEGIN_JUCE_NAMESPACE
  227110. class GLESContext : public OpenGLContext
  227111. {
  227112. public:
  227113. GLESContext (UIViewComponentPeer* peer,
  227114. Component* const component_,
  227115. const OpenGLPixelFormat& pixelFormat_,
  227116. const GLESContext* const sharedContext,
  227117. NSUInteger apiType)
  227118. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227119. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227120. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227121. {
  227122. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227123. view.opaque = YES;
  227124. view.hidden = NO;
  227125. view.backgroundColor = [UIColor blackColor];
  227126. view.userInteractionEnabled = NO;
  227127. glLayer = (CAEAGLLayer*) [view layer];
  227128. [peer->view addSubview: view];
  227129. if (sharedContext != 0)
  227130. context = [[EAGLContext alloc] initWithAPI: apiType
  227131. sharegroup: [sharedContext->context sharegroup]];
  227132. else
  227133. context = [[EAGLContext alloc] initWithAPI: apiType];
  227134. createGLBuffers();
  227135. }
  227136. ~GLESContext()
  227137. {
  227138. deleteContext();
  227139. [view removeFromSuperview];
  227140. [view release];
  227141. freeGLBuffers();
  227142. }
  227143. void deleteContext()
  227144. {
  227145. makeInactive();
  227146. [context release];
  227147. context = nil;
  227148. }
  227149. bool makeActive() const throw()
  227150. {
  227151. jassert (context != 0);
  227152. [EAGLContext setCurrentContext: context];
  227153. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227154. return true;
  227155. }
  227156. void swapBuffers()
  227157. {
  227158. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227159. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227160. }
  227161. bool makeInactive() const throw()
  227162. {
  227163. return [EAGLContext setCurrentContext: nil];
  227164. }
  227165. bool isActive() const throw()
  227166. {
  227167. return [EAGLContext currentContext] == context;
  227168. }
  227169. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227170. void* getRawContext() const throw() { return glLayer; }
  227171. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227172. {
  227173. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227174. if (lastWidth != w || lastHeight != h)
  227175. {
  227176. lastWidth = w;
  227177. lastHeight = h;
  227178. freeGLBuffers();
  227179. createGLBuffers();
  227180. }
  227181. }
  227182. bool setSwapInterval (const int numFramesPerSwap)
  227183. {
  227184. numFrames = numFramesPerSwap;
  227185. return true;
  227186. }
  227187. int getSwapInterval() const
  227188. {
  227189. return numFrames;
  227190. }
  227191. void repaint()
  227192. {
  227193. }
  227194. void createGLBuffers()
  227195. {
  227196. makeActive();
  227197. glGenFramebuffersOES (1, &frameBufferHandle);
  227198. glGenRenderbuffersOES (1, &colorBufferHandle);
  227199. glGenRenderbuffersOES (1, &depthBufferHandle);
  227200. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227201. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227202. GLint width, height;
  227203. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227204. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227205. if (useDepthBuffer)
  227206. {
  227207. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227208. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227209. }
  227210. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227211. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227212. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227213. if (useDepthBuffer)
  227214. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227215. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227216. }
  227217. void freeGLBuffers()
  227218. {
  227219. if (frameBufferHandle != 0)
  227220. {
  227221. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227222. frameBufferHandle = 0;
  227223. }
  227224. if (colorBufferHandle != 0)
  227225. {
  227226. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227227. colorBufferHandle = 0;
  227228. }
  227229. if (depthBufferHandle != 0)
  227230. {
  227231. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227232. depthBufferHandle = 0;
  227233. }
  227234. }
  227235. juce_UseDebuggingNewOperator
  227236. private:
  227237. Component::SafePointer<Component> component;
  227238. OpenGLPixelFormat pixelFormat;
  227239. JuceGLView* view;
  227240. CAEAGLLayer* glLayer;
  227241. EAGLContext* context;
  227242. bool useDepthBuffer;
  227243. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227244. int numFrames;
  227245. int lastWidth, lastHeight;
  227246. GLESContext (const GLESContext&);
  227247. GLESContext& operator= (const GLESContext&);
  227248. };
  227249. OpenGLContext* OpenGLComponent::createContext()
  227250. {
  227251. ScopedAutoReleasePool pool;
  227252. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227253. if (peer != 0)
  227254. return new GLESContext (peer, this, preferredPixelFormat,
  227255. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227256. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227257. return 0;
  227258. }
  227259. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227260. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227261. {
  227262. }
  227263. void juce_glViewport (const int w, const int h)
  227264. {
  227265. glViewport (0, 0, w, h);
  227266. }
  227267. #endif
  227268. #endif
  227269. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227270. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227271. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227272. // compiled on its own).
  227273. #if JUCE_INCLUDED_FILE
  227274. #if JUCE_MAC
  227275. namespace MouseCursorHelpers
  227276. {
  227277. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227278. {
  227279. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227280. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227281. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227282. [im release];
  227283. return c;
  227284. }
  227285. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227286. {
  227287. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227288. BufferedInputStream buf (&fileStream, 4096, false);
  227289. PNGImageFormat pngFormat;
  227290. Image im (pngFormat.decodeImage (buf));
  227291. if (im.isValid())
  227292. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227293. jassertfalse;
  227294. return 0;
  227295. }
  227296. }
  227297. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227298. {
  227299. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227300. }
  227301. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227302. {
  227303. const ScopedAutoReleasePool pool;
  227304. NSCursor* c = 0;
  227305. switch (type)
  227306. {
  227307. case NormalCursor: c = [NSCursor arrowCursor]; break;
  227308. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  227309. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  227310. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  227311. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  227312. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  227313. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227314. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227315. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227316. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227317. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227318. case UpDownResizeCursor:
  227319. case TopEdgeResizeCursor:
  227320. case BottomEdgeResizeCursor:
  227321. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227322. case TopLeftCornerResizeCursor:
  227323. case BottomRightCornerResizeCursor:
  227324. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227325. case TopRightCornerResizeCursor:
  227326. case BottomLeftCornerResizeCursor:
  227327. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227328. case UpDownLeftRightResizeCursor:
  227329. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227330. default:
  227331. jassertfalse;
  227332. break;
  227333. }
  227334. [c retain];
  227335. return c;
  227336. }
  227337. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227338. {
  227339. [((NSCursor*) cursorHandle) release];
  227340. }
  227341. void MouseCursor::showInAllWindows() const
  227342. {
  227343. showInWindow (0);
  227344. }
  227345. void MouseCursor::showInWindow (ComponentPeer*) const
  227346. {
  227347. [((NSCursor*) getHandle()) set];
  227348. }
  227349. #else
  227350. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  227351. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  227352. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  227353. void MouseCursor::showInAllWindows() const {}
  227354. void MouseCursor::showInWindow (ComponentPeer*) const {}
  227355. #endif
  227356. #endif
  227357. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  227358. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227359. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227360. // compiled on its own).
  227361. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  227362. #if JUCE_MAC
  227363. END_JUCE_NAMESPACE
  227364. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  227365. @interface DownloadClickDetector : NSObject
  227366. {
  227367. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  227368. }
  227369. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  227370. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227371. request: (NSURLRequest*) request
  227372. frame: (WebFrame*) frame
  227373. decisionListener: (id<WebPolicyDecisionListener>) listener;
  227374. @end
  227375. @implementation DownloadClickDetector
  227376. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227377. {
  227378. [super init];
  227379. ownerComponent = ownerComponent_;
  227380. return self;
  227381. }
  227382. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227383. request: (NSURLRequest*) request
  227384. frame: (WebFrame*) frame
  227385. decisionListener: (id <WebPolicyDecisionListener>) listener
  227386. {
  227387. (void) sender;
  227388. (void) request;
  227389. (void) frame;
  227390. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227391. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227392. [listener use];
  227393. else
  227394. [listener ignore];
  227395. }
  227396. @end
  227397. BEGIN_JUCE_NAMESPACE
  227398. class WebBrowserComponentInternal : public NSViewComponent
  227399. {
  227400. public:
  227401. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227402. {
  227403. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227404. frameName: @""
  227405. groupName: @""];
  227406. setView (webView);
  227407. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227408. [webView setPolicyDelegate: clickListener];
  227409. }
  227410. ~WebBrowserComponentInternal()
  227411. {
  227412. [webView setPolicyDelegate: nil];
  227413. [clickListener release];
  227414. setView (0);
  227415. }
  227416. void goToURL (const String& url,
  227417. const StringArray* headers,
  227418. const MemoryBlock* postData)
  227419. {
  227420. NSMutableURLRequest* r
  227421. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  227422. cachePolicy: NSURLRequestUseProtocolCachePolicy
  227423. timeoutInterval: 30.0];
  227424. if (postData != 0 && postData->getSize() > 0)
  227425. {
  227426. [r setHTTPMethod: @"POST"];
  227427. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  227428. length: postData->getSize()]];
  227429. }
  227430. if (headers != 0)
  227431. {
  227432. for (int i = 0; i < headers->size(); ++i)
  227433. {
  227434. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  227435. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  227436. [r setValue: juceStringToNS (headerValue)
  227437. forHTTPHeaderField: juceStringToNS (headerName)];
  227438. }
  227439. }
  227440. stop();
  227441. [[webView mainFrame] loadRequest: r];
  227442. }
  227443. void goBack()
  227444. {
  227445. [webView goBack];
  227446. }
  227447. void goForward()
  227448. {
  227449. [webView goForward];
  227450. }
  227451. void stop()
  227452. {
  227453. [webView stopLoading: nil];
  227454. }
  227455. void refresh()
  227456. {
  227457. [webView reload: nil];
  227458. }
  227459. private:
  227460. WebView* webView;
  227461. DownloadClickDetector* clickListener;
  227462. };
  227463. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227464. : browser (0),
  227465. blankPageShown (false),
  227466. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  227467. {
  227468. setOpaque (true);
  227469. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  227470. }
  227471. WebBrowserComponent::~WebBrowserComponent()
  227472. {
  227473. deleteAndZero (browser);
  227474. }
  227475. void WebBrowserComponent::goToURL (const String& url,
  227476. const StringArray* headers,
  227477. const MemoryBlock* postData)
  227478. {
  227479. lastURL = url;
  227480. lastHeaders.clear();
  227481. if (headers != 0)
  227482. lastHeaders = *headers;
  227483. lastPostData.setSize (0);
  227484. if (postData != 0)
  227485. lastPostData = *postData;
  227486. blankPageShown = false;
  227487. browser->goToURL (url, headers, postData);
  227488. }
  227489. void WebBrowserComponent::stop()
  227490. {
  227491. browser->stop();
  227492. }
  227493. void WebBrowserComponent::goBack()
  227494. {
  227495. lastURL = String::empty;
  227496. blankPageShown = false;
  227497. browser->goBack();
  227498. }
  227499. void WebBrowserComponent::goForward()
  227500. {
  227501. lastURL = String::empty;
  227502. browser->goForward();
  227503. }
  227504. void WebBrowserComponent::refresh()
  227505. {
  227506. browser->refresh();
  227507. }
  227508. void WebBrowserComponent::paint (Graphics&)
  227509. {
  227510. }
  227511. void WebBrowserComponent::checkWindowAssociation()
  227512. {
  227513. if (isShowing())
  227514. {
  227515. if (blankPageShown)
  227516. goBack();
  227517. }
  227518. else
  227519. {
  227520. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  227521. {
  227522. // when the component becomes invisible, some stuff like flash
  227523. // carries on playing audio, so we need to force it onto a blank
  227524. // page to avoid this, (and send it back when it's made visible again).
  227525. blankPageShown = true;
  227526. browser->goToURL ("about:blank", 0, 0);
  227527. }
  227528. }
  227529. }
  227530. void WebBrowserComponent::reloadLastURL()
  227531. {
  227532. if (lastURL.isNotEmpty())
  227533. {
  227534. goToURL (lastURL, &lastHeaders, &lastPostData);
  227535. lastURL = String::empty;
  227536. }
  227537. }
  227538. void WebBrowserComponent::parentHierarchyChanged()
  227539. {
  227540. checkWindowAssociation();
  227541. }
  227542. void WebBrowserComponent::resized()
  227543. {
  227544. browser->setSize (getWidth(), getHeight());
  227545. }
  227546. void WebBrowserComponent::visibilityChanged()
  227547. {
  227548. checkWindowAssociation();
  227549. }
  227550. bool WebBrowserComponent::pageAboutToLoad (const String&)
  227551. {
  227552. return true;
  227553. }
  227554. #else
  227555. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227556. {
  227557. }
  227558. WebBrowserComponent::~WebBrowserComponent()
  227559. {
  227560. }
  227561. void WebBrowserComponent::goToURL (const String& url,
  227562. const StringArray* headers,
  227563. const MemoryBlock* postData)
  227564. {
  227565. }
  227566. void WebBrowserComponent::stop()
  227567. {
  227568. }
  227569. void WebBrowserComponent::goBack()
  227570. {
  227571. }
  227572. void WebBrowserComponent::goForward()
  227573. {
  227574. }
  227575. void WebBrowserComponent::refresh()
  227576. {
  227577. }
  227578. void WebBrowserComponent::paint (Graphics& g)
  227579. {
  227580. }
  227581. void WebBrowserComponent::checkWindowAssociation()
  227582. {
  227583. }
  227584. void WebBrowserComponent::reloadLastURL()
  227585. {
  227586. }
  227587. void WebBrowserComponent::parentHierarchyChanged()
  227588. {
  227589. }
  227590. void WebBrowserComponent::resized()
  227591. {
  227592. }
  227593. void WebBrowserComponent::visibilityChanged()
  227594. {
  227595. }
  227596. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227597. {
  227598. return true;
  227599. }
  227600. #endif
  227601. #endif
  227602. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227603. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  227604. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227605. // compiled on its own).
  227606. #if JUCE_INCLUDED_FILE
  227607. class IPhoneAudioIODevice : public AudioIODevice
  227608. {
  227609. public:
  227610. IPhoneAudioIODevice (const String& deviceName)
  227611. : AudioIODevice (deviceName, "Audio"),
  227612. audioUnit (0),
  227613. isRunning (false),
  227614. callback (0),
  227615. actualBufferSize (0),
  227616. floatData (1, 2)
  227617. {
  227618. numInputChannels = 2;
  227619. numOutputChannels = 2;
  227620. preferredBufferSize = 0;
  227621. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  227622. updateDeviceInfo();
  227623. }
  227624. ~IPhoneAudioIODevice()
  227625. {
  227626. close();
  227627. }
  227628. const StringArray getOutputChannelNames()
  227629. {
  227630. StringArray s;
  227631. s.add ("Left");
  227632. s.add ("Right");
  227633. return s;
  227634. }
  227635. const StringArray getInputChannelNames()
  227636. {
  227637. StringArray s;
  227638. if (audioInputIsAvailable)
  227639. {
  227640. s.add ("Left");
  227641. s.add ("Right");
  227642. }
  227643. return s;
  227644. }
  227645. int getNumSampleRates()
  227646. {
  227647. return 1;
  227648. }
  227649. double getSampleRate (int index)
  227650. {
  227651. return sampleRate;
  227652. }
  227653. int getNumBufferSizesAvailable()
  227654. {
  227655. return 1;
  227656. }
  227657. int getBufferSizeSamples (int index)
  227658. {
  227659. return getDefaultBufferSize();
  227660. }
  227661. int getDefaultBufferSize()
  227662. {
  227663. return 1024;
  227664. }
  227665. const String open (const BigInteger& inputChannels,
  227666. const BigInteger& outputChannels,
  227667. double sampleRate,
  227668. int bufferSize)
  227669. {
  227670. close();
  227671. lastError = String::empty;
  227672. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  227673. // xxx set up channel mapping
  227674. activeOutputChans = outputChannels;
  227675. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  227676. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  227677. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  227678. activeInputChans = inputChannels;
  227679. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  227680. numInputChannels = activeInputChans.countNumberOfSetBits();
  227681. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  227682. AudioSessionSetActive (true);
  227683. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  227684. : kAudioSessionCategory_MediaPlayback;
  227685. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  227686. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  227687. fixAudioRouteIfSetToReceiver();
  227688. updateDeviceInfo();
  227689. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227690. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  227691. actualBufferSize = preferredBufferSize;
  227692. prepareFloatBuffers();
  227693. isRunning = true;
  227694. propertyChanged (0, 0, 0); // creates and starts the AU
  227695. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  227696. return lastError;
  227697. }
  227698. void close()
  227699. {
  227700. if (isRunning)
  227701. {
  227702. isRunning = false;
  227703. AudioSessionSetActive (false);
  227704. if (audioUnit != 0)
  227705. {
  227706. AudioComponentInstanceDispose (audioUnit);
  227707. audioUnit = 0;
  227708. }
  227709. }
  227710. }
  227711. bool isOpen()
  227712. {
  227713. return isRunning;
  227714. }
  227715. int getCurrentBufferSizeSamples()
  227716. {
  227717. return actualBufferSize;
  227718. }
  227719. double getCurrentSampleRate()
  227720. {
  227721. return sampleRate;
  227722. }
  227723. int getCurrentBitDepth()
  227724. {
  227725. return 16;
  227726. }
  227727. const BigInteger getActiveOutputChannels() const
  227728. {
  227729. return activeOutputChans;
  227730. }
  227731. const BigInteger getActiveInputChannels() const
  227732. {
  227733. return activeInputChans;
  227734. }
  227735. int getOutputLatencyInSamples()
  227736. {
  227737. return 0; //xxx
  227738. }
  227739. int getInputLatencyInSamples()
  227740. {
  227741. return 0; //xxx
  227742. }
  227743. void start (AudioIODeviceCallback* callback_)
  227744. {
  227745. if (isRunning && callback != callback_)
  227746. {
  227747. if (callback_ != 0)
  227748. callback_->audioDeviceAboutToStart (this);
  227749. const ScopedLock sl (callbackLock);
  227750. callback = callback_;
  227751. }
  227752. }
  227753. void stop()
  227754. {
  227755. if (isRunning)
  227756. {
  227757. AudioIODeviceCallback* lastCallback;
  227758. {
  227759. const ScopedLock sl (callbackLock);
  227760. lastCallback = callback;
  227761. callback = 0;
  227762. }
  227763. if (lastCallback != 0)
  227764. lastCallback->audioDeviceStopped();
  227765. }
  227766. }
  227767. bool isPlaying()
  227768. {
  227769. return isRunning && callback != 0;
  227770. }
  227771. const String getLastError()
  227772. {
  227773. return lastError;
  227774. }
  227775. private:
  227776. CriticalSection callbackLock;
  227777. Float64 sampleRate;
  227778. int numInputChannels, numOutputChannels;
  227779. int preferredBufferSize;
  227780. int actualBufferSize;
  227781. bool isRunning;
  227782. String lastError;
  227783. AudioStreamBasicDescription format;
  227784. AudioUnit audioUnit;
  227785. UInt32 audioInputIsAvailable;
  227786. AudioIODeviceCallback* callback;
  227787. BigInteger activeOutputChans, activeInputChans;
  227788. AudioSampleBuffer floatData;
  227789. float* inputChannels[3];
  227790. float* outputChannels[3];
  227791. bool monoInputChannelNumber, monoOutputChannelNumber;
  227792. void prepareFloatBuffers()
  227793. {
  227794. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  227795. zerostruct (inputChannels);
  227796. zerostruct (outputChannels);
  227797. for (int i = 0; i < numInputChannels; ++i)
  227798. inputChannels[i] = floatData.getSampleData (i);
  227799. for (int i = 0; i < numOutputChannels; ++i)
  227800. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  227801. }
  227802. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227803. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227804. {
  227805. OSStatus err = noErr;
  227806. if (audioInputIsAvailable)
  227807. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  227808. const ScopedLock sl (callbackLock);
  227809. if (callback != 0)
  227810. {
  227811. if (audioInputIsAvailable && numInputChannels > 0)
  227812. {
  227813. short* shortData = (short*) ioData->mBuffers[0].mData;
  227814. if (numInputChannels >= 2)
  227815. {
  227816. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227817. {
  227818. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227819. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  227820. }
  227821. }
  227822. else
  227823. {
  227824. if (monoInputChannelNumber > 0)
  227825. ++shortData;
  227826. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227827. {
  227828. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227829. ++shortData;
  227830. }
  227831. }
  227832. }
  227833. else
  227834. {
  227835. for (int i = numInputChannels; --i >= 0;)
  227836. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  227837. }
  227838. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  227839. outputChannels, numOutputChannels,
  227840. (int) inNumberFrames);
  227841. short* shortData = (short*) ioData->mBuffers[0].mData;
  227842. int n = 0;
  227843. if (numOutputChannels >= 2)
  227844. {
  227845. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227846. {
  227847. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  227848. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  227849. }
  227850. }
  227851. else if (numOutputChannels == 1)
  227852. {
  227853. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227854. {
  227855. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  227856. shortData [n++] = s;
  227857. shortData [n++] = s;
  227858. }
  227859. }
  227860. else
  227861. {
  227862. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227863. }
  227864. }
  227865. else
  227866. {
  227867. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227868. }
  227869. return err;
  227870. }
  227871. void updateDeviceInfo()
  227872. {
  227873. UInt32 size = sizeof (sampleRate);
  227874. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  227875. size = sizeof (audioInputIsAvailable);
  227876. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  227877. }
  227878. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227879. {
  227880. if (! isRunning)
  227881. return;
  227882. if (inPropertyValue != 0)
  227883. {
  227884. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  227885. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  227886. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  227887. SInt32 routeChangeReason;
  227888. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  227889. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  227890. fixAudioRouteIfSetToReceiver();
  227891. }
  227892. updateDeviceInfo();
  227893. createAudioUnit();
  227894. AudioSessionSetActive (true);
  227895. if (audioUnit != 0)
  227896. {
  227897. UInt32 formatSize = sizeof (format);
  227898. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  227899. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227900. UInt32 bufferDurationSize = sizeof (bufferDuration);
  227901. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  227902. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  227903. AudioOutputUnitStart (audioUnit);
  227904. }
  227905. }
  227906. void interruptionListener (UInt32 inInterruption)
  227907. {
  227908. /*if (inInterruption == kAudioSessionBeginInterruption)
  227909. {
  227910. isRunning = false;
  227911. AudioOutputUnitStop (audioUnit);
  227912. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  227913. "This could have been interrupted by another application or by unplugging a headset",
  227914. @"Resume",
  227915. @"Cancel"))
  227916. {
  227917. isRunning = true;
  227918. propertyChanged (0, 0, 0);
  227919. }
  227920. }*/
  227921. if (inInterruption == kAudioSessionEndInterruption)
  227922. {
  227923. isRunning = true;
  227924. AudioSessionSetActive (true);
  227925. AudioOutputUnitStart (audioUnit);
  227926. }
  227927. }
  227928. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227929. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227930. {
  227931. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  227932. }
  227933. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227934. {
  227935. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  227936. }
  227937. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  227938. {
  227939. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  227940. }
  227941. void resetFormat (const int numChannels)
  227942. {
  227943. memset (&format, 0, sizeof (format));
  227944. format.mFormatID = kAudioFormatLinearPCM;
  227945. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  227946. format.mBitsPerChannel = 8 * sizeof (short);
  227947. format.mChannelsPerFrame = 2;
  227948. format.mFramesPerPacket = 1;
  227949. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  227950. }
  227951. bool createAudioUnit()
  227952. {
  227953. if (audioUnit != 0)
  227954. {
  227955. AudioComponentInstanceDispose (audioUnit);
  227956. audioUnit = 0;
  227957. }
  227958. resetFormat (2);
  227959. AudioComponentDescription desc;
  227960. desc.componentType = kAudioUnitType_Output;
  227961. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  227962. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  227963. desc.componentFlags = 0;
  227964. desc.componentFlagsMask = 0;
  227965. AudioComponent comp = AudioComponentFindNext (0, &desc);
  227966. AudioComponentInstanceNew (comp, &audioUnit);
  227967. if (audioUnit == 0)
  227968. return false;
  227969. const UInt32 one = 1;
  227970. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  227971. AudioChannelLayout layout;
  227972. layout.mChannelBitmap = 0;
  227973. layout.mNumberChannelDescriptions = 0;
  227974. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  227975. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  227976. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  227977. AURenderCallbackStruct inputProc;
  227978. inputProc.inputProc = processStatic;
  227979. inputProc.inputProcRefCon = this;
  227980. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  227981. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  227982. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  227983. AudioUnitInitialize (audioUnit);
  227984. return true;
  227985. }
  227986. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  227987. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  227988. static void fixAudioRouteIfSetToReceiver()
  227989. {
  227990. CFStringRef audioRoute = 0;
  227991. UInt32 propertySize = sizeof (audioRoute);
  227992. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  227993. {
  227994. NSString* route = (NSString*) audioRoute;
  227995. //DBG ("audio route: " + nsStringToJuce (route));
  227996. if ([route hasPrefix: @"Receiver"])
  227997. {
  227998. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  227999. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  228000. }
  228001. CFRelease (audioRoute);
  228002. }
  228003. }
  228004. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  228005. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  228006. };
  228007. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228008. {
  228009. public:
  228010. IPhoneAudioIODeviceType()
  228011. : AudioIODeviceType ("iPhone Audio")
  228012. {
  228013. }
  228014. ~IPhoneAudioIODeviceType()
  228015. {
  228016. }
  228017. void scanForDevices()
  228018. {
  228019. }
  228020. const StringArray getDeviceNames (bool wantInputNames) const
  228021. {
  228022. StringArray s;
  228023. s.add ("iPhone Audio");
  228024. return s;
  228025. }
  228026. int getDefaultDeviceIndex (bool forInput) const
  228027. {
  228028. return 0;
  228029. }
  228030. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228031. {
  228032. return device != 0 ? 0 : -1;
  228033. }
  228034. bool hasSeparateInputsAndOutputs() const { return false; }
  228035. AudioIODevice* createDevice (const String& outputDeviceName,
  228036. const String& inputDeviceName)
  228037. {
  228038. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228039. {
  228040. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228041. : inputDeviceName);
  228042. }
  228043. return 0;
  228044. }
  228045. juce_UseDebuggingNewOperator
  228046. private:
  228047. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  228048. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  228049. };
  228050. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228051. {
  228052. return new IPhoneAudioIODeviceType();
  228053. }
  228054. #endif
  228055. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  228056. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228057. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228058. // compiled on its own).
  228059. #if JUCE_INCLUDED_FILE
  228060. #if JUCE_MAC
  228061. #undef log
  228062. #define log(a) Logger::writeToLog(a)
  228063. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  228064. {
  228065. if (err == noErr)
  228066. return true;
  228067. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228068. jassertfalse;
  228069. return false;
  228070. }
  228071. #undef OK
  228072. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  228073. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228074. {
  228075. String result;
  228076. CFStringRef str = 0;
  228077. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228078. if (str != 0)
  228079. {
  228080. result = PlatformUtilities::cfStringToJuceString (str);
  228081. CFRelease (str);
  228082. str = 0;
  228083. }
  228084. MIDIEntityRef entity = 0;
  228085. MIDIEndpointGetEntity (endpoint, &entity);
  228086. if (entity == 0)
  228087. return result; // probably virtual
  228088. if (result.isEmpty())
  228089. {
  228090. // endpoint name has zero length - try the entity
  228091. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228092. if (str != 0)
  228093. {
  228094. result += PlatformUtilities::cfStringToJuceString (str);
  228095. CFRelease (str);
  228096. str = 0;
  228097. }
  228098. }
  228099. // now consider the device's name
  228100. MIDIDeviceRef device = 0;
  228101. MIDIEntityGetDevice (entity, &device);
  228102. if (device == 0)
  228103. return result;
  228104. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228105. if (str != 0)
  228106. {
  228107. const String s (PlatformUtilities::cfStringToJuceString (str));
  228108. CFRelease (str);
  228109. // if an external device has only one entity, throw away
  228110. // the endpoint name and just use the device name
  228111. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228112. {
  228113. result = s;
  228114. }
  228115. else if (! result.startsWithIgnoreCase (s))
  228116. {
  228117. // prepend the device name to the entity name
  228118. result = (s + " " + result).trimEnd();
  228119. }
  228120. }
  228121. return result;
  228122. }
  228123. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228124. {
  228125. String result;
  228126. // Does the endpoint have connections?
  228127. CFDataRef connections = 0;
  228128. int numConnections = 0;
  228129. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228130. if (connections != 0)
  228131. {
  228132. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228133. if (numConnections > 0)
  228134. {
  228135. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228136. for (int i = 0; i < numConnections; ++i, ++pid)
  228137. {
  228138. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228139. MIDIObjectRef connObject;
  228140. MIDIObjectType connObjectType;
  228141. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228142. if (err == noErr)
  228143. {
  228144. String s;
  228145. if (connObjectType == kMIDIObjectType_ExternalSource
  228146. || connObjectType == kMIDIObjectType_ExternalDestination)
  228147. {
  228148. // Connected to an external device's endpoint (10.3 and later).
  228149. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228150. }
  228151. else
  228152. {
  228153. // Connected to an external device (10.2) (or something else, catch-all)
  228154. CFStringRef str = 0;
  228155. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228156. if (str != 0)
  228157. {
  228158. s = PlatformUtilities::cfStringToJuceString (str);
  228159. CFRelease (str);
  228160. }
  228161. }
  228162. if (s.isNotEmpty())
  228163. {
  228164. if (result.isNotEmpty())
  228165. result += ", ";
  228166. result += s;
  228167. }
  228168. }
  228169. }
  228170. }
  228171. CFRelease (connections);
  228172. }
  228173. if (result.isNotEmpty())
  228174. return result;
  228175. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228176. return getEndpointName (endpoint, false);
  228177. }
  228178. const StringArray MidiOutput::getDevices()
  228179. {
  228180. StringArray s;
  228181. const ItemCount num = MIDIGetNumberOfDestinations();
  228182. for (ItemCount i = 0; i < num; ++i)
  228183. {
  228184. MIDIEndpointRef dest = MIDIGetDestination (i);
  228185. if (dest != 0)
  228186. {
  228187. String name (getConnectedEndpointName (dest));
  228188. if (name.isEmpty())
  228189. name = "<error>";
  228190. s.add (name);
  228191. }
  228192. else
  228193. {
  228194. s.add ("<error>");
  228195. }
  228196. }
  228197. return s;
  228198. }
  228199. int MidiOutput::getDefaultDeviceIndex()
  228200. {
  228201. return 0;
  228202. }
  228203. static MIDIClientRef globalMidiClient;
  228204. static bool hasGlobalClientBeenCreated = false;
  228205. static bool makeSureClientExists()
  228206. {
  228207. if (! hasGlobalClientBeenCreated)
  228208. {
  228209. String name ("JUCE");
  228210. if (JUCEApplication::getInstance() != 0)
  228211. name = JUCEApplication::getInstance()->getApplicationName();
  228212. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228213. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228214. CFRelease (appName);
  228215. }
  228216. return hasGlobalClientBeenCreated;
  228217. }
  228218. class MidiPortAndEndpoint
  228219. {
  228220. public:
  228221. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228222. : port (port_), endPoint (endPoint_)
  228223. {
  228224. }
  228225. ~MidiPortAndEndpoint()
  228226. {
  228227. if (port != 0)
  228228. MIDIPortDispose (port);
  228229. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228230. MIDIEndpointDispose (endPoint);
  228231. }
  228232. MIDIPortRef port;
  228233. MIDIEndpointRef endPoint;
  228234. };
  228235. MidiOutput* MidiOutput::openDevice (int index)
  228236. {
  228237. MidiOutput* mo = 0;
  228238. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  228239. {
  228240. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228241. CFStringRef pname;
  228242. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228243. {
  228244. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  228245. if (makeSureClientExists())
  228246. {
  228247. MIDIPortRef port;
  228248. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  228249. {
  228250. mo = new MidiOutput();
  228251. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  228252. }
  228253. }
  228254. CFRelease (pname);
  228255. }
  228256. }
  228257. return mo;
  228258. }
  228259. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  228260. {
  228261. MidiOutput* mo = 0;
  228262. if (makeSureClientExists())
  228263. {
  228264. MIDIEndpointRef endPoint;
  228265. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  228266. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  228267. {
  228268. mo = new MidiOutput();
  228269. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  228270. }
  228271. CFRelease (name);
  228272. }
  228273. return mo;
  228274. }
  228275. MidiOutput::~MidiOutput()
  228276. {
  228277. delete (MidiPortAndEndpoint*) internal;
  228278. }
  228279. void MidiOutput::reset()
  228280. {
  228281. }
  228282. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228283. {
  228284. return false;
  228285. }
  228286. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228287. {
  228288. }
  228289. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228290. {
  228291. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  228292. if (message.isSysEx())
  228293. {
  228294. const int maxPacketSize = 256;
  228295. int pos = 0, bytesLeft = message.getRawDataSize();
  228296. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228297. HeapBlock <MIDIPacketList> packets;
  228298. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  228299. packets->numPackets = numPackets;
  228300. MIDIPacket* p = packets->packet;
  228301. for (int i = 0; i < numPackets; ++i)
  228302. {
  228303. p->timeStamp = 0;
  228304. p->length = jmin (maxPacketSize, bytesLeft);
  228305. memcpy (p->data, message.getRawData() + pos, p->length);
  228306. pos += p->length;
  228307. bytesLeft -= p->length;
  228308. p = MIDIPacketNext (p);
  228309. }
  228310. if (mpe->port != 0)
  228311. MIDISend (mpe->port, mpe->endPoint, packets);
  228312. else
  228313. MIDIReceived (mpe->endPoint, packets);
  228314. }
  228315. else
  228316. {
  228317. MIDIPacketList packets;
  228318. packets.numPackets = 1;
  228319. packets.packet[0].timeStamp = 0;
  228320. packets.packet[0].length = message.getRawDataSize();
  228321. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228322. if (mpe->port != 0)
  228323. MIDISend (mpe->port, mpe->endPoint, &packets);
  228324. else
  228325. MIDIReceived (mpe->endPoint, &packets);
  228326. }
  228327. }
  228328. const StringArray MidiInput::getDevices()
  228329. {
  228330. StringArray s;
  228331. const ItemCount num = MIDIGetNumberOfSources();
  228332. for (ItemCount i = 0; i < num; ++i)
  228333. {
  228334. MIDIEndpointRef source = MIDIGetSource (i);
  228335. if (source != 0)
  228336. {
  228337. String name (getConnectedEndpointName (source));
  228338. if (name.isEmpty())
  228339. name = "<error>";
  228340. s.add (name);
  228341. }
  228342. else
  228343. {
  228344. s.add ("<error>");
  228345. }
  228346. }
  228347. return s;
  228348. }
  228349. int MidiInput::getDefaultDeviceIndex()
  228350. {
  228351. return 0;
  228352. }
  228353. struct MidiPortAndCallback
  228354. {
  228355. MidiInput* input;
  228356. MidiPortAndEndpoint* portAndEndpoint;
  228357. MidiInputCallback* callback;
  228358. MemoryBlock pendingData;
  228359. int pendingBytes;
  228360. double pendingDataTime;
  228361. bool active;
  228362. void processSysex (const uint8*& d, int& size, const double time)
  228363. {
  228364. if (*d == 0xf0)
  228365. {
  228366. pendingBytes = 0;
  228367. pendingDataTime = time;
  228368. }
  228369. pendingData.ensureSize (pendingBytes + size, false);
  228370. uint8* totalMessage = (uint8*) pendingData.getData();
  228371. uint8* dest = totalMessage + pendingBytes;
  228372. while (size > 0)
  228373. {
  228374. if (pendingBytes > 0 && *d >= 0x80)
  228375. {
  228376. if (*d >= 0xfa || *d == 0xf8)
  228377. {
  228378. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  228379. ++d;
  228380. --size;
  228381. }
  228382. else
  228383. {
  228384. if (*d == 0xf7)
  228385. {
  228386. *dest++ = *d++;
  228387. pendingBytes++;
  228388. --size;
  228389. }
  228390. break;
  228391. }
  228392. }
  228393. else
  228394. {
  228395. *dest++ = *d++;
  228396. pendingBytes++;
  228397. --size;
  228398. }
  228399. }
  228400. if (totalMessage [pendingBytes - 1] == 0xf7)
  228401. {
  228402. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  228403. pendingBytes = 0;
  228404. }
  228405. else
  228406. {
  228407. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  228408. }
  228409. }
  228410. };
  228411. namespace CoreMidiCallbacks
  228412. {
  228413. static CriticalSection callbackLock;
  228414. static Array<void*> activeCallbacks;
  228415. }
  228416. static void midiInputProc (const MIDIPacketList* pktlist,
  228417. void* readProcRefCon,
  228418. void* /*srcConnRefCon*/)
  228419. {
  228420. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228421. const double originalTime = time;
  228422. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  228423. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228424. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  228425. {
  228426. const MIDIPacket* packet = &pktlist->packet[0];
  228427. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228428. {
  228429. const uint8* d = (const uint8*) (packet->data);
  228430. int size = packet->length;
  228431. while (size > 0)
  228432. {
  228433. time = originalTime;
  228434. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  228435. {
  228436. mpc->processSysex (d, size, time);
  228437. }
  228438. else
  228439. {
  228440. int used = 0;
  228441. const MidiMessage m (d, size, used, 0, time);
  228442. if (used <= 0)
  228443. {
  228444. jassertfalse; // malformed midi message
  228445. break;
  228446. }
  228447. else
  228448. {
  228449. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  228450. }
  228451. size -= used;
  228452. d += used;
  228453. }
  228454. }
  228455. packet = MIDIPacketNext (packet);
  228456. }
  228457. }
  228458. }
  228459. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228460. {
  228461. MidiInput* mi = 0;
  228462. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228463. {
  228464. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228465. if (endPoint != 0)
  228466. {
  228467. CFStringRef pname;
  228468. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228469. {
  228470. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  228471. if (makeSureClientExists())
  228472. {
  228473. MIDIPortRef port;
  228474. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228475. mpc->active = false;
  228476. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  228477. {
  228478. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228479. {
  228480. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  228481. mpc->callback = callback;
  228482. mpc->pendingBytes = 0;
  228483. mpc->pendingData.ensureSize (128);
  228484. mi = new MidiInput (getDevices() [index]);
  228485. mpc->input = mi;
  228486. mi->internal = mpc;
  228487. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228488. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228489. }
  228490. else
  228491. {
  228492. OK (MIDIPortDispose (port));
  228493. }
  228494. }
  228495. }
  228496. }
  228497. CFRelease (pname);
  228498. }
  228499. }
  228500. return mi;
  228501. }
  228502. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  228503. {
  228504. MidiInput* mi = 0;
  228505. if (makeSureClientExists())
  228506. {
  228507. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228508. mpc->active = false;
  228509. MIDIEndpointRef endPoint;
  228510. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  228511. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  228512. {
  228513. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  228514. mpc->callback = callback;
  228515. mpc->pendingBytes = 0;
  228516. mpc->pendingData.ensureSize (128);
  228517. mi = new MidiInput (deviceName);
  228518. mpc->input = mi;
  228519. mi->internal = mpc;
  228520. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228521. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228522. }
  228523. CFRelease (name);
  228524. }
  228525. return mi;
  228526. }
  228527. MidiInput::MidiInput (const String& name_)
  228528. : name (name_)
  228529. {
  228530. }
  228531. MidiInput::~MidiInput()
  228532. {
  228533. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  228534. mpc->active = false;
  228535. {
  228536. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228537. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  228538. }
  228539. if (mpc->portAndEndpoint->port != 0)
  228540. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  228541. delete mpc->portAndEndpoint;
  228542. delete mpc;
  228543. }
  228544. void MidiInput::start()
  228545. {
  228546. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228547. ((MidiPortAndCallback*) internal)->active = true;
  228548. }
  228549. void MidiInput::stop()
  228550. {
  228551. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228552. ((MidiPortAndCallback*) internal)->active = false;
  228553. }
  228554. #undef log
  228555. #else
  228556. MidiOutput::~MidiOutput()
  228557. {
  228558. }
  228559. void MidiOutput::reset()
  228560. {
  228561. }
  228562. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228563. {
  228564. return false;
  228565. }
  228566. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228567. {
  228568. }
  228569. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228570. {
  228571. }
  228572. const StringArray MidiOutput::getDevices()
  228573. {
  228574. return StringArray();
  228575. }
  228576. MidiOutput* MidiOutput::openDevice (int index)
  228577. {
  228578. return 0;
  228579. }
  228580. const StringArray MidiInput::getDevices()
  228581. {
  228582. return StringArray();
  228583. }
  228584. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228585. {
  228586. return 0;
  228587. }
  228588. #endif
  228589. #endif
  228590. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  228591. #else
  228592. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  228593. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228594. // compiled on its own).
  228595. #if JUCE_INCLUDED_FILE
  228596. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228597. #define SUPPORT_10_4_FONTS 1
  228598. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  228599. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228600. #define SUPPORT_ONLY_10_4_FONTS 1
  228601. #endif
  228602. END_JUCE_NAMESPACE
  228603. @interface NSFont (PrivateHack)
  228604. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  228605. @end
  228606. BEGIN_JUCE_NAMESPACE
  228607. #endif
  228608. class MacTypeface : public Typeface
  228609. {
  228610. public:
  228611. MacTypeface (const Font& font)
  228612. : Typeface (font.getTypefaceName())
  228613. {
  228614. const ScopedAutoReleasePool pool;
  228615. renderingTransform = CGAffineTransformIdentity;
  228616. bool needsItalicTransform = false;
  228617. #if JUCE_IOS
  228618. NSString* fontName = juceStringToNS (font.getTypefaceName());
  228619. if (font.isItalic() || font.isBold())
  228620. {
  228621. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  228622. for (NSString* i in familyFonts)
  228623. {
  228624. const String fn (nsStringToJuce (i));
  228625. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  228626. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  228627. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  228628. || afterDash.containsIgnoreCase ("italic")
  228629. || fn.endsWithIgnoreCase ("oblique")
  228630. || fn.endsWithIgnoreCase ("italic");
  228631. if (probablyBold == font.isBold()
  228632. && probablyItalic == font.isItalic())
  228633. {
  228634. fontName = i;
  228635. needsItalicTransform = false;
  228636. break;
  228637. }
  228638. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  228639. {
  228640. fontName = i;
  228641. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  228642. }
  228643. }
  228644. if (needsItalicTransform)
  228645. renderingTransform.c = 0.15f;
  228646. }
  228647. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  228648. const int ascender = abs (CGFontGetAscent (fontRef));
  228649. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  228650. ascent = ascender / totalHeight;
  228651. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228652. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  228653. #else
  228654. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  228655. if (font.isItalic())
  228656. {
  228657. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  228658. toHaveTrait: NSItalicFontMask];
  228659. if (newFont == nsFont)
  228660. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  228661. nsFont = newFont;
  228662. }
  228663. if (font.isBold())
  228664. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  228665. [nsFont retain];
  228666. ascent = std::abs ((float) [nsFont ascender]);
  228667. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  228668. ascent /= totalSize;
  228669. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  228670. if (needsItalicTransform)
  228671. {
  228672. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  228673. renderingTransform.c = 0.15f;
  228674. }
  228675. #if SUPPORT_ONLY_10_4_FONTS
  228676. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228677. if (atsFont == 0)
  228678. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228679. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228680. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228681. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228682. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228683. #else
  228684. #if SUPPORT_10_4_FONTS
  228685. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228686. {
  228687. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228688. if (atsFont == 0)
  228689. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228690. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228691. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228692. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228693. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228694. }
  228695. else
  228696. #endif
  228697. {
  228698. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  228699. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  228700. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228701. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  228702. }
  228703. #endif
  228704. #endif
  228705. }
  228706. ~MacTypeface()
  228707. {
  228708. #if ! JUCE_IOS
  228709. [nsFont release];
  228710. #endif
  228711. if (fontRef != 0)
  228712. CGFontRelease (fontRef);
  228713. }
  228714. float getAscent() const
  228715. {
  228716. return ascent;
  228717. }
  228718. float getDescent() const
  228719. {
  228720. return 1.0f - ascent;
  228721. }
  228722. float getStringWidth (const String& text)
  228723. {
  228724. if (fontRef == 0 || text.isEmpty())
  228725. return 0;
  228726. const int length = text.length();
  228727. HeapBlock <CGGlyph> glyphs;
  228728. createGlyphsForString (text, length, glyphs);
  228729. float x = 0;
  228730. #if SUPPORT_ONLY_10_4_FONTS
  228731. HeapBlock <NSSize> advances (length);
  228732. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228733. for (int i = 0; i < length; ++i)
  228734. x += advances[i].width;
  228735. #else
  228736. #if SUPPORT_10_4_FONTS
  228737. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228738. {
  228739. HeapBlock <NSSize> advances (length);
  228740. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  228741. for (int i = 0; i < length; ++i)
  228742. x += advances[i].width;
  228743. }
  228744. else
  228745. #endif
  228746. {
  228747. HeapBlock <int> advances (length);
  228748. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228749. for (int i = 0; i < length; ++i)
  228750. x += advances[i];
  228751. }
  228752. #endif
  228753. return x * unitsToHeightScaleFactor;
  228754. }
  228755. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  228756. {
  228757. xOffsets.add (0);
  228758. if (fontRef == 0 || text.isEmpty())
  228759. return;
  228760. const int length = text.length();
  228761. HeapBlock <CGGlyph> glyphs;
  228762. createGlyphsForString (text, length, glyphs);
  228763. #if SUPPORT_ONLY_10_4_FONTS
  228764. HeapBlock <NSSize> advances (length);
  228765. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228766. int x = 0;
  228767. for (int i = 0; i < length; ++i)
  228768. {
  228769. x += advances[i].width;
  228770. xOffsets.add (x * unitsToHeightScaleFactor);
  228771. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  228772. }
  228773. #else
  228774. #if SUPPORT_10_4_FONTS
  228775. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228776. {
  228777. HeapBlock <NSSize> advances (length);
  228778. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228779. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  228780. float x = 0;
  228781. for (int i = 0; i < length; ++i)
  228782. {
  228783. x += advances[i].width;
  228784. xOffsets.add (x * unitsToHeightScaleFactor);
  228785. resultGlyphs.add (nsGlyphs[i]);
  228786. }
  228787. }
  228788. else
  228789. #endif
  228790. {
  228791. HeapBlock <int> advances (length);
  228792. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228793. {
  228794. int x = 0;
  228795. for (int i = 0; i < length; ++i)
  228796. {
  228797. x += advances [i];
  228798. xOffsets.add (x * unitsToHeightScaleFactor);
  228799. resultGlyphs.add (glyphs[i]);
  228800. }
  228801. }
  228802. }
  228803. #endif
  228804. }
  228805. bool getOutlineForGlyph (int glyphNumber, Path& path)
  228806. {
  228807. #if JUCE_IOS
  228808. return false;
  228809. #else
  228810. if (nsFont == 0)
  228811. return false;
  228812. // we might need to apply a transform to the path, so it mustn't have anything else in it
  228813. jassert (path.isEmpty());
  228814. const ScopedAutoReleasePool pool;
  228815. NSBezierPath* bez = [NSBezierPath bezierPath];
  228816. [bez moveToPoint: NSMakePoint (0, 0)];
  228817. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  228818. inFont: nsFont];
  228819. for (int i = 0; i < [bez elementCount]; ++i)
  228820. {
  228821. NSPoint p[3];
  228822. switch ([bez elementAtIndex: i associatedPoints: p])
  228823. {
  228824. case NSMoveToBezierPathElement:
  228825. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  228826. break;
  228827. case NSLineToBezierPathElement:
  228828. path.lineTo ((float) p[0].x, (float) -p[0].y);
  228829. break;
  228830. case NSCurveToBezierPathElement:
  228831. 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);
  228832. break;
  228833. case NSClosePathBezierPathElement:
  228834. path.closeSubPath();
  228835. break;
  228836. default:
  228837. jassertfalse;
  228838. break;
  228839. }
  228840. }
  228841. path.applyTransform (pathTransform);
  228842. return true;
  228843. #endif
  228844. }
  228845. juce_UseDebuggingNewOperator
  228846. CGFontRef fontRef;
  228847. float fontHeightToCGSizeFactor;
  228848. CGAffineTransform renderingTransform;
  228849. private:
  228850. float ascent, unitsToHeightScaleFactor;
  228851. #if JUCE_IOS
  228852. #else
  228853. NSFont* nsFont;
  228854. AffineTransform pathTransform;
  228855. #endif
  228856. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  228857. {
  228858. #if SUPPORT_10_4_FONTS
  228859. #if ! SUPPORT_ONLY_10_4_FONTS
  228860. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228861. #endif
  228862. {
  228863. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  228864. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228865. for (int i = 0; i < length; ++i)
  228866. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  228867. return;
  228868. }
  228869. #endif
  228870. #if ! SUPPORT_ONLY_10_4_FONTS
  228871. if (charToGlyphMapper == 0)
  228872. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  228873. glyphs.malloc (length);
  228874. for (int i = 0; i < length; ++i)
  228875. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  228876. #endif
  228877. }
  228878. #if ! SUPPORT_ONLY_10_4_FONTS
  228879. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  228880. class CharToGlyphMapper
  228881. {
  228882. public:
  228883. CharToGlyphMapper (CGFontRef fontRef)
  228884. : segCount (0), endCode (0), startCode (0), idDelta (0),
  228885. idRangeOffset (0), glyphIndexes (0)
  228886. {
  228887. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  228888. if (cmapTable != 0)
  228889. {
  228890. const int numSubtables = getValue16 (cmapTable, 2);
  228891. for (int i = 0; i < numSubtables; ++i)
  228892. {
  228893. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  228894. {
  228895. const int offset = getValue32 (cmapTable, i * 8 + 8);
  228896. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  228897. {
  228898. const int length = getValue16 (cmapTable, offset + 2);
  228899. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  228900. segCount = segCountX2 / 2;
  228901. const int endCodeOffset = offset + 14;
  228902. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  228903. const int idDeltaOffset = startCodeOffset + segCountX2;
  228904. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  228905. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  228906. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  228907. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  228908. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  228909. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  228910. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  228911. }
  228912. break;
  228913. }
  228914. }
  228915. CFRelease (cmapTable);
  228916. }
  228917. }
  228918. ~CharToGlyphMapper()
  228919. {
  228920. if (endCode != 0)
  228921. {
  228922. CFRelease (endCode);
  228923. CFRelease (startCode);
  228924. CFRelease (idDelta);
  228925. CFRelease (idRangeOffset);
  228926. CFRelease (glyphIndexes);
  228927. }
  228928. }
  228929. int getGlyphForCharacter (const juce_wchar c) const
  228930. {
  228931. for (int i = 0; i < segCount; ++i)
  228932. {
  228933. if (getValue16 (endCode, i * 2) >= c)
  228934. {
  228935. const int start = getValue16 (startCode, i * 2);
  228936. if (start > c)
  228937. break;
  228938. const int delta = getValue16 (idDelta, i * 2);
  228939. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  228940. if (rangeOffset == 0)
  228941. return delta + c;
  228942. else
  228943. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  228944. }
  228945. }
  228946. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  228947. return jmax (-1, c - 29);
  228948. }
  228949. private:
  228950. int segCount;
  228951. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  228952. static uint16 getValue16 (CFDataRef data, const int index)
  228953. {
  228954. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  228955. }
  228956. static uint32 getValue32 (CFDataRef data, const int index)
  228957. {
  228958. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  228959. }
  228960. };
  228961. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  228962. #endif
  228963. MacTypeface (const MacTypeface&);
  228964. MacTypeface& operator= (const MacTypeface&);
  228965. };
  228966. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  228967. {
  228968. return new MacTypeface (font);
  228969. }
  228970. const StringArray Font::findAllTypefaceNames()
  228971. {
  228972. StringArray names;
  228973. const ScopedAutoReleasePool pool;
  228974. #if JUCE_IOS
  228975. NSArray* fonts = [UIFont familyNames];
  228976. #else
  228977. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  228978. #endif
  228979. for (unsigned int i = 0; i < [fonts count]; ++i)
  228980. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  228981. names.sort (true);
  228982. return names;
  228983. }
  228984. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  228985. {
  228986. #if JUCE_IOS
  228987. defaultSans = "Helvetica";
  228988. defaultSerif = "Times New Roman";
  228989. defaultFixed = "Courier New";
  228990. #else
  228991. defaultSans = "Lucida Grande";
  228992. defaultSerif = "Times New Roman";
  228993. defaultFixed = "Monaco";
  228994. #endif
  228995. }
  228996. #endif
  228997. /*** End of inlined file: juce_mac_Fonts.mm ***/
  228998. // (must go before juce_mac_CoreGraphicsContext.mm)
  228999. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229000. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229001. // compiled on its own).
  229002. #if JUCE_INCLUDED_FILE
  229003. class CoreGraphicsImage : public Image::SharedImage
  229004. {
  229005. public:
  229006. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229007. : Image::SharedImage (format_, width_, height_)
  229008. {
  229009. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229010. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229011. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229012. imageData = imageDataAllocated;
  229013. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229014. : CGColorSpaceCreateDeviceRGB();
  229015. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229016. colourSpace, getCGImageFlags (format_));
  229017. CGColorSpaceRelease (colourSpace);
  229018. }
  229019. ~CoreGraphicsImage()
  229020. {
  229021. CGContextRelease (context);
  229022. }
  229023. Image::ImageType getType() const { return Image::NativeImage; }
  229024. LowLevelGraphicsContext* createLowLevelContext();
  229025. SharedImage* clone()
  229026. {
  229027. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229028. memcpy (im->imageData, imageData, lineStride * height);
  229029. return im;
  229030. }
  229031. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  229032. {
  229033. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229034. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229035. {
  229036. return CGBitmapContextCreateImage (nativeImage->context);
  229037. }
  229038. else
  229039. {
  229040. const Image::BitmapData srcData (juceImage, false);
  229041. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229042. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229043. 8, srcData.pixelStride * 8, srcData.lineStride,
  229044. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229045. 0, true, kCGRenderingIntentDefault);
  229046. CGDataProviderRelease (provider);
  229047. return imageRef;
  229048. }
  229049. }
  229050. #if JUCE_MAC
  229051. static NSImage* createNSImage (const Image& image)
  229052. {
  229053. const ScopedAutoReleasePool pool;
  229054. NSImage* im = [[NSImage alloc] init];
  229055. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229056. [im lockFocus];
  229057. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229058. CGImageRef imageRef = createImage (image, false, colourSpace);
  229059. CGColorSpaceRelease (colourSpace);
  229060. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229061. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229062. CGImageRelease (imageRef);
  229063. [im unlockFocus];
  229064. return im;
  229065. }
  229066. #endif
  229067. CGContextRef context;
  229068. HeapBlock<uint8> imageDataAllocated;
  229069. private:
  229070. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229071. {
  229072. #if JUCE_BIG_ENDIAN
  229073. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229074. #else
  229075. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229076. #endif
  229077. }
  229078. };
  229079. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229080. {
  229081. #if USE_COREGRAPHICS_RENDERING
  229082. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229083. #else
  229084. return createSoftwareImage (format, width, height, clearImage);
  229085. #endif
  229086. }
  229087. class CoreGraphicsContext : public LowLevelGraphicsContext
  229088. {
  229089. public:
  229090. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229091. : context (context_),
  229092. flipHeight (flipHeight_),
  229093. state (new SavedState()),
  229094. numGradientLookupEntries (0),
  229095. lastClipRectIsValid (false)
  229096. {
  229097. CGContextRetain (context);
  229098. CGContextSaveGState(context);
  229099. CGContextSetShouldSmoothFonts (context, true);
  229100. CGContextSetShouldAntialias (context, true);
  229101. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229102. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229103. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229104. gradientCallbacks.version = 0;
  229105. gradientCallbacks.evaluate = gradientCallback;
  229106. gradientCallbacks.releaseInfo = 0;
  229107. setFont (Font());
  229108. }
  229109. ~CoreGraphicsContext()
  229110. {
  229111. CGContextRestoreGState (context);
  229112. CGContextRelease (context);
  229113. CGColorSpaceRelease (rgbColourSpace);
  229114. CGColorSpaceRelease (greyColourSpace);
  229115. }
  229116. bool isVectorDevice() const { return false; }
  229117. void setOrigin (int x, int y)
  229118. {
  229119. CGContextTranslateCTM (context, x, -y);
  229120. if (lastClipRectIsValid)
  229121. lastClipRect.translate (-x, -y);
  229122. }
  229123. bool clipToRectangle (const Rectangle<int>& r)
  229124. {
  229125. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229126. if (lastClipRectIsValid)
  229127. {
  229128. lastClipRect = lastClipRect.getIntersection (r);
  229129. return ! lastClipRect.isEmpty();
  229130. }
  229131. return ! isClipEmpty();
  229132. }
  229133. bool clipToRectangleList (const RectangleList& clipRegion)
  229134. {
  229135. if (clipRegion.isEmpty())
  229136. {
  229137. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229138. lastClipRectIsValid = true;
  229139. lastClipRect = Rectangle<int>();
  229140. return false;
  229141. }
  229142. else
  229143. {
  229144. const int numRects = clipRegion.getNumRectangles();
  229145. HeapBlock <CGRect> rects (numRects);
  229146. for (int i = 0; i < numRects; ++i)
  229147. {
  229148. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229149. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229150. }
  229151. CGContextClipToRects (context, rects, numRects);
  229152. lastClipRectIsValid = false;
  229153. return ! isClipEmpty();
  229154. }
  229155. }
  229156. void excludeClipRectangle (const Rectangle<int>& r)
  229157. {
  229158. RectangleList remaining (getClipBounds());
  229159. remaining.subtract (r);
  229160. clipToRectangleList (remaining);
  229161. lastClipRectIsValid = false;
  229162. }
  229163. void clipToPath (const Path& path, const AffineTransform& transform)
  229164. {
  229165. createPath (path, transform);
  229166. CGContextClip (context);
  229167. lastClipRectIsValid = false;
  229168. }
  229169. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229170. {
  229171. if (! transform.isSingularity())
  229172. {
  229173. Image singleChannelImage (sourceImage);
  229174. if (sourceImage.getFormat() != Image::SingleChannel)
  229175. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229176. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  229177. flip();
  229178. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229179. applyTransform (t);
  229180. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229181. CGContextClipToMask (context, r, image);
  229182. applyTransform (t.inverted());
  229183. flip();
  229184. CGImageRelease (image);
  229185. lastClipRectIsValid = false;
  229186. }
  229187. }
  229188. bool clipRegionIntersects (const Rectangle<int>& r)
  229189. {
  229190. return getClipBounds().intersects (r);
  229191. }
  229192. const Rectangle<int> getClipBounds() const
  229193. {
  229194. if (! lastClipRectIsValid)
  229195. {
  229196. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229197. lastClipRectIsValid = true;
  229198. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229199. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229200. roundToInt (bounds.size.width),
  229201. roundToInt (bounds.size.height));
  229202. }
  229203. return lastClipRect;
  229204. }
  229205. bool isClipEmpty() const
  229206. {
  229207. return getClipBounds().isEmpty();
  229208. }
  229209. void saveState()
  229210. {
  229211. CGContextSaveGState (context);
  229212. stateStack.add (new SavedState (*state));
  229213. }
  229214. void restoreState()
  229215. {
  229216. CGContextRestoreGState (context);
  229217. SavedState* const top = stateStack.getLast();
  229218. if (top != 0)
  229219. {
  229220. state = top;
  229221. stateStack.removeLast (1, false);
  229222. lastClipRectIsValid = false;
  229223. }
  229224. else
  229225. {
  229226. jassertfalse; // trying to pop with an empty stack!
  229227. }
  229228. }
  229229. void setFill (const FillType& fillType)
  229230. {
  229231. state->fillType = fillType;
  229232. if (fillType.isColour())
  229233. {
  229234. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229235. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229236. CGContextSetAlpha (context, 1.0f);
  229237. }
  229238. }
  229239. void setOpacity (float newOpacity)
  229240. {
  229241. state->fillType.setOpacity (newOpacity);
  229242. setFill (state->fillType);
  229243. }
  229244. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229245. {
  229246. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229247. ? kCGInterpolationLow
  229248. : kCGInterpolationHigh);
  229249. }
  229250. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229251. {
  229252. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229253. if (replaceExistingContents)
  229254. {
  229255. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229256. CGContextClearRect (context, cgRect);
  229257. #else
  229258. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229259. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229260. CGContextClearRect (context, cgRect);
  229261. else
  229262. #endif
  229263. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229264. #endif
  229265. fillRect (r, false);
  229266. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229267. }
  229268. else
  229269. {
  229270. if (state->fillType.isColour())
  229271. {
  229272. CGContextFillRect (context, cgRect);
  229273. }
  229274. else if (state->fillType.isGradient())
  229275. {
  229276. CGContextSaveGState (context);
  229277. CGContextClipToRect (context, cgRect);
  229278. drawGradient();
  229279. CGContextRestoreGState (context);
  229280. }
  229281. else
  229282. {
  229283. CGContextSaveGState (context);
  229284. CGContextClipToRect (context, cgRect);
  229285. drawImage (state->fillType.image, state->fillType.transform, true);
  229286. CGContextRestoreGState (context);
  229287. }
  229288. }
  229289. }
  229290. void fillPath (const Path& path, const AffineTransform& transform)
  229291. {
  229292. CGContextSaveGState (context);
  229293. if (state->fillType.isColour())
  229294. {
  229295. flip();
  229296. applyTransform (transform);
  229297. createPath (path);
  229298. if (path.isUsingNonZeroWinding())
  229299. CGContextFillPath (context);
  229300. else
  229301. CGContextEOFillPath (context);
  229302. }
  229303. else
  229304. {
  229305. createPath (path, transform);
  229306. if (path.isUsingNonZeroWinding())
  229307. CGContextClip (context);
  229308. else
  229309. CGContextEOClip (context);
  229310. if (state->fillType.isGradient())
  229311. drawGradient();
  229312. else
  229313. drawImage (state->fillType.image, state->fillType.transform, true);
  229314. }
  229315. CGContextRestoreGState (context);
  229316. }
  229317. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229318. {
  229319. const int iw = sourceImage.getWidth();
  229320. const int ih = sourceImage.getHeight();
  229321. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  229322. CGContextSaveGState (context);
  229323. CGContextSetAlpha (context, state->fillType.getOpacity());
  229324. flip();
  229325. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  229326. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  229327. if (fillEntireClipAsTiles)
  229328. {
  229329. #if JUCE_IOS
  229330. CGContextDrawTiledImage (context, imageRect, image);
  229331. #else
  229332. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229333. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229334. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229335. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229336. CGContextDrawTiledImage (context, imageRect, image);
  229337. else
  229338. #endif
  229339. {
  229340. // Fallback to manually doing a tiled fill on 10.4
  229341. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229342. int x = 0, y = 0;
  229343. while (x > clip.origin.x) x -= iw;
  229344. while (y > clip.origin.y) y -= ih;
  229345. const int right = (int) (clip.origin.x + clip.size.width);
  229346. const int bottom = (int) (clip.origin.y + clip.size.height);
  229347. while (y < bottom)
  229348. {
  229349. for (int x2 = x; x2 < right; x2 += iw)
  229350. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229351. y += ih;
  229352. }
  229353. }
  229354. #endif
  229355. }
  229356. else
  229357. {
  229358. CGContextDrawImage (context, imageRect, image);
  229359. }
  229360. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229361. CGContextRestoreGState (context);
  229362. }
  229363. void drawLine (const Line<float>& line)
  229364. {
  229365. CGContextSetLineCap (context, kCGLineCapSquare);
  229366. CGContextSetLineWidth (context, 1.0f);
  229367. CGContextSetRGBStrokeColor (context,
  229368. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229369. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229370. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229371. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229372. CGContextStrokeLineSegments (context, cgLine, 1);
  229373. }
  229374. void drawVerticalLine (const int x, float top, float bottom)
  229375. {
  229376. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229377. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229378. #else
  229379. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229380. // the x co-ord slightly to trick it..
  229381. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229382. #endif
  229383. }
  229384. void drawHorizontalLine (const int y, float left, float right)
  229385. {
  229386. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229387. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229388. #else
  229389. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229390. // the x co-ord slightly to trick it..
  229391. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229392. #endif
  229393. }
  229394. void setFont (const Font& newFont)
  229395. {
  229396. if (state->font != newFont)
  229397. {
  229398. state->fontRef = 0;
  229399. state->font = newFont;
  229400. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  229401. if (mf != 0)
  229402. {
  229403. state->fontRef = mf->fontRef;
  229404. CGContextSetFont (context, state->fontRef);
  229405. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  229406. state->fontTransform = mf->renderingTransform;
  229407. state->fontTransform.a *= state->font.getHorizontalScale();
  229408. CGContextSetTextMatrix (context, state->fontTransform);
  229409. }
  229410. }
  229411. }
  229412. const Font getFont()
  229413. {
  229414. return state->font;
  229415. }
  229416. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  229417. {
  229418. if (state->fontRef != 0 && state->fillType.isColour())
  229419. {
  229420. if (transform.isOnlyTranslation())
  229421. {
  229422. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  229423. CGGlyph g = glyphNumber;
  229424. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  229425. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  229426. }
  229427. else
  229428. {
  229429. CGContextSaveGState (context);
  229430. flip();
  229431. applyTransform (transform);
  229432. CGAffineTransform t = state->fontTransform;
  229433. t.d = -t.d;
  229434. CGContextSetTextMatrix (context, t);
  229435. CGGlyph g = glyphNumber;
  229436. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  229437. CGContextRestoreGState (context);
  229438. }
  229439. }
  229440. else
  229441. {
  229442. Path p;
  229443. Font& f = state->font;
  229444. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  229445. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  229446. .followedBy (transform));
  229447. }
  229448. }
  229449. private:
  229450. CGContextRef context;
  229451. const CGFloat flipHeight;
  229452. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  229453. CGFunctionCallbacks gradientCallbacks;
  229454. mutable Rectangle<int> lastClipRect;
  229455. mutable bool lastClipRectIsValid;
  229456. struct SavedState
  229457. {
  229458. SavedState()
  229459. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  229460. {
  229461. }
  229462. SavedState (const SavedState& other)
  229463. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  229464. fontTransform (other.fontTransform)
  229465. {
  229466. }
  229467. ~SavedState()
  229468. {
  229469. }
  229470. FillType fillType;
  229471. Font font;
  229472. CGFontRef fontRef;
  229473. CGAffineTransform fontTransform;
  229474. };
  229475. ScopedPointer <SavedState> state;
  229476. OwnedArray <SavedState> stateStack;
  229477. HeapBlock <PixelARGB> gradientLookupTable;
  229478. int numGradientLookupEntries;
  229479. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  229480. {
  229481. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  229482. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  229483. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  229484. colour.unpremultiply();
  229485. outData[0] = colour.getRed() / 255.0f;
  229486. outData[1] = colour.getGreen() / 255.0f;
  229487. outData[2] = colour.getBlue() / 255.0f;
  229488. outData[3] = colour.getAlpha() / 255.0f;
  229489. }
  229490. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  229491. {
  229492. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  229493. --numGradientLookupEntries;
  229494. CGShadingRef result = 0;
  229495. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  229496. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  229497. if (gradient.isRadial)
  229498. {
  229499. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  229500. p1, gradient.point1.getDistanceFrom (gradient.point2),
  229501. function, true, true);
  229502. }
  229503. else
  229504. {
  229505. result = CGShadingCreateAxial (rgbColourSpace, p1,
  229506. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  229507. function, true, true);
  229508. }
  229509. CGFunctionRelease (function);
  229510. return result;
  229511. }
  229512. void drawGradient()
  229513. {
  229514. flip();
  229515. applyTransform (state->fillType.transform);
  229516. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  229517. // you draw a gradient with high quality interp enabled).
  229518. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  229519. CGContextSetAlpha (context, state->fillType.getOpacity());
  229520. CGContextDrawShading (context, shading);
  229521. CGShadingRelease (shading);
  229522. }
  229523. void createPath (const Path& path) const
  229524. {
  229525. CGContextBeginPath (context);
  229526. Path::Iterator i (path);
  229527. while (i.next())
  229528. {
  229529. switch (i.elementType)
  229530. {
  229531. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  229532. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  229533. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  229534. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  229535. case Path::Iterator::closePath: CGContextClosePath (context); break;
  229536. default: jassertfalse; break;
  229537. }
  229538. }
  229539. }
  229540. void createPath (const Path& path, const AffineTransform& transform) const
  229541. {
  229542. CGContextBeginPath (context);
  229543. Path::Iterator i (path);
  229544. while (i.next())
  229545. {
  229546. switch (i.elementType)
  229547. {
  229548. case Path::Iterator::startNewSubPath:
  229549. transform.transformPoint (i.x1, i.y1);
  229550. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  229551. break;
  229552. case Path::Iterator::lineTo:
  229553. transform.transformPoint (i.x1, i.y1);
  229554. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  229555. break;
  229556. case Path::Iterator::quadraticTo:
  229557. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  229558. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  229559. break;
  229560. case Path::Iterator::cubicTo:
  229561. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  229562. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  229563. break;
  229564. case Path::Iterator::closePath:
  229565. CGContextClosePath (context); break;
  229566. default:
  229567. jassertfalse;
  229568. break;
  229569. }
  229570. }
  229571. }
  229572. void flip() const
  229573. {
  229574. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  229575. }
  229576. void applyTransform (const AffineTransform& transform) const
  229577. {
  229578. CGAffineTransform t;
  229579. t.a = transform.mat00;
  229580. t.b = transform.mat10;
  229581. t.c = transform.mat01;
  229582. t.d = transform.mat11;
  229583. t.tx = transform.mat02;
  229584. t.ty = transform.mat12;
  229585. CGContextConcatCTM (context, t);
  229586. }
  229587. CoreGraphicsContext (const CoreGraphicsContext&);
  229588. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  229589. };
  229590. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  229591. {
  229592. return new CoreGraphicsContext (context, height);
  229593. }
  229594. #endif
  229595. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229596. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  229597. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229598. // compiled on its own).
  229599. #if JUCE_INCLUDED_FILE
  229600. class NSViewComponentPeer;
  229601. END_JUCE_NAMESPACE
  229602. @interface NSEvent (JuceDeviceDelta)
  229603. - (float) deviceDeltaX;
  229604. - (float) deviceDeltaY;
  229605. @end
  229606. #define JuceNSView MakeObjCClassName(JuceNSView)
  229607. @interface JuceNSView : NSView<NSTextInput>
  229608. {
  229609. @public
  229610. NSViewComponentPeer* owner;
  229611. NSNotificationCenter* notificationCenter;
  229612. String* stringBeingComposed;
  229613. bool textWasInserted;
  229614. }
  229615. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  229616. - (void) dealloc;
  229617. - (BOOL) isOpaque;
  229618. - (void) drawRect: (NSRect) r;
  229619. - (void) mouseDown: (NSEvent*) ev;
  229620. - (void) asyncMouseDown: (NSEvent*) ev;
  229621. - (void) mouseUp: (NSEvent*) ev;
  229622. - (void) asyncMouseUp: (NSEvent*) ev;
  229623. - (void) mouseDragged: (NSEvent*) ev;
  229624. - (void) mouseMoved: (NSEvent*) ev;
  229625. - (void) mouseEntered: (NSEvent*) ev;
  229626. - (void) mouseExited: (NSEvent*) ev;
  229627. - (void) rightMouseDown: (NSEvent*) ev;
  229628. - (void) rightMouseDragged: (NSEvent*) ev;
  229629. - (void) rightMouseUp: (NSEvent*) ev;
  229630. - (void) otherMouseDown: (NSEvent*) ev;
  229631. - (void) otherMouseDragged: (NSEvent*) ev;
  229632. - (void) otherMouseUp: (NSEvent*) ev;
  229633. - (void) scrollWheel: (NSEvent*) ev;
  229634. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  229635. - (void) frameChanged: (NSNotification*) n;
  229636. - (void) viewDidMoveToWindow;
  229637. - (void) keyDown: (NSEvent*) ev;
  229638. - (void) keyUp: (NSEvent*) ev;
  229639. // NSTextInput Methods
  229640. - (void) insertText: (id) aString;
  229641. - (void) doCommandBySelector: (SEL) aSelector;
  229642. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  229643. - (void) unmarkText;
  229644. - (BOOL) hasMarkedText;
  229645. - (long) conversationIdentifier;
  229646. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  229647. - (NSRange) markedRange;
  229648. - (NSRange) selectedRange;
  229649. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  229650. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  229651. - (NSArray*) validAttributesForMarkedText;
  229652. - (void) flagsChanged: (NSEvent*) ev;
  229653. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229654. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  229655. #endif
  229656. - (BOOL) becomeFirstResponder;
  229657. - (BOOL) resignFirstResponder;
  229658. - (BOOL) acceptsFirstResponder;
  229659. - (void) asyncRepaint: (id) rect;
  229660. - (NSArray*) getSupportedDragTypes;
  229661. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  229662. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  229663. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  229664. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  229665. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  229666. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  229667. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  229668. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  229669. @end
  229670. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  229671. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229672. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  229673. #else
  229674. @interface JuceNSWindow : NSWindow
  229675. #endif
  229676. {
  229677. @private
  229678. NSViewComponentPeer* owner;
  229679. bool isZooming;
  229680. }
  229681. - (void) setOwner: (NSViewComponentPeer*) owner;
  229682. - (BOOL) canBecomeKeyWindow;
  229683. - (void) becomeKeyWindow;
  229684. - (BOOL) windowShouldClose: (id) window;
  229685. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  229686. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  229687. - (void) zoom: (id) sender;
  229688. @end
  229689. BEGIN_JUCE_NAMESPACE
  229690. class NSViewComponentPeer : public ComponentPeer
  229691. {
  229692. public:
  229693. NSViewComponentPeer (Component* const component,
  229694. const int windowStyleFlags,
  229695. NSView* viewToAttachTo);
  229696. ~NSViewComponentPeer();
  229697. void* getNativeHandle() const;
  229698. void setVisible (bool shouldBeVisible);
  229699. void setTitle (const String& title);
  229700. void setPosition (int x, int y);
  229701. void setSize (int w, int h);
  229702. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  229703. const Rectangle<int> getBounds (const bool global) const;
  229704. const Rectangle<int> getBounds() const;
  229705. const Point<int> getScreenPosition() const;
  229706. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  229707. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  229708. void setMinimised (bool shouldBeMinimised);
  229709. bool isMinimised() const;
  229710. void setFullScreen (bool shouldBeFullScreen);
  229711. bool isFullScreen() const;
  229712. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  229713. const BorderSize getFrameSize() const;
  229714. bool setAlwaysOnTop (bool alwaysOnTop);
  229715. void toFront (bool makeActiveWindow);
  229716. void toBehind (ComponentPeer* other);
  229717. void setIcon (const Image& newIcon);
  229718. const StringArray getAvailableRenderingEngines() throw();
  229719. int getCurrentRenderingEngine() throw();
  229720. void setCurrentRenderingEngine (int index) throw();
  229721. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  229722. for example having more than one juce plugin loaded into a host, then when a
  229723. method is called, the actual code that runs might actually be in a different module
  229724. than the one you expect... So any calls to library functions or statics that are
  229725. made inside obj-c methods will probably end up getting executed in a different DLL's
  229726. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  229727. To work around this insanity, I'm only allowing obj-c methods to make calls to
  229728. virtual methods of an object that's known to live inside the right module's space.
  229729. */
  229730. virtual void redirectMouseDown (NSEvent* ev);
  229731. virtual void redirectMouseUp (NSEvent* ev);
  229732. virtual void redirectMouseDrag (NSEvent* ev);
  229733. virtual void redirectMouseMove (NSEvent* ev);
  229734. virtual void redirectMouseEnter (NSEvent* ev);
  229735. virtual void redirectMouseExit (NSEvent* ev);
  229736. virtual void redirectMouseWheel (NSEvent* ev);
  229737. void sendMouseEvent (NSEvent* ev);
  229738. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  229739. virtual bool redirectKeyDown (NSEvent* ev);
  229740. virtual bool redirectKeyUp (NSEvent* ev);
  229741. virtual void redirectModKeyChange (NSEvent* ev);
  229742. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229743. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  229744. #endif
  229745. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  229746. virtual bool isOpaque();
  229747. virtual void drawRect (NSRect r);
  229748. virtual bool canBecomeKeyWindow();
  229749. virtual bool windowShouldClose();
  229750. virtual void redirectMovedOrResized();
  229751. virtual void viewMovedToWindow();
  229752. virtual NSRect constrainRect (NSRect r);
  229753. static void showArrowCursorIfNeeded();
  229754. static void updateModifiers (NSEvent* e);
  229755. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  229756. static int getKeyCodeFromEvent (NSEvent* ev)
  229757. {
  229758. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  229759. int keyCode = unmodified[0];
  229760. if (keyCode == 0x19) // (backwards-tab)
  229761. keyCode = '\t';
  229762. else if (keyCode == 0x03) // (enter)
  229763. keyCode = '\r';
  229764. return keyCode;
  229765. }
  229766. static int64 getMouseTime (NSEvent* e)
  229767. {
  229768. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  229769. + (int64) ([e timestamp] * 1000.0);
  229770. }
  229771. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  229772. {
  229773. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  229774. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  229775. }
  229776. static int getModifierForButtonNumber (const NSInteger num)
  229777. {
  229778. return num == 0 ? ModifierKeys::leftButtonModifier
  229779. : (num == 1 ? ModifierKeys::rightButtonModifier
  229780. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  229781. }
  229782. virtual void viewFocusGain();
  229783. virtual void viewFocusLoss();
  229784. bool isFocused() const;
  229785. void grabFocus();
  229786. void textInputRequired (const Point<int>& position);
  229787. void repaint (const Rectangle<int>& area);
  229788. void performAnyPendingRepaintsNow();
  229789. juce_UseDebuggingNewOperator
  229790. NSWindow* window;
  229791. JuceNSView* view;
  229792. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  229793. static ModifierKeys currentModifiers;
  229794. static ComponentPeer* currentlyFocusedPeer;
  229795. static Array<int> keysCurrentlyDown;
  229796. };
  229797. END_JUCE_NAMESPACE
  229798. @implementation JuceNSView
  229799. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  229800. withFrame: (NSRect) frame
  229801. {
  229802. [super initWithFrame: frame];
  229803. owner = owner_;
  229804. stringBeingComposed = 0;
  229805. textWasInserted = false;
  229806. notificationCenter = [NSNotificationCenter defaultCenter];
  229807. [notificationCenter addObserver: self
  229808. selector: @selector (frameChanged:)
  229809. name: NSViewFrameDidChangeNotification
  229810. object: self];
  229811. if (! owner_->isSharedWindow)
  229812. {
  229813. [notificationCenter addObserver: self
  229814. selector: @selector (frameChanged:)
  229815. name: NSWindowDidMoveNotification
  229816. object: owner_->window];
  229817. }
  229818. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  229819. return self;
  229820. }
  229821. - (void) dealloc
  229822. {
  229823. [notificationCenter removeObserver: self];
  229824. delete stringBeingComposed;
  229825. [super dealloc];
  229826. }
  229827. - (void) drawRect: (NSRect) r
  229828. {
  229829. if (owner != 0)
  229830. owner->drawRect (r);
  229831. }
  229832. - (BOOL) isOpaque
  229833. {
  229834. return owner == 0 || owner->isOpaque();
  229835. }
  229836. - (void) mouseDown: (NSEvent*) ev
  229837. {
  229838. // In some host situations, the host will stop modal loops from working
  229839. // correctly if they're called from a mouse event, so we'll trigger
  229840. // the event asynchronously..
  229841. if (JUCEApplication::getInstance() == 0)
  229842. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  229843. withObject: ev
  229844. waitUntilDone: NO];
  229845. else
  229846. [self asyncMouseDown: ev];
  229847. }
  229848. - (void) asyncMouseDown: (NSEvent*) ev
  229849. {
  229850. if (owner != 0)
  229851. owner->redirectMouseDown (ev);
  229852. }
  229853. - (void) mouseUp: (NSEvent*) ev
  229854. {
  229855. // In some host situations, the host will stop modal loops from working
  229856. // correctly if they're called from a mouse event, so we'll trigger
  229857. // the event asynchronously..
  229858. if (JUCEApplication::getInstance() == 0)
  229859. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  229860. withObject: ev
  229861. waitUntilDone: NO];
  229862. else
  229863. [self asyncMouseUp: ev];
  229864. }
  229865. - (void) asyncMouseUp: (NSEvent*) ev
  229866. {
  229867. if (owner != 0)
  229868. owner->redirectMouseUp (ev);
  229869. }
  229870. - (void) mouseDragged: (NSEvent*) ev
  229871. {
  229872. if (owner != 0)
  229873. owner->redirectMouseDrag (ev);
  229874. }
  229875. - (void) mouseMoved: (NSEvent*) ev
  229876. {
  229877. if (owner != 0)
  229878. owner->redirectMouseMove (ev);
  229879. }
  229880. - (void) mouseEntered: (NSEvent*) ev
  229881. {
  229882. if (owner != 0)
  229883. owner->redirectMouseEnter (ev);
  229884. }
  229885. - (void) mouseExited: (NSEvent*) ev
  229886. {
  229887. if (owner != 0)
  229888. owner->redirectMouseExit (ev);
  229889. }
  229890. - (void) rightMouseDown: (NSEvent*) ev
  229891. {
  229892. [self mouseDown: ev];
  229893. }
  229894. - (void) rightMouseDragged: (NSEvent*) ev
  229895. {
  229896. [self mouseDragged: ev];
  229897. }
  229898. - (void) rightMouseUp: (NSEvent*) ev
  229899. {
  229900. [self mouseUp: ev];
  229901. }
  229902. - (void) otherMouseDown: (NSEvent*) ev
  229903. {
  229904. [self mouseDown: ev];
  229905. }
  229906. - (void) otherMouseDragged: (NSEvent*) ev
  229907. {
  229908. [self mouseDragged: ev];
  229909. }
  229910. - (void) otherMouseUp: (NSEvent*) ev
  229911. {
  229912. [self mouseUp: ev];
  229913. }
  229914. - (void) scrollWheel: (NSEvent*) ev
  229915. {
  229916. if (owner != 0)
  229917. owner->redirectMouseWheel (ev);
  229918. }
  229919. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  229920. {
  229921. (void) ev;
  229922. return YES;
  229923. }
  229924. - (void) frameChanged: (NSNotification*) n
  229925. {
  229926. (void) n;
  229927. if (owner != 0)
  229928. owner->redirectMovedOrResized();
  229929. }
  229930. - (void) viewDidMoveToWindow
  229931. {
  229932. if (owner != 0)
  229933. owner->viewMovedToWindow();
  229934. }
  229935. - (void) asyncRepaint: (id) rect
  229936. {
  229937. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  229938. [self setNeedsDisplayInRect: *r];
  229939. }
  229940. - (void) keyDown: (NSEvent*) ev
  229941. {
  229942. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229943. textWasInserted = false;
  229944. if (target != 0)
  229945. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  229946. else
  229947. deleteAndZero (stringBeingComposed);
  229948. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  229949. [super keyDown: ev];
  229950. }
  229951. - (void) keyUp: (NSEvent*) ev
  229952. {
  229953. if (owner == 0 || ! owner->redirectKeyUp (ev))
  229954. [super keyUp: ev];
  229955. }
  229956. - (void) insertText: (id) aString
  229957. {
  229958. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  229959. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  229960. if ([newText length] > 0)
  229961. {
  229962. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229963. if (target != 0)
  229964. {
  229965. target->insertTextAtCaret (nsStringToJuce (newText));
  229966. textWasInserted = true;
  229967. }
  229968. }
  229969. deleteAndZero (stringBeingComposed);
  229970. }
  229971. - (void) doCommandBySelector: (SEL) aSelector
  229972. {
  229973. (void) aSelector;
  229974. }
  229975. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  229976. {
  229977. (void) selectionRange;
  229978. if (stringBeingComposed == 0)
  229979. stringBeingComposed = new String();
  229980. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  229981. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229982. if (target != 0)
  229983. {
  229984. const Range<int> currentHighlight (target->getHighlightedRegion());
  229985. target->insertTextAtCaret (*stringBeingComposed);
  229986. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  229987. textWasInserted = true;
  229988. }
  229989. }
  229990. - (void) unmarkText
  229991. {
  229992. if (stringBeingComposed != 0)
  229993. {
  229994. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229995. if (target != 0)
  229996. {
  229997. target->insertTextAtCaret (*stringBeingComposed);
  229998. textWasInserted = true;
  229999. }
  230000. }
  230001. deleteAndZero (stringBeingComposed);
  230002. }
  230003. - (BOOL) hasMarkedText
  230004. {
  230005. return stringBeingComposed != 0;
  230006. }
  230007. - (long) conversationIdentifier
  230008. {
  230009. return (long) (pointer_sized_int) self;
  230010. }
  230011. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230012. {
  230013. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230014. if (target != 0)
  230015. {
  230016. const Range<int> r ((int) theRange.location,
  230017. (int) (theRange.location + theRange.length));
  230018. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230019. }
  230020. return nil;
  230021. }
  230022. - (NSRange) markedRange
  230023. {
  230024. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230025. : NSMakeRange (NSNotFound, 0);
  230026. }
  230027. - (NSRange) selectedRange
  230028. {
  230029. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230030. if (target != 0)
  230031. {
  230032. const Range<int> highlight (target->getHighlightedRegion());
  230033. if (! highlight.isEmpty())
  230034. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230035. }
  230036. return NSMakeRange (NSNotFound, 0);
  230037. }
  230038. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230039. {
  230040. (void) theRange;
  230041. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230042. if (comp == 0)
  230043. return NSMakeRect (0, 0, 0, 0);
  230044. const Rectangle<int> bounds (comp->getScreenBounds());
  230045. return NSMakeRect (bounds.getX(),
  230046. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230047. bounds.getWidth(),
  230048. bounds.getHeight());
  230049. }
  230050. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230051. {
  230052. (void) thePoint;
  230053. return NSNotFound;
  230054. }
  230055. - (NSArray*) validAttributesForMarkedText
  230056. {
  230057. return [NSArray array];
  230058. }
  230059. - (void) flagsChanged: (NSEvent*) ev
  230060. {
  230061. if (owner != 0)
  230062. owner->redirectModKeyChange (ev);
  230063. }
  230064. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230065. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230066. {
  230067. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230068. return true;
  230069. return [super performKeyEquivalent: ev];
  230070. }
  230071. #endif
  230072. - (BOOL) becomeFirstResponder
  230073. {
  230074. if (owner != 0)
  230075. owner->viewFocusGain();
  230076. return true;
  230077. }
  230078. - (BOOL) resignFirstResponder
  230079. {
  230080. if (owner != 0)
  230081. owner->viewFocusLoss();
  230082. return true;
  230083. }
  230084. - (BOOL) acceptsFirstResponder
  230085. {
  230086. return owner != 0 && owner->canBecomeKeyWindow();
  230087. }
  230088. - (NSArray*) getSupportedDragTypes
  230089. {
  230090. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230091. }
  230092. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230093. {
  230094. return owner != 0 && owner->sendDragCallback (type, sender);
  230095. }
  230096. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230097. {
  230098. if ([self sendDragCallback: 0 sender: sender])
  230099. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230100. else
  230101. return NSDragOperationNone;
  230102. }
  230103. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230104. {
  230105. if ([self sendDragCallback: 0 sender: sender])
  230106. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230107. else
  230108. return NSDragOperationNone;
  230109. }
  230110. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230111. {
  230112. [self sendDragCallback: 1 sender: sender];
  230113. }
  230114. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230115. {
  230116. [self sendDragCallback: 1 sender: sender];
  230117. }
  230118. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230119. {
  230120. (void) sender;
  230121. return YES;
  230122. }
  230123. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230124. {
  230125. return [self sendDragCallback: 2 sender: sender];
  230126. }
  230127. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230128. {
  230129. (void) sender;
  230130. }
  230131. @end
  230132. @implementation JuceNSWindow
  230133. - (void) setOwner: (NSViewComponentPeer*) owner_
  230134. {
  230135. owner = owner_;
  230136. isZooming = false;
  230137. }
  230138. - (BOOL) canBecomeKeyWindow
  230139. {
  230140. return owner != 0 && owner->canBecomeKeyWindow();
  230141. }
  230142. - (void) becomeKeyWindow
  230143. {
  230144. [super becomeKeyWindow];
  230145. if (owner != 0)
  230146. owner->grabFocus();
  230147. }
  230148. - (BOOL) windowShouldClose: (id) window
  230149. {
  230150. (void) window;
  230151. return owner == 0 || owner->windowShouldClose();
  230152. }
  230153. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230154. {
  230155. (void) screen;
  230156. if (owner != 0)
  230157. frameRect = owner->constrainRect (frameRect);
  230158. return frameRect;
  230159. }
  230160. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230161. {
  230162. (void) window;
  230163. if (isZooming)
  230164. return proposedFrameSize;
  230165. NSRect frameRect = [self frame];
  230166. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230167. frameRect.size = proposedFrameSize;
  230168. if (owner != 0)
  230169. frameRect = owner->constrainRect (frameRect);
  230170. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230171. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230172. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230173. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230174. return frameRect.size;
  230175. }
  230176. - (void) zoom: (id) sender
  230177. {
  230178. isZooming = true;
  230179. [super zoom: sender];
  230180. isZooming = false;
  230181. }
  230182. - (void) windowWillMove: (NSNotification*) notification
  230183. {
  230184. (void) notification;
  230185. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230186. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230187. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230188. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230189. }
  230190. @end
  230191. BEGIN_JUCE_NAMESPACE
  230192. ModifierKeys NSViewComponentPeer::currentModifiers;
  230193. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230194. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230195. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230196. {
  230197. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230198. return true;
  230199. if (keyCode >= 'A' && keyCode <= 'Z'
  230200. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230201. return true;
  230202. if (keyCode >= 'a' && keyCode <= 'z'
  230203. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230204. return true;
  230205. return false;
  230206. }
  230207. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230208. {
  230209. int m = 0;
  230210. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230211. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230212. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230213. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230214. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230215. }
  230216. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230217. {
  230218. updateModifiers (ev);
  230219. int keyCode = getKeyCodeFromEvent (ev);
  230220. if (keyCode != 0)
  230221. {
  230222. if (isKeyDown)
  230223. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230224. else
  230225. keysCurrentlyDown.removeValue (keyCode);
  230226. }
  230227. }
  230228. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230229. {
  230230. return NSViewComponentPeer::currentModifiers;
  230231. }
  230232. void ModifierKeys::updateCurrentModifiers() throw()
  230233. {
  230234. currentModifiers = NSViewComponentPeer::currentModifiers;
  230235. }
  230236. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230237. const int windowStyleFlags,
  230238. NSView* viewToAttachTo)
  230239. : ComponentPeer (component_, windowStyleFlags),
  230240. window (0),
  230241. view (0),
  230242. isSharedWindow (viewToAttachTo != 0),
  230243. fullScreen (false),
  230244. insideDrawRect (false),
  230245. #if USE_COREGRAPHICS_RENDERING
  230246. usingCoreGraphics (true),
  230247. #else
  230248. usingCoreGraphics (false),
  230249. #endif
  230250. recursiveToFrontCall (false)
  230251. {
  230252. NSRect r;
  230253. r.origin.x = 0;
  230254. r.origin.y = 0;
  230255. r.size.width = (float) component->getWidth();
  230256. r.size.height = (float) component->getHeight();
  230257. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230258. [view setPostsFrameChangedNotifications: YES];
  230259. if (isSharedWindow)
  230260. {
  230261. window = [viewToAttachTo window];
  230262. [viewToAttachTo addSubview: view];
  230263. setVisible (component->isVisible());
  230264. }
  230265. else
  230266. {
  230267. r.origin.x = (float) component->getX();
  230268. r.origin.y = (float) component->getY();
  230269. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230270. unsigned int style = 0;
  230271. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230272. style = NSBorderlessWindowMask;
  230273. else
  230274. style = NSTitledWindowMask;
  230275. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230276. style |= NSMiniaturizableWindowMask;
  230277. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230278. style |= NSClosableWindowMask;
  230279. if ((windowStyleFlags & windowIsResizable) != 0)
  230280. style |= NSResizableWindowMask;
  230281. window = [[JuceNSWindow alloc] initWithContentRect: r
  230282. styleMask: style
  230283. backing: NSBackingStoreBuffered
  230284. defer: YES];
  230285. [((JuceNSWindow*) window) setOwner: this];
  230286. [window orderOut: nil];
  230287. [window setDelegate: (JuceNSWindow*) window];
  230288. [window setOpaque: component->isOpaque()];
  230289. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  230290. if (component->isAlwaysOnTop())
  230291. [window setLevel: NSFloatingWindowLevel];
  230292. [window setContentView: view];
  230293. [window setAutodisplay: YES];
  230294. [window setAcceptsMouseMovedEvents: YES];
  230295. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  230296. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  230297. [window setReleasedWhenClosed: YES];
  230298. [window retain];
  230299. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230300. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230301. }
  230302. setTitle (component->getName());
  230303. }
  230304. NSViewComponentPeer::~NSViewComponentPeer()
  230305. {
  230306. view->owner = 0;
  230307. [view removeFromSuperview];
  230308. [view release];
  230309. if (! isSharedWindow)
  230310. {
  230311. [((JuceNSWindow*) window) setOwner: 0];
  230312. [window close];
  230313. [window release];
  230314. }
  230315. }
  230316. void* NSViewComponentPeer::getNativeHandle() const
  230317. {
  230318. return view;
  230319. }
  230320. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230321. {
  230322. if (isSharedWindow)
  230323. {
  230324. [view setHidden: ! shouldBeVisible];
  230325. }
  230326. else
  230327. {
  230328. if (shouldBeVisible)
  230329. {
  230330. [window orderFront: nil];
  230331. handleBroughtToFront();
  230332. }
  230333. else
  230334. {
  230335. [window orderOut: nil];
  230336. }
  230337. }
  230338. }
  230339. void NSViewComponentPeer::setTitle (const String& title)
  230340. {
  230341. const ScopedAutoReleasePool pool;
  230342. if (! isSharedWindow)
  230343. [window setTitle: juceStringToNS (title)];
  230344. }
  230345. void NSViewComponentPeer::setPosition (int x, int y)
  230346. {
  230347. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  230348. }
  230349. void NSViewComponentPeer::setSize (int w, int h)
  230350. {
  230351. setBounds (component->getX(), component->getY(), w, h, false);
  230352. }
  230353. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  230354. {
  230355. fullScreen = isNowFullScreen;
  230356. w = jmax (0, w);
  230357. h = jmax (0, h);
  230358. NSRect r;
  230359. r.origin.x = (float) x;
  230360. r.origin.y = (float) y;
  230361. r.size.width = (float) w;
  230362. r.size.height = (float) h;
  230363. if (isSharedWindow)
  230364. {
  230365. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230366. if ([view frame].size.width != r.size.width
  230367. || [view frame].size.height != r.size.height)
  230368. [view setNeedsDisplay: true];
  230369. [view setFrame: r];
  230370. }
  230371. else
  230372. {
  230373. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230374. [window setFrame: [window frameRectForContentRect: r]
  230375. display: true];
  230376. }
  230377. }
  230378. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  230379. {
  230380. NSRect r = [view frame];
  230381. if (global && [view window] != 0)
  230382. {
  230383. r = [view convertRect: r toView: nil];
  230384. NSRect wr = [[view window] frame];
  230385. r.origin.x += wr.origin.x;
  230386. r.origin.y += wr.origin.y;
  230387. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230388. }
  230389. else
  230390. {
  230391. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  230392. }
  230393. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  230394. }
  230395. const Rectangle<int> NSViewComponentPeer::getBounds() const
  230396. {
  230397. return getBounds (! isSharedWindow);
  230398. }
  230399. const Point<int> NSViewComponentPeer::getScreenPosition() const
  230400. {
  230401. return getBounds (true).getPosition();
  230402. }
  230403. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  230404. {
  230405. return relativePosition + getScreenPosition();
  230406. }
  230407. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  230408. {
  230409. return screenPosition - getScreenPosition();
  230410. }
  230411. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  230412. {
  230413. if (constrainer != 0)
  230414. {
  230415. NSRect current = [window frame];
  230416. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  230417. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230418. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  230419. (int) r.size.width, (int) r.size.height);
  230420. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  230421. (int) current.size.width, (int) current.size.height);
  230422. constrainer->checkBounds (pos, original,
  230423. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  230424. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  230425. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  230426. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  230427. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  230428. r.origin.x = pos.getX();
  230429. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  230430. r.size.width = pos.getWidth();
  230431. r.size.height = pos.getHeight();
  230432. }
  230433. return r;
  230434. }
  230435. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  230436. {
  230437. if (! isSharedWindow)
  230438. {
  230439. if (shouldBeMinimised)
  230440. [window miniaturize: nil];
  230441. else
  230442. [window deminiaturize: nil];
  230443. }
  230444. }
  230445. bool NSViewComponentPeer::isMinimised() const
  230446. {
  230447. return window != 0 && [window isMiniaturized];
  230448. }
  230449. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  230450. {
  230451. if (! isSharedWindow)
  230452. {
  230453. Rectangle<int> r (lastNonFullscreenBounds);
  230454. setMinimised (false);
  230455. if (fullScreen != shouldBeFullScreen)
  230456. {
  230457. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  230458. {
  230459. fullScreen = true;
  230460. [window performZoom: nil];
  230461. }
  230462. else
  230463. {
  230464. if (shouldBeFullScreen)
  230465. r = Desktop::getInstance().getMainMonitorArea();
  230466. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  230467. if (r != getComponent()->getBounds() && ! r.isEmpty())
  230468. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  230469. }
  230470. }
  230471. }
  230472. }
  230473. bool NSViewComponentPeer::isFullScreen() const
  230474. {
  230475. return fullScreen;
  230476. }
  230477. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  230478. {
  230479. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  230480. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  230481. return false;
  230482. NSPoint p;
  230483. p.x = (float) position.getX();
  230484. p.y = (float) position.getY();
  230485. NSView* v = [view hitTest: p];
  230486. if (trueIfInAChildWindow)
  230487. return v != nil;
  230488. return v == view;
  230489. }
  230490. const BorderSize NSViewComponentPeer::getFrameSize() const
  230491. {
  230492. BorderSize b;
  230493. if (! isSharedWindow)
  230494. {
  230495. NSRect v = [view convertRect: [view frame] toView: nil];
  230496. NSRect w = [window frame];
  230497. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  230498. b.setBottom ((int) v.origin.y);
  230499. b.setLeft ((int) v.origin.x);
  230500. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  230501. }
  230502. return b;
  230503. }
  230504. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  230505. {
  230506. if (! isSharedWindow)
  230507. {
  230508. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  230509. : NSNormalWindowLevel];
  230510. }
  230511. return true;
  230512. }
  230513. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  230514. {
  230515. if (isSharedWindow)
  230516. {
  230517. [[view superview] addSubview: view
  230518. positioned: NSWindowAbove
  230519. relativeTo: nil];
  230520. }
  230521. if (window != 0 && component->isVisible())
  230522. {
  230523. if (makeActiveWindow)
  230524. [window makeKeyAndOrderFront: nil];
  230525. else
  230526. [window orderFront: nil];
  230527. if (! recursiveToFrontCall)
  230528. {
  230529. recursiveToFrontCall = true;
  230530. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230531. handleBroughtToFront();
  230532. recursiveToFrontCall = false;
  230533. }
  230534. }
  230535. }
  230536. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  230537. {
  230538. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  230539. jassert (otherPeer != 0); // wrong type of window?
  230540. if (otherPeer != 0)
  230541. {
  230542. if (isSharedWindow)
  230543. {
  230544. [[view superview] addSubview: view
  230545. positioned: NSWindowBelow
  230546. relativeTo: otherPeer->view];
  230547. }
  230548. else
  230549. {
  230550. [window orderWindow: NSWindowBelow
  230551. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  230552. : nil ];
  230553. }
  230554. }
  230555. }
  230556. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  230557. {
  230558. // to do..
  230559. }
  230560. void NSViewComponentPeer::viewFocusGain()
  230561. {
  230562. if (currentlyFocusedPeer != this)
  230563. {
  230564. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  230565. currentlyFocusedPeer->handleFocusLoss();
  230566. currentlyFocusedPeer = this;
  230567. handleFocusGain();
  230568. }
  230569. }
  230570. void NSViewComponentPeer::viewFocusLoss()
  230571. {
  230572. if (currentlyFocusedPeer == this)
  230573. {
  230574. currentlyFocusedPeer = 0;
  230575. handleFocusLoss();
  230576. }
  230577. }
  230578. void juce_HandleProcessFocusChange()
  230579. {
  230580. NSViewComponentPeer::keysCurrentlyDown.clear();
  230581. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  230582. {
  230583. if (Process::isForegroundProcess())
  230584. {
  230585. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  230586. ComponentPeer::bringModalComponentToFront();
  230587. }
  230588. else
  230589. {
  230590. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  230591. // turn kiosk mode off if we lose focus..
  230592. Desktop::getInstance().setKioskModeComponent (0);
  230593. }
  230594. }
  230595. }
  230596. bool NSViewComponentPeer::isFocused() const
  230597. {
  230598. return isSharedWindow ? this == currentlyFocusedPeer
  230599. : (window != 0 && [window isKeyWindow]);
  230600. }
  230601. void NSViewComponentPeer::grabFocus()
  230602. {
  230603. if (window != 0)
  230604. {
  230605. [window makeKeyWindow];
  230606. [window makeFirstResponder: view];
  230607. viewFocusGain();
  230608. }
  230609. }
  230610. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  230611. {
  230612. }
  230613. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  230614. {
  230615. String unicode (nsStringToJuce ([ev characters]));
  230616. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230617. int keyCode = getKeyCodeFromEvent (ev);
  230618. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  230619. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  230620. if (unicode.isNotEmpty() || keyCode != 0)
  230621. {
  230622. if (isKeyDown)
  230623. {
  230624. bool used = false;
  230625. while (unicode.length() > 0)
  230626. {
  230627. juce_wchar textCharacter = unicode[0];
  230628. unicode = unicode.substring (1);
  230629. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230630. textCharacter = 0;
  230631. used = handleKeyUpOrDown (true) || used;
  230632. used = handleKeyPress (keyCode, textCharacter) || used;
  230633. }
  230634. return used;
  230635. }
  230636. else
  230637. {
  230638. if (handleKeyUpOrDown (false))
  230639. return true;
  230640. }
  230641. }
  230642. return false;
  230643. }
  230644. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  230645. {
  230646. updateKeysDown (ev, true);
  230647. bool used = handleKeyEvent (ev, true);
  230648. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230649. {
  230650. // for command keys, the key-up event is thrown away, so simulate one..
  230651. updateKeysDown (ev, false);
  230652. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  230653. }
  230654. // (If we're running modally, don't allow unused keystrokes to be passed
  230655. // along to other blocked views..)
  230656. if (Component::getCurrentlyModalComponent() != 0)
  230657. used = true;
  230658. return used;
  230659. }
  230660. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  230661. {
  230662. updateKeysDown (ev, false);
  230663. return handleKeyEvent (ev, false)
  230664. || Component::getCurrentlyModalComponent() != 0;
  230665. }
  230666. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  230667. {
  230668. keysCurrentlyDown.clear();
  230669. handleKeyUpOrDown (true);
  230670. updateModifiers (ev);
  230671. handleModifierKeysChange();
  230672. }
  230673. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230674. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  230675. {
  230676. if ([ev type] == NSKeyDown)
  230677. return redirectKeyDown (ev);
  230678. else if ([ev type] == NSKeyUp)
  230679. return redirectKeyUp (ev);
  230680. return false;
  230681. }
  230682. #endif
  230683. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  230684. {
  230685. updateModifiers (ev);
  230686. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  230687. }
  230688. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  230689. {
  230690. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230691. sendMouseEvent (ev);
  230692. }
  230693. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  230694. {
  230695. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230696. sendMouseEvent (ev);
  230697. showArrowCursorIfNeeded();
  230698. }
  230699. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  230700. {
  230701. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230702. sendMouseEvent (ev);
  230703. }
  230704. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  230705. {
  230706. currentModifiers = currentModifiers.withoutMouseButtons();
  230707. sendMouseEvent (ev);
  230708. showArrowCursorIfNeeded();
  230709. }
  230710. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  230711. {
  230712. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230713. currentModifiers = currentModifiers.withoutMouseButtons();
  230714. sendMouseEvent (ev);
  230715. }
  230716. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  230717. {
  230718. currentModifiers = currentModifiers.withoutMouseButtons();
  230719. sendMouseEvent (ev);
  230720. }
  230721. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  230722. {
  230723. updateModifiers (ev);
  230724. float x = 0, y = 0;
  230725. @try
  230726. {
  230727. x = [ev deviceDeltaX] * 0.5f;
  230728. y = [ev deviceDeltaY] * 0.5f;
  230729. }
  230730. @catch (...)
  230731. {}
  230732. if (x == 0 && y == 0)
  230733. {
  230734. x = [ev deltaX] * 10.0f;
  230735. y = [ev deltaY] * 10.0f;
  230736. }
  230737. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  230738. }
  230739. void NSViewComponentPeer::showArrowCursorIfNeeded()
  230740. {
  230741. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  230742. if (mouse.getComponentUnderMouse() == 0
  230743. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  230744. {
  230745. [[NSCursor arrowCursor] set];
  230746. }
  230747. }
  230748. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  230749. {
  230750. NSString* bestType
  230751. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  230752. if (bestType == nil)
  230753. return false;
  230754. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  230755. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  230756. StringArray files;
  230757. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  230758. if (list == nil)
  230759. return false;
  230760. if ([list isKindOfClass: [NSArray class]])
  230761. {
  230762. NSArray* items = (NSArray*) list;
  230763. for (unsigned int i = 0; i < [items count]; ++i)
  230764. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  230765. }
  230766. if (files.size() == 0)
  230767. return false;
  230768. if (type == 0)
  230769. handleFileDragMove (files, pos);
  230770. else if (type == 1)
  230771. handleFileDragExit (files);
  230772. else if (type == 2)
  230773. handleFileDragDrop (files, pos);
  230774. return true;
  230775. }
  230776. bool NSViewComponentPeer::isOpaque()
  230777. {
  230778. return component == 0 || component->isOpaque();
  230779. }
  230780. void NSViewComponentPeer::drawRect (NSRect r)
  230781. {
  230782. if (r.size.width < 1.0f || r.size.height < 1.0f)
  230783. return;
  230784. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230785. if (! component->isOpaque())
  230786. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  230787. #if USE_COREGRAPHICS_RENDERING
  230788. if (usingCoreGraphics)
  230789. {
  230790. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  230791. insideDrawRect = true;
  230792. handlePaint (context);
  230793. insideDrawRect = false;
  230794. }
  230795. else
  230796. #endif
  230797. {
  230798. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  230799. (int) (r.size.width + 0.5f),
  230800. (int) (r.size.height + 0.5f),
  230801. ! getComponent()->isOpaque());
  230802. const int xOffset = -roundToInt (r.origin.x);
  230803. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  230804. const NSRect* rects = 0;
  230805. NSInteger numRects = 0;
  230806. [view getRectsBeingDrawn: &rects count: &numRects];
  230807. const Rectangle<int> clipBounds (temp.getBounds());
  230808. RectangleList clip;
  230809. for (int i = 0; i < numRects; ++i)
  230810. {
  230811. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  230812. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  230813. roundToInt (rects[i].size.width),
  230814. roundToInt (rects[i].size.height))));
  230815. }
  230816. if (! clip.isEmpty())
  230817. {
  230818. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  230819. insideDrawRect = true;
  230820. handlePaint (context);
  230821. insideDrawRect = false;
  230822. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230823. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  230824. CGColorSpaceRelease (colourSpace);
  230825. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  230826. CGImageRelease (image);
  230827. }
  230828. }
  230829. }
  230830. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  230831. {
  230832. StringArray s;
  230833. s.add ("Software Renderer");
  230834. #if USE_COREGRAPHICS_RENDERING
  230835. s.add ("CoreGraphics Renderer");
  230836. #endif
  230837. return s;
  230838. }
  230839. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  230840. {
  230841. return usingCoreGraphics ? 1 : 0;
  230842. }
  230843. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  230844. {
  230845. #if USE_COREGRAPHICS_RENDERING
  230846. if (usingCoreGraphics != (index > 0))
  230847. {
  230848. usingCoreGraphics = index > 0;
  230849. [view setNeedsDisplay: true];
  230850. }
  230851. #endif
  230852. }
  230853. bool NSViewComponentPeer::canBecomeKeyWindow()
  230854. {
  230855. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  230856. }
  230857. bool NSViewComponentPeer::windowShouldClose()
  230858. {
  230859. if (! isValidPeer (this))
  230860. return YES;
  230861. handleUserClosingWindow();
  230862. return NO;
  230863. }
  230864. void NSViewComponentPeer::redirectMovedOrResized()
  230865. {
  230866. handleMovedOrResized();
  230867. }
  230868. void NSViewComponentPeer::viewMovedToWindow()
  230869. {
  230870. if (isSharedWindow)
  230871. window = [view window];
  230872. }
  230873. void Desktop::createMouseInputSources()
  230874. {
  230875. mouseSources.add (new MouseInputSource (0, true));
  230876. }
  230877. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  230878. {
  230879. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  230880. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  230881. // is apparently still available in 64-bit apps..
  230882. if (enableOrDisable)
  230883. {
  230884. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  230885. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  230886. }
  230887. else
  230888. {
  230889. SetSystemUIMode (kUIModeNormal, 0);
  230890. }
  230891. }
  230892. class AsyncRepaintMessage : public CallbackMessage
  230893. {
  230894. public:
  230895. NSViewComponentPeer* const peer;
  230896. const Rectangle<int> rect;
  230897. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  230898. : peer (peer_), rect (rect_)
  230899. {
  230900. }
  230901. void messageCallback()
  230902. {
  230903. if (ComponentPeer::isValidPeer (peer))
  230904. peer->repaint (rect);
  230905. }
  230906. };
  230907. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  230908. {
  230909. if (insideDrawRect)
  230910. {
  230911. (new AsyncRepaintMessage (this, area))->post();
  230912. }
  230913. else
  230914. {
  230915. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  230916. (float) area.getWidth(), (float) area.getHeight())];
  230917. }
  230918. }
  230919. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  230920. {
  230921. [view displayIfNeeded];
  230922. }
  230923. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  230924. {
  230925. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  230926. }
  230927. const Image juce_createIconForFile (const File& file)
  230928. {
  230929. const ScopedAutoReleasePool pool;
  230930. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  230931. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  230932. [NSGraphicsContext saveGraphicsState];
  230933. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  230934. [image drawAtPoint: NSMakePoint (0, 0)
  230935. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  230936. operation: NSCompositeSourceOver fraction: 1.0f];
  230937. [[NSGraphicsContext currentContext] flushGraphics];
  230938. [NSGraphicsContext restoreGraphicsState];
  230939. return Image (result);
  230940. }
  230941. const int KeyPress::spaceKey = ' ';
  230942. const int KeyPress::returnKey = 0x0d;
  230943. const int KeyPress::escapeKey = 0x1b;
  230944. const int KeyPress::backspaceKey = 0x7f;
  230945. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  230946. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  230947. const int KeyPress::upKey = NSUpArrowFunctionKey;
  230948. const int KeyPress::downKey = NSDownArrowFunctionKey;
  230949. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  230950. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  230951. const int KeyPress::endKey = NSEndFunctionKey;
  230952. const int KeyPress::homeKey = NSHomeFunctionKey;
  230953. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  230954. const int KeyPress::insertKey = -1;
  230955. const int KeyPress::tabKey = 9;
  230956. const int KeyPress::F1Key = NSF1FunctionKey;
  230957. const int KeyPress::F2Key = NSF2FunctionKey;
  230958. const int KeyPress::F3Key = NSF3FunctionKey;
  230959. const int KeyPress::F4Key = NSF4FunctionKey;
  230960. const int KeyPress::F5Key = NSF5FunctionKey;
  230961. const int KeyPress::F6Key = NSF6FunctionKey;
  230962. const int KeyPress::F7Key = NSF7FunctionKey;
  230963. const int KeyPress::F8Key = NSF8FunctionKey;
  230964. const int KeyPress::F9Key = NSF9FunctionKey;
  230965. const int KeyPress::F10Key = NSF10FunctionKey;
  230966. const int KeyPress::F11Key = NSF1FunctionKey;
  230967. const int KeyPress::F12Key = NSF12FunctionKey;
  230968. const int KeyPress::F13Key = NSF13FunctionKey;
  230969. const int KeyPress::F14Key = NSF14FunctionKey;
  230970. const int KeyPress::F15Key = NSF15FunctionKey;
  230971. const int KeyPress::F16Key = NSF16FunctionKey;
  230972. const int KeyPress::numberPad0 = 0x30020;
  230973. const int KeyPress::numberPad1 = 0x30021;
  230974. const int KeyPress::numberPad2 = 0x30022;
  230975. const int KeyPress::numberPad3 = 0x30023;
  230976. const int KeyPress::numberPad4 = 0x30024;
  230977. const int KeyPress::numberPad5 = 0x30025;
  230978. const int KeyPress::numberPad6 = 0x30026;
  230979. const int KeyPress::numberPad7 = 0x30027;
  230980. const int KeyPress::numberPad8 = 0x30028;
  230981. const int KeyPress::numberPad9 = 0x30029;
  230982. const int KeyPress::numberPadAdd = 0x3002a;
  230983. const int KeyPress::numberPadSubtract = 0x3002b;
  230984. const int KeyPress::numberPadMultiply = 0x3002c;
  230985. const int KeyPress::numberPadDivide = 0x3002d;
  230986. const int KeyPress::numberPadSeparator = 0x3002e;
  230987. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  230988. const int KeyPress::numberPadEquals = 0x30030;
  230989. const int KeyPress::numberPadDelete = 0x30031;
  230990. const int KeyPress::playKey = 0x30000;
  230991. const int KeyPress::stopKey = 0x30001;
  230992. const int KeyPress::fastForwardKey = 0x30002;
  230993. const int KeyPress::rewindKey = 0x30003;
  230994. #endif
  230995. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230996. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  230997. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230998. // compiled on its own).
  230999. #if JUCE_INCLUDED_FILE
  231000. #if JUCE_MAC
  231001. namespace MouseCursorHelpers
  231002. {
  231003. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231004. {
  231005. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231006. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231007. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231008. [im release];
  231009. return c;
  231010. }
  231011. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231012. {
  231013. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231014. BufferedInputStream buf (&fileStream, 4096, false);
  231015. PNGImageFormat pngFormat;
  231016. Image im (pngFormat.decodeImage (buf));
  231017. if (im.isValid())
  231018. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231019. jassertfalse;
  231020. return 0;
  231021. }
  231022. }
  231023. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231024. {
  231025. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231026. }
  231027. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231028. {
  231029. const ScopedAutoReleasePool pool;
  231030. NSCursor* c = 0;
  231031. switch (type)
  231032. {
  231033. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231034. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231035. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231036. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231037. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231038. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231039. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231040. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231041. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231042. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231043. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231044. case UpDownResizeCursor:
  231045. case TopEdgeResizeCursor:
  231046. case BottomEdgeResizeCursor:
  231047. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231048. case TopLeftCornerResizeCursor:
  231049. case BottomRightCornerResizeCursor:
  231050. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231051. case TopRightCornerResizeCursor:
  231052. case BottomLeftCornerResizeCursor:
  231053. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231054. case UpDownLeftRightResizeCursor:
  231055. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231056. default:
  231057. jassertfalse;
  231058. break;
  231059. }
  231060. [c retain];
  231061. return c;
  231062. }
  231063. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231064. {
  231065. [((NSCursor*) cursorHandle) release];
  231066. }
  231067. void MouseCursor::showInAllWindows() const
  231068. {
  231069. showInWindow (0);
  231070. }
  231071. void MouseCursor::showInWindow (ComponentPeer*) const
  231072. {
  231073. [((NSCursor*) getHandle()) set];
  231074. }
  231075. #else
  231076. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231077. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231078. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231079. void MouseCursor::showInAllWindows() const {}
  231080. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231081. #endif
  231082. #endif
  231083. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231084. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231085. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231086. // compiled on its own).
  231087. #if JUCE_INCLUDED_FILE
  231088. class NSViewComponentInternal : public ComponentMovementWatcher
  231089. {
  231090. Component* const owner;
  231091. NSViewComponentPeer* currentPeer;
  231092. bool wasShowing;
  231093. public:
  231094. NSView* const view;
  231095. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  231096. : ComponentMovementWatcher (owner_),
  231097. owner (owner_),
  231098. currentPeer (0),
  231099. wasShowing (false),
  231100. view (view_)
  231101. {
  231102. [view_ retain];
  231103. if (owner_->isShowing())
  231104. componentPeerChanged();
  231105. }
  231106. ~NSViewComponentInternal()
  231107. {
  231108. [view removeFromSuperview];
  231109. [view release];
  231110. }
  231111. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231112. {
  231113. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231114. // The ComponentMovementWatcher version of this method avoids calling
  231115. // us when the top-level comp is resized, but for an NSView we need to know this
  231116. // because with inverted co-ords, we need to update the position even if the
  231117. // top-left pos hasn't changed
  231118. if (comp.isOnDesktop() && wasResized)
  231119. componentMovedOrResized (wasMoved, wasResized);
  231120. }
  231121. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231122. {
  231123. Component* const topComp = owner->getTopLevelComponent();
  231124. if (topComp->getPeer() != 0)
  231125. {
  231126. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  231127. NSRect r;
  231128. r.origin.x = (float) pos.getX();
  231129. r.origin.y = (float) pos.getY();
  231130. r.size.width = (float) owner->getWidth();
  231131. r.size.height = (float) owner->getHeight();
  231132. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231133. [view setFrame: r];
  231134. }
  231135. }
  231136. void componentPeerChanged()
  231137. {
  231138. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  231139. if (currentPeer != peer)
  231140. {
  231141. [view removeFromSuperview];
  231142. currentPeer = peer;
  231143. if (peer != 0)
  231144. {
  231145. [peer->view addSubview: view];
  231146. componentMovedOrResized (false, false);
  231147. }
  231148. }
  231149. [view setHidden: ! owner->isShowing()];
  231150. }
  231151. void componentVisibilityChanged (Component&)
  231152. {
  231153. componentPeerChanged();
  231154. }
  231155. juce_UseDebuggingNewOperator
  231156. private:
  231157. NSViewComponentInternal (const NSViewComponentInternal&);
  231158. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  231159. };
  231160. NSViewComponent::NSViewComponent()
  231161. {
  231162. }
  231163. NSViewComponent::~NSViewComponent()
  231164. {
  231165. }
  231166. void NSViewComponent::setView (void* view)
  231167. {
  231168. if (view != getView())
  231169. {
  231170. if (view != 0)
  231171. info = new NSViewComponentInternal ((NSView*) view, this);
  231172. else
  231173. info = 0;
  231174. }
  231175. }
  231176. void* NSViewComponent::getView() const
  231177. {
  231178. return info == 0 ? 0 : info->view;
  231179. }
  231180. void NSViewComponent::paint (Graphics&)
  231181. {
  231182. }
  231183. #endif
  231184. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231185. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231186. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231187. // compiled on its own).
  231188. #if JUCE_INCLUDED_FILE
  231189. AppleRemoteDevice::AppleRemoteDevice()
  231190. : device (0),
  231191. queue (0),
  231192. remoteId (0)
  231193. {
  231194. }
  231195. AppleRemoteDevice::~AppleRemoteDevice()
  231196. {
  231197. stop();
  231198. }
  231199. static io_object_t getAppleRemoteDevice()
  231200. {
  231201. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231202. io_iterator_t iter = 0;
  231203. io_object_t iod = 0;
  231204. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231205. && iter != 0)
  231206. {
  231207. iod = IOIteratorNext (iter);
  231208. }
  231209. IOObjectRelease (iter);
  231210. return iod;
  231211. }
  231212. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  231213. {
  231214. jassert (*device == 0);
  231215. io_name_t classname;
  231216. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231217. {
  231218. IOCFPlugInInterface** cfPlugInInterface = 0;
  231219. SInt32 score = 0;
  231220. if (IOCreatePlugInInterfaceForService (iod,
  231221. kIOHIDDeviceUserClientTypeID,
  231222. kIOCFPlugInInterfaceID,
  231223. &cfPlugInInterface,
  231224. &score) == kIOReturnSuccess)
  231225. {
  231226. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231227. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231228. device);
  231229. (void) hr;
  231230. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231231. }
  231232. }
  231233. return *device != 0;
  231234. }
  231235. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231236. {
  231237. if (queue != 0)
  231238. return true;
  231239. stop();
  231240. bool result = false;
  231241. io_object_t iod = getAppleRemoteDevice();
  231242. if (iod != 0)
  231243. {
  231244. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  231245. result = true;
  231246. else
  231247. stop();
  231248. IOObjectRelease (iod);
  231249. }
  231250. return result;
  231251. }
  231252. void AppleRemoteDevice::stop()
  231253. {
  231254. if (queue != 0)
  231255. {
  231256. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  231257. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  231258. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  231259. queue = 0;
  231260. }
  231261. if (device != 0)
  231262. {
  231263. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  231264. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  231265. device = 0;
  231266. }
  231267. }
  231268. bool AppleRemoteDevice::isActive() const
  231269. {
  231270. return queue != 0;
  231271. }
  231272. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231273. {
  231274. if (result == kIOReturnSuccess)
  231275. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231276. }
  231277. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  231278. {
  231279. Array <int> cookies;
  231280. CFArrayRef elements;
  231281. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  231282. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  231283. return false;
  231284. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  231285. {
  231286. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  231287. // get the cookie
  231288. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  231289. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  231290. continue;
  231291. long number;
  231292. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  231293. continue;
  231294. cookies.add ((int) number);
  231295. }
  231296. CFRelease (elements);
  231297. if ((*(IOHIDDeviceInterface**) device)
  231298. ->open ((IOHIDDeviceInterface**) device,
  231299. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  231300. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  231301. {
  231302. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  231303. if (queue != 0)
  231304. {
  231305. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  231306. for (int i = 0; i < cookies.size(); ++i)
  231307. {
  231308. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  231309. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  231310. }
  231311. CFRunLoopSourceRef eventSource;
  231312. if ((*(IOHIDQueueInterface**) queue)
  231313. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  231314. {
  231315. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  231316. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  231317. {
  231318. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  231319. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  231320. return true;
  231321. }
  231322. }
  231323. }
  231324. }
  231325. return false;
  231326. }
  231327. void AppleRemoteDevice::handleCallbackInternal()
  231328. {
  231329. int totalValues = 0;
  231330. AbsoluteTime nullTime = { 0, 0 };
  231331. char cookies [12];
  231332. int numCookies = 0;
  231333. while (numCookies < numElementsInArray (cookies))
  231334. {
  231335. IOHIDEventStruct e;
  231336. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  231337. break;
  231338. if ((int) e.elementCookie == 19)
  231339. {
  231340. remoteId = e.value;
  231341. buttonPressed (switched, false);
  231342. }
  231343. else
  231344. {
  231345. totalValues += e.value;
  231346. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  231347. }
  231348. }
  231349. cookies [numCookies++] = 0;
  231350. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  231351. static const char buttonPatterns[] =
  231352. {
  231353. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  231354. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  231355. 0x1f, 0x1d, 0x1c, 0x12, 0,
  231356. 0x1f, 0x1e, 0x1c, 0x12, 0,
  231357. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  231358. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  231359. 0x1f, 0x12, 0x04, 0x02, 0,
  231360. 0x1f, 0x12, 0x03, 0x02, 0,
  231361. 0x1f, 0x12, 0x1f, 0x12, 0,
  231362. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  231363. 19, 0
  231364. };
  231365. int buttonNum = (int) menuButton;
  231366. int i = 0;
  231367. while (i < numElementsInArray (buttonPatterns))
  231368. {
  231369. if (strcmp (cookies, buttonPatterns + i) == 0)
  231370. {
  231371. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  231372. break;
  231373. }
  231374. i += (int) strlen (buttonPatterns + i) + 1;
  231375. ++buttonNum;
  231376. }
  231377. }
  231378. #endif
  231379. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  231380. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  231381. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231382. // compiled on its own).
  231383. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  231384. #if JUCE_MAC
  231385. END_JUCE_NAMESPACE
  231386. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  231387. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  231388. {
  231389. CriticalSection* contextLock;
  231390. bool needsUpdate;
  231391. }
  231392. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  231393. - (bool) makeActive;
  231394. - (void) makeInactive;
  231395. - (void) reshape;
  231396. @end
  231397. @implementation ThreadSafeNSOpenGLView
  231398. - (id) initWithFrame: (NSRect) frameRect
  231399. pixelFormat: (NSOpenGLPixelFormat*) format
  231400. {
  231401. contextLock = new CriticalSection();
  231402. self = [super initWithFrame: frameRect pixelFormat: format];
  231403. if (self != nil)
  231404. [[NSNotificationCenter defaultCenter] addObserver: self
  231405. selector: @selector (_surfaceNeedsUpdate:)
  231406. name: NSViewGlobalFrameDidChangeNotification
  231407. object: self];
  231408. return self;
  231409. }
  231410. - (void) dealloc
  231411. {
  231412. [[NSNotificationCenter defaultCenter] removeObserver: self];
  231413. delete contextLock;
  231414. [super dealloc];
  231415. }
  231416. - (bool) makeActive
  231417. {
  231418. const ScopedLock sl (*contextLock);
  231419. if ([self openGLContext] == 0)
  231420. return false;
  231421. [[self openGLContext] makeCurrentContext];
  231422. if (needsUpdate)
  231423. {
  231424. [super update];
  231425. needsUpdate = false;
  231426. }
  231427. return true;
  231428. }
  231429. - (void) makeInactive
  231430. {
  231431. const ScopedLock sl (*contextLock);
  231432. [NSOpenGLContext clearCurrentContext];
  231433. }
  231434. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  231435. {
  231436. const ScopedLock sl (*contextLock);
  231437. needsUpdate = true;
  231438. }
  231439. - (void) update
  231440. {
  231441. const ScopedLock sl (*contextLock);
  231442. needsUpdate = true;
  231443. }
  231444. - (void) reshape
  231445. {
  231446. const ScopedLock sl (*contextLock);
  231447. needsUpdate = true;
  231448. }
  231449. @end
  231450. BEGIN_JUCE_NAMESPACE
  231451. class WindowedGLContext : public OpenGLContext
  231452. {
  231453. public:
  231454. WindowedGLContext (Component* const component,
  231455. const OpenGLPixelFormat& pixelFormat_,
  231456. NSOpenGLContext* sharedContext)
  231457. : renderContext (0),
  231458. pixelFormat (pixelFormat_)
  231459. {
  231460. jassert (component != 0);
  231461. NSOpenGLPixelFormatAttribute attribs [64];
  231462. int n = 0;
  231463. attribs[n++] = NSOpenGLPFADoubleBuffer;
  231464. attribs[n++] = NSOpenGLPFAAccelerated;
  231465. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  231466. attribs[n++] = NSOpenGLPFAColorSize;
  231467. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  231468. pixelFormat.greenBits,
  231469. pixelFormat.blueBits);
  231470. attribs[n++] = NSOpenGLPFAAlphaSize;
  231471. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  231472. attribs[n++] = NSOpenGLPFADepthSize;
  231473. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  231474. attribs[n++] = NSOpenGLPFAStencilSize;
  231475. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  231476. attribs[n++] = NSOpenGLPFAAccumSize;
  231477. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  231478. pixelFormat.accumulationBufferGreenBits,
  231479. pixelFormat.accumulationBufferBlueBits,
  231480. pixelFormat.accumulationBufferAlphaBits);
  231481. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  231482. attribs[n++] = NSOpenGLPFASampleBuffers;
  231483. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  231484. attribs[n++] = NSOpenGLPFAClosestPolicy;
  231485. attribs[n++] = NSOpenGLPFANoRecovery;
  231486. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  231487. NSOpenGLPixelFormat* format
  231488. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  231489. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231490. pixelFormat: format];
  231491. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  231492. shareContext: sharedContext] autorelease];
  231493. const GLint swapInterval = 1;
  231494. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  231495. [view setOpenGLContext: renderContext];
  231496. [renderContext setView: view];
  231497. [format release];
  231498. viewHolder = new NSViewComponentInternal (view, component);
  231499. }
  231500. ~WindowedGLContext()
  231501. {
  231502. deleteContext();
  231503. viewHolder = 0;
  231504. }
  231505. void deleteContext()
  231506. {
  231507. makeInactive();
  231508. [renderContext clearDrawable];
  231509. [renderContext setView: nil];
  231510. [view setOpenGLContext: nil];
  231511. renderContext = nil;
  231512. }
  231513. bool makeActive() const throw()
  231514. {
  231515. jassert (renderContext != 0);
  231516. [view makeActive];
  231517. return isActive();
  231518. }
  231519. bool makeInactive() const throw()
  231520. {
  231521. [view makeInactive];
  231522. return true;
  231523. }
  231524. bool isActive() const throw()
  231525. {
  231526. return [NSOpenGLContext currentContext] == renderContext;
  231527. }
  231528. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231529. void* getRawContext() const throw() { return renderContext; }
  231530. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231531. {
  231532. }
  231533. void swapBuffers()
  231534. {
  231535. [renderContext flushBuffer];
  231536. }
  231537. bool setSwapInterval (const int numFramesPerSwap)
  231538. {
  231539. [renderContext setValues: (const GLint*) &numFramesPerSwap
  231540. forParameter: NSOpenGLCPSwapInterval];
  231541. return true;
  231542. }
  231543. int getSwapInterval() const
  231544. {
  231545. GLint numFrames = 0;
  231546. [renderContext getValues: &numFrames
  231547. forParameter: NSOpenGLCPSwapInterval];
  231548. return numFrames;
  231549. }
  231550. void repaint()
  231551. {
  231552. // we need to invalidate the juce view that holds this gl view, to make it
  231553. // cause a repaint callback
  231554. NSView* v = (NSView*) viewHolder->view;
  231555. NSRect r = [v frame];
  231556. // bit of a bodge here.. if we only invalidate the area of the gl component,
  231557. // it's completely covered by the NSOpenGLView, so the OS throws away the
  231558. // repaint message, thus never causing our paint() callback, and never repainting
  231559. // the comp. So invalidating just a little bit around the edge helps..
  231560. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  231561. }
  231562. void* getNativeWindowHandle() const { return viewHolder->view; }
  231563. juce_UseDebuggingNewOperator
  231564. NSOpenGLContext* renderContext;
  231565. ThreadSafeNSOpenGLView* view;
  231566. private:
  231567. OpenGLPixelFormat pixelFormat;
  231568. ScopedPointer <NSViewComponentInternal> viewHolder;
  231569. WindowedGLContext (const WindowedGLContext&);
  231570. WindowedGLContext& operator= (const WindowedGLContext&);
  231571. };
  231572. OpenGLContext* OpenGLComponent::createContext()
  231573. {
  231574. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  231575. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  231576. return (c->renderContext != 0) ? c.release() : 0;
  231577. }
  231578. void* OpenGLComponent::getNativeWindowHandle() const
  231579. {
  231580. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  231581. : 0;
  231582. }
  231583. void juce_glViewport (const int w, const int h)
  231584. {
  231585. glViewport (0, 0, w, h);
  231586. }
  231587. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231588. OwnedArray <OpenGLPixelFormat>& results)
  231589. {
  231590. /* GLint attribs [64];
  231591. int n = 0;
  231592. attribs[n++] = AGL_RGBA;
  231593. attribs[n++] = AGL_DOUBLEBUFFER;
  231594. attribs[n++] = AGL_ACCELERATED;
  231595. attribs[n++] = AGL_NO_RECOVERY;
  231596. attribs[n++] = AGL_NONE;
  231597. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  231598. while (p != 0)
  231599. {
  231600. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  231601. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  231602. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  231603. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  231604. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  231605. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  231606. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  231607. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  231608. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  231609. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  231610. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  231611. results.add (pf);
  231612. p = aglNextPixelFormat (p);
  231613. }*/
  231614. //jassertfalse //xxx can't see how you do this in cocoa!
  231615. }
  231616. #else
  231617. END_JUCE_NAMESPACE
  231618. @interface JuceGLView : UIView
  231619. {
  231620. }
  231621. + (Class) layerClass;
  231622. @end
  231623. @implementation JuceGLView
  231624. + (Class) layerClass
  231625. {
  231626. return [CAEAGLLayer class];
  231627. }
  231628. @end
  231629. BEGIN_JUCE_NAMESPACE
  231630. class GLESContext : public OpenGLContext
  231631. {
  231632. public:
  231633. GLESContext (UIViewComponentPeer* peer,
  231634. Component* const component_,
  231635. const OpenGLPixelFormat& pixelFormat_,
  231636. const GLESContext* const sharedContext,
  231637. NSUInteger apiType)
  231638. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  231639. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  231640. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  231641. {
  231642. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  231643. view.opaque = YES;
  231644. view.hidden = NO;
  231645. view.backgroundColor = [UIColor blackColor];
  231646. view.userInteractionEnabled = NO;
  231647. glLayer = (CAEAGLLayer*) [view layer];
  231648. [peer->view addSubview: view];
  231649. if (sharedContext != 0)
  231650. context = [[EAGLContext alloc] initWithAPI: apiType
  231651. sharegroup: [sharedContext->context sharegroup]];
  231652. else
  231653. context = [[EAGLContext alloc] initWithAPI: apiType];
  231654. createGLBuffers();
  231655. }
  231656. ~GLESContext()
  231657. {
  231658. deleteContext();
  231659. [view removeFromSuperview];
  231660. [view release];
  231661. freeGLBuffers();
  231662. }
  231663. void deleteContext()
  231664. {
  231665. makeInactive();
  231666. [context release];
  231667. context = nil;
  231668. }
  231669. bool makeActive() const throw()
  231670. {
  231671. jassert (context != 0);
  231672. [EAGLContext setCurrentContext: context];
  231673. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231674. return true;
  231675. }
  231676. void swapBuffers()
  231677. {
  231678. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231679. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  231680. }
  231681. bool makeInactive() const throw()
  231682. {
  231683. return [EAGLContext setCurrentContext: nil];
  231684. }
  231685. bool isActive() const throw()
  231686. {
  231687. return [EAGLContext currentContext] == context;
  231688. }
  231689. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231690. void* getRawContext() const throw() { return glLayer; }
  231691. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231692. {
  231693. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  231694. if (lastWidth != w || lastHeight != h)
  231695. {
  231696. lastWidth = w;
  231697. lastHeight = h;
  231698. freeGLBuffers();
  231699. createGLBuffers();
  231700. }
  231701. }
  231702. bool setSwapInterval (const int numFramesPerSwap)
  231703. {
  231704. numFrames = numFramesPerSwap;
  231705. return true;
  231706. }
  231707. int getSwapInterval() const
  231708. {
  231709. return numFrames;
  231710. }
  231711. void repaint()
  231712. {
  231713. }
  231714. void createGLBuffers()
  231715. {
  231716. makeActive();
  231717. glGenFramebuffersOES (1, &frameBufferHandle);
  231718. glGenRenderbuffersOES (1, &colorBufferHandle);
  231719. glGenRenderbuffersOES (1, &depthBufferHandle);
  231720. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231721. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  231722. GLint width, height;
  231723. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  231724. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  231725. if (useDepthBuffer)
  231726. {
  231727. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  231728. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  231729. }
  231730. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231731. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231732. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  231733. if (useDepthBuffer)
  231734. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  231735. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  231736. }
  231737. void freeGLBuffers()
  231738. {
  231739. if (frameBufferHandle != 0)
  231740. {
  231741. glDeleteFramebuffersOES (1, &frameBufferHandle);
  231742. frameBufferHandle = 0;
  231743. }
  231744. if (colorBufferHandle != 0)
  231745. {
  231746. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  231747. colorBufferHandle = 0;
  231748. }
  231749. if (depthBufferHandle != 0)
  231750. {
  231751. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  231752. depthBufferHandle = 0;
  231753. }
  231754. }
  231755. juce_UseDebuggingNewOperator
  231756. private:
  231757. Component::SafePointer<Component> component;
  231758. OpenGLPixelFormat pixelFormat;
  231759. JuceGLView* view;
  231760. CAEAGLLayer* glLayer;
  231761. EAGLContext* context;
  231762. bool useDepthBuffer;
  231763. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  231764. int numFrames;
  231765. int lastWidth, lastHeight;
  231766. GLESContext (const GLESContext&);
  231767. GLESContext& operator= (const GLESContext&);
  231768. };
  231769. OpenGLContext* OpenGLComponent::createContext()
  231770. {
  231771. ScopedAutoReleasePool pool;
  231772. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  231773. if (peer != 0)
  231774. return new GLESContext (peer, this, preferredPixelFormat,
  231775. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  231776. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  231777. return 0;
  231778. }
  231779. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231780. OwnedArray <OpenGLPixelFormat>& /*results*/)
  231781. {
  231782. }
  231783. void juce_glViewport (const int w, const int h)
  231784. {
  231785. glViewport (0, 0, w, h);
  231786. }
  231787. #endif
  231788. #endif
  231789. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  231790. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  231791. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231792. // compiled on its own).
  231793. #if JUCE_INCLUDED_FILE
  231794. class JuceMainMenuHandler;
  231795. END_JUCE_NAMESPACE
  231796. using namespace JUCE_NAMESPACE;
  231797. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  231798. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231799. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  231800. #else
  231801. @interface JuceMenuCallback : NSObject
  231802. #endif
  231803. {
  231804. JuceMainMenuHandler* owner;
  231805. }
  231806. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  231807. - (void) dealloc;
  231808. - (void) menuItemInvoked: (id) menu;
  231809. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231810. @end
  231811. BEGIN_JUCE_NAMESPACE
  231812. class JuceMainMenuHandler : private MenuBarModel::Listener,
  231813. private DeletedAtShutdown
  231814. {
  231815. public:
  231816. static JuceMainMenuHandler* instance;
  231817. JuceMainMenuHandler()
  231818. : currentModel (0),
  231819. lastUpdateTime (0)
  231820. {
  231821. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  231822. }
  231823. ~JuceMainMenuHandler()
  231824. {
  231825. setMenu (0);
  231826. jassert (instance == this);
  231827. instance = 0;
  231828. [callback release];
  231829. }
  231830. void setMenu (MenuBarModel* const newMenuBarModel)
  231831. {
  231832. if (currentModel != newMenuBarModel)
  231833. {
  231834. if (currentModel != 0)
  231835. currentModel->removeListener (this);
  231836. currentModel = newMenuBarModel;
  231837. if (currentModel != 0)
  231838. currentModel->addListener (this);
  231839. menuBarItemsChanged (0);
  231840. }
  231841. }
  231842. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  231843. const String& name, const int menuId, const int tag)
  231844. {
  231845. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  231846. action: nil
  231847. keyEquivalent: @""];
  231848. [item setTag: tag];
  231849. NSMenu* sub = createMenu (child, name, menuId, tag);
  231850. [parent setSubmenu: sub forItem: item];
  231851. [sub setAutoenablesItems: false];
  231852. [sub release];
  231853. }
  231854. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  231855. const String& name, const int menuId, const int tag)
  231856. {
  231857. [parentItem setTag: tag];
  231858. NSMenu* menu = [parentItem submenu];
  231859. [menu setTitle: juceStringToNS (name)];
  231860. while ([menu numberOfItems] > 0)
  231861. [menu removeItemAtIndex: 0];
  231862. PopupMenu::MenuItemIterator iter (menuToCopy);
  231863. while (iter.next())
  231864. addMenuItem (iter, menu, menuId, tag);
  231865. [menu setAutoenablesItems: false];
  231866. [menu update];
  231867. }
  231868. void menuBarItemsChanged (MenuBarModel*)
  231869. {
  231870. lastUpdateTime = Time::getMillisecondCounter();
  231871. StringArray menuNames;
  231872. if (currentModel != 0)
  231873. menuNames = currentModel->getMenuBarNames();
  231874. NSMenu* menuBar = [NSApp mainMenu];
  231875. while ([menuBar numberOfItems] > 1 + menuNames.size())
  231876. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  231877. int menuId = 1;
  231878. for (int i = 0; i < menuNames.size(); ++i)
  231879. {
  231880. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  231881. if (i >= [menuBar numberOfItems] - 1)
  231882. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  231883. else
  231884. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  231885. }
  231886. }
  231887. static void flashMenuBar (NSMenu* menu)
  231888. {
  231889. if ([[menu title] isEqualToString: @"Apple"])
  231890. return;
  231891. [menu retain];
  231892. const unichar f35Key = NSF35FunctionKey;
  231893. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  231894. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  231895. action: nil
  231896. keyEquivalent: f35String];
  231897. [item setTarget: nil];
  231898. [menu insertItem: item atIndex: [menu numberOfItems]];
  231899. [item release];
  231900. if ([menu indexOfItem: item] >= 0)
  231901. {
  231902. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  231903. location: NSZeroPoint
  231904. modifierFlags: NSCommandKeyMask
  231905. timestamp: 0
  231906. windowNumber: 0
  231907. context: [NSGraphicsContext currentContext]
  231908. characters: f35String
  231909. charactersIgnoringModifiers: f35String
  231910. isARepeat: NO
  231911. keyCode: 0];
  231912. [menu performKeyEquivalent: f35Event];
  231913. if ([menu indexOfItem: item] >= 0)
  231914. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  231915. }
  231916. [menu release];
  231917. }
  231918. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  231919. {
  231920. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  231921. {
  231922. NSMenuItem* m = [menu itemAtIndex: i];
  231923. if ([m tag] == info.commandID)
  231924. return m;
  231925. if ([m submenu] != 0)
  231926. {
  231927. NSMenuItem* found = findMenuItem ([m submenu], info);
  231928. if (found != 0)
  231929. return found;
  231930. }
  231931. }
  231932. return 0;
  231933. }
  231934. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  231935. {
  231936. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  231937. if (item != 0)
  231938. flashMenuBar ([item menu]);
  231939. }
  231940. void updateMenus()
  231941. {
  231942. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  231943. menuBarItemsChanged (0);
  231944. }
  231945. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  231946. {
  231947. if (currentModel != 0)
  231948. {
  231949. if (commandManager != 0)
  231950. {
  231951. ApplicationCommandTarget::InvocationInfo info (commandId);
  231952. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  231953. commandManager->invoke (info, true);
  231954. }
  231955. currentModel->menuItemSelected (commandId, topLevelIndex);
  231956. }
  231957. }
  231958. MenuBarModel* currentModel;
  231959. uint32 lastUpdateTime;
  231960. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  231961. const int topLevelMenuId, const int topLevelIndex)
  231962. {
  231963. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  231964. if (text == 0)
  231965. text = @"";
  231966. if (iter.isSeparator)
  231967. {
  231968. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  231969. }
  231970. else if (iter.isSectionHeader)
  231971. {
  231972. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231973. action: nil
  231974. keyEquivalent: @""];
  231975. [item setEnabled: false];
  231976. }
  231977. else if (iter.subMenu != 0)
  231978. {
  231979. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231980. action: nil
  231981. keyEquivalent: @""];
  231982. [item setTag: iter.itemId];
  231983. [item setEnabled: iter.isEnabled];
  231984. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  231985. [sub setDelegate: nil];
  231986. [menuToAddTo setSubmenu: sub forItem: item];
  231987. [sub release];
  231988. }
  231989. else
  231990. {
  231991. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231992. action: @selector (menuItemInvoked:)
  231993. keyEquivalent: @""];
  231994. [item setTag: iter.itemId];
  231995. [item setEnabled: iter.isEnabled];
  231996. [item setState: iter.isTicked ? NSOnState : NSOffState];
  231997. [item setTarget: (id) callback];
  231998. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  231999. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  232000. [item setRepresentedObject: info];
  232001. if (iter.commandManager != 0)
  232002. {
  232003. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232004. ->getKeyPressesAssignedToCommand (iter.itemId));
  232005. if (keyPresses.size() > 0)
  232006. {
  232007. const KeyPress& kp = keyPresses.getReference(0);
  232008. if (kp.getKeyCode() != KeyPress::backspaceKey
  232009. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232010. // every time you press the key while editing text)
  232011. {
  232012. juce_wchar key = kp.getTextCharacter();
  232013. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232014. key = NSBackspaceCharacter;
  232015. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232016. key = NSDeleteCharacter;
  232017. else if (key == 0)
  232018. key = (juce_wchar) kp.getKeyCode();
  232019. unsigned int mods = 0;
  232020. if (kp.getModifiers().isShiftDown())
  232021. mods |= NSShiftKeyMask;
  232022. if (kp.getModifiers().isCtrlDown())
  232023. mods |= NSControlKeyMask;
  232024. if (kp.getModifiers().isAltDown())
  232025. mods |= NSAlternateKeyMask;
  232026. if (kp.getModifiers().isCommandDown())
  232027. mods |= NSCommandKeyMask;
  232028. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232029. [item setKeyEquivalentModifierMask: mods];
  232030. }
  232031. }
  232032. }
  232033. }
  232034. }
  232035. JuceMenuCallback* callback;
  232036. private:
  232037. NSMenu* createMenu (const PopupMenu menu,
  232038. const String& menuName,
  232039. const int topLevelMenuId,
  232040. const int topLevelIndex)
  232041. {
  232042. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232043. [m setAutoenablesItems: false];
  232044. [m setDelegate: callback];
  232045. PopupMenu::MenuItemIterator iter (menu);
  232046. while (iter.next())
  232047. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232048. [m update];
  232049. return m;
  232050. }
  232051. };
  232052. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232053. END_JUCE_NAMESPACE
  232054. @implementation JuceMenuCallback
  232055. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232056. {
  232057. [super init];
  232058. owner = owner_;
  232059. return self;
  232060. }
  232061. - (void) dealloc
  232062. {
  232063. [super dealloc];
  232064. }
  232065. - (void) menuItemInvoked: (id) menu
  232066. {
  232067. NSMenuItem* item = (NSMenuItem*) menu;
  232068. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232069. {
  232070. // 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
  232071. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232072. // into the focused component and let it trigger the menu item indirectly.
  232073. NSEvent* e = [NSApp currentEvent];
  232074. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232075. {
  232076. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232077. {
  232078. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232079. if (peer != 0)
  232080. {
  232081. if ([e type] == NSKeyDown)
  232082. peer->redirectKeyDown (e);
  232083. else
  232084. peer->redirectKeyUp (e);
  232085. return;
  232086. }
  232087. }
  232088. }
  232089. NSArray* info = (NSArray*) [item representedObject];
  232090. owner->invoke ((int) [item tag],
  232091. (ApplicationCommandManager*) (pointer_sized_int)
  232092. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232093. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232094. }
  232095. }
  232096. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232097. {
  232098. (void) menu;
  232099. if (JuceMainMenuHandler::instance != 0)
  232100. JuceMainMenuHandler::instance->updateMenus();
  232101. }
  232102. @end
  232103. BEGIN_JUCE_NAMESPACE
  232104. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  232105. const PopupMenu* extraItems)
  232106. {
  232107. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232108. {
  232109. PopupMenu::MenuItemIterator iter (*extraItems);
  232110. while (iter.next())
  232111. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232112. [menu addItem: [NSMenuItem separatorItem]];
  232113. }
  232114. NSMenuItem* item;
  232115. // Services...
  232116. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232117. action: nil keyEquivalent: @""];
  232118. [menu addItem: item];
  232119. [item release];
  232120. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232121. [menu setSubmenu: servicesMenu forItem: item];
  232122. [NSApp setServicesMenu: servicesMenu];
  232123. [servicesMenu release];
  232124. [menu addItem: [NSMenuItem separatorItem]];
  232125. // Hide + Show stuff...
  232126. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232127. action: @selector (hide:) keyEquivalent: @"h"];
  232128. [item setTarget: NSApp];
  232129. [menu addItem: item];
  232130. [item release];
  232131. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232132. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232133. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232134. [item setTarget: NSApp];
  232135. [menu addItem: item];
  232136. [item release];
  232137. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232138. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232139. [item setTarget: NSApp];
  232140. [menu addItem: item];
  232141. [item release];
  232142. [menu addItem: [NSMenuItem separatorItem]];
  232143. // Quit item....
  232144. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  232145. action: @selector (terminate:) keyEquivalent: @"q"];
  232146. [item setTarget: NSApp];
  232147. [menu addItem: item];
  232148. [item release];
  232149. return menu;
  232150. }
  232151. // Since our app has no NIB, this initialises a standard app menu...
  232152. static void rebuildMainMenu (const PopupMenu* extraItems)
  232153. {
  232154. // this can't be used in a plugin!
  232155. jassert (JUCEApplication::getInstance() != 0);
  232156. if (JUCEApplication::getInstance() != 0)
  232157. {
  232158. const ScopedAutoReleasePool pool;
  232159. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  232160. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  232161. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  232162. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  232163. [mainMenu setSubmenu: appMenu forItem: item];
  232164. [NSApp setMainMenu: mainMenu];
  232165. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  232166. [appMenu release];
  232167. [mainMenu release];
  232168. }
  232169. }
  232170. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  232171. const PopupMenu* extraAppleMenuItems)
  232172. {
  232173. if (getMacMainMenu() != newMenuBarModel)
  232174. {
  232175. const ScopedAutoReleasePool pool;
  232176. if (newMenuBarModel == 0)
  232177. {
  232178. delete JuceMainMenuHandler::instance;
  232179. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  232180. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  232181. extraAppleMenuItems = 0;
  232182. }
  232183. else
  232184. {
  232185. if (JuceMainMenuHandler::instance == 0)
  232186. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  232187. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  232188. }
  232189. }
  232190. rebuildMainMenu (extraAppleMenuItems);
  232191. if (newMenuBarModel != 0)
  232192. newMenuBarModel->menuItemsChanged();
  232193. }
  232194. MenuBarModel* MenuBarModel::getMacMainMenu()
  232195. {
  232196. return JuceMainMenuHandler::instance != 0
  232197. ? JuceMainMenuHandler::instance->currentModel : 0;
  232198. }
  232199. void initialiseMainMenu()
  232200. {
  232201. if (JUCEApplication::getInstance() != 0) // only needed in an app
  232202. rebuildMainMenu (0);
  232203. }
  232204. #endif
  232205. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232206. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232207. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232208. // compiled on its own).
  232209. #if JUCE_INCLUDED_FILE
  232210. #if JUCE_MAC
  232211. END_JUCE_NAMESPACE
  232212. using namespace JUCE_NAMESPACE;
  232213. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232214. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232215. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232216. #else
  232217. @interface JuceFileChooserDelegate : NSObject
  232218. #endif
  232219. {
  232220. StringArray* filters;
  232221. }
  232222. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232223. - (void) dealloc;
  232224. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232225. @end
  232226. @implementation JuceFileChooserDelegate
  232227. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232228. {
  232229. [super init];
  232230. filters = filters_;
  232231. return self;
  232232. }
  232233. - (void) dealloc
  232234. {
  232235. delete filters;
  232236. [super dealloc];
  232237. }
  232238. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232239. {
  232240. (void) sender;
  232241. const File f (nsStringToJuce (filename));
  232242. for (int i = filters->size(); --i >= 0;)
  232243. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  232244. return true;
  232245. return f.isDirectory();
  232246. }
  232247. @end
  232248. BEGIN_JUCE_NAMESPACE
  232249. void FileChooser::showPlatformDialog (Array<File>& results,
  232250. const String& title,
  232251. const File& currentFileOrDirectory,
  232252. const String& filter,
  232253. bool selectsDirectory,
  232254. bool selectsFiles,
  232255. bool isSaveDialogue,
  232256. bool warnAboutOverwritingExistingFiles,
  232257. bool selectMultipleFiles,
  232258. FilePreviewComponent* extraInfoComponent)
  232259. {
  232260. const ScopedAutoReleasePool pool;
  232261. StringArray* filters = new StringArray();
  232262. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  232263. filters->trim();
  232264. filters->removeEmptyStrings();
  232265. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  232266. [delegate autorelease];
  232267. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  232268. : [NSOpenPanel openPanel];
  232269. [panel setTitle: juceStringToNS (title)];
  232270. if (! isSaveDialogue)
  232271. {
  232272. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232273. [openPanel setCanChooseDirectories: selectsDirectory];
  232274. [openPanel setCanChooseFiles: selectsFiles];
  232275. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  232276. }
  232277. [panel setDelegate: delegate];
  232278. if (isSaveDialogue || selectsDirectory)
  232279. [panel setCanCreateDirectories: YES];
  232280. String directory, filename;
  232281. if (currentFileOrDirectory.isDirectory())
  232282. {
  232283. directory = currentFileOrDirectory.getFullPathName();
  232284. }
  232285. else
  232286. {
  232287. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  232288. filename = currentFileOrDirectory.getFileName();
  232289. }
  232290. if ([panel runModalForDirectory: juceStringToNS (directory)
  232291. file: juceStringToNS (filename)]
  232292. == NSOKButton)
  232293. {
  232294. if (isSaveDialogue)
  232295. {
  232296. results.add (File (nsStringToJuce ([panel filename])));
  232297. }
  232298. else
  232299. {
  232300. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232301. NSArray* urls = [openPanel filenames];
  232302. for (unsigned int i = 0; i < [urls count]; ++i)
  232303. {
  232304. NSString* f = [urls objectAtIndex: i];
  232305. results.add (File (nsStringToJuce (f)));
  232306. }
  232307. }
  232308. }
  232309. [panel setDelegate: nil];
  232310. }
  232311. #else
  232312. void FileChooser::showPlatformDialog (Array<File>& results,
  232313. const String& title,
  232314. const File& currentFileOrDirectory,
  232315. const String& filter,
  232316. bool selectsDirectory,
  232317. bool selectsFiles,
  232318. bool isSaveDialogue,
  232319. bool warnAboutOverwritingExistingFiles,
  232320. bool selectMultipleFiles,
  232321. FilePreviewComponent* extraInfoComponent)
  232322. {
  232323. const ScopedAutoReleasePool pool;
  232324. jassertfalse; //xxx to do
  232325. }
  232326. #endif
  232327. #endif
  232328. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  232329. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232330. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232331. // compiled on its own).
  232332. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  232333. END_JUCE_NAMESPACE
  232334. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  232335. @interface NonInterceptingQTMovieView : QTMovieView
  232336. {
  232337. }
  232338. - (id) initWithFrame: (NSRect) frame;
  232339. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  232340. - (NSView*) hitTest: (NSPoint) p;
  232341. @end
  232342. @implementation NonInterceptingQTMovieView
  232343. - (id) initWithFrame: (NSRect) frame
  232344. {
  232345. self = [super initWithFrame: frame];
  232346. [self setNextResponder: [self superview]];
  232347. return self;
  232348. }
  232349. - (void) dealloc
  232350. {
  232351. [super dealloc];
  232352. }
  232353. - (NSView*) hitTest: (NSPoint) point
  232354. {
  232355. return [self isControllerVisible] ? [super hitTest: point] : nil;
  232356. }
  232357. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  232358. {
  232359. return YES;
  232360. }
  232361. @end
  232362. BEGIN_JUCE_NAMESPACE
  232363. #define theMovie (static_cast <QTMovie*> (movie))
  232364. QuickTimeMovieComponent::QuickTimeMovieComponent()
  232365. : movie (0)
  232366. {
  232367. setOpaque (true);
  232368. setVisible (true);
  232369. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  232370. setView (view);
  232371. [view release];
  232372. }
  232373. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  232374. {
  232375. closeMovie();
  232376. setView (0);
  232377. }
  232378. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  232379. {
  232380. return true;
  232381. }
  232382. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  232383. {
  232384. // unfortunately, QTMovie objects can only be created on the main thread..
  232385. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232386. QTMovie* movie = 0;
  232387. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  232388. if (fin != 0)
  232389. {
  232390. movieFile = fin->getFile();
  232391. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  232392. error: nil];
  232393. }
  232394. else
  232395. {
  232396. MemoryBlock temp;
  232397. movieStream->readIntoMemoryBlock (temp);
  232398. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  232399. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  232400. {
  232401. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  232402. length: temp.getSize()]
  232403. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  232404. MIMEType: @""]
  232405. error: nil];
  232406. if (movie != 0)
  232407. break;
  232408. }
  232409. }
  232410. return movie;
  232411. }
  232412. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  232413. const bool isControllerVisible_)
  232414. {
  232415. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  232416. }
  232417. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  232418. const bool controllerVisible_)
  232419. {
  232420. closeMovie();
  232421. if (getPeer() == 0)
  232422. {
  232423. // To open a movie, this component must be visible inside a functioning window, so that
  232424. // the QT control can be assigned to the window.
  232425. jassertfalse;
  232426. return false;
  232427. }
  232428. movie = openMovieFromStream (movieStream, movieFile);
  232429. [theMovie retain];
  232430. QTMovieView* view = (QTMovieView*) getView();
  232431. [view setMovie: theMovie];
  232432. [view setControllerVisible: controllerVisible_];
  232433. setLooping (looping);
  232434. return movie != nil;
  232435. }
  232436. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  232437. const bool isControllerVisible_)
  232438. {
  232439. // unfortunately, QTMovie objects can only be created on the main thread..
  232440. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232441. closeMovie();
  232442. if (getPeer() == 0)
  232443. {
  232444. // To open a movie, this component must be visible inside a functioning window, so that
  232445. // the QT control can be assigned to the window.
  232446. jassertfalse;
  232447. return false;
  232448. }
  232449. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  232450. NSError* err;
  232451. if ([QTMovie canInitWithURL: url])
  232452. movie = [QTMovie movieWithURL: url error: &err];
  232453. [theMovie retain];
  232454. QTMovieView* view = (QTMovieView*) getView();
  232455. [view setMovie: theMovie];
  232456. [view setControllerVisible: controllerVisible];
  232457. setLooping (looping);
  232458. return movie != nil;
  232459. }
  232460. void QuickTimeMovieComponent::closeMovie()
  232461. {
  232462. stop();
  232463. QTMovieView* view = (QTMovieView*) getView();
  232464. [view setMovie: nil];
  232465. [theMovie release];
  232466. movie = 0;
  232467. movieFile = File::nonexistent;
  232468. }
  232469. bool QuickTimeMovieComponent::isMovieOpen() const
  232470. {
  232471. return movie != nil;
  232472. }
  232473. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  232474. {
  232475. return movieFile;
  232476. }
  232477. void QuickTimeMovieComponent::play()
  232478. {
  232479. [theMovie play];
  232480. }
  232481. void QuickTimeMovieComponent::stop()
  232482. {
  232483. [theMovie stop];
  232484. }
  232485. bool QuickTimeMovieComponent::isPlaying() const
  232486. {
  232487. return movie != 0 && [theMovie rate] != 0;
  232488. }
  232489. void QuickTimeMovieComponent::setPosition (const double seconds)
  232490. {
  232491. if (movie != 0)
  232492. {
  232493. QTTime t;
  232494. t.timeValue = (uint64) (100000.0 * seconds);
  232495. t.timeScale = 100000;
  232496. t.flags = 0;
  232497. [theMovie setCurrentTime: t];
  232498. }
  232499. }
  232500. double QuickTimeMovieComponent::getPosition() const
  232501. {
  232502. if (movie == 0)
  232503. return 0.0;
  232504. QTTime t = [theMovie currentTime];
  232505. return t.timeValue / (double) t.timeScale;
  232506. }
  232507. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  232508. {
  232509. [theMovie setRate: newSpeed];
  232510. }
  232511. double QuickTimeMovieComponent::getMovieDuration() const
  232512. {
  232513. if (movie == 0)
  232514. return 0.0;
  232515. QTTime t = [theMovie duration];
  232516. return t.timeValue / (double) t.timeScale;
  232517. }
  232518. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  232519. {
  232520. looping = shouldLoop;
  232521. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  232522. forKey: QTMovieLoopsAttribute];
  232523. }
  232524. bool QuickTimeMovieComponent::isLooping() const
  232525. {
  232526. return looping;
  232527. }
  232528. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  232529. {
  232530. [theMovie setVolume: newVolume];
  232531. }
  232532. float QuickTimeMovieComponent::getMovieVolume() const
  232533. {
  232534. return movie != 0 ? [theMovie volume] : 0.0f;
  232535. }
  232536. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  232537. {
  232538. width = 0;
  232539. height = 0;
  232540. if (movie != 0)
  232541. {
  232542. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  232543. width = (int) s.width;
  232544. height = (int) s.height;
  232545. }
  232546. }
  232547. void QuickTimeMovieComponent::paint (Graphics& g)
  232548. {
  232549. if (movie == 0)
  232550. g.fillAll (Colours::black);
  232551. }
  232552. bool QuickTimeMovieComponent::isControllerVisible() const
  232553. {
  232554. return controllerVisible;
  232555. }
  232556. void QuickTimeMovieComponent::goToStart()
  232557. {
  232558. setPosition (0.0);
  232559. }
  232560. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  232561. const RectanglePlacement& placement)
  232562. {
  232563. int normalWidth, normalHeight;
  232564. getMovieNormalSize (normalWidth, normalHeight);
  232565. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  232566. {
  232567. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  232568. placement.applyTo (x, y, w, h,
  232569. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  232570. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  232571. if (w > 0 && h > 0)
  232572. {
  232573. setBounds (roundToInt (x), roundToInt (y),
  232574. roundToInt (w), roundToInt (h));
  232575. }
  232576. }
  232577. else
  232578. {
  232579. setBounds (spaceToFitWithin);
  232580. }
  232581. }
  232582. #if ! (JUCE_MAC && JUCE_64BIT)
  232583. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  232584. {
  232585. if (movieStream == 0)
  232586. return false;
  232587. File file;
  232588. QTMovie* movie = openMovieFromStream (movieStream, file);
  232589. if (movie != nil)
  232590. result = [movie quickTimeMovie];
  232591. return movie != nil;
  232592. }
  232593. #endif
  232594. #endif
  232595. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232596. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  232597. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232598. // compiled on its own).
  232599. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  232600. const int kilobytesPerSecond1x = 176;
  232601. END_JUCE_NAMESPACE
  232602. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  232603. @interface OpenDiskDevice : NSObject
  232604. {
  232605. @public
  232606. DRDevice* device;
  232607. NSMutableArray* tracks;
  232608. bool underrunProtection;
  232609. }
  232610. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  232611. - (void) dealloc;
  232612. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  232613. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232614. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  232615. @end
  232616. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  232617. @interface AudioTrackProducer : NSObject
  232618. {
  232619. JUCE_NAMESPACE::AudioSource* source;
  232620. int readPosition, lengthInFrames;
  232621. }
  232622. - (AudioTrackProducer*) init: (int) lengthInFrames;
  232623. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  232624. - (void) dealloc;
  232625. - (void) setupTrackProperties: (DRTrack*) track;
  232626. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  232627. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  232628. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  232629. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  232630. toMedia:(NSDictionary*)mediaInfo;
  232631. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  232632. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  232633. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232634. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232635. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232636. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232637. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232638. ioFlags:(uint32_t*)flags;
  232639. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  232640. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232641. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232642. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232643. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232644. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232645. ioFlags:(uint32_t*)flags;
  232646. @end
  232647. @implementation OpenDiskDevice
  232648. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  232649. {
  232650. [super init];
  232651. device = device_;
  232652. tracks = [[NSMutableArray alloc] init];
  232653. underrunProtection = true;
  232654. return self;
  232655. }
  232656. - (void) dealloc
  232657. {
  232658. [tracks release];
  232659. [super dealloc];
  232660. }
  232661. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  232662. {
  232663. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  232664. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  232665. [p setupTrackProperties: t];
  232666. [tracks addObject: t];
  232667. [t release];
  232668. [p release];
  232669. }
  232670. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232671. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  232672. {
  232673. DRBurn* burn = [DRBurn burnForDevice: device];
  232674. if (! [device acquireExclusiveAccess])
  232675. {
  232676. *error = "Couldn't open or write to the CD device";
  232677. return;
  232678. }
  232679. [device acquireMediaReservation];
  232680. NSMutableDictionary* d = [[burn properties] mutableCopy];
  232681. [d autorelease];
  232682. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  232683. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  232684. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  232685. if (burnSpeed > 0)
  232686. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  232687. if (! underrunProtection)
  232688. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  232689. [burn setProperties: d];
  232690. [burn writeLayout: tracks];
  232691. for (;;)
  232692. {
  232693. JUCE_NAMESPACE::Thread::sleep (300);
  232694. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  232695. if (listener != 0 && listener->audioCDBurnProgress (progress))
  232696. {
  232697. [burn abort];
  232698. *error = "User cancelled the write operation";
  232699. break;
  232700. }
  232701. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  232702. {
  232703. *error = "Write operation failed";
  232704. break;
  232705. }
  232706. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  232707. {
  232708. break;
  232709. }
  232710. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  232711. objectForKey: DRErrorStatusErrorStringKey];
  232712. if ([err length] > 0)
  232713. {
  232714. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  232715. break;
  232716. }
  232717. }
  232718. [device releaseMediaReservation];
  232719. [device releaseExclusiveAccess];
  232720. }
  232721. @end
  232722. @implementation AudioTrackProducer
  232723. - (AudioTrackProducer*) init: (int) lengthInFrames_
  232724. {
  232725. lengthInFrames = lengthInFrames_;
  232726. readPosition = 0;
  232727. return self;
  232728. }
  232729. - (void) setupTrackProperties: (DRTrack*) track
  232730. {
  232731. NSMutableDictionary* p = [[track properties] mutableCopy];
  232732. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  232733. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  232734. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  232735. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  232736. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  232737. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  232738. [track setProperties: p];
  232739. [p release];
  232740. }
  232741. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  232742. {
  232743. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  232744. if (s != nil)
  232745. s->source = source_;
  232746. return s;
  232747. }
  232748. - (void) dealloc
  232749. {
  232750. if (source != 0)
  232751. {
  232752. source->releaseResources();
  232753. delete source;
  232754. }
  232755. [super dealloc];
  232756. }
  232757. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  232758. {
  232759. }
  232760. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  232761. {
  232762. return true;
  232763. }
  232764. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  232765. {
  232766. return lengthInFrames;
  232767. }
  232768. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  232769. toMedia: (NSDictionary*) mediaInfo
  232770. {
  232771. if (source != 0)
  232772. source->prepareToPlay (44100 / 75, 44100);
  232773. readPosition = 0;
  232774. return true;
  232775. }
  232776. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  232777. {
  232778. if (source != 0)
  232779. source->prepareToPlay (44100 / 75, 44100);
  232780. return true;
  232781. }
  232782. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  232783. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232784. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232785. {
  232786. if (source != 0)
  232787. {
  232788. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  232789. if (numSamples > 0)
  232790. {
  232791. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  232792. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  232793. info.buffer = &tempBuffer;
  232794. info.startSample = 0;
  232795. info.numSamples = numSamples;
  232796. source->getNextAudioBlock (info);
  232797. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  232798. buffer, numSamples, 4);
  232799. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  232800. buffer + 2, numSamples, 4);
  232801. readPosition += numSamples;
  232802. }
  232803. return numSamples * 4;
  232804. }
  232805. return 0;
  232806. }
  232807. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  232808. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  232809. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  232810. ioFlags: (uint32_t*) flags
  232811. {
  232812. zeromem (buffer, bufferLength);
  232813. return bufferLength;
  232814. }
  232815. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  232816. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232817. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232818. {
  232819. return true;
  232820. }
  232821. @end
  232822. BEGIN_JUCE_NAMESPACE
  232823. class AudioCDBurner::Pimpl : public Timer
  232824. {
  232825. public:
  232826. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  232827. : device (0), owner (owner_)
  232828. {
  232829. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  232830. if (dev != 0)
  232831. {
  232832. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  232833. lastState = getDiskState();
  232834. startTimer (1000);
  232835. }
  232836. }
  232837. ~Pimpl()
  232838. {
  232839. stopTimer();
  232840. [device release];
  232841. }
  232842. void timerCallback()
  232843. {
  232844. const DiskState state = getDiskState();
  232845. if (state != lastState)
  232846. {
  232847. lastState = state;
  232848. owner.sendChangeMessage (&owner);
  232849. }
  232850. }
  232851. DiskState getDiskState() const
  232852. {
  232853. if ([device->device isValid])
  232854. {
  232855. NSDictionary* status = [device->device status];
  232856. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  232857. if ([state isEqualTo: DRDeviceMediaStateNone])
  232858. {
  232859. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  232860. return trayOpen;
  232861. return noDisc;
  232862. }
  232863. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  232864. {
  232865. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  232866. return writableDiskPresent;
  232867. else
  232868. return readOnlyDiskPresent;
  232869. }
  232870. }
  232871. return unknown;
  232872. }
  232873. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  232874. const Array<int> getAvailableWriteSpeeds() const
  232875. {
  232876. Array<int> results;
  232877. if ([device->device isValid])
  232878. {
  232879. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  232880. for (unsigned int i = 0; i < [speeds count]; ++i)
  232881. {
  232882. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  232883. results.add (kbPerSec / kilobytesPerSecond1x);
  232884. }
  232885. }
  232886. return results;
  232887. }
  232888. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  232889. {
  232890. if ([device->device isValid])
  232891. {
  232892. device->underrunProtection = shouldBeEnabled;
  232893. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  232894. }
  232895. return false;
  232896. }
  232897. int getNumAvailableAudioBlocks() const
  232898. {
  232899. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  232900. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  232901. }
  232902. OpenDiskDevice* device;
  232903. private:
  232904. DiskState lastState;
  232905. AudioCDBurner& owner;
  232906. };
  232907. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  232908. {
  232909. pimpl = new Pimpl (*this, deviceIndex);
  232910. }
  232911. AudioCDBurner::~AudioCDBurner()
  232912. {
  232913. }
  232914. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  232915. {
  232916. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  232917. if (b->pimpl->device == 0)
  232918. b = 0;
  232919. return b.release();
  232920. }
  232921. static NSArray* findDiskBurnerDevices()
  232922. {
  232923. NSMutableArray* results = [NSMutableArray array];
  232924. NSArray* devs = [DRDevice devices];
  232925. if (devs != 0)
  232926. {
  232927. int num = [devs count];
  232928. int i;
  232929. for (i = 0; i < num; ++i)
  232930. {
  232931. NSDictionary* dic = [[devs objectAtIndex: i] info];
  232932. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  232933. if (name != nil)
  232934. [results addObject: name];
  232935. }
  232936. }
  232937. return results;
  232938. }
  232939. const StringArray AudioCDBurner::findAvailableDevices()
  232940. {
  232941. NSArray* names = findDiskBurnerDevices();
  232942. StringArray s;
  232943. for (unsigned int i = 0; i < [names count]; ++i)
  232944. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  232945. return s;
  232946. }
  232947. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  232948. {
  232949. return pimpl->getDiskState();
  232950. }
  232951. bool AudioCDBurner::isDiskPresent() const
  232952. {
  232953. return getDiskState() == writableDiskPresent;
  232954. }
  232955. bool AudioCDBurner::openTray()
  232956. {
  232957. return pimpl->openTray();
  232958. }
  232959. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  232960. {
  232961. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  232962. DiskState oldState = getDiskState();
  232963. DiskState newState = oldState;
  232964. while (newState == oldState && Time::currentTimeMillis() < timeout)
  232965. {
  232966. newState = getDiskState();
  232967. Thread::sleep (100);
  232968. }
  232969. return newState;
  232970. }
  232971. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  232972. {
  232973. return pimpl->getAvailableWriteSpeeds();
  232974. }
  232975. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  232976. {
  232977. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  232978. }
  232979. int AudioCDBurner::getNumAvailableAudioBlocks() const
  232980. {
  232981. return pimpl->getNumAvailableAudioBlocks();
  232982. }
  232983. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  232984. {
  232985. if ([pimpl->device->device isValid])
  232986. {
  232987. [pimpl->device addSourceTrack: source numSamples: numSamps];
  232988. return true;
  232989. }
  232990. return false;
  232991. }
  232992. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  232993. bool ejectDiscAfterwards,
  232994. bool performFakeBurnForTesting,
  232995. int writeSpeed)
  232996. {
  232997. String error ("Couldn't open or write to the CD device");
  232998. if ([pimpl->device->device isValid])
  232999. {
  233000. error = String::empty;
  233001. [pimpl->device burn: listener
  233002. errorString: &error
  233003. ejectAfterwards: ejectDiscAfterwards
  233004. isFake: performFakeBurnForTesting
  233005. speed: writeSpeed];
  233006. }
  233007. return error;
  233008. }
  233009. #endif
  233010. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233011. void AudioCDReader::ejectDisk()
  233012. {
  233013. const ScopedAutoReleasePool p;
  233014. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233015. }
  233016. #endif
  233017. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233018. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233019. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233020. // compiled on its own).
  233021. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233022. static void juce_findCDs (Array<File>& cds)
  233023. {
  233024. File volumes ("/Volumes");
  233025. volumes.findChildFiles (cds, File::findDirectories, false);
  233026. for (int i = cds.size(); --i >= 0;)
  233027. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233028. cds.remove (i);
  233029. }
  233030. const StringArray AudioCDReader::getAvailableCDNames()
  233031. {
  233032. Array<File> cds;
  233033. juce_findCDs (cds);
  233034. StringArray names;
  233035. for (int i = 0; i < cds.size(); ++i)
  233036. names.add (cds.getReference(i).getFileName());
  233037. return names;
  233038. }
  233039. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233040. {
  233041. Array<File> cds;
  233042. juce_findCDs (cds);
  233043. if (cds[index].exists())
  233044. return new AudioCDReader (cds[index]);
  233045. return 0;
  233046. }
  233047. AudioCDReader::AudioCDReader (const File& volume)
  233048. : AudioFormatReader (0, "CD Audio"),
  233049. volumeDir (volume),
  233050. currentReaderTrack (-1),
  233051. reader (0)
  233052. {
  233053. sampleRate = 44100.0;
  233054. bitsPerSample = 16;
  233055. numChannels = 2;
  233056. usesFloatingPointData = false;
  233057. refreshTrackLengths();
  233058. }
  233059. AudioCDReader::~AudioCDReader()
  233060. {
  233061. }
  233062. static int juce_getCDTrackNumber (const File& file)
  233063. {
  233064. return file.getFileName()
  233065. .initialSectionContainingOnly ("0123456789")
  233066. .getIntValue();
  233067. }
  233068. int AudioCDReader::compareElements (const File& first, const File& second)
  233069. {
  233070. const int firstTrack = juce_getCDTrackNumber (first);
  233071. const int secondTrack = juce_getCDTrackNumber (second);
  233072. jassert (firstTrack > 0 && secondTrack > 0);
  233073. return firstTrack - secondTrack;
  233074. }
  233075. void AudioCDReader::refreshTrackLengths()
  233076. {
  233077. tracks.clear();
  233078. trackStartSamples.clear();
  233079. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233080. tracks.sort (*this);
  233081. AiffAudioFormat format;
  233082. int sample = 0;
  233083. for (int i = 0; i < tracks.size(); ++i)
  233084. {
  233085. trackStartSamples.add (sample);
  233086. FileInputStream* const in = tracks.getReference(i).createInputStream();
  233087. if (in != 0)
  233088. {
  233089. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  233090. if (r != 0)
  233091. sample += (int) r->lengthInSamples;
  233092. }
  233093. }
  233094. trackStartSamples.add (sample);
  233095. lengthInSamples = sample;
  233096. }
  233097. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  233098. int64 startSampleInFile, int numSamples)
  233099. {
  233100. while (numSamples > 0)
  233101. {
  233102. int track = -1;
  233103. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  233104. {
  233105. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  233106. {
  233107. track = i;
  233108. break;
  233109. }
  233110. }
  233111. if (track < 0)
  233112. return false;
  233113. if (track != currentReaderTrack)
  233114. {
  233115. reader = 0;
  233116. FileInputStream* const in = tracks [track].createInputStream();
  233117. if (in != 0)
  233118. {
  233119. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  233120. AiffAudioFormat format;
  233121. reader = format.createReaderFor (bin, true);
  233122. if (reader == 0)
  233123. currentReaderTrack = -1;
  233124. else
  233125. currentReaderTrack = track;
  233126. }
  233127. }
  233128. if (reader == 0)
  233129. return false;
  233130. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  233131. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  233132. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  233133. numSamples -= numAvailable;
  233134. startSampleInFile += numAvailable;
  233135. }
  233136. return true;
  233137. }
  233138. bool AudioCDReader::isCDStillPresent() const
  233139. {
  233140. return volumeDir.exists();
  233141. }
  233142. int AudioCDReader::getNumTracks() const
  233143. {
  233144. return tracks.size();
  233145. }
  233146. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  233147. {
  233148. return trackStartSamples [trackNum];
  233149. }
  233150. bool AudioCDReader::isTrackAudio (int trackNum) const
  233151. {
  233152. return tracks [trackNum] != File::nonexistent;
  233153. }
  233154. void AudioCDReader::enableIndexScanning (bool b)
  233155. {
  233156. // any way to do this on a Mac??
  233157. }
  233158. int AudioCDReader::getLastIndex() const
  233159. {
  233160. return 0;
  233161. }
  233162. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  233163. {
  233164. return Array <int>();
  233165. }
  233166. int AudioCDReader::getCDDBId()
  233167. {
  233168. return 0; //xxx
  233169. }
  233170. #endif
  233171. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  233172. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  233173. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233174. // compiled on its own).
  233175. #if JUCE_INCLUDED_FILE
  233176. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  233177. for example having more than one juce plugin loaded into a host, then when a
  233178. method is called, the actual code that runs might actually be in a different module
  233179. than the one you expect... So any calls to library functions or statics that are
  233180. made inside obj-c methods will probably end up getting executed in a different DLL's
  233181. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  233182. To work around this insanity, I'm only allowing obj-c methods to make calls to
  233183. virtual methods of an object that's known to live inside the right module's space.
  233184. */
  233185. class AppDelegateRedirector
  233186. {
  233187. public:
  233188. AppDelegateRedirector()
  233189. {
  233190. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  233191. runLoop = CFRunLoopGetMain();
  233192. #else
  233193. runLoop = CFRunLoopGetCurrent();
  233194. #endif
  233195. CFRunLoopSourceContext sourceContext;
  233196. zerostruct (sourceContext);
  233197. sourceContext.info = this;
  233198. sourceContext.perform = runLoopSourceCallback;
  233199. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  233200. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  233201. }
  233202. virtual ~AppDelegateRedirector()
  233203. {
  233204. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  233205. CFRunLoopSourceInvalidate (runLoopSource);
  233206. CFRelease (runLoopSource);
  233207. }
  233208. virtual NSApplicationTerminateReply shouldTerminate()
  233209. {
  233210. if (JUCEApplication::getInstance() != 0)
  233211. {
  233212. JUCEApplication::getInstance()->systemRequestedQuit();
  233213. return NSTerminateCancel;
  233214. }
  233215. return NSTerminateNow;
  233216. }
  233217. virtual BOOL openFile (const NSString* filename)
  233218. {
  233219. if (JUCEApplication::getInstance() != 0)
  233220. {
  233221. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  233222. return YES;
  233223. }
  233224. return NO;
  233225. }
  233226. virtual void openFiles (NSArray* filenames)
  233227. {
  233228. StringArray files;
  233229. for (unsigned int i = 0; i < [filenames count]; ++i)
  233230. {
  233231. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  233232. if (filename.containsChar (' '))
  233233. filename = filename.quoted('"');
  233234. files.add (filename);
  233235. }
  233236. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  233237. {
  233238. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  233239. }
  233240. }
  233241. virtual void focusChanged()
  233242. {
  233243. juce_HandleProcessFocusChange();
  233244. }
  233245. struct CallbackMessagePayload
  233246. {
  233247. MessageCallbackFunction* function;
  233248. void* parameter;
  233249. void* volatile result;
  233250. bool volatile hasBeenExecuted;
  233251. };
  233252. virtual void performCallback (CallbackMessagePayload* pl)
  233253. {
  233254. pl->result = (*pl->function) (pl->parameter);
  233255. pl->hasBeenExecuted = true;
  233256. }
  233257. virtual void deleteSelf()
  233258. {
  233259. delete this;
  233260. }
  233261. void postMessage (Message* const m)
  233262. {
  233263. messages.add (m);
  233264. CFRunLoopSourceSignal (runLoopSource);
  233265. CFRunLoopWakeUp (runLoop);
  233266. }
  233267. private:
  233268. CFRunLoopRef runLoop;
  233269. CFRunLoopSourceRef runLoopSource;
  233270. OwnedArray <Message, CriticalSection> messages;
  233271. void runLoopCallback()
  233272. {
  233273. int numDispatched = 0;
  233274. do
  233275. {
  233276. Message* const nextMessage = messages.removeAndReturn (0);
  233277. if (nextMessage == 0)
  233278. return;
  233279. const ScopedAutoReleasePool pool;
  233280. MessageManager::getInstance()->deliverMessage (nextMessage);
  233281. } while (++numDispatched <= 4);
  233282. CFRunLoopSourceSignal (runLoopSource);
  233283. CFRunLoopWakeUp (runLoop);
  233284. }
  233285. static void runLoopSourceCallback (void* info)
  233286. {
  233287. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  233288. }
  233289. };
  233290. END_JUCE_NAMESPACE
  233291. using namespace JUCE_NAMESPACE;
  233292. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  233293. @interface JuceAppDelegate : NSObject
  233294. {
  233295. @private
  233296. id oldDelegate;
  233297. @public
  233298. AppDelegateRedirector* redirector;
  233299. }
  233300. - (JuceAppDelegate*) init;
  233301. - (void) dealloc;
  233302. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  233303. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  233304. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  233305. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  233306. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  233307. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  233308. - (void) performCallback: (id) info;
  233309. - (void) dummyMethod;
  233310. @end
  233311. @implementation JuceAppDelegate
  233312. - (JuceAppDelegate*) init
  233313. {
  233314. [super init];
  233315. redirector = new AppDelegateRedirector();
  233316. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  233317. if (JUCEApplication::getInstance() != 0)
  233318. {
  233319. oldDelegate = [NSApp delegate];
  233320. [NSApp setDelegate: self];
  233321. }
  233322. else
  233323. {
  233324. oldDelegate = 0;
  233325. [center addObserver: self selector: @selector (applicationDidResignActive:)
  233326. name: NSApplicationDidResignActiveNotification object: NSApp];
  233327. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  233328. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  233329. [center addObserver: self selector: @selector (applicationWillUnhide:)
  233330. name: NSApplicationWillUnhideNotification object: NSApp];
  233331. }
  233332. return self;
  233333. }
  233334. - (void) dealloc
  233335. {
  233336. if (oldDelegate != 0)
  233337. [NSApp setDelegate: oldDelegate];
  233338. redirector->deleteSelf();
  233339. [super dealloc];
  233340. }
  233341. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  233342. {
  233343. (void) app;
  233344. return redirector->shouldTerminate();
  233345. }
  233346. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  233347. {
  233348. (void) app;
  233349. return redirector->openFile (filename);
  233350. }
  233351. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  233352. {
  233353. (void) sender;
  233354. return redirector->openFiles (filenames);
  233355. }
  233356. - (void) applicationDidBecomeActive: (NSNotification*) notification
  233357. {
  233358. (void) notification;
  233359. redirector->focusChanged();
  233360. }
  233361. - (void) applicationDidResignActive: (NSNotification*) notification
  233362. {
  233363. (void) notification;
  233364. redirector->focusChanged();
  233365. }
  233366. - (void) applicationWillUnhide: (NSNotification*) notification
  233367. {
  233368. (void) notification;
  233369. redirector->focusChanged();
  233370. }
  233371. - (void) performCallback: (id) info
  233372. {
  233373. if ([info isKindOfClass: [NSData class]])
  233374. {
  233375. AppDelegateRedirector::CallbackMessagePayload* pl
  233376. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  233377. if (pl != 0)
  233378. redirector->performCallback (pl);
  233379. }
  233380. else
  233381. {
  233382. jassertfalse; // should never get here!
  233383. }
  233384. }
  233385. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  233386. @end
  233387. BEGIN_JUCE_NAMESPACE
  233388. static JuceAppDelegate* juceAppDelegate = 0;
  233389. void MessageManager::runDispatchLoop()
  233390. {
  233391. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  233392. {
  233393. const ScopedAutoReleasePool pool;
  233394. // must only be called by the message thread!
  233395. jassert (isThisTheMessageThread());
  233396. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  233397. @try
  233398. {
  233399. [NSApp run];
  233400. }
  233401. @catch (NSException* e)
  233402. {
  233403. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  233404. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  233405. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  233406. }
  233407. @finally
  233408. {
  233409. }
  233410. #else
  233411. [NSApp run];
  233412. #endif
  233413. }
  233414. }
  233415. void MessageManager::stopDispatchLoop()
  233416. {
  233417. quitMessagePosted = true;
  233418. [NSApp stop: nil];
  233419. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  233420. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  233421. }
  233422. static bool isEventBlockedByModalComps (NSEvent* e)
  233423. {
  233424. if (Component::getNumCurrentlyModalComponents() == 0)
  233425. return false;
  233426. NSWindow* const w = [e window];
  233427. if (w == 0 || [w worksWhenModal])
  233428. return false;
  233429. bool isKey = false, isInputAttempt = false;
  233430. switch ([e type])
  233431. {
  233432. case NSKeyDown:
  233433. case NSKeyUp:
  233434. isKey = isInputAttempt = true;
  233435. break;
  233436. case NSLeftMouseDown:
  233437. case NSRightMouseDown:
  233438. case NSOtherMouseDown:
  233439. isInputAttempt = true;
  233440. break;
  233441. case NSLeftMouseDragged:
  233442. case NSRightMouseDragged:
  233443. case NSLeftMouseUp:
  233444. case NSRightMouseUp:
  233445. case NSOtherMouseUp:
  233446. case NSOtherMouseDragged:
  233447. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  233448. return false;
  233449. break;
  233450. case NSMouseMoved:
  233451. case NSMouseEntered:
  233452. case NSMouseExited:
  233453. case NSCursorUpdate:
  233454. case NSScrollWheel:
  233455. case NSTabletPoint:
  233456. case NSTabletProximity:
  233457. break;
  233458. default:
  233459. return false;
  233460. }
  233461. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  233462. {
  233463. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  233464. NSView* const compView = (NSView*) peer->getNativeHandle();
  233465. if ([compView window] == w)
  233466. {
  233467. if (isKey)
  233468. {
  233469. if (compView == [w firstResponder])
  233470. return false;
  233471. }
  233472. else
  233473. {
  233474. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  233475. [compView bounds]))
  233476. return false;
  233477. }
  233478. }
  233479. }
  233480. if (isInputAttempt)
  233481. {
  233482. if (! [NSApp isActive])
  233483. [NSApp activateIgnoringOtherApps: YES];
  233484. Component* const modal = Component::getCurrentlyModalComponent (0);
  233485. if (modal != 0)
  233486. modal->inputAttemptWhenModal();
  233487. }
  233488. return true;
  233489. }
  233490. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  233491. {
  233492. jassert (isThisTheMessageThread()); // must only be called by the message thread
  233493. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  233494. while (! quitMessagePosted)
  233495. {
  233496. const ScopedAutoReleasePool pool;
  233497. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  233498. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  233499. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  233500. inMode: NSDefaultRunLoopMode
  233501. dequeue: YES];
  233502. if (e != 0 && ! isEventBlockedByModalComps (e))
  233503. [NSApp sendEvent: e];
  233504. if (Time::getMillisecondCounter() >= endTime)
  233505. break;
  233506. }
  233507. return ! quitMessagePosted;
  233508. }
  233509. void MessageManager::doPlatformSpecificInitialisation()
  233510. {
  233511. if (juceAppDelegate == 0)
  233512. juceAppDelegate = [[JuceAppDelegate alloc] init];
  233513. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  233514. // correctly (needed prior to 10.5)
  233515. if (! [NSThread isMultiThreaded])
  233516. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  233517. toTarget: juceAppDelegate
  233518. withObject: nil];
  233519. initialiseMainMenu();
  233520. }
  233521. void MessageManager::doPlatformSpecificShutdown()
  233522. {
  233523. if (juceAppDelegate != 0)
  233524. {
  233525. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  233526. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  233527. [juceAppDelegate release];
  233528. juceAppDelegate = 0;
  233529. }
  233530. }
  233531. bool juce_postMessageToSystemQueue (Message* message)
  233532. {
  233533. juceAppDelegate->redirector->postMessage (message);
  233534. return true;
  233535. }
  233536. void MessageManager::broadcastMessage (const String& value) throw()
  233537. {
  233538. }
  233539. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  233540. void* data)
  233541. {
  233542. if (isThisTheMessageThread())
  233543. {
  233544. return (*callback) (data);
  233545. }
  233546. else
  233547. {
  233548. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  233549. // deadlock because the message manager is blocked from running, so can never
  233550. // call your function..
  233551. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  233552. const ScopedAutoReleasePool pool;
  233553. AppDelegateRedirector::CallbackMessagePayload cmp;
  233554. cmp.function = callback;
  233555. cmp.parameter = data;
  233556. cmp.result = 0;
  233557. cmp.hasBeenExecuted = false;
  233558. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  233559. withObject: [NSData dataWithBytesNoCopy: &cmp
  233560. length: sizeof (cmp)
  233561. freeWhenDone: NO]
  233562. waitUntilDone: YES];
  233563. return cmp.result;
  233564. }
  233565. }
  233566. #endif
  233567. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  233568. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233569. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233570. // compiled on its own).
  233571. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  233572. #if JUCE_MAC
  233573. END_JUCE_NAMESPACE
  233574. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  233575. @interface DownloadClickDetector : NSObject
  233576. {
  233577. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  233578. }
  233579. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  233580. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233581. request: (NSURLRequest*) request
  233582. frame: (WebFrame*) frame
  233583. decisionListener: (id<WebPolicyDecisionListener>) listener;
  233584. @end
  233585. @implementation DownloadClickDetector
  233586. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  233587. {
  233588. [super init];
  233589. ownerComponent = ownerComponent_;
  233590. return self;
  233591. }
  233592. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233593. request: (NSURLRequest*) request
  233594. frame: (WebFrame*) frame
  233595. decisionListener: (id <WebPolicyDecisionListener>) listener
  233596. {
  233597. (void) sender;
  233598. (void) request;
  233599. (void) frame;
  233600. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  233601. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  233602. [listener use];
  233603. else
  233604. [listener ignore];
  233605. }
  233606. @end
  233607. BEGIN_JUCE_NAMESPACE
  233608. class WebBrowserComponentInternal : public NSViewComponent
  233609. {
  233610. public:
  233611. WebBrowserComponentInternal (WebBrowserComponent* owner)
  233612. {
  233613. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233614. frameName: @""
  233615. groupName: @""];
  233616. setView (webView);
  233617. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  233618. [webView setPolicyDelegate: clickListener];
  233619. }
  233620. ~WebBrowserComponentInternal()
  233621. {
  233622. [webView setPolicyDelegate: nil];
  233623. [clickListener release];
  233624. setView (0);
  233625. }
  233626. void goToURL (const String& url,
  233627. const StringArray* headers,
  233628. const MemoryBlock* postData)
  233629. {
  233630. NSMutableURLRequest* r
  233631. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  233632. cachePolicy: NSURLRequestUseProtocolCachePolicy
  233633. timeoutInterval: 30.0];
  233634. if (postData != 0 && postData->getSize() > 0)
  233635. {
  233636. [r setHTTPMethod: @"POST"];
  233637. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  233638. length: postData->getSize()]];
  233639. }
  233640. if (headers != 0)
  233641. {
  233642. for (int i = 0; i < headers->size(); ++i)
  233643. {
  233644. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  233645. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  233646. [r setValue: juceStringToNS (headerValue)
  233647. forHTTPHeaderField: juceStringToNS (headerName)];
  233648. }
  233649. }
  233650. stop();
  233651. [[webView mainFrame] loadRequest: r];
  233652. }
  233653. void goBack()
  233654. {
  233655. [webView goBack];
  233656. }
  233657. void goForward()
  233658. {
  233659. [webView goForward];
  233660. }
  233661. void stop()
  233662. {
  233663. [webView stopLoading: nil];
  233664. }
  233665. void refresh()
  233666. {
  233667. [webView reload: nil];
  233668. }
  233669. private:
  233670. WebView* webView;
  233671. DownloadClickDetector* clickListener;
  233672. };
  233673. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233674. : browser (0),
  233675. blankPageShown (false),
  233676. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  233677. {
  233678. setOpaque (true);
  233679. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  233680. }
  233681. WebBrowserComponent::~WebBrowserComponent()
  233682. {
  233683. deleteAndZero (browser);
  233684. }
  233685. void WebBrowserComponent::goToURL (const String& url,
  233686. const StringArray* headers,
  233687. const MemoryBlock* postData)
  233688. {
  233689. lastURL = url;
  233690. lastHeaders.clear();
  233691. if (headers != 0)
  233692. lastHeaders = *headers;
  233693. lastPostData.setSize (0);
  233694. if (postData != 0)
  233695. lastPostData = *postData;
  233696. blankPageShown = false;
  233697. browser->goToURL (url, headers, postData);
  233698. }
  233699. void WebBrowserComponent::stop()
  233700. {
  233701. browser->stop();
  233702. }
  233703. void WebBrowserComponent::goBack()
  233704. {
  233705. lastURL = String::empty;
  233706. blankPageShown = false;
  233707. browser->goBack();
  233708. }
  233709. void WebBrowserComponent::goForward()
  233710. {
  233711. lastURL = String::empty;
  233712. browser->goForward();
  233713. }
  233714. void WebBrowserComponent::refresh()
  233715. {
  233716. browser->refresh();
  233717. }
  233718. void WebBrowserComponent::paint (Graphics&)
  233719. {
  233720. }
  233721. void WebBrowserComponent::checkWindowAssociation()
  233722. {
  233723. if (isShowing())
  233724. {
  233725. if (blankPageShown)
  233726. goBack();
  233727. }
  233728. else
  233729. {
  233730. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  233731. {
  233732. // when the component becomes invisible, some stuff like flash
  233733. // carries on playing audio, so we need to force it onto a blank
  233734. // page to avoid this, (and send it back when it's made visible again).
  233735. blankPageShown = true;
  233736. browser->goToURL ("about:blank", 0, 0);
  233737. }
  233738. }
  233739. }
  233740. void WebBrowserComponent::reloadLastURL()
  233741. {
  233742. if (lastURL.isNotEmpty())
  233743. {
  233744. goToURL (lastURL, &lastHeaders, &lastPostData);
  233745. lastURL = String::empty;
  233746. }
  233747. }
  233748. void WebBrowserComponent::parentHierarchyChanged()
  233749. {
  233750. checkWindowAssociation();
  233751. }
  233752. void WebBrowserComponent::resized()
  233753. {
  233754. browser->setSize (getWidth(), getHeight());
  233755. }
  233756. void WebBrowserComponent::visibilityChanged()
  233757. {
  233758. checkWindowAssociation();
  233759. }
  233760. bool WebBrowserComponent::pageAboutToLoad (const String&)
  233761. {
  233762. return true;
  233763. }
  233764. #else
  233765. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233766. {
  233767. }
  233768. WebBrowserComponent::~WebBrowserComponent()
  233769. {
  233770. }
  233771. void WebBrowserComponent::goToURL (const String& url,
  233772. const StringArray* headers,
  233773. const MemoryBlock* postData)
  233774. {
  233775. }
  233776. void WebBrowserComponent::stop()
  233777. {
  233778. }
  233779. void WebBrowserComponent::goBack()
  233780. {
  233781. }
  233782. void WebBrowserComponent::goForward()
  233783. {
  233784. }
  233785. void WebBrowserComponent::refresh()
  233786. {
  233787. }
  233788. void WebBrowserComponent::paint (Graphics& g)
  233789. {
  233790. }
  233791. void WebBrowserComponent::checkWindowAssociation()
  233792. {
  233793. }
  233794. void WebBrowserComponent::reloadLastURL()
  233795. {
  233796. }
  233797. void WebBrowserComponent::parentHierarchyChanged()
  233798. {
  233799. }
  233800. void WebBrowserComponent::resized()
  233801. {
  233802. }
  233803. void WebBrowserComponent::visibilityChanged()
  233804. {
  233805. }
  233806. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  233807. {
  233808. return true;
  233809. }
  233810. #endif
  233811. #endif
  233812. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233813. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  233814. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233815. // compiled on its own).
  233816. #if JUCE_INCLUDED_FILE
  233817. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233818. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  233819. #endif
  233820. #undef log
  233821. #if JUCE_COREAUDIO_LOGGING_ENABLED
  233822. #define log(a) Logger::writeToLog (a)
  233823. #else
  233824. #define log(a)
  233825. #endif
  233826. #undef OK
  233827. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233828. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  233829. {
  233830. if (err == noErr)
  233831. return true;
  233832. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  233833. jassertfalse;
  233834. return false;
  233835. }
  233836. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  233837. #else
  233838. #define OK(a) (a == noErr)
  233839. #endif
  233840. class CoreAudioInternal : public Timer
  233841. {
  233842. public:
  233843. CoreAudioInternal (AudioDeviceID id)
  233844. : inputLatency (0),
  233845. outputLatency (0),
  233846. callback (0),
  233847. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233848. audioProcID (0),
  233849. #endif
  233850. isSlaveDevice (false),
  233851. deviceID (id),
  233852. started (false),
  233853. sampleRate (0),
  233854. bufferSize (512),
  233855. numInputChans (0),
  233856. numOutputChans (0),
  233857. callbacksAllowed (true),
  233858. numInputChannelInfos (0),
  233859. numOutputChannelInfos (0)
  233860. {
  233861. jassert (deviceID != 0);
  233862. updateDetailsFromDevice();
  233863. AudioObjectPropertyAddress pa;
  233864. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233865. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233866. pa.mElement = kAudioObjectPropertyElementWildcard;
  233867. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  233868. }
  233869. ~CoreAudioInternal()
  233870. {
  233871. AudioObjectPropertyAddress pa;
  233872. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233873. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233874. pa.mElement = kAudioObjectPropertyElementWildcard;
  233875. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  233876. stop (false);
  233877. }
  233878. void allocateTempBuffers()
  233879. {
  233880. const int tempBufSize = bufferSize + 4;
  233881. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  233882. tempInputBuffers.calloc (numInputChans + 2);
  233883. tempOutputBuffers.calloc (numOutputChans + 2);
  233884. int i, count = 0;
  233885. for (i = 0; i < numInputChans; ++i)
  233886. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233887. for (i = 0; i < numOutputChans; ++i)
  233888. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233889. }
  233890. // returns the number of actual available channels
  233891. void fillInChannelInfo (const bool input)
  233892. {
  233893. int chanNum = 0;
  233894. UInt32 size;
  233895. AudioObjectPropertyAddress pa;
  233896. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  233897. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233898. pa.mElement = kAudioObjectPropertyElementMaster;
  233899. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233900. {
  233901. HeapBlock <AudioBufferList> bufList;
  233902. bufList.calloc (size, 1);
  233903. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  233904. {
  233905. const int numStreams = bufList->mNumberBuffers;
  233906. for (int i = 0; i < numStreams; ++i)
  233907. {
  233908. const AudioBuffer& b = bufList->mBuffers[i];
  233909. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  233910. {
  233911. String name;
  233912. {
  233913. char channelName [256];
  233914. zerostruct (channelName);
  233915. UInt32 nameSize = sizeof (channelName);
  233916. UInt32 channelNum = chanNum + 1;
  233917. pa.mSelector = kAudioDevicePropertyChannelName;
  233918. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  233919. name = String::fromUTF8 (channelName, nameSize);
  233920. }
  233921. if (input)
  233922. {
  233923. if (activeInputChans[chanNum])
  233924. {
  233925. inputChannelInfo [numInputChannelInfos].streamNum = i;
  233926. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  233927. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233928. ++numInputChannelInfos;
  233929. }
  233930. if (name.isEmpty())
  233931. name << "Input " << (chanNum + 1);
  233932. inChanNames.add (name);
  233933. }
  233934. else
  233935. {
  233936. if (activeOutputChans[chanNum])
  233937. {
  233938. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  233939. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  233940. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233941. ++numOutputChannelInfos;
  233942. }
  233943. if (name.isEmpty())
  233944. name << "Output " << (chanNum + 1);
  233945. outChanNames.add (name);
  233946. }
  233947. ++chanNum;
  233948. }
  233949. }
  233950. }
  233951. }
  233952. }
  233953. void updateDetailsFromDevice()
  233954. {
  233955. stopTimer();
  233956. if (deviceID == 0)
  233957. return;
  233958. const ScopedLock sl (callbackLock);
  233959. Float64 sr;
  233960. UInt32 size = sizeof (Float64);
  233961. AudioObjectPropertyAddress pa;
  233962. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233963. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233964. pa.mElement = kAudioObjectPropertyElementMaster;
  233965. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  233966. sampleRate = sr;
  233967. UInt32 framesPerBuf;
  233968. size = sizeof (framesPerBuf);
  233969. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233970. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  233971. {
  233972. bufferSize = framesPerBuf;
  233973. allocateTempBuffers();
  233974. }
  233975. bufferSizes.clear();
  233976. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  233977. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233978. {
  233979. HeapBlock <AudioValueRange> ranges;
  233980. ranges.calloc (size, 1);
  233981. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233982. {
  233983. bufferSizes.add ((int) ranges[0].mMinimum);
  233984. for (int i = 32; i < 2048; i += 32)
  233985. {
  233986. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233987. {
  233988. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  233989. {
  233990. bufferSizes.addIfNotAlreadyThere (i);
  233991. break;
  233992. }
  233993. }
  233994. }
  233995. if (bufferSize > 0)
  233996. bufferSizes.addIfNotAlreadyThere (bufferSize);
  233997. }
  233998. }
  233999. if (bufferSizes.size() == 0 && bufferSize > 0)
  234000. bufferSizes.add (bufferSize);
  234001. sampleRates.clear();
  234002. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  234003. String rates;
  234004. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234005. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234006. {
  234007. HeapBlock <AudioValueRange> ranges;
  234008. ranges.calloc (size, 1);
  234009. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234010. {
  234011. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234012. {
  234013. bool ok = false;
  234014. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234015. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234016. ok = true;
  234017. if (ok)
  234018. {
  234019. sampleRates.add (possibleRates[i]);
  234020. rates << possibleRates[i] << ' ';
  234021. }
  234022. }
  234023. }
  234024. }
  234025. if (sampleRates.size() == 0 && sampleRate > 0)
  234026. {
  234027. sampleRates.add (sampleRate);
  234028. rates << sampleRate;
  234029. }
  234030. log ("sr: " + rates);
  234031. inputLatency = 0;
  234032. outputLatency = 0;
  234033. UInt32 lat;
  234034. size = sizeof (lat);
  234035. pa.mSelector = kAudioDevicePropertyLatency;
  234036. pa.mScope = kAudioDevicePropertyScopeInput;
  234037. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  234038. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234039. inputLatency = (int) lat;
  234040. pa.mScope = kAudioDevicePropertyScopeOutput;
  234041. size = sizeof (lat);
  234042. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234043. outputLatency = (int) lat;
  234044. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234045. inChanNames.clear();
  234046. outChanNames.clear();
  234047. inputChannelInfo.calloc (numInputChans + 2);
  234048. numInputChannelInfos = 0;
  234049. outputChannelInfo.calloc (numOutputChans + 2);
  234050. numOutputChannelInfos = 0;
  234051. fillInChannelInfo (true);
  234052. fillInChannelInfo (false);
  234053. }
  234054. const StringArray getSources (bool input)
  234055. {
  234056. StringArray s;
  234057. HeapBlock <OSType> types;
  234058. const int num = getAllDataSourcesForDevice (deviceID, types);
  234059. for (int i = 0; i < num; ++i)
  234060. {
  234061. AudioValueTranslation avt;
  234062. char buffer[256];
  234063. avt.mInputData = &(types[i]);
  234064. avt.mInputDataSize = sizeof (UInt32);
  234065. avt.mOutputData = buffer;
  234066. avt.mOutputDataSize = 256;
  234067. UInt32 transSize = sizeof (avt);
  234068. AudioObjectPropertyAddress pa;
  234069. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234070. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234071. pa.mElement = kAudioObjectPropertyElementMaster;
  234072. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234073. {
  234074. DBG (buffer);
  234075. s.add (buffer);
  234076. }
  234077. }
  234078. return s;
  234079. }
  234080. int getCurrentSourceIndex (bool input) const
  234081. {
  234082. OSType currentSourceID = 0;
  234083. UInt32 size = sizeof (currentSourceID);
  234084. int result = -1;
  234085. AudioObjectPropertyAddress pa;
  234086. pa.mSelector = kAudioDevicePropertyDataSource;
  234087. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234088. pa.mElement = kAudioObjectPropertyElementMaster;
  234089. if (deviceID != 0)
  234090. {
  234091. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234092. {
  234093. HeapBlock <OSType> types;
  234094. const int num = getAllDataSourcesForDevice (deviceID, types);
  234095. for (int i = 0; i < num; ++i)
  234096. {
  234097. if (types[num] == currentSourceID)
  234098. {
  234099. result = i;
  234100. break;
  234101. }
  234102. }
  234103. }
  234104. }
  234105. return result;
  234106. }
  234107. void setCurrentSourceIndex (int index, bool input)
  234108. {
  234109. if (deviceID != 0)
  234110. {
  234111. HeapBlock <OSType> types;
  234112. const int num = getAllDataSourcesForDevice (deviceID, types);
  234113. if (((unsigned int) index) < (unsigned int) num)
  234114. {
  234115. AudioObjectPropertyAddress pa;
  234116. pa.mSelector = kAudioDevicePropertyDataSource;
  234117. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234118. pa.mElement = kAudioObjectPropertyElementMaster;
  234119. OSType typeId = types[index];
  234120. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  234121. }
  234122. }
  234123. }
  234124. const String reopen (const BigInteger& inputChannels,
  234125. const BigInteger& outputChannels,
  234126. double newSampleRate,
  234127. int bufferSizeSamples)
  234128. {
  234129. String error;
  234130. log ("CoreAudio reopen");
  234131. callbacksAllowed = false;
  234132. stopTimer();
  234133. stop (false);
  234134. activeInputChans = inputChannels;
  234135. activeInputChans.setRange (inChanNames.size(),
  234136. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  234137. false);
  234138. activeOutputChans = outputChannels;
  234139. activeOutputChans.setRange (outChanNames.size(),
  234140. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  234141. false);
  234142. numInputChans = activeInputChans.countNumberOfSetBits();
  234143. numOutputChans = activeOutputChans.countNumberOfSetBits();
  234144. // set sample rate
  234145. AudioObjectPropertyAddress pa;
  234146. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234147. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234148. pa.mElement = kAudioObjectPropertyElementMaster;
  234149. Float64 sr = newSampleRate;
  234150. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  234151. {
  234152. error = "Couldn't change sample rate";
  234153. }
  234154. else
  234155. {
  234156. // change buffer size
  234157. UInt32 framesPerBuf = bufferSizeSamples;
  234158. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234159. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  234160. {
  234161. error = "Couldn't change buffer size";
  234162. }
  234163. else
  234164. {
  234165. // Annoyingly, after changing the rate and buffer size, some devices fail to
  234166. // correctly report their new settings until some random time in the future, so
  234167. // after calling updateDetailsFromDevice, we need to manually bodge these values
  234168. // to make sure we're using the correct numbers..
  234169. updateDetailsFromDevice();
  234170. sampleRate = newSampleRate;
  234171. bufferSize = bufferSizeSamples;
  234172. if (sampleRates.size() == 0)
  234173. error = "Device has no available sample-rates";
  234174. else if (bufferSizes.size() == 0)
  234175. error = "Device has no available buffer-sizes";
  234176. else if (inputDevice != 0)
  234177. error = inputDevice->reopen (inputChannels,
  234178. outputChannels,
  234179. newSampleRate,
  234180. bufferSizeSamples);
  234181. }
  234182. }
  234183. callbacksAllowed = true;
  234184. return error;
  234185. }
  234186. bool start (AudioIODeviceCallback* cb)
  234187. {
  234188. if (! started)
  234189. {
  234190. callback = 0;
  234191. if (deviceID != 0)
  234192. {
  234193. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234194. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234195. #else
  234196. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234197. #endif
  234198. {
  234199. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234200. {
  234201. started = true;
  234202. }
  234203. else
  234204. {
  234205. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234206. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234207. #else
  234208. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234209. audioProcID = 0;
  234210. #endif
  234211. }
  234212. }
  234213. }
  234214. }
  234215. if (started)
  234216. {
  234217. const ScopedLock sl (callbackLock);
  234218. callback = cb;
  234219. }
  234220. if (inputDevice != 0)
  234221. return started && inputDevice->start (cb);
  234222. else
  234223. return started;
  234224. }
  234225. void stop (bool leaveInterruptRunning)
  234226. {
  234227. {
  234228. const ScopedLock sl (callbackLock);
  234229. callback = 0;
  234230. }
  234231. if (started
  234232. && (deviceID != 0)
  234233. && ! leaveInterruptRunning)
  234234. {
  234235. OK (AudioDeviceStop (deviceID, audioIOProc));
  234236. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234237. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234238. #else
  234239. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234240. audioProcID = 0;
  234241. #endif
  234242. started = false;
  234243. { const ScopedLock sl (callbackLock); }
  234244. // wait until it's definately stopped calling back..
  234245. for (int i = 40; --i >= 0;)
  234246. {
  234247. Thread::sleep (50);
  234248. UInt32 running = 0;
  234249. UInt32 size = sizeof (running);
  234250. AudioObjectPropertyAddress pa;
  234251. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  234252. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234253. pa.mElement = kAudioObjectPropertyElementMaster;
  234254. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  234255. if (running == 0)
  234256. break;
  234257. }
  234258. const ScopedLock sl (callbackLock);
  234259. }
  234260. if (inputDevice != 0)
  234261. inputDevice->stop (leaveInterruptRunning);
  234262. }
  234263. double getSampleRate() const
  234264. {
  234265. return sampleRate;
  234266. }
  234267. int getBufferSize() const
  234268. {
  234269. return bufferSize;
  234270. }
  234271. void audioCallback (const AudioBufferList* inInputData,
  234272. AudioBufferList* outOutputData)
  234273. {
  234274. int i;
  234275. const ScopedLock sl (callbackLock);
  234276. if (callback != 0)
  234277. {
  234278. if (inputDevice == 0)
  234279. {
  234280. for (i = numInputChans; --i >= 0;)
  234281. {
  234282. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  234283. float* dest = tempInputBuffers [i];
  234284. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  234285. + info.dataOffsetSamples;
  234286. const int stride = info.dataStrideSamples;
  234287. if (stride != 0) // if this is zero, info is invalid
  234288. {
  234289. for (int j = bufferSize; --j >= 0;)
  234290. {
  234291. *dest++ = *src;
  234292. src += stride;
  234293. }
  234294. }
  234295. }
  234296. }
  234297. if (! isSlaveDevice)
  234298. {
  234299. if (inputDevice == 0)
  234300. {
  234301. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  234302. numInputChans,
  234303. tempOutputBuffers,
  234304. numOutputChans,
  234305. bufferSize);
  234306. }
  234307. else
  234308. {
  234309. jassert (inputDevice->bufferSize == bufferSize);
  234310. // Sometimes the two linked devices seem to get their callbacks in
  234311. // parallel, so we need to lock both devices to stop the input data being
  234312. // changed while inside our callback..
  234313. const ScopedLock sl2 (inputDevice->callbackLock);
  234314. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  234315. inputDevice->numInputChans,
  234316. tempOutputBuffers,
  234317. numOutputChans,
  234318. bufferSize);
  234319. }
  234320. for (i = numOutputChans; --i >= 0;)
  234321. {
  234322. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234323. const float* src = tempOutputBuffers [i];
  234324. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234325. + info.dataOffsetSamples;
  234326. const int stride = info.dataStrideSamples;
  234327. if (stride != 0) // if this is zero, info is invalid
  234328. {
  234329. for (int j = bufferSize; --j >= 0;)
  234330. {
  234331. *dest = *src++;
  234332. dest += stride;
  234333. }
  234334. }
  234335. }
  234336. }
  234337. }
  234338. else
  234339. {
  234340. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  234341. {
  234342. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234343. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234344. + info.dataOffsetSamples;
  234345. const int stride = info.dataStrideSamples;
  234346. if (stride != 0) // if this is zero, info is invalid
  234347. {
  234348. for (int j = bufferSize; --j >= 0;)
  234349. {
  234350. *dest = 0.0f;
  234351. dest += stride;
  234352. }
  234353. }
  234354. }
  234355. }
  234356. }
  234357. // called by callbacks
  234358. void deviceDetailsChanged()
  234359. {
  234360. if (callbacksAllowed)
  234361. startTimer (100);
  234362. }
  234363. void timerCallback()
  234364. {
  234365. stopTimer();
  234366. log ("CoreAudio device changed callback");
  234367. const double oldSampleRate = sampleRate;
  234368. const int oldBufferSize = bufferSize;
  234369. updateDetailsFromDevice();
  234370. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  234371. {
  234372. callbacksAllowed = false;
  234373. stop (false);
  234374. updateDetailsFromDevice();
  234375. callbacksAllowed = true;
  234376. }
  234377. }
  234378. CoreAudioInternal* getRelatedDevice() const
  234379. {
  234380. UInt32 size = 0;
  234381. ScopedPointer <CoreAudioInternal> result;
  234382. AudioObjectPropertyAddress pa;
  234383. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  234384. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234385. pa.mElement = kAudioObjectPropertyElementMaster;
  234386. if (deviceID != 0
  234387. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  234388. && size > 0)
  234389. {
  234390. HeapBlock <AudioDeviceID> devs;
  234391. devs.calloc (size, 1);
  234392. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  234393. {
  234394. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  234395. {
  234396. if (devs[i] != deviceID && devs[i] != 0)
  234397. {
  234398. result = new CoreAudioInternal (devs[i]);
  234399. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  234400. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  234401. if (thisIsInput != otherIsInput
  234402. || (inChanNames.size() + outChanNames.size() == 0)
  234403. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  234404. break;
  234405. result = 0;
  234406. }
  234407. }
  234408. }
  234409. }
  234410. return result.release();
  234411. }
  234412. juce_UseDebuggingNewOperator
  234413. int inputLatency, outputLatency;
  234414. BigInteger activeInputChans, activeOutputChans;
  234415. StringArray inChanNames, outChanNames;
  234416. Array <double> sampleRates;
  234417. Array <int> bufferSizes;
  234418. AudioIODeviceCallback* callback;
  234419. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234420. AudioDeviceIOProcID audioProcID;
  234421. #endif
  234422. ScopedPointer<CoreAudioInternal> inputDevice;
  234423. bool isSlaveDevice;
  234424. private:
  234425. CriticalSection callbackLock;
  234426. AudioDeviceID deviceID;
  234427. bool started;
  234428. double sampleRate;
  234429. int bufferSize;
  234430. HeapBlock <float> audioBuffer;
  234431. int numInputChans, numOutputChans;
  234432. bool callbacksAllowed;
  234433. struct CallbackDetailsForChannel
  234434. {
  234435. int streamNum;
  234436. int dataOffsetSamples;
  234437. int dataStrideSamples;
  234438. };
  234439. int numInputChannelInfos, numOutputChannelInfos;
  234440. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  234441. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  234442. CoreAudioInternal (const CoreAudioInternal&);
  234443. CoreAudioInternal& operator= (const CoreAudioInternal&);
  234444. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  234445. const AudioTimeStamp* /*inNow*/,
  234446. const AudioBufferList* inInputData,
  234447. const AudioTimeStamp* /*inInputTime*/,
  234448. AudioBufferList* outOutputData,
  234449. const AudioTimeStamp* /*inOutputTime*/,
  234450. void* device)
  234451. {
  234452. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  234453. return noErr;
  234454. }
  234455. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234456. {
  234457. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234458. switch (pa->mSelector)
  234459. {
  234460. case kAudioDevicePropertyBufferSize:
  234461. case kAudioDevicePropertyBufferFrameSize:
  234462. case kAudioDevicePropertyNominalSampleRate:
  234463. case kAudioDevicePropertyStreamFormat:
  234464. case kAudioDevicePropertyDeviceIsAlive:
  234465. intern->deviceDetailsChanged();
  234466. break;
  234467. case kAudioDevicePropertyBufferSizeRange:
  234468. case kAudioDevicePropertyVolumeScalar:
  234469. case kAudioDevicePropertyMute:
  234470. case kAudioDevicePropertyPlayThru:
  234471. case kAudioDevicePropertyDataSource:
  234472. case kAudioDevicePropertyDeviceIsRunning:
  234473. break;
  234474. }
  234475. return noErr;
  234476. }
  234477. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  234478. {
  234479. AudioObjectPropertyAddress pa;
  234480. pa.mSelector = kAudioDevicePropertyDataSources;
  234481. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234482. pa.mElement = kAudioObjectPropertyElementMaster;
  234483. UInt32 size = 0;
  234484. if (deviceID != 0
  234485. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234486. {
  234487. types.calloc (size, 1);
  234488. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  234489. return size / (int) sizeof (OSType);
  234490. }
  234491. return 0;
  234492. }
  234493. };
  234494. class CoreAudioIODevice : public AudioIODevice
  234495. {
  234496. public:
  234497. CoreAudioIODevice (const String& deviceName,
  234498. AudioDeviceID inputDeviceId,
  234499. const int inputIndex_,
  234500. AudioDeviceID outputDeviceId,
  234501. const int outputIndex_)
  234502. : AudioIODevice (deviceName, "CoreAudio"),
  234503. inputIndex (inputIndex_),
  234504. outputIndex (outputIndex_),
  234505. isOpen_ (false),
  234506. isStarted (false)
  234507. {
  234508. CoreAudioInternal* device = 0;
  234509. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  234510. {
  234511. jassert (inputDeviceId != 0);
  234512. device = new CoreAudioInternal (inputDeviceId);
  234513. }
  234514. else
  234515. {
  234516. device = new CoreAudioInternal (outputDeviceId);
  234517. if (inputDeviceId != 0)
  234518. {
  234519. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  234520. device->inputDevice = secondDevice;
  234521. secondDevice->isSlaveDevice = true;
  234522. }
  234523. }
  234524. internal = device;
  234525. AudioObjectPropertyAddress pa;
  234526. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234527. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234528. pa.mElement = kAudioObjectPropertyElementWildcard;
  234529. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234530. }
  234531. ~CoreAudioIODevice()
  234532. {
  234533. AudioObjectPropertyAddress pa;
  234534. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234535. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234536. pa.mElement = kAudioObjectPropertyElementWildcard;
  234537. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234538. }
  234539. const StringArray getOutputChannelNames()
  234540. {
  234541. return internal->outChanNames;
  234542. }
  234543. const StringArray getInputChannelNames()
  234544. {
  234545. if (internal->inputDevice != 0)
  234546. return internal->inputDevice->inChanNames;
  234547. else
  234548. return internal->inChanNames;
  234549. }
  234550. int getNumSampleRates()
  234551. {
  234552. return internal->sampleRates.size();
  234553. }
  234554. double getSampleRate (int index)
  234555. {
  234556. return internal->sampleRates [index];
  234557. }
  234558. int getNumBufferSizesAvailable()
  234559. {
  234560. return internal->bufferSizes.size();
  234561. }
  234562. int getBufferSizeSamples (int index)
  234563. {
  234564. return internal->bufferSizes [index];
  234565. }
  234566. int getDefaultBufferSize()
  234567. {
  234568. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  234569. if (getBufferSizeSamples(i) >= 512)
  234570. return getBufferSizeSamples(i);
  234571. return 512;
  234572. }
  234573. const String open (const BigInteger& inputChannels,
  234574. const BigInteger& outputChannels,
  234575. double sampleRate,
  234576. int bufferSizeSamples)
  234577. {
  234578. isOpen_ = true;
  234579. if (bufferSizeSamples <= 0)
  234580. bufferSizeSamples = getDefaultBufferSize();
  234581. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  234582. isOpen_ = lastError.isEmpty();
  234583. return lastError;
  234584. }
  234585. void close()
  234586. {
  234587. isOpen_ = false;
  234588. internal->stop (false);
  234589. }
  234590. bool isOpen()
  234591. {
  234592. return isOpen_;
  234593. }
  234594. int getCurrentBufferSizeSamples()
  234595. {
  234596. return internal != 0 ? internal->getBufferSize() : 512;
  234597. }
  234598. double getCurrentSampleRate()
  234599. {
  234600. return internal != 0 ? internal->getSampleRate() : 0;
  234601. }
  234602. int getCurrentBitDepth()
  234603. {
  234604. return 32; // no way to find out, so just assume it's high..
  234605. }
  234606. const BigInteger getActiveOutputChannels() const
  234607. {
  234608. return internal != 0 ? internal->activeOutputChans : BigInteger();
  234609. }
  234610. const BigInteger getActiveInputChannels() const
  234611. {
  234612. BigInteger chans;
  234613. if (internal != 0)
  234614. {
  234615. chans = internal->activeInputChans;
  234616. if (internal->inputDevice != 0)
  234617. chans |= internal->inputDevice->activeInputChans;
  234618. }
  234619. return chans;
  234620. }
  234621. int getOutputLatencyInSamples()
  234622. {
  234623. if (internal == 0)
  234624. return 0;
  234625. // this seems like a good guess at getting the latency right - comparing
  234626. // this with a round-trip measurement, it gets it to within a few millisecs
  234627. // for the built-in mac soundcard
  234628. return internal->outputLatency + internal->getBufferSize() * 2;
  234629. }
  234630. int getInputLatencyInSamples()
  234631. {
  234632. if (internal == 0)
  234633. return 0;
  234634. return internal->inputLatency + internal->getBufferSize() * 2;
  234635. }
  234636. void start (AudioIODeviceCallback* callback)
  234637. {
  234638. if (internal != 0 && ! isStarted)
  234639. {
  234640. if (callback != 0)
  234641. callback->audioDeviceAboutToStart (this);
  234642. isStarted = true;
  234643. internal->start (callback);
  234644. }
  234645. }
  234646. void stop()
  234647. {
  234648. if (isStarted && internal != 0)
  234649. {
  234650. AudioIODeviceCallback* const lastCallback = internal->callback;
  234651. isStarted = false;
  234652. internal->stop (true);
  234653. if (lastCallback != 0)
  234654. lastCallback->audioDeviceStopped();
  234655. }
  234656. }
  234657. bool isPlaying()
  234658. {
  234659. if (internal->callback == 0)
  234660. isStarted = false;
  234661. return isStarted;
  234662. }
  234663. const String getLastError()
  234664. {
  234665. return lastError;
  234666. }
  234667. int inputIndex, outputIndex;
  234668. juce_UseDebuggingNewOperator
  234669. private:
  234670. ScopedPointer<CoreAudioInternal> internal;
  234671. bool isOpen_, isStarted;
  234672. String lastError;
  234673. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234674. {
  234675. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234676. switch (pa->mSelector)
  234677. {
  234678. case kAudioHardwarePropertyDevices:
  234679. intern->deviceDetailsChanged();
  234680. break;
  234681. case kAudioHardwarePropertyDefaultOutputDevice:
  234682. case kAudioHardwarePropertyDefaultInputDevice:
  234683. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  234684. break;
  234685. }
  234686. return noErr;
  234687. }
  234688. CoreAudioIODevice (const CoreAudioIODevice&);
  234689. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  234690. };
  234691. class CoreAudioIODeviceType : public AudioIODeviceType
  234692. {
  234693. public:
  234694. CoreAudioIODeviceType()
  234695. : AudioIODeviceType ("CoreAudio"),
  234696. hasScanned (false)
  234697. {
  234698. }
  234699. ~CoreAudioIODeviceType()
  234700. {
  234701. }
  234702. void scanForDevices()
  234703. {
  234704. hasScanned = true;
  234705. inputDeviceNames.clear();
  234706. outputDeviceNames.clear();
  234707. inputIds.clear();
  234708. outputIds.clear();
  234709. UInt32 size;
  234710. AudioObjectPropertyAddress pa;
  234711. pa.mSelector = kAudioHardwarePropertyDevices;
  234712. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234713. pa.mElement = kAudioObjectPropertyElementMaster;
  234714. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  234715. {
  234716. HeapBlock <AudioDeviceID> devs;
  234717. devs.calloc (size, 1);
  234718. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  234719. {
  234720. static bool alreadyLogged = false;
  234721. const int num = size / (int) sizeof (AudioDeviceID);
  234722. for (int i = 0; i < num; ++i)
  234723. {
  234724. char name [1024];
  234725. size = sizeof (name);
  234726. pa.mSelector = kAudioDevicePropertyDeviceName;
  234727. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  234728. {
  234729. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  234730. if (! alreadyLogged)
  234731. log ("CoreAudio device: " + nameString);
  234732. const int numIns = getNumChannels (devs[i], true);
  234733. const int numOuts = getNumChannels (devs[i], false);
  234734. if (numIns > 0)
  234735. {
  234736. inputDeviceNames.add (nameString);
  234737. inputIds.add (devs[i]);
  234738. }
  234739. if (numOuts > 0)
  234740. {
  234741. outputDeviceNames.add (nameString);
  234742. outputIds.add (devs[i]);
  234743. }
  234744. }
  234745. }
  234746. alreadyLogged = true;
  234747. }
  234748. }
  234749. inputDeviceNames.appendNumbersToDuplicates (false, true);
  234750. outputDeviceNames.appendNumbersToDuplicates (false, true);
  234751. }
  234752. const StringArray getDeviceNames (bool wantInputNames) const
  234753. {
  234754. jassert (hasScanned); // need to call scanForDevices() before doing this
  234755. if (wantInputNames)
  234756. return inputDeviceNames;
  234757. else
  234758. return outputDeviceNames;
  234759. }
  234760. int getDefaultDeviceIndex (bool forInput) const
  234761. {
  234762. jassert (hasScanned); // need to call scanForDevices() before doing this
  234763. AudioDeviceID deviceID;
  234764. UInt32 size = sizeof (deviceID);
  234765. // if they're asking for any input channels at all, use the default input, so we
  234766. // get the built-in mic rather than the built-in output with no inputs..
  234767. AudioObjectPropertyAddress pa;
  234768. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  234769. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234770. pa.mElement = kAudioObjectPropertyElementMaster;
  234771. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  234772. {
  234773. if (forInput)
  234774. {
  234775. for (int i = inputIds.size(); --i >= 0;)
  234776. if (inputIds[i] == deviceID)
  234777. return i;
  234778. }
  234779. else
  234780. {
  234781. for (int i = outputIds.size(); --i >= 0;)
  234782. if (outputIds[i] == deviceID)
  234783. return i;
  234784. }
  234785. }
  234786. return 0;
  234787. }
  234788. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  234789. {
  234790. jassert (hasScanned); // need to call scanForDevices() before doing this
  234791. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  234792. if (d == 0)
  234793. return -1;
  234794. return asInput ? d->inputIndex
  234795. : d->outputIndex;
  234796. }
  234797. bool hasSeparateInputsAndOutputs() const { return true; }
  234798. AudioIODevice* createDevice (const String& outputDeviceName,
  234799. const String& inputDeviceName)
  234800. {
  234801. jassert (hasScanned); // need to call scanForDevices() before doing this
  234802. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  234803. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  234804. String deviceName (outputDeviceName);
  234805. if (deviceName.isEmpty())
  234806. deviceName = inputDeviceName;
  234807. if (index >= 0)
  234808. return new CoreAudioIODevice (deviceName,
  234809. inputIds [inputIndex],
  234810. inputIndex,
  234811. outputIds [outputIndex],
  234812. outputIndex);
  234813. return 0;
  234814. }
  234815. juce_UseDebuggingNewOperator
  234816. private:
  234817. StringArray inputDeviceNames, outputDeviceNames;
  234818. Array <AudioDeviceID> inputIds, outputIds;
  234819. bool hasScanned;
  234820. static int getNumChannels (AudioDeviceID deviceID, bool input)
  234821. {
  234822. int total = 0;
  234823. UInt32 size;
  234824. AudioObjectPropertyAddress pa;
  234825. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234826. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234827. pa.mElement = kAudioObjectPropertyElementMaster;
  234828. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234829. {
  234830. HeapBlock <AudioBufferList> bufList;
  234831. bufList.calloc (size, 1);
  234832. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234833. {
  234834. const int numStreams = bufList->mNumberBuffers;
  234835. for (int i = 0; i < numStreams; ++i)
  234836. {
  234837. const AudioBuffer& b = bufList->mBuffers[i];
  234838. total += b.mNumberChannels;
  234839. }
  234840. }
  234841. }
  234842. return total;
  234843. }
  234844. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  234845. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  234846. };
  234847. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  234848. {
  234849. return new CoreAudioIODeviceType();
  234850. }
  234851. #undef log
  234852. #endif
  234853. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  234854. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  234855. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234856. // compiled on its own).
  234857. #if JUCE_INCLUDED_FILE
  234858. #if JUCE_MAC
  234859. #undef log
  234860. #define log(a) Logger::writeToLog(a)
  234861. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  234862. {
  234863. if (err == noErr)
  234864. return true;
  234865. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234866. jassertfalse;
  234867. return false;
  234868. }
  234869. #undef OK
  234870. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  234871. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  234872. {
  234873. String result;
  234874. CFStringRef str = 0;
  234875. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  234876. if (str != 0)
  234877. {
  234878. result = PlatformUtilities::cfStringToJuceString (str);
  234879. CFRelease (str);
  234880. str = 0;
  234881. }
  234882. MIDIEntityRef entity = 0;
  234883. MIDIEndpointGetEntity (endpoint, &entity);
  234884. if (entity == 0)
  234885. return result; // probably virtual
  234886. if (result.isEmpty())
  234887. {
  234888. // endpoint name has zero length - try the entity
  234889. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  234890. if (str != 0)
  234891. {
  234892. result += PlatformUtilities::cfStringToJuceString (str);
  234893. CFRelease (str);
  234894. str = 0;
  234895. }
  234896. }
  234897. // now consider the device's name
  234898. MIDIDeviceRef device = 0;
  234899. MIDIEntityGetDevice (entity, &device);
  234900. if (device == 0)
  234901. return result;
  234902. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  234903. if (str != 0)
  234904. {
  234905. const String s (PlatformUtilities::cfStringToJuceString (str));
  234906. CFRelease (str);
  234907. // if an external device has only one entity, throw away
  234908. // the endpoint name and just use the device name
  234909. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  234910. {
  234911. result = s;
  234912. }
  234913. else if (! result.startsWithIgnoreCase (s))
  234914. {
  234915. // prepend the device name to the entity name
  234916. result = (s + " " + result).trimEnd();
  234917. }
  234918. }
  234919. return result;
  234920. }
  234921. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  234922. {
  234923. String result;
  234924. // Does the endpoint have connections?
  234925. CFDataRef connections = 0;
  234926. int numConnections = 0;
  234927. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  234928. if (connections != 0)
  234929. {
  234930. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  234931. if (numConnections > 0)
  234932. {
  234933. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  234934. for (int i = 0; i < numConnections; ++i, ++pid)
  234935. {
  234936. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  234937. MIDIObjectRef connObject;
  234938. MIDIObjectType connObjectType;
  234939. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  234940. if (err == noErr)
  234941. {
  234942. String s;
  234943. if (connObjectType == kMIDIObjectType_ExternalSource
  234944. || connObjectType == kMIDIObjectType_ExternalDestination)
  234945. {
  234946. // Connected to an external device's endpoint (10.3 and later).
  234947. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  234948. }
  234949. else
  234950. {
  234951. // Connected to an external device (10.2) (or something else, catch-all)
  234952. CFStringRef str = 0;
  234953. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  234954. if (str != 0)
  234955. {
  234956. s = PlatformUtilities::cfStringToJuceString (str);
  234957. CFRelease (str);
  234958. }
  234959. }
  234960. if (s.isNotEmpty())
  234961. {
  234962. if (result.isNotEmpty())
  234963. result += ", ";
  234964. result += s;
  234965. }
  234966. }
  234967. }
  234968. }
  234969. CFRelease (connections);
  234970. }
  234971. if (result.isNotEmpty())
  234972. return result;
  234973. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  234974. return getEndpointName (endpoint, false);
  234975. }
  234976. const StringArray MidiOutput::getDevices()
  234977. {
  234978. StringArray s;
  234979. const ItemCount num = MIDIGetNumberOfDestinations();
  234980. for (ItemCount i = 0; i < num; ++i)
  234981. {
  234982. MIDIEndpointRef dest = MIDIGetDestination (i);
  234983. if (dest != 0)
  234984. {
  234985. String name (getConnectedEndpointName (dest));
  234986. if (name.isEmpty())
  234987. name = "<error>";
  234988. s.add (name);
  234989. }
  234990. else
  234991. {
  234992. s.add ("<error>");
  234993. }
  234994. }
  234995. return s;
  234996. }
  234997. int MidiOutput::getDefaultDeviceIndex()
  234998. {
  234999. return 0;
  235000. }
  235001. static MIDIClientRef globalMidiClient;
  235002. static bool hasGlobalClientBeenCreated = false;
  235003. static bool makeSureClientExists()
  235004. {
  235005. if (! hasGlobalClientBeenCreated)
  235006. {
  235007. String name ("JUCE");
  235008. if (JUCEApplication::getInstance() != 0)
  235009. name = JUCEApplication::getInstance()->getApplicationName();
  235010. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235011. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235012. CFRelease (appName);
  235013. }
  235014. return hasGlobalClientBeenCreated;
  235015. }
  235016. class MidiPortAndEndpoint
  235017. {
  235018. public:
  235019. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235020. : port (port_), endPoint (endPoint_)
  235021. {
  235022. }
  235023. ~MidiPortAndEndpoint()
  235024. {
  235025. if (port != 0)
  235026. MIDIPortDispose (port);
  235027. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235028. MIDIEndpointDispose (endPoint);
  235029. }
  235030. MIDIPortRef port;
  235031. MIDIEndpointRef endPoint;
  235032. };
  235033. MidiOutput* MidiOutput::openDevice (int index)
  235034. {
  235035. MidiOutput* mo = 0;
  235036. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  235037. {
  235038. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235039. CFStringRef pname;
  235040. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235041. {
  235042. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  235043. if (makeSureClientExists())
  235044. {
  235045. MIDIPortRef port;
  235046. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  235047. {
  235048. mo = new MidiOutput();
  235049. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  235050. }
  235051. }
  235052. CFRelease (pname);
  235053. }
  235054. }
  235055. return mo;
  235056. }
  235057. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235058. {
  235059. MidiOutput* mo = 0;
  235060. if (makeSureClientExists())
  235061. {
  235062. MIDIEndpointRef endPoint;
  235063. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235064. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  235065. {
  235066. mo = new MidiOutput();
  235067. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  235068. }
  235069. CFRelease (name);
  235070. }
  235071. return mo;
  235072. }
  235073. MidiOutput::~MidiOutput()
  235074. {
  235075. delete (MidiPortAndEndpoint*) internal;
  235076. }
  235077. void MidiOutput::reset()
  235078. {
  235079. }
  235080. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235081. {
  235082. return false;
  235083. }
  235084. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235085. {
  235086. }
  235087. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235088. {
  235089. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  235090. if (message.isSysEx())
  235091. {
  235092. const int maxPacketSize = 256;
  235093. int pos = 0, bytesLeft = message.getRawDataSize();
  235094. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  235095. HeapBlock <MIDIPacketList> packets;
  235096. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  235097. packets->numPackets = numPackets;
  235098. MIDIPacket* p = packets->packet;
  235099. for (int i = 0; i < numPackets; ++i)
  235100. {
  235101. p->timeStamp = 0;
  235102. p->length = jmin (maxPacketSize, bytesLeft);
  235103. memcpy (p->data, message.getRawData() + pos, p->length);
  235104. pos += p->length;
  235105. bytesLeft -= p->length;
  235106. p = MIDIPacketNext (p);
  235107. }
  235108. if (mpe->port != 0)
  235109. MIDISend (mpe->port, mpe->endPoint, packets);
  235110. else
  235111. MIDIReceived (mpe->endPoint, packets);
  235112. }
  235113. else
  235114. {
  235115. MIDIPacketList packets;
  235116. packets.numPackets = 1;
  235117. packets.packet[0].timeStamp = 0;
  235118. packets.packet[0].length = message.getRawDataSize();
  235119. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  235120. if (mpe->port != 0)
  235121. MIDISend (mpe->port, mpe->endPoint, &packets);
  235122. else
  235123. MIDIReceived (mpe->endPoint, &packets);
  235124. }
  235125. }
  235126. const StringArray MidiInput::getDevices()
  235127. {
  235128. StringArray s;
  235129. const ItemCount num = MIDIGetNumberOfSources();
  235130. for (ItemCount i = 0; i < num; ++i)
  235131. {
  235132. MIDIEndpointRef source = MIDIGetSource (i);
  235133. if (source != 0)
  235134. {
  235135. String name (getConnectedEndpointName (source));
  235136. if (name.isEmpty())
  235137. name = "<error>";
  235138. s.add (name);
  235139. }
  235140. else
  235141. {
  235142. s.add ("<error>");
  235143. }
  235144. }
  235145. return s;
  235146. }
  235147. int MidiInput::getDefaultDeviceIndex()
  235148. {
  235149. return 0;
  235150. }
  235151. struct MidiPortAndCallback
  235152. {
  235153. MidiInput* input;
  235154. MidiPortAndEndpoint* portAndEndpoint;
  235155. MidiInputCallback* callback;
  235156. MemoryBlock pendingData;
  235157. int pendingBytes;
  235158. double pendingDataTime;
  235159. bool active;
  235160. void processSysex (const uint8*& d, int& size, const double time)
  235161. {
  235162. if (*d == 0xf0)
  235163. {
  235164. pendingBytes = 0;
  235165. pendingDataTime = time;
  235166. }
  235167. pendingData.ensureSize (pendingBytes + size, false);
  235168. uint8* totalMessage = (uint8*) pendingData.getData();
  235169. uint8* dest = totalMessage + pendingBytes;
  235170. while (size > 0)
  235171. {
  235172. if (pendingBytes > 0 && *d >= 0x80)
  235173. {
  235174. if (*d >= 0xfa || *d == 0xf8)
  235175. {
  235176. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  235177. ++d;
  235178. --size;
  235179. }
  235180. else
  235181. {
  235182. if (*d == 0xf7)
  235183. {
  235184. *dest++ = *d++;
  235185. pendingBytes++;
  235186. --size;
  235187. }
  235188. break;
  235189. }
  235190. }
  235191. else
  235192. {
  235193. *dest++ = *d++;
  235194. pendingBytes++;
  235195. --size;
  235196. }
  235197. }
  235198. if (totalMessage [pendingBytes - 1] == 0xf7)
  235199. {
  235200. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  235201. pendingBytes = 0;
  235202. }
  235203. else
  235204. {
  235205. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  235206. }
  235207. }
  235208. };
  235209. namespace CoreMidiCallbacks
  235210. {
  235211. static CriticalSection callbackLock;
  235212. static Array<void*> activeCallbacks;
  235213. }
  235214. static void midiInputProc (const MIDIPacketList* pktlist,
  235215. void* readProcRefCon,
  235216. void* /*srcConnRefCon*/)
  235217. {
  235218. double time = Time::getMillisecondCounterHiRes() * 0.001;
  235219. const double originalTime = time;
  235220. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  235221. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235222. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  235223. {
  235224. const MIDIPacket* packet = &pktlist->packet[0];
  235225. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235226. {
  235227. const uint8* d = (const uint8*) (packet->data);
  235228. int size = packet->length;
  235229. while (size > 0)
  235230. {
  235231. time = originalTime;
  235232. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  235233. {
  235234. mpc->processSysex (d, size, time);
  235235. }
  235236. else
  235237. {
  235238. int used = 0;
  235239. const MidiMessage m (d, size, used, 0, time);
  235240. if (used <= 0)
  235241. {
  235242. jassertfalse; // malformed midi message
  235243. break;
  235244. }
  235245. else
  235246. {
  235247. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  235248. }
  235249. size -= used;
  235250. d += used;
  235251. }
  235252. }
  235253. packet = MIDIPacketNext (packet);
  235254. }
  235255. }
  235256. }
  235257. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235258. {
  235259. MidiInput* mi = 0;
  235260. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  235261. {
  235262. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235263. if (endPoint != 0)
  235264. {
  235265. CFStringRef pname;
  235266. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235267. {
  235268. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  235269. if (makeSureClientExists())
  235270. {
  235271. MIDIPortRef port;
  235272. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  235273. mpc->active = false;
  235274. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  235275. {
  235276. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  235277. {
  235278. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235279. mpc->callback = callback;
  235280. mpc->pendingBytes = 0;
  235281. mpc->pendingData.ensureSize (128);
  235282. mi = new MidiInput (getDevices() [index]);
  235283. mpc->input = mi;
  235284. mi->internal = mpc;
  235285. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235286. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235287. }
  235288. else
  235289. {
  235290. OK (MIDIPortDispose (port));
  235291. }
  235292. }
  235293. }
  235294. }
  235295. CFRelease (pname);
  235296. }
  235297. }
  235298. return mi;
  235299. }
  235300. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  235301. {
  235302. MidiInput* mi = 0;
  235303. if (makeSureClientExists())
  235304. {
  235305. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  235306. mpc->active = false;
  235307. MIDIEndpointRef endPoint;
  235308. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  235309. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  235310. {
  235311. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  235312. mpc->callback = callback;
  235313. mpc->pendingBytes = 0;
  235314. mpc->pendingData.ensureSize (128);
  235315. mi = new MidiInput (deviceName);
  235316. mpc->input = mi;
  235317. mi->internal = mpc;
  235318. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235319. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235320. }
  235321. CFRelease (name);
  235322. }
  235323. return mi;
  235324. }
  235325. MidiInput::MidiInput (const String& name_)
  235326. : name (name_)
  235327. {
  235328. }
  235329. MidiInput::~MidiInput()
  235330. {
  235331. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  235332. mpc->active = false;
  235333. {
  235334. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235335. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  235336. }
  235337. if (mpc->portAndEndpoint->port != 0)
  235338. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  235339. delete mpc->portAndEndpoint;
  235340. delete mpc;
  235341. }
  235342. void MidiInput::start()
  235343. {
  235344. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235345. ((MidiPortAndCallback*) internal)->active = true;
  235346. }
  235347. void MidiInput::stop()
  235348. {
  235349. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235350. ((MidiPortAndCallback*) internal)->active = false;
  235351. }
  235352. #undef log
  235353. #else
  235354. MidiOutput::~MidiOutput()
  235355. {
  235356. }
  235357. void MidiOutput::reset()
  235358. {
  235359. }
  235360. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235361. {
  235362. return false;
  235363. }
  235364. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235365. {
  235366. }
  235367. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235368. {
  235369. }
  235370. const StringArray MidiOutput::getDevices()
  235371. {
  235372. return StringArray();
  235373. }
  235374. MidiOutput* MidiOutput::openDevice (int index)
  235375. {
  235376. return 0;
  235377. }
  235378. const StringArray MidiInput::getDevices()
  235379. {
  235380. return StringArray();
  235381. }
  235382. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235383. {
  235384. return 0;
  235385. }
  235386. #endif
  235387. #endif
  235388. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  235389. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  235390. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235391. // compiled on its own).
  235392. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  235393. #if ! JUCE_QUICKTIME
  235394. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  235395. #endif
  235396. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  235397. class QTCameraDeviceInteral;
  235398. END_JUCE_NAMESPACE
  235399. @interface QTCaptureCallbackDelegate : NSObject
  235400. {
  235401. @public
  235402. CameraDevice* owner;
  235403. QTCameraDeviceInteral* internal;
  235404. int64 firstPresentationTime;
  235405. int64 averageTimeOffset;
  235406. }
  235407. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  235408. - (void) dealloc;
  235409. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235410. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235411. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235412. fromConnection: (QTCaptureConnection*) connection;
  235413. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235414. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235415. fromConnection: (QTCaptureConnection*) connection;
  235416. @end
  235417. BEGIN_JUCE_NAMESPACE
  235418. class QTCameraDeviceInteral
  235419. {
  235420. public:
  235421. QTCameraDeviceInteral (CameraDevice* owner, int index)
  235422. {
  235423. const ScopedAutoReleasePool pool;
  235424. session = [[QTCaptureSession alloc] init];
  235425. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235426. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  235427. input = 0;
  235428. audioInput = 0;
  235429. audioDevice = 0;
  235430. fileOutput = 0;
  235431. imageOutput = 0;
  235432. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  235433. internalDev: this];
  235434. NSError* err = 0;
  235435. [device retain];
  235436. [device open: &err];
  235437. if (err == 0)
  235438. {
  235439. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235440. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235441. [session addInput: input error: &err];
  235442. if (err == 0)
  235443. {
  235444. resetFile();
  235445. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  235446. [imageOutput setDelegate: callbackDelegate];
  235447. if (err == 0)
  235448. {
  235449. [session startRunning];
  235450. return;
  235451. }
  235452. }
  235453. }
  235454. openingError = nsStringToJuce ([err description]);
  235455. DBG (openingError);
  235456. }
  235457. ~QTCameraDeviceInteral()
  235458. {
  235459. [session stopRunning];
  235460. [session removeOutput: imageOutput];
  235461. [session release];
  235462. [input release];
  235463. [device release];
  235464. [audioDevice release];
  235465. [audioInput release];
  235466. [fileOutput release];
  235467. [imageOutput release];
  235468. [callbackDelegate release];
  235469. }
  235470. void resetFile()
  235471. {
  235472. [fileOutput recordToOutputFileURL: nil];
  235473. [session removeOutput: fileOutput];
  235474. [fileOutput release];
  235475. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  235476. [session removeInput: audioInput];
  235477. [audioInput release];
  235478. audioInput = 0;
  235479. [audioDevice release];
  235480. audioDevice = 0;
  235481. [fileOutput setDelegate: callbackDelegate];
  235482. }
  235483. void addDefaultAudioInput()
  235484. {
  235485. NSError* err = nil;
  235486. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  235487. if ([audioDevice open: &err])
  235488. [audioDevice retain];
  235489. else
  235490. audioDevice = nil;
  235491. if (audioDevice != 0)
  235492. {
  235493. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  235494. [session addInput: audioInput error: &err];
  235495. }
  235496. }
  235497. void addListener (CameraDevice::Listener* listenerToAdd)
  235498. {
  235499. const ScopedLock sl (listenerLock);
  235500. if (listeners.size() == 0)
  235501. [session addOutput: imageOutput error: nil];
  235502. listeners.addIfNotAlreadyThere (listenerToAdd);
  235503. }
  235504. void removeListener (CameraDevice::Listener* listenerToRemove)
  235505. {
  235506. const ScopedLock sl (listenerLock);
  235507. listeners.removeValue (listenerToRemove);
  235508. if (listeners.size() == 0)
  235509. [session removeOutput: imageOutput];
  235510. }
  235511. void callListeners (CIImage* frame, int w, int h)
  235512. {
  235513. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  235514. Image image (cgImage);
  235515. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  235516. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  235517. CGContextFlush (cgImage->context);
  235518. const ScopedLock sl (listenerLock);
  235519. for (int i = listeners.size(); --i >= 0;)
  235520. {
  235521. CameraDevice::Listener* const l = listeners[i];
  235522. if (l != 0)
  235523. l->imageReceived (image);
  235524. }
  235525. }
  235526. QTCaptureDevice* device;
  235527. QTCaptureDeviceInput* input;
  235528. QTCaptureDevice* audioDevice;
  235529. QTCaptureDeviceInput* audioInput;
  235530. QTCaptureSession* session;
  235531. QTCaptureMovieFileOutput* fileOutput;
  235532. QTCaptureDecompressedVideoOutput* imageOutput;
  235533. QTCaptureCallbackDelegate* callbackDelegate;
  235534. String openingError;
  235535. Array<CameraDevice::Listener*> listeners;
  235536. CriticalSection listenerLock;
  235537. };
  235538. END_JUCE_NAMESPACE
  235539. @implementation QTCaptureCallbackDelegate
  235540. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  235541. internalDev: (QTCameraDeviceInteral*) d
  235542. {
  235543. [super init];
  235544. owner = owner_;
  235545. internal = d;
  235546. firstPresentationTime = 0;
  235547. averageTimeOffset = 0;
  235548. return self;
  235549. }
  235550. - (void) dealloc
  235551. {
  235552. [super dealloc];
  235553. }
  235554. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235555. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235556. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235557. fromConnection: (QTCaptureConnection*) connection
  235558. {
  235559. if (internal->listeners.size() > 0)
  235560. {
  235561. const ScopedAutoReleasePool pool;
  235562. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  235563. CVPixelBufferGetWidth (videoFrame),
  235564. CVPixelBufferGetHeight (videoFrame));
  235565. }
  235566. }
  235567. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235568. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235569. fromConnection: (QTCaptureConnection*) connection
  235570. {
  235571. const Time now (Time::getCurrentTime());
  235572. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  235573. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  235574. #else
  235575. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  235576. #endif
  235577. int64 presentationTime = (hosttime != nil)
  235578. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  235579. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  235580. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  235581. if (firstPresentationTime == 0)
  235582. {
  235583. firstPresentationTime = presentationTime;
  235584. averageTimeOffset = timeDiff;
  235585. }
  235586. else
  235587. {
  235588. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  235589. }
  235590. }
  235591. @end
  235592. BEGIN_JUCE_NAMESPACE
  235593. class QTCaptureViewerComp : public NSViewComponent
  235594. {
  235595. public:
  235596. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  235597. {
  235598. const ScopedAutoReleasePool pool;
  235599. captureView = [[QTCaptureView alloc] init];
  235600. [captureView setCaptureSession: internal->session];
  235601. setSize (640, 480); // xxx need to somehow get the movie size - how?
  235602. setView (captureView);
  235603. }
  235604. ~QTCaptureViewerComp()
  235605. {
  235606. setView (0);
  235607. [captureView setCaptureSession: nil];
  235608. [captureView release];
  235609. }
  235610. QTCaptureView* captureView;
  235611. };
  235612. CameraDevice::CameraDevice (const String& name_, int index)
  235613. : name (name_)
  235614. {
  235615. isRecording = false;
  235616. internal = new QTCameraDeviceInteral (this, index);
  235617. }
  235618. CameraDevice::~CameraDevice()
  235619. {
  235620. stopRecording();
  235621. delete static_cast <QTCameraDeviceInteral*> (internal);
  235622. internal = 0;
  235623. }
  235624. Component* CameraDevice::createViewerComponent()
  235625. {
  235626. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  235627. }
  235628. const String CameraDevice::getFileExtension()
  235629. {
  235630. return ".mov";
  235631. }
  235632. void CameraDevice::startRecordingToFile (const File& file, int quality)
  235633. {
  235634. stopRecording();
  235635. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235636. d->callbackDelegate->firstPresentationTime = 0;
  235637. file.deleteFile();
  235638. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  235639. // out wrong, so we'll put some audio in there too..,
  235640. d->addDefaultAudioInput();
  235641. [d->session addOutput: d->fileOutput error: nil];
  235642. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  235643. for (;;)
  235644. {
  235645. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  235646. if (connection == 0)
  235647. break;
  235648. QTCompressionOptions* options = 0;
  235649. NSString* mediaType = [connection mediaType];
  235650. if ([mediaType isEqualToString: QTMediaTypeVideo])
  235651. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  235652. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  235653. : @"QTCompressionOptions240SizeH264Video"];
  235654. else if ([mediaType isEqualToString: QTMediaTypeSound])
  235655. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  235656. [d->fileOutput setCompressionOptions: options forConnection: connection];
  235657. }
  235658. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  235659. isRecording = true;
  235660. }
  235661. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  235662. {
  235663. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235664. if (d->callbackDelegate->firstPresentationTime != 0)
  235665. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  235666. return Time();
  235667. }
  235668. void CameraDevice::stopRecording()
  235669. {
  235670. if (isRecording)
  235671. {
  235672. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  235673. isRecording = false;
  235674. }
  235675. }
  235676. void CameraDevice::addListener (Listener* listenerToAdd)
  235677. {
  235678. if (listenerToAdd != 0)
  235679. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  235680. }
  235681. void CameraDevice::removeListener (Listener* listenerToRemove)
  235682. {
  235683. if (listenerToRemove != 0)
  235684. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  235685. }
  235686. const StringArray CameraDevice::getAvailableDevices()
  235687. {
  235688. const ScopedAutoReleasePool pool;
  235689. StringArray results;
  235690. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235691. for (int i = 0; i < (int) [devs count]; ++i)
  235692. {
  235693. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  235694. results.add (nsStringToJuce ([dev localizedDisplayName]));
  235695. }
  235696. return results;
  235697. }
  235698. CameraDevice* CameraDevice::openDevice (int index,
  235699. int minWidth, int minHeight,
  235700. int maxWidth, int maxHeight)
  235701. {
  235702. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  235703. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  235704. return d.release();
  235705. return 0;
  235706. }
  235707. #endif
  235708. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  235709. #endif
  235710. #endif
  235711. END_JUCE_NAMESPACE
  235712. #endif
  235713. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  235714. #endif
  235715. #endif